xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision c4f7ac64)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2021 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/slab.h>
29 #include <linux/lockdep.h>
30 
31 #include <scsi/scsi.h>
32 #include <scsi/scsi_cmnd.h>
33 #include <scsi/scsi_device.h>
34 #include <scsi/scsi_host.h>
35 #include <scsi/scsi_transport_fc.h>
36 #include <scsi/fc/fc_fs.h>
37 #include <linux/aer.h>
38 #include <linux/crash_dump.h>
39 #ifdef CONFIG_X86
40 #include <asm/set_memory.h>
41 #endif
42 
43 #include "lpfc_hw4.h"
44 #include "lpfc_hw.h"
45 #include "lpfc_sli.h"
46 #include "lpfc_sli4.h"
47 #include "lpfc_nl.h"
48 #include "lpfc_disc.h"
49 #include "lpfc.h"
50 #include "lpfc_scsi.h"
51 #include "lpfc_nvme.h"
52 #include "lpfc_crtn.h"
53 #include "lpfc_logmsg.h"
54 #include "lpfc_compat.h"
55 #include "lpfc_debugfs.h"
56 #include "lpfc_vport.h"
57 #include "lpfc_version.h"
58 
59 /* There are only four IOCB completion types. */
60 typedef enum _lpfc_iocb_type {
61 	LPFC_UNKNOWN_IOCB,
62 	LPFC_UNSOL_IOCB,
63 	LPFC_SOL_IOCB,
64 	LPFC_ABORT_IOCB
65 } lpfc_iocb_type;
66 
67 
68 /* Provide function prototypes local to this module. */
69 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
70 				  uint32_t);
71 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
72 			      uint8_t *, uint32_t *);
73 static struct lpfc_iocbq *lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *,
74 							 struct lpfc_iocbq *);
75 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
76 				      struct hbq_dmabuf *);
77 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
78 					  struct hbq_dmabuf *dmabuf);
79 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
80 				   struct lpfc_queue *cq, struct lpfc_cqe *cqe);
81 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
82 				       int);
83 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
84 				     struct lpfc_queue *eq,
85 				     struct lpfc_eqe *eqe);
86 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
87 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
88 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
89 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
90 				    struct lpfc_queue *cq,
91 				    struct lpfc_cqe *cqe);
92 
93 union lpfc_wqe128 lpfc_iread_cmd_template;
94 union lpfc_wqe128 lpfc_iwrite_cmd_template;
95 union lpfc_wqe128 lpfc_icmnd_cmd_template;
96 
97 static IOCB_t *
98 lpfc_get_iocb_from_iocbq(struct lpfc_iocbq *iocbq)
99 {
100 	return &iocbq->iocb;
101 }
102 
103 /* Setup WQE templates for IOs */
104 void lpfc_wqe_cmd_template(void)
105 {
106 	union lpfc_wqe128 *wqe;
107 
108 	/* IREAD template */
109 	wqe = &lpfc_iread_cmd_template;
110 	memset(wqe, 0, sizeof(union lpfc_wqe128));
111 
112 	/* Word 0, 1, 2 - BDE is variable */
113 
114 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
115 
116 	/* Word 4 - total_xfer_len is variable */
117 
118 	/* Word 5 - is zero */
119 
120 	/* Word 6 - ctxt_tag, xri_tag is variable */
121 
122 	/* Word 7 */
123 	bf_set(wqe_cmnd, &wqe->fcp_iread.wqe_com, CMD_FCP_IREAD64_WQE);
124 	bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, PARM_READ_CHECK);
125 	bf_set(wqe_class, &wqe->fcp_iread.wqe_com, CLASS3);
126 	bf_set(wqe_ct, &wqe->fcp_iread.wqe_com, SLI4_CT_RPI);
127 
128 	/* Word 8 - abort_tag is variable */
129 
130 	/* Word 9  - reqtag is variable */
131 
132 	/* Word 10 - dbde, wqes is variable */
133 	bf_set(wqe_qosd, &wqe->fcp_iread.wqe_com, 0);
134 	bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
135 	bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com, LPFC_WQE_LENLOC_WORD4);
136 	bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
137 	bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
138 
139 	/* Word 11 - pbde is variable */
140 	bf_set(wqe_cmd_type, &wqe->fcp_iread.wqe_com, COMMAND_DATA_IN);
141 	bf_set(wqe_cqid, &wqe->fcp_iread.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
142 	bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
143 
144 	/* Word 12 - is zero */
145 
146 	/* Word 13, 14, 15 - PBDE is variable */
147 
148 	/* IWRITE template */
149 	wqe = &lpfc_iwrite_cmd_template;
150 	memset(wqe, 0, sizeof(union lpfc_wqe128));
151 
152 	/* Word 0, 1, 2 - BDE is variable */
153 
154 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
155 
156 	/* Word 4 - total_xfer_len is variable */
157 
158 	/* Word 5 - initial_xfer_len is variable */
159 
160 	/* Word 6 - ctxt_tag, xri_tag is variable */
161 
162 	/* Word 7 */
163 	bf_set(wqe_cmnd, &wqe->fcp_iwrite.wqe_com, CMD_FCP_IWRITE64_WQE);
164 	bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, PARM_READ_CHECK);
165 	bf_set(wqe_class, &wqe->fcp_iwrite.wqe_com, CLASS3);
166 	bf_set(wqe_ct, &wqe->fcp_iwrite.wqe_com, SLI4_CT_RPI);
167 
168 	/* Word 8 - abort_tag is variable */
169 
170 	/* Word 9  - reqtag is variable */
171 
172 	/* Word 10 - dbde, wqes is variable */
173 	bf_set(wqe_qosd, &wqe->fcp_iwrite.wqe_com, 0);
174 	bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
175 	bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_LENLOC_WORD4);
176 	bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
177 	bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
178 
179 	/* Word 11 - pbde is variable */
180 	bf_set(wqe_cmd_type, &wqe->fcp_iwrite.wqe_com, COMMAND_DATA_OUT);
181 	bf_set(wqe_cqid, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
182 	bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
183 
184 	/* Word 12 - is zero */
185 
186 	/* Word 13, 14, 15 - PBDE is variable */
187 
188 	/* ICMND template */
189 	wqe = &lpfc_icmnd_cmd_template;
190 	memset(wqe, 0, sizeof(union lpfc_wqe128));
191 
192 	/* Word 0, 1, 2 - BDE is variable */
193 
194 	/* Word 3 - payload_offset_len is variable */
195 
196 	/* Word 4, 5 - is zero */
197 
198 	/* Word 6 - ctxt_tag, xri_tag is variable */
199 
200 	/* Word 7 */
201 	bf_set(wqe_cmnd, &wqe->fcp_icmd.wqe_com, CMD_FCP_ICMND64_WQE);
202 	bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
203 	bf_set(wqe_class, &wqe->fcp_icmd.wqe_com, CLASS3);
204 	bf_set(wqe_ct, &wqe->fcp_icmd.wqe_com, SLI4_CT_RPI);
205 
206 	/* Word 8 - abort_tag is variable */
207 
208 	/* Word 9  - reqtag is variable */
209 
210 	/* Word 10 - dbde, wqes is variable */
211 	bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
212 	bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_NONE);
213 	bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com, LPFC_WQE_LENLOC_NONE);
214 	bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
215 	bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
216 
217 	/* Word 11 */
218 	bf_set(wqe_cmd_type, &wqe->fcp_icmd.wqe_com, COMMAND_DATA_IN);
219 	bf_set(wqe_cqid, &wqe->fcp_icmd.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
220 	bf_set(wqe_pbde, &wqe->fcp_icmd.wqe_com, 0);
221 
222 	/* Word 12, 13, 14, 15 - is zero */
223 }
224 
225 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
226 /**
227  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
228  * @srcp: Source memory pointer.
229  * @destp: Destination memory pointer.
230  * @cnt: Number of words required to be copied.
231  *       Must be a multiple of sizeof(uint64_t)
232  *
233  * This function is used for copying data between driver memory
234  * and the SLI WQ. This function also changes the endianness
235  * of each word if native endianness is different from SLI
236  * endianness. This function can be called with or without
237  * lock.
238  **/
239 static void
240 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
241 {
242 	uint64_t *src = srcp;
243 	uint64_t *dest = destp;
244 	int i;
245 
246 	for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
247 		*dest++ = *src++;
248 }
249 #else
250 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
251 #endif
252 
253 /**
254  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
255  * @q: The Work Queue to operate on.
256  * @wqe: The work Queue Entry to put on the Work queue.
257  *
258  * This routine will copy the contents of @wqe to the next available entry on
259  * the @q. This function will then ring the Work Queue Doorbell to signal the
260  * HBA to start processing the Work Queue Entry. This function returns 0 if
261  * successful. If no entries are available on @q then this function will return
262  * -ENOMEM.
263  * The caller is expected to hold the hbalock when calling this routine.
264  **/
265 static int
266 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
267 {
268 	union lpfc_wqe *temp_wqe;
269 	struct lpfc_register doorbell;
270 	uint32_t host_index;
271 	uint32_t idx;
272 	uint32_t i = 0;
273 	uint8_t *tmp;
274 	u32 if_type;
275 
276 	/* sanity check on queue memory */
277 	if (unlikely(!q))
278 		return -ENOMEM;
279 
280 	temp_wqe = lpfc_sli4_qe(q, q->host_index);
281 
282 	/* If the host has not yet processed the next entry then we are done */
283 	idx = ((q->host_index + 1) % q->entry_count);
284 	if (idx == q->hba_index) {
285 		q->WQ_overflow++;
286 		return -EBUSY;
287 	}
288 	q->WQ_posted++;
289 	/* set consumption flag every once in a while */
290 	if (!((q->host_index + 1) % q->notify_interval))
291 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
292 	else
293 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
294 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
295 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
296 	lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
297 	if (q->dpp_enable && q->phba->cfg_enable_dpp) {
298 		/* write to DPP aperture taking advatage of Combined Writes */
299 		tmp = (uint8_t *)temp_wqe;
300 #ifdef __raw_writeq
301 		for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
302 			__raw_writeq(*((uint64_t *)(tmp + i)),
303 					q->dpp_regaddr + i);
304 #else
305 		for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
306 			__raw_writel(*((uint32_t *)(tmp + i)),
307 					q->dpp_regaddr + i);
308 #endif
309 	}
310 	/* ensure WQE bcopy and DPP flushed before doorbell write */
311 	wmb();
312 
313 	/* Update the host index before invoking device */
314 	host_index = q->host_index;
315 
316 	q->host_index = idx;
317 
318 	/* Ring Doorbell */
319 	doorbell.word0 = 0;
320 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
321 		if (q->dpp_enable && q->phba->cfg_enable_dpp) {
322 			bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
323 			bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
324 			bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
325 			    q->dpp_id);
326 			bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
327 			    q->queue_id);
328 		} else {
329 			bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
330 			bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
331 
332 			/* Leave bits <23:16> clear for if_type 6 dpp */
333 			if_type = bf_get(lpfc_sli_intf_if_type,
334 					 &q->phba->sli4_hba.sli_intf);
335 			if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
336 				bf_set(lpfc_wq_db_list_fm_index, &doorbell,
337 				       host_index);
338 		}
339 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
340 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
341 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
342 	} else {
343 		return -EINVAL;
344 	}
345 	writel(doorbell.word0, q->db_regaddr);
346 
347 	return 0;
348 }
349 
350 /**
351  * lpfc_sli4_wq_release - Updates internal hba index for WQ
352  * @q: The Work Queue to operate on.
353  * @index: The index to advance the hba index to.
354  *
355  * This routine will update the HBA index of a queue to reflect consumption of
356  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
357  * an entry the host calls this function to update the queue's internal
358  * pointers.
359  **/
360 static void
361 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
362 {
363 	/* sanity check on queue memory */
364 	if (unlikely(!q))
365 		return;
366 
367 	q->hba_index = index;
368 }
369 
370 /**
371  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
372  * @q: The Mailbox Queue to operate on.
373  * @mqe: The Mailbox Queue Entry to put on the Work queue.
374  *
375  * This routine will copy the contents of @mqe to the next available entry on
376  * the @q. This function will then ring the Work Queue Doorbell to signal the
377  * HBA to start processing the Work Queue Entry. This function returns 0 if
378  * successful. If no entries are available on @q then this function will return
379  * -ENOMEM.
380  * The caller is expected to hold the hbalock when calling this routine.
381  **/
382 static uint32_t
383 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
384 {
385 	struct lpfc_mqe *temp_mqe;
386 	struct lpfc_register doorbell;
387 
388 	/* sanity check on queue memory */
389 	if (unlikely(!q))
390 		return -ENOMEM;
391 	temp_mqe = lpfc_sli4_qe(q, q->host_index);
392 
393 	/* If the host has not yet processed the next entry then we are done */
394 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
395 		return -ENOMEM;
396 	lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
397 	/* Save off the mailbox pointer for completion */
398 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
399 
400 	/* Update the host index before invoking device */
401 	q->host_index = ((q->host_index + 1) % q->entry_count);
402 
403 	/* Ring Doorbell */
404 	doorbell.word0 = 0;
405 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
406 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
407 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
408 	return 0;
409 }
410 
411 /**
412  * lpfc_sli4_mq_release - Updates internal hba index for MQ
413  * @q: The Mailbox Queue to operate on.
414  *
415  * This routine will update the HBA index of a queue to reflect consumption of
416  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
417  * an entry the host calls this function to update the queue's internal
418  * pointers. This routine returns the number of entries that were consumed by
419  * the HBA.
420  **/
421 static uint32_t
422 lpfc_sli4_mq_release(struct lpfc_queue *q)
423 {
424 	/* sanity check on queue memory */
425 	if (unlikely(!q))
426 		return 0;
427 
428 	/* Clear the mailbox pointer for completion */
429 	q->phba->mbox = NULL;
430 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
431 	return 1;
432 }
433 
434 /**
435  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
436  * @q: The Event Queue to get the first valid EQE from
437  *
438  * This routine will get the first valid Event Queue Entry from @q, update
439  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
440  * the Queue (no more work to do), or the Queue is full of EQEs that have been
441  * processed, but not popped back to the HBA then this routine will return NULL.
442  **/
443 static struct lpfc_eqe *
444 lpfc_sli4_eq_get(struct lpfc_queue *q)
445 {
446 	struct lpfc_eqe *eqe;
447 
448 	/* sanity check on queue memory */
449 	if (unlikely(!q))
450 		return NULL;
451 	eqe = lpfc_sli4_qe(q, q->host_index);
452 
453 	/* If the next EQE is not valid then we are done */
454 	if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
455 		return NULL;
456 
457 	/*
458 	 * insert barrier for instruction interlock : data from the hardware
459 	 * must have the valid bit checked before it can be copied and acted
460 	 * upon. Speculative instructions were allowing a bcopy at the start
461 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
462 	 * after our return, to copy data before the valid bit check above
463 	 * was done. As such, some of the copied data was stale. The barrier
464 	 * ensures the check is before any data is copied.
465 	 */
466 	mb();
467 	return eqe;
468 }
469 
470 /**
471  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
472  * @q: The Event Queue to disable interrupts
473  *
474  **/
475 void
476 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
477 {
478 	struct lpfc_register doorbell;
479 
480 	doorbell.word0 = 0;
481 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
482 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
483 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
484 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
485 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
486 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
487 }
488 
489 /**
490  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
491  * @q: The Event Queue to disable interrupts
492  *
493  **/
494 void
495 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
496 {
497 	struct lpfc_register doorbell;
498 
499 	doorbell.word0 = 0;
500 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
501 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
502 }
503 
504 /**
505  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
506  * @phba: adapter with EQ
507  * @q: The Event Queue that the host has completed processing for.
508  * @count: Number of elements that have been consumed
509  * @arm: Indicates whether the host wants to arms this CQ.
510  *
511  * This routine will notify the HBA, by ringing the doorbell, that count
512  * number of EQEs have been processed. The @arm parameter indicates whether
513  * the queue should be rearmed when ringing the doorbell.
514  **/
515 void
516 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
517 		     uint32_t count, bool arm)
518 {
519 	struct lpfc_register doorbell;
520 
521 	/* sanity check on queue memory */
522 	if (unlikely(!q || (count == 0 && !arm)))
523 		return;
524 
525 	/* ring doorbell for number popped */
526 	doorbell.word0 = 0;
527 	if (arm) {
528 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
529 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
530 	}
531 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
532 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
533 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
534 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
535 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
536 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
537 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
538 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
539 		readl(q->phba->sli4_hba.EQDBregaddr);
540 }
541 
542 /**
543  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
544  * @phba: adapter with EQ
545  * @q: The Event Queue that the host has completed processing for.
546  * @count: Number of elements that have been consumed
547  * @arm: Indicates whether the host wants to arms this CQ.
548  *
549  * This routine will notify the HBA, by ringing the doorbell, that count
550  * number of EQEs have been processed. The @arm parameter indicates whether
551  * the queue should be rearmed when ringing the doorbell.
552  **/
553 void
554 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
555 			  uint32_t count, bool arm)
556 {
557 	struct lpfc_register doorbell;
558 
559 	/* sanity check on queue memory */
560 	if (unlikely(!q || (count == 0 && !arm)))
561 		return;
562 
563 	/* ring doorbell for number popped */
564 	doorbell.word0 = 0;
565 	if (arm)
566 		bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
567 	bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
568 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
569 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
570 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
571 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
572 		readl(q->phba->sli4_hba.EQDBregaddr);
573 }
574 
575 static void
576 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
577 			struct lpfc_eqe *eqe)
578 {
579 	if (!phba->sli4_hba.pc_sli4_params.eqav)
580 		bf_set_le32(lpfc_eqe_valid, eqe, 0);
581 
582 	eq->host_index = ((eq->host_index + 1) % eq->entry_count);
583 
584 	/* if the index wrapped around, toggle the valid bit */
585 	if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
586 		eq->qe_valid = (eq->qe_valid) ? 0 : 1;
587 }
588 
589 static void
590 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
591 {
592 	struct lpfc_eqe *eqe = NULL;
593 	u32 eq_count = 0, cq_count = 0;
594 	struct lpfc_cqe *cqe = NULL;
595 	struct lpfc_queue *cq = NULL, *childq = NULL;
596 	int cqid = 0;
597 
598 	/* walk all the EQ entries and drop on the floor */
599 	eqe = lpfc_sli4_eq_get(eq);
600 	while (eqe) {
601 		/* Get the reference to the corresponding CQ */
602 		cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
603 		cq = NULL;
604 
605 		list_for_each_entry(childq, &eq->child_list, list) {
606 			if (childq->queue_id == cqid) {
607 				cq = childq;
608 				break;
609 			}
610 		}
611 		/* If CQ is valid, iterate through it and drop all the CQEs */
612 		if (cq) {
613 			cqe = lpfc_sli4_cq_get(cq);
614 			while (cqe) {
615 				__lpfc_sli4_consume_cqe(phba, cq, cqe);
616 				cq_count++;
617 				cqe = lpfc_sli4_cq_get(cq);
618 			}
619 			/* Clear and re-arm the CQ */
620 			phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
621 			    LPFC_QUEUE_REARM);
622 			cq_count = 0;
623 		}
624 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
625 		eq_count++;
626 		eqe = lpfc_sli4_eq_get(eq);
627 	}
628 
629 	/* Clear and re-arm the EQ */
630 	phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
631 }
632 
633 static int
634 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
635 		     uint8_t rearm)
636 {
637 	struct lpfc_eqe *eqe;
638 	int count = 0, consumed = 0;
639 
640 	if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
641 		goto rearm_and_exit;
642 
643 	eqe = lpfc_sli4_eq_get(eq);
644 	while (eqe) {
645 		lpfc_sli4_hba_handle_eqe(phba, eq, eqe);
646 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
647 
648 		consumed++;
649 		if (!(++count % eq->max_proc_limit))
650 			break;
651 
652 		if (!(count % eq->notify_interval)) {
653 			phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
654 							LPFC_QUEUE_NOARM);
655 			consumed = 0;
656 		}
657 
658 		eqe = lpfc_sli4_eq_get(eq);
659 	}
660 	eq->EQ_processed += count;
661 
662 	/* Track the max number of EQEs processed in 1 intr */
663 	if (count > eq->EQ_max_eqe)
664 		eq->EQ_max_eqe = count;
665 
666 	xchg(&eq->queue_claimed, 0);
667 
668 rearm_and_exit:
669 	/* Always clear the EQ. */
670 	phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
671 
672 	return count;
673 }
674 
675 /**
676  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
677  * @q: The Completion Queue to get the first valid CQE from
678  *
679  * This routine will get the first valid Completion Queue Entry from @q, update
680  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
681  * the Queue (no more work to do), or the Queue is full of CQEs that have been
682  * processed, but not popped back to the HBA then this routine will return NULL.
683  **/
684 static struct lpfc_cqe *
685 lpfc_sli4_cq_get(struct lpfc_queue *q)
686 {
687 	struct lpfc_cqe *cqe;
688 
689 	/* sanity check on queue memory */
690 	if (unlikely(!q))
691 		return NULL;
692 	cqe = lpfc_sli4_qe(q, q->host_index);
693 
694 	/* If the next CQE is not valid then we are done */
695 	if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
696 		return NULL;
697 
698 	/*
699 	 * insert barrier for instruction interlock : data from the hardware
700 	 * must have the valid bit checked before it can be copied and acted
701 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
702 	 * instructions allowing action on content before valid bit checked,
703 	 * add barrier here as well. May not be needed as "content" is a
704 	 * single 32-bit entity here (vs multi word structure for cq's).
705 	 */
706 	mb();
707 	return cqe;
708 }
709 
710 static void
711 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
712 			struct lpfc_cqe *cqe)
713 {
714 	if (!phba->sli4_hba.pc_sli4_params.cqav)
715 		bf_set_le32(lpfc_cqe_valid, cqe, 0);
716 
717 	cq->host_index = ((cq->host_index + 1) % cq->entry_count);
718 
719 	/* if the index wrapped around, toggle the valid bit */
720 	if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
721 		cq->qe_valid = (cq->qe_valid) ? 0 : 1;
722 }
723 
724 /**
725  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
726  * @phba: the adapter with the CQ
727  * @q: The Completion Queue that the host has completed processing for.
728  * @count: the number of elements that were consumed
729  * @arm: Indicates whether the host wants to arms this CQ.
730  *
731  * This routine will notify the HBA, by ringing the doorbell, that the
732  * CQEs have been processed. The @arm parameter specifies whether the
733  * queue should be rearmed when ringing the doorbell.
734  **/
735 void
736 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
737 		     uint32_t count, bool arm)
738 {
739 	struct lpfc_register doorbell;
740 
741 	/* sanity check on queue memory */
742 	if (unlikely(!q || (count == 0 && !arm)))
743 		return;
744 
745 	/* ring doorbell for number popped */
746 	doorbell.word0 = 0;
747 	if (arm)
748 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
749 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
750 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
751 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
752 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
753 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
754 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
755 }
756 
757 /**
758  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
759  * @phba: the adapter with the CQ
760  * @q: The Completion Queue that the host has completed processing for.
761  * @count: the number of elements that were consumed
762  * @arm: Indicates whether the host wants to arms this CQ.
763  *
764  * This routine will notify the HBA, by ringing the doorbell, that the
765  * CQEs have been processed. The @arm parameter specifies whether the
766  * queue should be rearmed when ringing the doorbell.
767  **/
768 void
769 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
770 			 uint32_t count, bool arm)
771 {
772 	struct lpfc_register doorbell;
773 
774 	/* sanity check on queue memory */
775 	if (unlikely(!q || (count == 0 && !arm)))
776 		return;
777 
778 	/* ring doorbell for number popped */
779 	doorbell.word0 = 0;
780 	if (arm)
781 		bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
782 	bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
783 	bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
784 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
785 }
786 
787 /*
788  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
789  *
790  * This routine will copy the contents of @wqe to the next available entry on
791  * the @q. This function will then ring the Receive Queue Doorbell to signal the
792  * HBA to start processing the Receive Queue Entry. This function returns the
793  * index that the rqe was copied to if successful. If no entries are available
794  * on @q then this function will return -ENOMEM.
795  * The caller is expected to hold the hbalock when calling this routine.
796  **/
797 int
798 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
799 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
800 {
801 	struct lpfc_rqe *temp_hrqe;
802 	struct lpfc_rqe *temp_drqe;
803 	struct lpfc_register doorbell;
804 	int hq_put_index;
805 	int dq_put_index;
806 
807 	/* sanity check on queue memory */
808 	if (unlikely(!hq) || unlikely(!dq))
809 		return -ENOMEM;
810 	hq_put_index = hq->host_index;
811 	dq_put_index = dq->host_index;
812 	temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
813 	temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
814 
815 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
816 		return -EINVAL;
817 	if (hq_put_index != dq_put_index)
818 		return -EINVAL;
819 	/* If the host has not yet processed the next entry then we are done */
820 	if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
821 		return -EBUSY;
822 	lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
823 	lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
824 
825 	/* Update the host index to point to the next slot */
826 	hq->host_index = ((hq_put_index + 1) % hq->entry_count);
827 	dq->host_index = ((dq_put_index + 1) % dq->entry_count);
828 	hq->RQ_buf_posted++;
829 
830 	/* Ring The Header Receive Queue Doorbell */
831 	if (!(hq->host_index % hq->notify_interval)) {
832 		doorbell.word0 = 0;
833 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
834 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
835 			       hq->notify_interval);
836 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
837 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
838 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
839 			       hq->notify_interval);
840 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
841 			       hq->host_index);
842 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
843 		} else {
844 			return -EINVAL;
845 		}
846 		writel(doorbell.word0, hq->db_regaddr);
847 	}
848 	return hq_put_index;
849 }
850 
851 /*
852  * lpfc_sli4_rq_release - Updates internal hba index for RQ
853  *
854  * This routine will update the HBA index of a queue to reflect consumption of
855  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
856  * consumed an entry the host calls this function to update the queue's
857  * internal pointers. This routine returns the number of entries that were
858  * consumed by the HBA.
859  **/
860 static uint32_t
861 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
862 {
863 	/* sanity check on queue memory */
864 	if (unlikely(!hq) || unlikely(!dq))
865 		return 0;
866 
867 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
868 		return 0;
869 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
870 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
871 	return 1;
872 }
873 
874 /**
875  * lpfc_cmd_iocb - Get next command iocb entry in the ring
876  * @phba: Pointer to HBA context object.
877  * @pring: Pointer to driver SLI ring object.
878  *
879  * This function returns pointer to next command iocb entry
880  * in the command ring. The caller must hold hbalock to prevent
881  * other threads consume the next command iocb.
882  * SLI-2/SLI-3 provide different sized iocbs.
883  **/
884 static inline IOCB_t *
885 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
886 {
887 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
888 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
889 }
890 
891 /**
892  * lpfc_resp_iocb - Get next response iocb entry in the ring
893  * @phba: Pointer to HBA context object.
894  * @pring: Pointer to driver SLI ring object.
895  *
896  * This function returns pointer to next response iocb entry
897  * in the response ring. The caller must hold hbalock to make sure
898  * that no other thread consume the next response iocb.
899  * SLI-2/SLI-3 provide different sized iocbs.
900  **/
901 static inline IOCB_t *
902 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
903 {
904 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
905 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
906 }
907 
908 /**
909  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
910  * @phba: Pointer to HBA context object.
911  *
912  * This function is called with hbalock held. This function
913  * allocates a new driver iocb object from the iocb pool. If the
914  * allocation is successful, it returns pointer to the newly
915  * allocated iocb object else it returns NULL.
916  **/
917 struct lpfc_iocbq *
918 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
919 {
920 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
921 	struct lpfc_iocbq * iocbq = NULL;
922 
923 	lockdep_assert_held(&phba->hbalock);
924 
925 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
926 	if (iocbq)
927 		phba->iocb_cnt++;
928 	if (phba->iocb_cnt > phba->iocb_max)
929 		phba->iocb_max = phba->iocb_cnt;
930 	return iocbq;
931 }
932 
933 /**
934  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
935  * @phba: Pointer to HBA context object.
936  * @xritag: XRI value.
937  *
938  * This function clears the sglq pointer from the array of active
939  * sglq's. The xritag that is passed in is used to index into the
940  * array. Before the xritag can be used it needs to be adjusted
941  * by subtracting the xribase.
942  *
943  * Returns sglq ponter = success, NULL = Failure.
944  **/
945 struct lpfc_sglq *
946 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
947 {
948 	struct lpfc_sglq *sglq;
949 
950 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
951 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
952 	return sglq;
953 }
954 
955 /**
956  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
957  * @phba: Pointer to HBA context object.
958  * @xritag: XRI value.
959  *
960  * This function returns the sglq pointer from the array of active
961  * sglq's. The xritag that is passed in is used to index into the
962  * array. Before the xritag can be used it needs to be adjusted
963  * by subtracting the xribase.
964  *
965  * Returns sglq ponter = success, NULL = Failure.
966  **/
967 struct lpfc_sglq *
968 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
969 {
970 	struct lpfc_sglq *sglq;
971 
972 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
973 	return sglq;
974 }
975 
976 /**
977  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
978  * @phba: Pointer to HBA context object.
979  * @xritag: xri used in this exchange.
980  * @rrq: The RRQ to be cleared.
981  *
982  **/
983 void
984 lpfc_clr_rrq_active(struct lpfc_hba *phba,
985 		    uint16_t xritag,
986 		    struct lpfc_node_rrq *rrq)
987 {
988 	struct lpfc_nodelist *ndlp = NULL;
989 
990 	/* Lookup did to verify if did is still active on this vport */
991 	if (rrq->vport)
992 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
993 
994 	if (!ndlp)
995 		goto out;
996 
997 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
998 		rrq->send_rrq = 0;
999 		rrq->xritag = 0;
1000 		rrq->rrq_stop_time = 0;
1001 	}
1002 out:
1003 	mempool_free(rrq, phba->rrq_pool);
1004 }
1005 
1006 /**
1007  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
1008  * @phba: Pointer to HBA context object.
1009  *
1010  * This function is called with hbalock held. This function
1011  * Checks if stop_time (ratov from setting rrq active) has
1012  * been reached, if it has and the send_rrq flag is set then
1013  * it will call lpfc_send_rrq. If the send_rrq flag is not set
1014  * then it will just call the routine to clear the rrq and
1015  * free the rrq resource.
1016  * The timer is set to the next rrq that is going to expire before
1017  * leaving the routine.
1018  *
1019  **/
1020 void
1021 lpfc_handle_rrq_active(struct lpfc_hba *phba)
1022 {
1023 	struct lpfc_node_rrq *rrq;
1024 	struct lpfc_node_rrq *nextrrq;
1025 	unsigned long next_time;
1026 	unsigned long iflags;
1027 	LIST_HEAD(send_rrq);
1028 
1029 	spin_lock_irqsave(&phba->hbalock, iflags);
1030 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1031 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1032 	list_for_each_entry_safe(rrq, nextrrq,
1033 				 &phba->active_rrq_list, list) {
1034 		if (time_after(jiffies, rrq->rrq_stop_time))
1035 			list_move(&rrq->list, &send_rrq);
1036 		else if (time_before(rrq->rrq_stop_time, next_time))
1037 			next_time = rrq->rrq_stop_time;
1038 	}
1039 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1040 	if ((!list_empty(&phba->active_rrq_list)) &&
1041 	    (!(phba->pport->load_flag & FC_UNLOADING)))
1042 		mod_timer(&phba->rrq_tmr, next_time);
1043 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
1044 		list_del(&rrq->list);
1045 		if (!rrq->send_rrq) {
1046 			/* this call will free the rrq */
1047 			lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1048 		} else if (lpfc_send_rrq(phba, rrq)) {
1049 			/* if we send the rrq then the completion handler
1050 			*  will clear the bit in the xribitmap.
1051 			*/
1052 			lpfc_clr_rrq_active(phba, rrq->xritag,
1053 					    rrq);
1054 		}
1055 	}
1056 }
1057 
1058 /**
1059  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
1060  * @vport: Pointer to vport context object.
1061  * @xri: The xri used in the exchange.
1062  * @did: The targets DID for this exchange.
1063  *
1064  * returns NULL = rrq not found in the phba->active_rrq_list.
1065  *         rrq = rrq for this xri and target.
1066  **/
1067 struct lpfc_node_rrq *
1068 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
1069 {
1070 	struct lpfc_hba *phba = vport->phba;
1071 	struct lpfc_node_rrq *rrq;
1072 	struct lpfc_node_rrq *nextrrq;
1073 	unsigned long iflags;
1074 
1075 	if (phba->sli_rev != LPFC_SLI_REV4)
1076 		return NULL;
1077 	spin_lock_irqsave(&phba->hbalock, iflags);
1078 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1079 		if (rrq->vport == vport && rrq->xritag == xri &&
1080 				rrq->nlp_DID == did){
1081 			list_del(&rrq->list);
1082 			spin_unlock_irqrestore(&phba->hbalock, iflags);
1083 			return rrq;
1084 		}
1085 	}
1086 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1087 	return NULL;
1088 }
1089 
1090 /**
1091  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
1092  * @vport: Pointer to vport context object.
1093  * @ndlp: Pointer to the lpfc_node_list structure.
1094  * If ndlp is NULL Remove all active RRQs for this vport from the
1095  * phba->active_rrq_list and clear the rrq.
1096  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
1097  **/
1098 void
1099 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
1100 
1101 {
1102 	struct lpfc_hba *phba = vport->phba;
1103 	struct lpfc_node_rrq *rrq;
1104 	struct lpfc_node_rrq *nextrrq;
1105 	unsigned long iflags;
1106 	LIST_HEAD(rrq_list);
1107 
1108 	if (phba->sli_rev != LPFC_SLI_REV4)
1109 		return;
1110 	if (!ndlp) {
1111 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
1112 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
1113 	}
1114 	spin_lock_irqsave(&phba->hbalock, iflags);
1115 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1116 		if (rrq->vport != vport)
1117 			continue;
1118 
1119 		if (!ndlp || ndlp == lpfc_findnode_did(vport, rrq->nlp_DID))
1120 			list_move(&rrq->list, &rrq_list);
1121 
1122 	}
1123 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1124 
1125 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1126 		list_del(&rrq->list);
1127 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1128 	}
1129 }
1130 
1131 /**
1132  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1133  * @phba: Pointer to HBA context object.
1134  * @ndlp: Targets nodelist pointer for this exchange.
1135  * @xritag: the xri in the bitmap to test.
1136  *
1137  * This function returns:
1138  * 0 = rrq not active for this xri
1139  * 1 = rrq is valid for this xri.
1140  **/
1141 int
1142 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1143 			uint16_t  xritag)
1144 {
1145 	if (!ndlp)
1146 		return 0;
1147 	if (!ndlp->active_rrqs_xri_bitmap)
1148 		return 0;
1149 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1150 		return 1;
1151 	else
1152 		return 0;
1153 }
1154 
1155 /**
1156  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1157  * @phba: Pointer to HBA context object.
1158  * @ndlp: nodelist pointer for this target.
1159  * @xritag: xri used in this exchange.
1160  * @rxid: Remote Exchange ID.
1161  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1162  *
1163  * This function takes the hbalock.
1164  * The active bit is always set in the active rrq xri_bitmap even
1165  * if there is no slot avaiable for the other rrq information.
1166  *
1167  * returns 0 rrq actived for this xri
1168  *         < 0 No memory or invalid ndlp.
1169  **/
1170 int
1171 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1172 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1173 {
1174 	unsigned long iflags;
1175 	struct lpfc_node_rrq *rrq;
1176 	int empty;
1177 
1178 	if (!ndlp)
1179 		return -EINVAL;
1180 
1181 	if (!phba->cfg_enable_rrq)
1182 		return -EINVAL;
1183 
1184 	spin_lock_irqsave(&phba->hbalock, iflags);
1185 	if (phba->pport->load_flag & FC_UNLOADING) {
1186 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1187 		goto out;
1188 	}
1189 
1190 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
1191 		goto out;
1192 
1193 	if (!ndlp->active_rrqs_xri_bitmap)
1194 		goto out;
1195 
1196 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1197 		goto out;
1198 
1199 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1200 	rrq = mempool_alloc(phba->rrq_pool, GFP_ATOMIC);
1201 	if (!rrq) {
1202 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1203 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1204 				" DID:0x%x Send:%d\n",
1205 				xritag, rxid, ndlp->nlp_DID, send_rrq);
1206 		return -EINVAL;
1207 	}
1208 	if (phba->cfg_enable_rrq == 1)
1209 		rrq->send_rrq = send_rrq;
1210 	else
1211 		rrq->send_rrq = 0;
1212 	rrq->xritag = xritag;
1213 	rrq->rrq_stop_time = jiffies +
1214 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1215 	rrq->nlp_DID = ndlp->nlp_DID;
1216 	rrq->vport = ndlp->vport;
1217 	rrq->rxid = rxid;
1218 	spin_lock_irqsave(&phba->hbalock, iflags);
1219 	empty = list_empty(&phba->active_rrq_list);
1220 	list_add_tail(&rrq->list, &phba->active_rrq_list);
1221 	phba->hba_flag |= HBA_RRQ_ACTIVE;
1222 	if (empty)
1223 		lpfc_worker_wake_up(phba);
1224 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1225 	return 0;
1226 out:
1227 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1228 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1229 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
1230 			" DID:0x%x Send:%d\n",
1231 			xritag, rxid, ndlp->nlp_DID, send_rrq);
1232 	return -EINVAL;
1233 }
1234 
1235 /**
1236  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1237  * @phba: Pointer to HBA context object.
1238  * @piocbq: Pointer to the iocbq.
1239  *
1240  * The driver calls this function with either the nvme ls ring lock
1241  * or the fc els ring lock held depending on the iocb usage.  This function
1242  * gets a new driver sglq object from the sglq list. If the list is not empty
1243  * then it is successful, it returns pointer to the newly allocated sglq
1244  * object else it returns NULL.
1245  **/
1246 static struct lpfc_sglq *
1247 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1248 {
1249 	struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1250 	struct lpfc_sglq *sglq = NULL;
1251 	struct lpfc_sglq *start_sglq = NULL;
1252 	struct lpfc_io_buf *lpfc_cmd;
1253 	struct lpfc_nodelist *ndlp;
1254 	struct lpfc_sli_ring *pring = NULL;
1255 	int found = 0;
1256 
1257 	if (piocbq->iocb_flag & LPFC_IO_NVME_LS)
1258 		pring =  phba->sli4_hba.nvmels_wq->pring;
1259 	else
1260 		pring = lpfc_phba_elsring(phba);
1261 
1262 	lockdep_assert_held(&pring->ring_lock);
1263 
1264 	if (piocbq->iocb_flag &  LPFC_IO_FCP) {
1265 		lpfc_cmd = (struct lpfc_io_buf *) piocbq->context1;
1266 		ndlp = lpfc_cmd->rdata->pnode;
1267 	} else  if ((piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) &&
1268 			!(piocbq->iocb_flag & LPFC_IO_LIBDFC)) {
1269 		ndlp = piocbq->context_un.ndlp;
1270 	} else  if (piocbq->iocb_flag & LPFC_IO_LIBDFC) {
1271 		if (piocbq->iocb_flag & LPFC_IO_LOOPBACK)
1272 			ndlp = NULL;
1273 		else
1274 			ndlp = piocbq->context_un.ndlp;
1275 	} else {
1276 		ndlp = piocbq->context1;
1277 	}
1278 
1279 	spin_lock(&phba->sli4_hba.sgl_list_lock);
1280 	list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1281 	start_sglq = sglq;
1282 	while (!found) {
1283 		if (!sglq)
1284 			break;
1285 		if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1286 		    test_bit(sglq->sli4_lxritag,
1287 		    ndlp->active_rrqs_xri_bitmap)) {
1288 			/* This xri has an rrq outstanding for this DID.
1289 			 * put it back in the list and get another xri.
1290 			 */
1291 			list_add_tail(&sglq->list, lpfc_els_sgl_list);
1292 			sglq = NULL;
1293 			list_remove_head(lpfc_els_sgl_list, sglq,
1294 						struct lpfc_sglq, list);
1295 			if (sglq == start_sglq) {
1296 				list_add_tail(&sglq->list, lpfc_els_sgl_list);
1297 				sglq = NULL;
1298 				break;
1299 			} else
1300 				continue;
1301 		}
1302 		sglq->ndlp = ndlp;
1303 		found = 1;
1304 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1305 		sglq->state = SGL_ALLOCATED;
1306 	}
1307 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
1308 	return sglq;
1309 }
1310 
1311 /**
1312  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1313  * @phba: Pointer to HBA context object.
1314  * @piocbq: Pointer to the iocbq.
1315  *
1316  * This function is called with the sgl_list lock held. This function
1317  * gets a new driver sglq object from the sglq list. If the
1318  * list is not empty then it is successful, it returns pointer to the newly
1319  * allocated sglq object else it returns NULL.
1320  **/
1321 struct lpfc_sglq *
1322 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1323 {
1324 	struct list_head *lpfc_nvmet_sgl_list;
1325 	struct lpfc_sglq *sglq = NULL;
1326 
1327 	lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1328 
1329 	lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1330 
1331 	list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1332 	if (!sglq)
1333 		return NULL;
1334 	phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1335 	sglq->state = SGL_ALLOCATED;
1336 	return sglq;
1337 }
1338 
1339 /**
1340  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1341  * @phba: Pointer to HBA context object.
1342  *
1343  * This function is called with no lock held. This function
1344  * allocates a new driver iocb object from the iocb pool. If the
1345  * allocation is successful, it returns pointer to the newly
1346  * allocated iocb object else it returns NULL.
1347  **/
1348 struct lpfc_iocbq *
1349 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1350 {
1351 	struct lpfc_iocbq * iocbq = NULL;
1352 	unsigned long iflags;
1353 
1354 	spin_lock_irqsave(&phba->hbalock, iflags);
1355 	iocbq = __lpfc_sli_get_iocbq(phba);
1356 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1357 	return iocbq;
1358 }
1359 
1360 /**
1361  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1362  * @phba: Pointer to HBA context object.
1363  * @iocbq: Pointer to driver iocb object.
1364  *
1365  * This function is called to release the driver iocb object
1366  * to the iocb pool. The iotag in the iocb object
1367  * does not change for each use of the iocb object. This function
1368  * clears all other fields of the iocb object when it is freed.
1369  * The sqlq structure that holds the xritag and phys and virtual
1370  * mappings for the scatter gather list is retrieved from the
1371  * active array of sglq. The get of the sglq pointer also clears
1372  * the entry in the array. If the status of the IO indiactes that
1373  * this IO was aborted then the sglq entry it put on the
1374  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1375  * IO has good status or fails for any other reason then the sglq
1376  * entry is added to the free list (lpfc_els_sgl_list). The hbalock is
1377  *  asserted held in the code path calling this routine.
1378  **/
1379 static void
1380 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1381 {
1382 	struct lpfc_sglq *sglq;
1383 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1384 	unsigned long iflag = 0;
1385 	struct lpfc_sli_ring *pring;
1386 
1387 	if (iocbq->sli4_xritag == NO_XRI)
1388 		sglq = NULL;
1389 	else
1390 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1391 
1392 
1393 	if (sglq)  {
1394 		if (iocbq->iocb_flag & LPFC_IO_NVMET) {
1395 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1396 					  iflag);
1397 			sglq->state = SGL_FREED;
1398 			sglq->ndlp = NULL;
1399 			list_add_tail(&sglq->list,
1400 				      &phba->sli4_hba.lpfc_nvmet_sgl_list);
1401 			spin_unlock_irqrestore(
1402 				&phba->sli4_hba.sgl_list_lock, iflag);
1403 			goto out;
1404 		}
1405 
1406 		if ((iocbq->iocb_flag & LPFC_EXCHANGE_BUSY) &&
1407 			(sglq->state != SGL_XRI_ABORTED)) {
1408 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1409 					  iflag);
1410 
1411 			/* Check if we can get a reference on ndlp */
1412 			if (sglq->ndlp && !lpfc_nlp_get(sglq->ndlp))
1413 				sglq->ndlp = NULL;
1414 
1415 			list_add(&sglq->list,
1416 				 &phba->sli4_hba.lpfc_abts_els_sgl_list);
1417 			spin_unlock_irqrestore(
1418 				&phba->sli4_hba.sgl_list_lock, iflag);
1419 		} else {
1420 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1421 					  iflag);
1422 			sglq->state = SGL_FREED;
1423 			sglq->ndlp = NULL;
1424 			list_add_tail(&sglq->list,
1425 				      &phba->sli4_hba.lpfc_els_sgl_list);
1426 			spin_unlock_irqrestore(
1427 				&phba->sli4_hba.sgl_list_lock, iflag);
1428 			pring = lpfc_phba_elsring(phba);
1429 			/* Check if TXQ queue needs to be serviced */
1430 			if (pring && (!list_empty(&pring->txq)))
1431 				lpfc_worker_wake_up(phba);
1432 		}
1433 	}
1434 
1435 out:
1436 	/*
1437 	 * Clean all volatile data fields, preserve iotag and node struct.
1438 	 */
1439 	memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1440 	iocbq->sli4_lxritag = NO_XRI;
1441 	iocbq->sli4_xritag = NO_XRI;
1442 	iocbq->iocb_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET |
1443 			      LPFC_IO_NVME_LS);
1444 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1445 }
1446 
1447 
1448 /**
1449  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1450  * @phba: Pointer to HBA context object.
1451  * @iocbq: Pointer to driver iocb object.
1452  *
1453  * This function is called to release the driver iocb object to the
1454  * iocb pool. The iotag in the iocb object does not change for each
1455  * use of the iocb object. This function clears all other fields of
1456  * the iocb object when it is freed. The hbalock is asserted held in
1457  * the code path calling this routine.
1458  **/
1459 static void
1460 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1461 {
1462 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1463 
1464 	/*
1465 	 * Clean all volatile data fields, preserve iotag and node struct.
1466 	 */
1467 	memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1468 	iocbq->sli4_xritag = NO_XRI;
1469 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1470 }
1471 
1472 /**
1473  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1474  * @phba: Pointer to HBA context object.
1475  * @iocbq: Pointer to driver iocb object.
1476  *
1477  * This function is called with hbalock held to release driver
1478  * iocb object to the iocb pool. The iotag in the iocb object
1479  * does not change for each use of the iocb object. This function
1480  * clears all other fields of the iocb object when it is freed.
1481  **/
1482 static void
1483 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1484 {
1485 	lockdep_assert_held(&phba->hbalock);
1486 
1487 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1488 	phba->iocb_cnt--;
1489 }
1490 
1491 /**
1492  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1493  * @phba: Pointer to HBA context object.
1494  * @iocbq: Pointer to driver iocb object.
1495  *
1496  * This function is called with no lock held to release the iocb to
1497  * iocb pool.
1498  **/
1499 void
1500 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1501 {
1502 	unsigned long iflags;
1503 
1504 	/*
1505 	 * Clean all volatile data fields, preserve iotag and node struct.
1506 	 */
1507 	spin_lock_irqsave(&phba->hbalock, iflags);
1508 	__lpfc_sli_release_iocbq(phba, iocbq);
1509 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1510 }
1511 
1512 /**
1513  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1514  * @phba: Pointer to HBA context object.
1515  * @iocblist: List of IOCBs.
1516  * @ulpstatus: ULP status in IOCB command field.
1517  * @ulpWord4: ULP word-4 in IOCB command field.
1518  *
1519  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1520  * on the list by invoking the complete callback function associated with the
1521  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1522  * fields.
1523  **/
1524 void
1525 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1526 		      uint32_t ulpstatus, uint32_t ulpWord4)
1527 {
1528 	struct lpfc_iocbq *piocb;
1529 
1530 	while (!list_empty(iocblist)) {
1531 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1532 		if (piocb->wqe_cmpl) {
1533 			if (piocb->iocb_flag & LPFC_IO_NVME)
1534 				lpfc_nvme_cancel_iocb(phba, piocb,
1535 						      ulpstatus, ulpWord4);
1536 			else
1537 				lpfc_sli_release_iocbq(phba, piocb);
1538 
1539 		} else if (piocb->iocb_cmpl) {
1540 			piocb->iocb.ulpStatus = ulpstatus;
1541 			piocb->iocb.un.ulpWord[4] = ulpWord4;
1542 			(piocb->iocb_cmpl) (phba, piocb, piocb);
1543 		} else {
1544 			lpfc_sli_release_iocbq(phba, piocb);
1545 		}
1546 	}
1547 	return;
1548 }
1549 
1550 /**
1551  * lpfc_sli_iocb_cmd_type - Get the iocb type
1552  * @iocb_cmnd: iocb command code.
1553  *
1554  * This function is called by ring event handler function to get the iocb type.
1555  * This function translates the iocb command to an iocb command type used to
1556  * decide the final disposition of each completed IOCB.
1557  * The function returns
1558  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1559  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1560  * LPFC_ABORT_IOCB   if it is an abort iocb
1561  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1562  *
1563  * The caller is not required to hold any lock.
1564  **/
1565 static lpfc_iocb_type
1566 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1567 {
1568 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1569 
1570 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1571 		return 0;
1572 
1573 	switch (iocb_cmnd) {
1574 	case CMD_XMIT_SEQUENCE_CR:
1575 	case CMD_XMIT_SEQUENCE_CX:
1576 	case CMD_XMIT_BCAST_CN:
1577 	case CMD_XMIT_BCAST_CX:
1578 	case CMD_ELS_REQUEST_CR:
1579 	case CMD_ELS_REQUEST_CX:
1580 	case CMD_CREATE_XRI_CR:
1581 	case CMD_CREATE_XRI_CX:
1582 	case CMD_GET_RPI_CN:
1583 	case CMD_XMIT_ELS_RSP_CX:
1584 	case CMD_GET_RPI_CR:
1585 	case CMD_FCP_IWRITE_CR:
1586 	case CMD_FCP_IWRITE_CX:
1587 	case CMD_FCP_IREAD_CR:
1588 	case CMD_FCP_IREAD_CX:
1589 	case CMD_FCP_ICMND_CR:
1590 	case CMD_FCP_ICMND_CX:
1591 	case CMD_FCP_TSEND_CX:
1592 	case CMD_FCP_TRSP_CX:
1593 	case CMD_FCP_TRECEIVE_CX:
1594 	case CMD_FCP_AUTO_TRSP_CX:
1595 	case CMD_ADAPTER_MSG:
1596 	case CMD_ADAPTER_DUMP:
1597 	case CMD_XMIT_SEQUENCE64_CR:
1598 	case CMD_XMIT_SEQUENCE64_CX:
1599 	case CMD_XMIT_BCAST64_CN:
1600 	case CMD_XMIT_BCAST64_CX:
1601 	case CMD_ELS_REQUEST64_CR:
1602 	case CMD_ELS_REQUEST64_CX:
1603 	case CMD_FCP_IWRITE64_CR:
1604 	case CMD_FCP_IWRITE64_CX:
1605 	case CMD_FCP_IREAD64_CR:
1606 	case CMD_FCP_IREAD64_CX:
1607 	case CMD_FCP_ICMND64_CR:
1608 	case CMD_FCP_ICMND64_CX:
1609 	case CMD_FCP_TSEND64_CX:
1610 	case CMD_FCP_TRSP64_CX:
1611 	case CMD_FCP_TRECEIVE64_CX:
1612 	case CMD_GEN_REQUEST64_CR:
1613 	case CMD_GEN_REQUEST64_CX:
1614 	case CMD_XMIT_ELS_RSP64_CX:
1615 	case DSSCMD_IWRITE64_CR:
1616 	case DSSCMD_IWRITE64_CX:
1617 	case DSSCMD_IREAD64_CR:
1618 	case DSSCMD_IREAD64_CX:
1619 	case CMD_SEND_FRAME:
1620 		type = LPFC_SOL_IOCB;
1621 		break;
1622 	case CMD_ABORT_XRI_CN:
1623 	case CMD_ABORT_XRI_CX:
1624 	case CMD_CLOSE_XRI_CN:
1625 	case CMD_CLOSE_XRI_CX:
1626 	case CMD_XRI_ABORTED_CX:
1627 	case CMD_ABORT_MXRI64_CN:
1628 	case CMD_XMIT_BLS_RSP64_CX:
1629 		type = LPFC_ABORT_IOCB;
1630 		break;
1631 	case CMD_RCV_SEQUENCE_CX:
1632 	case CMD_RCV_ELS_REQ_CX:
1633 	case CMD_RCV_SEQUENCE64_CX:
1634 	case CMD_RCV_ELS_REQ64_CX:
1635 	case CMD_ASYNC_STATUS:
1636 	case CMD_IOCB_RCV_SEQ64_CX:
1637 	case CMD_IOCB_RCV_ELS64_CX:
1638 	case CMD_IOCB_RCV_CONT64_CX:
1639 	case CMD_IOCB_RET_XRI64_CX:
1640 		type = LPFC_UNSOL_IOCB;
1641 		break;
1642 	case CMD_IOCB_XMIT_MSEQ64_CR:
1643 	case CMD_IOCB_XMIT_MSEQ64_CX:
1644 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1645 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1646 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1647 	case CMD_IOCB_ABORT_EXTENDED_CN:
1648 	case CMD_IOCB_RET_HBQE64_CN:
1649 	case CMD_IOCB_FCP_IBIDIR64_CR:
1650 	case CMD_IOCB_FCP_IBIDIR64_CX:
1651 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1652 	case CMD_IOCB_LOGENTRY_CN:
1653 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1654 		printk("%s - Unhandled SLI-3 Command x%x\n",
1655 				__func__, iocb_cmnd);
1656 		type = LPFC_UNKNOWN_IOCB;
1657 		break;
1658 	default:
1659 		type = LPFC_UNKNOWN_IOCB;
1660 		break;
1661 	}
1662 
1663 	return type;
1664 }
1665 
1666 /**
1667  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1668  * @phba: Pointer to HBA context object.
1669  *
1670  * This function is called from SLI initialization code
1671  * to configure every ring of the HBA's SLI interface. The
1672  * caller is not required to hold any lock. This function issues
1673  * a config_ring mailbox command for each ring.
1674  * This function returns zero if successful else returns a negative
1675  * error code.
1676  **/
1677 static int
1678 lpfc_sli_ring_map(struct lpfc_hba *phba)
1679 {
1680 	struct lpfc_sli *psli = &phba->sli;
1681 	LPFC_MBOXQ_t *pmb;
1682 	MAILBOX_t *pmbox;
1683 	int i, rc, ret = 0;
1684 
1685 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1686 	if (!pmb)
1687 		return -ENOMEM;
1688 	pmbox = &pmb->u.mb;
1689 	phba->link_state = LPFC_INIT_MBX_CMDS;
1690 	for (i = 0; i < psli->num_rings; i++) {
1691 		lpfc_config_ring(phba, i, pmb);
1692 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1693 		if (rc != MBX_SUCCESS) {
1694 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1695 					"0446 Adapter failed to init (%d), "
1696 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1697 					"ring %d\n",
1698 					rc, pmbox->mbxCommand,
1699 					pmbox->mbxStatus, i);
1700 			phba->link_state = LPFC_HBA_ERROR;
1701 			ret = -ENXIO;
1702 			break;
1703 		}
1704 	}
1705 	mempool_free(pmb, phba->mbox_mem_pool);
1706 	return ret;
1707 }
1708 
1709 /**
1710  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1711  * @phba: Pointer to HBA context object.
1712  * @pring: Pointer to driver SLI ring object.
1713  * @piocb: Pointer to the driver iocb object.
1714  *
1715  * The driver calls this function with the hbalock held for SLI3 ports or
1716  * the ring lock held for SLI4 ports. The function adds the
1717  * new iocb to txcmplq of the given ring. This function always returns
1718  * 0. If this function is called for ELS ring, this function checks if
1719  * there is a vport associated with the ELS command. This function also
1720  * starts els_tmofunc timer if this is an ELS command.
1721  **/
1722 static int
1723 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1724 			struct lpfc_iocbq *piocb)
1725 {
1726 	if (phba->sli_rev == LPFC_SLI_REV4)
1727 		lockdep_assert_held(&pring->ring_lock);
1728 	else
1729 		lockdep_assert_held(&phba->hbalock);
1730 
1731 	BUG_ON(!piocb);
1732 
1733 	list_add_tail(&piocb->list, &pring->txcmplq);
1734 	piocb->iocb_flag |= LPFC_IO_ON_TXCMPLQ;
1735 	pring->txcmplq_cnt++;
1736 
1737 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1738 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
1739 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
1740 		BUG_ON(!piocb->vport);
1741 		if (!(piocb->vport->load_flag & FC_UNLOADING))
1742 			mod_timer(&piocb->vport->els_tmofunc,
1743 				  jiffies +
1744 				  msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1745 	}
1746 
1747 	return 0;
1748 }
1749 
1750 /**
1751  * lpfc_sli_ringtx_get - Get first element of the txq
1752  * @phba: Pointer to HBA context object.
1753  * @pring: Pointer to driver SLI ring object.
1754  *
1755  * This function is called with hbalock held to get next
1756  * iocb in txq of the given ring. If there is any iocb in
1757  * the txq, the function returns first iocb in the list after
1758  * removing the iocb from the list, else it returns NULL.
1759  **/
1760 struct lpfc_iocbq *
1761 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1762 {
1763 	struct lpfc_iocbq *cmd_iocb;
1764 
1765 	lockdep_assert_held(&phba->hbalock);
1766 
1767 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1768 	return cmd_iocb;
1769 }
1770 
1771 /**
1772  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
1773  * @phba: Pointer to HBA context object.
1774  * @pring: Pointer to driver SLI ring object.
1775  *
1776  * This function is called with hbalock held and the caller must post the
1777  * iocb without releasing the lock. If the caller releases the lock,
1778  * iocb slot returned by the function is not guaranteed to be available.
1779  * The function returns pointer to the next available iocb slot if there
1780  * is available slot in the ring, else it returns NULL.
1781  * If the get index of the ring is ahead of the put index, the function
1782  * will post an error attention event to the worker thread to take the
1783  * HBA to offline state.
1784  **/
1785 static IOCB_t *
1786 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1787 {
1788 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
1789 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
1790 
1791 	lockdep_assert_held(&phba->hbalock);
1792 
1793 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
1794 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
1795 		pring->sli.sli3.next_cmdidx = 0;
1796 
1797 	if (unlikely(pring->sli.sli3.local_getidx ==
1798 		pring->sli.sli3.next_cmdidx)) {
1799 
1800 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
1801 
1802 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
1803 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1804 					"0315 Ring %d issue: portCmdGet %d "
1805 					"is bigger than cmd ring %d\n",
1806 					pring->ringno,
1807 					pring->sli.sli3.local_getidx,
1808 					max_cmd_idx);
1809 
1810 			phba->link_state = LPFC_HBA_ERROR;
1811 			/*
1812 			 * All error attention handlers are posted to
1813 			 * worker thread
1814 			 */
1815 			phba->work_ha |= HA_ERATT;
1816 			phba->work_hs = HS_FFER3;
1817 
1818 			lpfc_worker_wake_up(phba);
1819 
1820 			return NULL;
1821 		}
1822 
1823 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
1824 			return NULL;
1825 	}
1826 
1827 	return lpfc_cmd_iocb(phba, pring);
1828 }
1829 
1830 /**
1831  * lpfc_sli_next_iotag - Get an iotag for the iocb
1832  * @phba: Pointer to HBA context object.
1833  * @iocbq: Pointer to driver iocb object.
1834  *
1835  * This function gets an iotag for the iocb. If there is no unused iotag and
1836  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
1837  * array and assigns a new iotag.
1838  * The function returns the allocated iotag if successful, else returns zero.
1839  * Zero is not a valid iotag.
1840  * The caller is not required to hold any lock.
1841  **/
1842 uint16_t
1843 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1844 {
1845 	struct lpfc_iocbq **new_arr;
1846 	struct lpfc_iocbq **old_arr;
1847 	size_t new_len;
1848 	struct lpfc_sli *psli = &phba->sli;
1849 	uint16_t iotag;
1850 
1851 	spin_lock_irq(&phba->hbalock);
1852 	iotag = psli->last_iotag;
1853 	if(++iotag < psli->iocbq_lookup_len) {
1854 		psli->last_iotag = iotag;
1855 		psli->iocbq_lookup[iotag] = iocbq;
1856 		spin_unlock_irq(&phba->hbalock);
1857 		iocbq->iotag = iotag;
1858 		return iotag;
1859 	} else if (psli->iocbq_lookup_len < (0xffff
1860 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
1861 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
1862 		spin_unlock_irq(&phba->hbalock);
1863 		new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
1864 				  GFP_KERNEL);
1865 		if (new_arr) {
1866 			spin_lock_irq(&phba->hbalock);
1867 			old_arr = psli->iocbq_lookup;
1868 			if (new_len <= psli->iocbq_lookup_len) {
1869 				/* highly unprobable case */
1870 				kfree(new_arr);
1871 				iotag = psli->last_iotag;
1872 				if(++iotag < psli->iocbq_lookup_len) {
1873 					psli->last_iotag = iotag;
1874 					psli->iocbq_lookup[iotag] = iocbq;
1875 					spin_unlock_irq(&phba->hbalock);
1876 					iocbq->iotag = iotag;
1877 					return iotag;
1878 				}
1879 				spin_unlock_irq(&phba->hbalock);
1880 				return 0;
1881 			}
1882 			if (psli->iocbq_lookup)
1883 				memcpy(new_arr, old_arr,
1884 				       ((psli->last_iotag  + 1) *
1885 					sizeof (struct lpfc_iocbq *)));
1886 			psli->iocbq_lookup = new_arr;
1887 			psli->iocbq_lookup_len = new_len;
1888 			psli->last_iotag = iotag;
1889 			psli->iocbq_lookup[iotag] = iocbq;
1890 			spin_unlock_irq(&phba->hbalock);
1891 			iocbq->iotag = iotag;
1892 			kfree(old_arr);
1893 			return iotag;
1894 		}
1895 	} else
1896 		spin_unlock_irq(&phba->hbalock);
1897 
1898 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
1899 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
1900 			psli->last_iotag);
1901 
1902 	return 0;
1903 }
1904 
1905 /**
1906  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
1907  * @phba: Pointer to HBA context object.
1908  * @pring: Pointer to driver SLI ring object.
1909  * @iocb: Pointer to iocb slot in the ring.
1910  * @nextiocb: Pointer to driver iocb object which need to be
1911  *            posted to firmware.
1912  *
1913  * This function is called to post a new iocb to the firmware. This
1914  * function copies the new iocb to ring iocb slot and updates the
1915  * ring pointers. It adds the new iocb to txcmplq if there is
1916  * a completion call back for this iocb else the function will free the
1917  * iocb object.  The hbalock is asserted held in the code path calling
1918  * this routine.
1919  **/
1920 static void
1921 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1922 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
1923 {
1924 	/*
1925 	 * Set up an iotag
1926 	 */
1927 	nextiocb->iocb.ulpIoTag = (nextiocb->iocb_cmpl) ? nextiocb->iotag : 0;
1928 
1929 
1930 	if (pring->ringno == LPFC_ELS_RING) {
1931 		lpfc_debugfs_slow_ring_trc(phba,
1932 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
1933 			*(((uint32_t *) &nextiocb->iocb) + 4),
1934 			*(((uint32_t *) &nextiocb->iocb) + 6),
1935 			*(((uint32_t *) &nextiocb->iocb) + 7));
1936 	}
1937 
1938 	/*
1939 	 * Issue iocb command to adapter
1940 	 */
1941 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
1942 	wmb();
1943 	pring->stats.iocb_cmd++;
1944 
1945 	/*
1946 	 * If there is no completion routine to call, we can release the
1947 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
1948 	 * that have no rsp ring completion, iocb_cmpl MUST be NULL.
1949 	 */
1950 	if (nextiocb->iocb_cmpl)
1951 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
1952 	else
1953 		__lpfc_sli_release_iocbq(phba, nextiocb);
1954 
1955 	/*
1956 	 * Let the HBA know what IOCB slot will be the next one the
1957 	 * driver will put a command into.
1958 	 */
1959 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
1960 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
1961 }
1962 
1963 /**
1964  * lpfc_sli_update_full_ring - Update the chip attention register
1965  * @phba: Pointer to HBA context object.
1966  * @pring: Pointer to driver SLI ring object.
1967  *
1968  * The caller is not required to hold any lock for calling this function.
1969  * This function updates the chip attention bits for the ring to inform firmware
1970  * that there are pending work to be done for this ring and requests an
1971  * interrupt when there is space available in the ring. This function is
1972  * called when the driver is unable to post more iocbs to the ring due
1973  * to unavailability of space in the ring.
1974  **/
1975 static void
1976 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1977 {
1978 	int ringno = pring->ringno;
1979 
1980 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
1981 
1982 	wmb();
1983 
1984 	/*
1985 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
1986 	 * The HBA will tell us when an IOCB entry is available.
1987 	 */
1988 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
1989 	readl(phba->CAregaddr); /* flush */
1990 
1991 	pring->stats.iocb_cmd_full++;
1992 }
1993 
1994 /**
1995  * lpfc_sli_update_ring - Update chip attention register
1996  * @phba: Pointer to HBA context object.
1997  * @pring: Pointer to driver SLI ring object.
1998  *
1999  * This function updates the chip attention register bit for the
2000  * given ring to inform HBA that there is more work to be done
2001  * in this ring. The caller is not required to hold any lock.
2002  **/
2003 static void
2004 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2005 {
2006 	int ringno = pring->ringno;
2007 
2008 	/*
2009 	 * Tell the HBA that there is work to do in this ring.
2010 	 */
2011 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
2012 		wmb();
2013 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
2014 		readl(phba->CAregaddr); /* flush */
2015 	}
2016 }
2017 
2018 /**
2019  * lpfc_sli_resume_iocb - Process iocbs in the txq
2020  * @phba: Pointer to HBA context object.
2021  * @pring: Pointer to driver SLI ring object.
2022  *
2023  * This function is called with hbalock held to post pending iocbs
2024  * in the txq to the firmware. This function is called when driver
2025  * detects space available in the ring.
2026  **/
2027 static void
2028 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2029 {
2030 	IOCB_t *iocb;
2031 	struct lpfc_iocbq *nextiocb;
2032 
2033 	lockdep_assert_held(&phba->hbalock);
2034 
2035 	/*
2036 	 * Check to see if:
2037 	 *  (a) there is anything on the txq to send
2038 	 *  (b) link is up
2039 	 *  (c) link attention events can be processed (fcp ring only)
2040 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
2041 	 */
2042 
2043 	if (lpfc_is_link_up(phba) &&
2044 	    (!list_empty(&pring->txq)) &&
2045 	    (pring->ringno != LPFC_FCP_RING ||
2046 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
2047 
2048 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
2049 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
2050 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
2051 
2052 		if (iocb)
2053 			lpfc_sli_update_ring(phba, pring);
2054 		else
2055 			lpfc_sli_update_full_ring(phba, pring);
2056 	}
2057 
2058 	return;
2059 }
2060 
2061 /**
2062  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
2063  * @phba: Pointer to HBA context object.
2064  * @hbqno: HBQ number.
2065  *
2066  * This function is called with hbalock held to get the next
2067  * available slot for the given HBQ. If there is free slot
2068  * available for the HBQ it will return pointer to the next available
2069  * HBQ entry else it will return NULL.
2070  **/
2071 static struct lpfc_hbq_entry *
2072 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
2073 {
2074 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
2075 
2076 	lockdep_assert_held(&phba->hbalock);
2077 
2078 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
2079 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
2080 		hbqp->next_hbqPutIdx = 0;
2081 
2082 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
2083 		uint32_t raw_index = phba->hbq_get[hbqno];
2084 		uint32_t getidx = le32_to_cpu(raw_index);
2085 
2086 		hbqp->local_hbqGetIdx = getidx;
2087 
2088 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
2089 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2090 					"1802 HBQ %d: local_hbqGetIdx "
2091 					"%u is > than hbqp->entry_count %u\n",
2092 					hbqno, hbqp->local_hbqGetIdx,
2093 					hbqp->entry_count);
2094 
2095 			phba->link_state = LPFC_HBA_ERROR;
2096 			return NULL;
2097 		}
2098 
2099 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
2100 			return NULL;
2101 	}
2102 
2103 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
2104 			hbqp->hbqPutIdx;
2105 }
2106 
2107 /**
2108  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
2109  * @phba: Pointer to HBA context object.
2110  *
2111  * This function is called with no lock held to free all the
2112  * hbq buffers while uninitializing the SLI interface. It also
2113  * frees the HBQ buffers returned by the firmware but not yet
2114  * processed by the upper layers.
2115  **/
2116 void
2117 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
2118 {
2119 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
2120 	struct hbq_dmabuf *hbq_buf;
2121 	unsigned long flags;
2122 	int i, hbq_count;
2123 
2124 	hbq_count = lpfc_sli_hbq_count();
2125 	/* Return all memory used by all HBQs */
2126 	spin_lock_irqsave(&phba->hbalock, flags);
2127 	for (i = 0; i < hbq_count; ++i) {
2128 		list_for_each_entry_safe(dmabuf, next_dmabuf,
2129 				&phba->hbqs[i].hbq_buffer_list, list) {
2130 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2131 			list_del(&hbq_buf->dbuf.list);
2132 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2133 		}
2134 		phba->hbqs[i].buffer_count = 0;
2135 	}
2136 
2137 	/* Mark the HBQs not in use */
2138 	phba->hbq_in_use = 0;
2139 	spin_unlock_irqrestore(&phba->hbalock, flags);
2140 }
2141 
2142 /**
2143  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2144  * @phba: Pointer to HBA context object.
2145  * @hbqno: HBQ number.
2146  * @hbq_buf: Pointer to HBQ buffer.
2147  *
2148  * This function is called with the hbalock held to post a
2149  * hbq buffer to the firmware. If the function finds an empty
2150  * slot in the HBQ, it will post the buffer. The function will return
2151  * pointer to the hbq entry if it successfully post the buffer
2152  * else it will return NULL.
2153  **/
2154 static int
2155 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2156 			 struct hbq_dmabuf *hbq_buf)
2157 {
2158 	lockdep_assert_held(&phba->hbalock);
2159 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2160 }
2161 
2162 /**
2163  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2164  * @phba: Pointer to HBA context object.
2165  * @hbqno: HBQ number.
2166  * @hbq_buf: Pointer to HBQ buffer.
2167  *
2168  * This function is called with the hbalock held to post a hbq buffer to the
2169  * firmware. If the function finds an empty slot in the HBQ, it will post the
2170  * buffer and place it on the hbq_buffer_list. The function will return zero if
2171  * it successfully post the buffer else it will return an error.
2172  **/
2173 static int
2174 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2175 			    struct hbq_dmabuf *hbq_buf)
2176 {
2177 	struct lpfc_hbq_entry *hbqe;
2178 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
2179 
2180 	lockdep_assert_held(&phba->hbalock);
2181 	/* Get next HBQ entry slot to use */
2182 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2183 	if (hbqe) {
2184 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
2185 
2186 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2187 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2188 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2189 		hbqe->bde.tus.f.bdeFlags = 0;
2190 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2191 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2192 				/* Sync SLIM */
2193 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2194 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2195 				/* flush */
2196 		readl(phba->hbq_put + hbqno);
2197 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2198 		return 0;
2199 	} else
2200 		return -ENOMEM;
2201 }
2202 
2203 /**
2204  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2205  * @phba: Pointer to HBA context object.
2206  * @hbqno: HBQ number.
2207  * @hbq_buf: Pointer to HBQ buffer.
2208  *
2209  * This function is called with the hbalock held to post an RQE to the SLI4
2210  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2211  * the hbq_buffer_list and return zero, otherwise it will return an error.
2212  **/
2213 static int
2214 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2215 			    struct hbq_dmabuf *hbq_buf)
2216 {
2217 	int rc;
2218 	struct lpfc_rqe hrqe;
2219 	struct lpfc_rqe drqe;
2220 	struct lpfc_queue *hrq;
2221 	struct lpfc_queue *drq;
2222 
2223 	if (hbqno != LPFC_ELS_HBQ)
2224 		return 1;
2225 	hrq = phba->sli4_hba.hdr_rq;
2226 	drq = phba->sli4_hba.dat_rq;
2227 
2228 	lockdep_assert_held(&phba->hbalock);
2229 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2230 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2231 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2232 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2233 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2234 	if (rc < 0)
2235 		return rc;
2236 	hbq_buf->tag = (rc | (hbqno << 16));
2237 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2238 	return 0;
2239 }
2240 
2241 /* HBQ for ELS and CT traffic. */
2242 static struct lpfc_hbq_init lpfc_els_hbq = {
2243 	.rn = 1,
2244 	.entry_count = 256,
2245 	.mask_count = 0,
2246 	.profile = 0,
2247 	.ring_mask = (1 << LPFC_ELS_RING),
2248 	.buffer_count = 0,
2249 	.init_count = 40,
2250 	.add_count = 40,
2251 };
2252 
2253 /* Array of HBQs */
2254 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2255 	&lpfc_els_hbq,
2256 };
2257 
2258 /**
2259  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2260  * @phba: Pointer to HBA context object.
2261  * @hbqno: HBQ number.
2262  * @count: Number of HBQ buffers to be posted.
2263  *
2264  * This function is called with no lock held to post more hbq buffers to the
2265  * given HBQ. The function returns the number of HBQ buffers successfully
2266  * posted.
2267  **/
2268 static int
2269 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2270 {
2271 	uint32_t i, posted = 0;
2272 	unsigned long flags;
2273 	struct hbq_dmabuf *hbq_buffer;
2274 	LIST_HEAD(hbq_buf_list);
2275 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2276 		return 0;
2277 
2278 	if ((phba->hbqs[hbqno].buffer_count + count) >
2279 	    lpfc_hbq_defs[hbqno]->entry_count)
2280 		count = lpfc_hbq_defs[hbqno]->entry_count -
2281 					phba->hbqs[hbqno].buffer_count;
2282 	if (!count)
2283 		return 0;
2284 	/* Allocate HBQ entries */
2285 	for (i = 0; i < count; i++) {
2286 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2287 		if (!hbq_buffer)
2288 			break;
2289 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2290 	}
2291 	/* Check whether HBQ is still in use */
2292 	spin_lock_irqsave(&phba->hbalock, flags);
2293 	if (!phba->hbq_in_use)
2294 		goto err;
2295 	while (!list_empty(&hbq_buf_list)) {
2296 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2297 				 dbuf.list);
2298 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2299 				      (hbqno << 16));
2300 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2301 			phba->hbqs[hbqno].buffer_count++;
2302 			posted++;
2303 		} else
2304 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2305 	}
2306 	spin_unlock_irqrestore(&phba->hbalock, flags);
2307 	return posted;
2308 err:
2309 	spin_unlock_irqrestore(&phba->hbalock, flags);
2310 	while (!list_empty(&hbq_buf_list)) {
2311 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2312 				 dbuf.list);
2313 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2314 	}
2315 	return 0;
2316 }
2317 
2318 /**
2319  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2320  * @phba: Pointer to HBA context object.
2321  * @qno: HBQ number.
2322  *
2323  * This function posts more buffers to the HBQ. This function
2324  * is called with no lock held. The function returns the number of HBQ entries
2325  * successfully allocated.
2326  **/
2327 int
2328 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2329 {
2330 	if (phba->sli_rev == LPFC_SLI_REV4)
2331 		return 0;
2332 	else
2333 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2334 					 lpfc_hbq_defs[qno]->add_count);
2335 }
2336 
2337 /**
2338  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2339  * @phba: Pointer to HBA context object.
2340  * @qno:  HBQ queue number.
2341  *
2342  * This function is called from SLI initialization code path with
2343  * no lock held to post initial HBQ buffers to firmware. The
2344  * function returns the number of HBQ entries successfully allocated.
2345  **/
2346 static int
2347 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2348 {
2349 	if (phba->sli_rev == LPFC_SLI_REV4)
2350 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2351 					lpfc_hbq_defs[qno]->entry_count);
2352 	else
2353 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2354 					 lpfc_hbq_defs[qno]->init_count);
2355 }
2356 
2357 /*
2358  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2359  *
2360  * This function removes the first hbq buffer on an hbq list and returns a
2361  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2362  **/
2363 static struct hbq_dmabuf *
2364 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2365 {
2366 	struct lpfc_dmabuf *d_buf;
2367 
2368 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2369 	if (!d_buf)
2370 		return NULL;
2371 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2372 }
2373 
2374 /**
2375  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2376  * @phba: Pointer to HBA context object.
2377  * @hrq: HBQ number.
2378  *
2379  * This function removes the first RQ buffer on an RQ buffer list and returns a
2380  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2381  **/
2382 static struct rqb_dmabuf *
2383 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2384 {
2385 	struct lpfc_dmabuf *h_buf;
2386 	struct lpfc_rqb *rqbp;
2387 
2388 	rqbp = hrq->rqbp;
2389 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2390 			 struct lpfc_dmabuf, list);
2391 	if (!h_buf)
2392 		return NULL;
2393 	rqbp->buffer_count--;
2394 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2395 }
2396 
2397 /**
2398  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2399  * @phba: Pointer to HBA context object.
2400  * @tag: Tag of the hbq buffer.
2401  *
2402  * This function searches for the hbq buffer associated with the given tag in
2403  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2404  * otherwise it returns NULL.
2405  **/
2406 static struct hbq_dmabuf *
2407 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2408 {
2409 	struct lpfc_dmabuf *d_buf;
2410 	struct hbq_dmabuf *hbq_buf;
2411 	uint32_t hbqno;
2412 
2413 	hbqno = tag >> 16;
2414 	if (hbqno >= LPFC_MAX_HBQS)
2415 		return NULL;
2416 
2417 	spin_lock_irq(&phba->hbalock);
2418 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2419 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2420 		if (hbq_buf->tag == tag) {
2421 			spin_unlock_irq(&phba->hbalock);
2422 			return hbq_buf;
2423 		}
2424 	}
2425 	spin_unlock_irq(&phba->hbalock);
2426 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2427 			"1803 Bad hbq tag. Data: x%x x%x\n",
2428 			tag, phba->hbqs[tag >> 16].buffer_count);
2429 	return NULL;
2430 }
2431 
2432 /**
2433  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2434  * @phba: Pointer to HBA context object.
2435  * @hbq_buffer: Pointer to HBQ buffer.
2436  *
2437  * This function is called with hbalock. This function gives back
2438  * the hbq buffer to firmware. If the HBQ does not have space to
2439  * post the buffer, it will free the buffer.
2440  **/
2441 void
2442 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2443 {
2444 	uint32_t hbqno;
2445 
2446 	if (hbq_buffer) {
2447 		hbqno = hbq_buffer->tag >> 16;
2448 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2449 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2450 	}
2451 }
2452 
2453 /**
2454  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2455  * @mbxCommand: mailbox command code.
2456  *
2457  * This function is called by the mailbox event handler function to verify
2458  * that the completed mailbox command is a legitimate mailbox command. If the
2459  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2460  * and the mailbox event handler will take the HBA offline.
2461  **/
2462 static int
2463 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2464 {
2465 	uint8_t ret;
2466 
2467 	switch (mbxCommand) {
2468 	case MBX_LOAD_SM:
2469 	case MBX_READ_NV:
2470 	case MBX_WRITE_NV:
2471 	case MBX_WRITE_VPARMS:
2472 	case MBX_RUN_BIU_DIAG:
2473 	case MBX_INIT_LINK:
2474 	case MBX_DOWN_LINK:
2475 	case MBX_CONFIG_LINK:
2476 	case MBX_CONFIG_RING:
2477 	case MBX_RESET_RING:
2478 	case MBX_READ_CONFIG:
2479 	case MBX_READ_RCONFIG:
2480 	case MBX_READ_SPARM:
2481 	case MBX_READ_STATUS:
2482 	case MBX_READ_RPI:
2483 	case MBX_READ_XRI:
2484 	case MBX_READ_REV:
2485 	case MBX_READ_LNK_STAT:
2486 	case MBX_REG_LOGIN:
2487 	case MBX_UNREG_LOGIN:
2488 	case MBX_CLEAR_LA:
2489 	case MBX_DUMP_MEMORY:
2490 	case MBX_DUMP_CONTEXT:
2491 	case MBX_RUN_DIAGS:
2492 	case MBX_RESTART:
2493 	case MBX_UPDATE_CFG:
2494 	case MBX_DOWN_LOAD:
2495 	case MBX_DEL_LD_ENTRY:
2496 	case MBX_RUN_PROGRAM:
2497 	case MBX_SET_MASK:
2498 	case MBX_SET_VARIABLE:
2499 	case MBX_UNREG_D_ID:
2500 	case MBX_KILL_BOARD:
2501 	case MBX_CONFIG_FARP:
2502 	case MBX_BEACON:
2503 	case MBX_LOAD_AREA:
2504 	case MBX_RUN_BIU_DIAG64:
2505 	case MBX_CONFIG_PORT:
2506 	case MBX_READ_SPARM64:
2507 	case MBX_READ_RPI64:
2508 	case MBX_REG_LOGIN64:
2509 	case MBX_READ_TOPOLOGY:
2510 	case MBX_WRITE_WWN:
2511 	case MBX_SET_DEBUG:
2512 	case MBX_LOAD_EXP_ROM:
2513 	case MBX_ASYNCEVT_ENABLE:
2514 	case MBX_REG_VPI:
2515 	case MBX_UNREG_VPI:
2516 	case MBX_HEARTBEAT:
2517 	case MBX_PORT_CAPABILITIES:
2518 	case MBX_PORT_IOV_CONTROL:
2519 	case MBX_SLI4_CONFIG:
2520 	case MBX_SLI4_REQ_FTRS:
2521 	case MBX_REG_FCFI:
2522 	case MBX_UNREG_FCFI:
2523 	case MBX_REG_VFI:
2524 	case MBX_UNREG_VFI:
2525 	case MBX_INIT_VPI:
2526 	case MBX_INIT_VFI:
2527 	case MBX_RESUME_RPI:
2528 	case MBX_READ_EVENT_LOG_STATUS:
2529 	case MBX_READ_EVENT_LOG:
2530 	case MBX_SECURITY_MGMT:
2531 	case MBX_AUTH_PORT:
2532 	case MBX_ACCESS_VDATA:
2533 		ret = mbxCommand;
2534 		break;
2535 	default:
2536 		ret = MBX_SHUTDOWN;
2537 		break;
2538 	}
2539 	return ret;
2540 }
2541 
2542 /**
2543  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2544  * @phba: Pointer to HBA context object.
2545  * @pmboxq: Pointer to mailbox command.
2546  *
2547  * This is completion handler function for mailbox commands issued from
2548  * lpfc_sli_issue_mbox_wait function. This function is called by the
2549  * mailbox event handler function with no lock held. This function
2550  * will wake up thread waiting on the wait queue pointed by context1
2551  * of the mailbox.
2552  **/
2553 void
2554 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2555 {
2556 	unsigned long drvr_flag;
2557 	struct completion *pmbox_done;
2558 
2559 	/*
2560 	 * If pmbox_done is empty, the driver thread gave up waiting and
2561 	 * continued running.
2562 	 */
2563 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2564 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2565 	pmbox_done = (struct completion *)pmboxq->context3;
2566 	if (pmbox_done)
2567 		complete(pmbox_done);
2568 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2569 	return;
2570 }
2571 
2572 static void
2573 __lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2574 {
2575 	unsigned long iflags;
2576 
2577 	if (ndlp->nlp_flag & NLP_RELEASE_RPI) {
2578 		lpfc_sli4_free_rpi(vport->phba, ndlp->nlp_rpi);
2579 		spin_lock_irqsave(&ndlp->lock, iflags);
2580 		ndlp->nlp_flag &= ~NLP_RELEASE_RPI;
2581 		ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
2582 		spin_unlock_irqrestore(&ndlp->lock, iflags);
2583 	}
2584 	ndlp->nlp_flag &= ~NLP_UNREG_INP;
2585 }
2586 
2587 /**
2588  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2589  * @phba: Pointer to HBA context object.
2590  * @pmb: Pointer to mailbox object.
2591  *
2592  * This function is the default mailbox completion handler. It
2593  * frees the memory resources associated with the completed mailbox
2594  * command. If the completed command is a REG_LOGIN mailbox command,
2595  * this function will issue a UREG_LOGIN to re-claim the RPI.
2596  **/
2597 void
2598 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2599 {
2600 	struct lpfc_vport  *vport = pmb->vport;
2601 	struct lpfc_dmabuf *mp;
2602 	struct lpfc_nodelist *ndlp;
2603 	struct Scsi_Host *shost;
2604 	uint16_t rpi, vpi;
2605 	int rc;
2606 
2607 	mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
2608 
2609 	if (mp) {
2610 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
2611 		kfree(mp);
2612 	}
2613 
2614 	/*
2615 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2616 	 * is in re-discovery driver need to cleanup the RPI.
2617 	 */
2618 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2619 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2620 	    !pmb->u.mb.mbxStatus) {
2621 		rpi = pmb->u.mb.un.varWords[0];
2622 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2623 		if (phba->sli_rev == LPFC_SLI_REV4)
2624 			vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2625 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2626 		pmb->vport = vport;
2627 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2628 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2629 		if (rc != MBX_NOT_FINISHED)
2630 			return;
2631 	}
2632 
2633 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2634 		!(phba->pport->load_flag & FC_UNLOADING) &&
2635 		!pmb->u.mb.mbxStatus) {
2636 		shost = lpfc_shost_from_vport(vport);
2637 		spin_lock_irq(shost->host_lock);
2638 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2639 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2640 		spin_unlock_irq(shost->host_lock);
2641 	}
2642 
2643 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2644 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2645 		lpfc_nlp_put(ndlp);
2646 		pmb->ctx_buf = NULL;
2647 		pmb->ctx_ndlp = NULL;
2648 	}
2649 
2650 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2651 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2652 
2653 		/* Check to see if there are any deferred events to process */
2654 		if (ndlp) {
2655 			lpfc_printf_vlog(
2656 				vport,
2657 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2658 				"1438 UNREG cmpl deferred mbox x%x "
2659 				"on NPort x%x Data: x%x x%x x%px x%x x%x\n",
2660 				ndlp->nlp_rpi, ndlp->nlp_DID,
2661 				ndlp->nlp_flag, ndlp->nlp_defer_did,
2662 				ndlp, vport->load_flag, kref_read(&ndlp->kref));
2663 
2664 			if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2665 			    (ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING)) {
2666 				ndlp->nlp_flag &= ~NLP_UNREG_INP;
2667 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2668 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2669 			} else {
2670 				__lpfc_sli_rpi_release(vport, ndlp);
2671 			}
2672 
2673 			/* The unreg_login mailbox is complete and had a
2674 			 * reference that has to be released.  The PLOGI
2675 			 * got its own ref.
2676 			 */
2677 			lpfc_nlp_put(ndlp);
2678 			pmb->ctx_ndlp = NULL;
2679 		}
2680 	}
2681 
2682 	/* This nlp_put pairs with lpfc_sli4_resume_rpi */
2683 	if (pmb->u.mb.mbxCommand == MBX_RESUME_RPI) {
2684 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2685 		lpfc_nlp_put(ndlp);
2686 	}
2687 
2688 	/* Check security permission status on INIT_LINK mailbox command */
2689 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2690 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2691 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2692 				"2860 SLI authentication is required "
2693 				"for INIT_LINK but has not done yet\n");
2694 
2695 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2696 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2697 	else
2698 		mempool_free(pmb, phba->mbox_mem_pool);
2699 }
2700  /**
2701  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2702  * @phba: Pointer to HBA context object.
2703  * @pmb: Pointer to mailbox object.
2704  *
2705  * This function is the unreg rpi mailbox completion handler. It
2706  * frees the memory resources associated with the completed mailbox
2707  * command. An additional reference is put on the ndlp to prevent
2708  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2709  * the unreg mailbox command completes, this routine puts the
2710  * reference back.
2711  *
2712  **/
2713 void
2714 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2715 {
2716 	struct lpfc_vport  *vport = pmb->vport;
2717 	struct lpfc_nodelist *ndlp;
2718 
2719 	ndlp = pmb->ctx_ndlp;
2720 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2721 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2722 		    (bf_get(lpfc_sli_intf_if_type,
2723 		     &phba->sli4_hba.sli_intf) >=
2724 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2725 			if (ndlp) {
2726 				lpfc_printf_vlog(
2727 					 vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2728 					 "0010 UNREG_LOGIN vpi:%x "
2729 					 "rpi:%x DID:%x defer x%x flg x%x "
2730 					 "x%px\n",
2731 					 vport->vpi, ndlp->nlp_rpi,
2732 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
2733 					 ndlp->nlp_flag,
2734 					 ndlp);
2735 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2736 
2737 				/* Check to see if there are any deferred
2738 				 * events to process
2739 				 */
2740 				if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2741 				    (ndlp->nlp_defer_did !=
2742 				    NLP_EVT_NOTHING_PENDING)) {
2743 					lpfc_printf_vlog(
2744 						vport, KERN_INFO, LOG_DISCOVERY,
2745 						"4111 UNREG cmpl deferred "
2746 						"clr x%x on "
2747 						"NPort x%x Data: x%x x%px\n",
2748 						ndlp->nlp_rpi, ndlp->nlp_DID,
2749 						ndlp->nlp_defer_did, ndlp);
2750 					ndlp->nlp_flag &= ~NLP_UNREG_INP;
2751 					ndlp->nlp_defer_did =
2752 						NLP_EVT_NOTHING_PENDING;
2753 					lpfc_issue_els_plogi(
2754 						vport, ndlp->nlp_DID, 0);
2755 				} else {
2756 					__lpfc_sli_rpi_release(vport, ndlp);
2757 				}
2758 				lpfc_nlp_put(ndlp);
2759 			}
2760 		}
2761 	}
2762 
2763 	mempool_free(pmb, phba->mbox_mem_pool);
2764 }
2765 
2766 /**
2767  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
2768  * @phba: Pointer to HBA context object.
2769  *
2770  * This function is called with no lock held. This function processes all
2771  * the completed mailbox commands and gives it to upper layers. The interrupt
2772  * service routine processes mailbox completion interrupt and adds completed
2773  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
2774  * Worker thread call lpfc_sli_handle_mb_event, which will return the
2775  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
2776  * function returns the mailbox commands to the upper layer by calling the
2777  * completion handler function of each mailbox.
2778  **/
2779 int
2780 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
2781 {
2782 	MAILBOX_t *pmbox;
2783 	LPFC_MBOXQ_t *pmb;
2784 	int rc;
2785 	LIST_HEAD(cmplq);
2786 
2787 	phba->sli.slistat.mbox_event++;
2788 
2789 	/* Get all completed mailboxe buffers into the cmplq */
2790 	spin_lock_irq(&phba->hbalock);
2791 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
2792 	spin_unlock_irq(&phba->hbalock);
2793 
2794 	/* Get a Mailbox buffer to setup mailbox commands for callback */
2795 	do {
2796 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
2797 		if (pmb == NULL)
2798 			break;
2799 
2800 		pmbox = &pmb->u.mb;
2801 
2802 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
2803 			if (pmb->vport) {
2804 				lpfc_debugfs_disc_trc(pmb->vport,
2805 					LPFC_DISC_TRC_MBOX_VPORT,
2806 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
2807 					(uint32_t)pmbox->mbxCommand,
2808 					pmbox->un.varWords[0],
2809 					pmbox->un.varWords[1]);
2810 			}
2811 			else {
2812 				lpfc_debugfs_disc_trc(phba->pport,
2813 					LPFC_DISC_TRC_MBOX,
2814 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
2815 					(uint32_t)pmbox->mbxCommand,
2816 					pmbox->un.varWords[0],
2817 					pmbox->un.varWords[1]);
2818 			}
2819 		}
2820 
2821 		/*
2822 		 * It is a fatal error if unknown mbox command completion.
2823 		 */
2824 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
2825 		    MBX_SHUTDOWN) {
2826 			/* Unknown mailbox command compl */
2827 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2828 					"(%d):0323 Unknown Mailbox command "
2829 					"x%x (x%x/x%x) Cmpl\n",
2830 					pmb->vport ? pmb->vport->vpi :
2831 					LPFC_VPORT_UNKNOWN,
2832 					pmbox->mbxCommand,
2833 					lpfc_sli_config_mbox_subsys_get(phba,
2834 									pmb),
2835 					lpfc_sli_config_mbox_opcode_get(phba,
2836 									pmb));
2837 			phba->link_state = LPFC_HBA_ERROR;
2838 			phba->work_hs = HS_FFER3;
2839 			lpfc_handle_eratt(phba);
2840 			continue;
2841 		}
2842 
2843 		if (pmbox->mbxStatus) {
2844 			phba->sli.slistat.mbox_stat_err++;
2845 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
2846 				/* Mbox cmd cmpl error - RETRYing */
2847 				lpfc_printf_log(phba, KERN_INFO,
2848 					LOG_MBOX | LOG_SLI,
2849 					"(%d):0305 Mbox cmd cmpl "
2850 					"error - RETRYing Data: x%x "
2851 					"(x%x/x%x) x%x x%x x%x\n",
2852 					pmb->vport ? pmb->vport->vpi :
2853 					LPFC_VPORT_UNKNOWN,
2854 					pmbox->mbxCommand,
2855 					lpfc_sli_config_mbox_subsys_get(phba,
2856 									pmb),
2857 					lpfc_sli_config_mbox_opcode_get(phba,
2858 									pmb),
2859 					pmbox->mbxStatus,
2860 					pmbox->un.varWords[0],
2861 					pmb->vport ? pmb->vport->port_state :
2862 					LPFC_VPORT_UNKNOWN);
2863 				pmbox->mbxStatus = 0;
2864 				pmbox->mbxOwner = OWN_HOST;
2865 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2866 				if (rc != MBX_NOT_FINISHED)
2867 					continue;
2868 			}
2869 		}
2870 
2871 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
2872 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
2873 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
2874 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
2875 				"x%x x%x x%x\n",
2876 				pmb->vport ? pmb->vport->vpi : 0,
2877 				pmbox->mbxCommand,
2878 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
2879 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
2880 				pmb->mbox_cmpl,
2881 				*((uint32_t *) pmbox),
2882 				pmbox->un.varWords[0],
2883 				pmbox->un.varWords[1],
2884 				pmbox->un.varWords[2],
2885 				pmbox->un.varWords[3],
2886 				pmbox->un.varWords[4],
2887 				pmbox->un.varWords[5],
2888 				pmbox->un.varWords[6],
2889 				pmbox->un.varWords[7],
2890 				pmbox->un.varWords[8],
2891 				pmbox->un.varWords[9],
2892 				pmbox->un.varWords[10]);
2893 
2894 		if (pmb->mbox_cmpl)
2895 			pmb->mbox_cmpl(phba,pmb);
2896 	} while (1);
2897 	return 0;
2898 }
2899 
2900 /**
2901  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
2902  * @phba: Pointer to HBA context object.
2903  * @pring: Pointer to driver SLI ring object.
2904  * @tag: buffer tag.
2905  *
2906  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
2907  * is set in the tag the buffer is posted for a particular exchange,
2908  * the function will return the buffer without replacing the buffer.
2909  * If the buffer is for unsolicited ELS or CT traffic, this function
2910  * returns the buffer and also posts another buffer to the firmware.
2911  **/
2912 static struct lpfc_dmabuf *
2913 lpfc_sli_get_buff(struct lpfc_hba *phba,
2914 		  struct lpfc_sli_ring *pring,
2915 		  uint32_t tag)
2916 {
2917 	struct hbq_dmabuf *hbq_entry;
2918 
2919 	if (tag & QUE_BUFTAG_BIT)
2920 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
2921 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
2922 	if (!hbq_entry)
2923 		return NULL;
2924 	return &hbq_entry->dbuf;
2925 }
2926 
2927 /**
2928  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
2929  *                              containing a NVME LS request.
2930  * @phba: pointer to lpfc hba data structure.
2931  * @piocb: pointer to the iocbq struct representing the sequence starting
2932  *        frame.
2933  *
2934  * This routine initially validates the NVME LS, validates there is a login
2935  * with the port that sent the LS, and then calls the appropriate nvme host
2936  * or target LS request handler.
2937  **/
2938 static void
2939 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
2940 {
2941 	struct lpfc_nodelist *ndlp;
2942 	struct lpfc_dmabuf *d_buf;
2943 	struct hbq_dmabuf *nvmebuf;
2944 	struct fc_frame_header *fc_hdr;
2945 	struct lpfc_async_xchg_ctx *axchg = NULL;
2946 	char *failwhy = NULL;
2947 	uint32_t oxid, sid, did, fctl, size;
2948 	int ret = 1;
2949 
2950 	d_buf = piocb->context2;
2951 
2952 	nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2953 	fc_hdr = nvmebuf->hbuf.virt;
2954 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
2955 	sid = sli4_sid_from_fc_hdr(fc_hdr);
2956 	did = sli4_did_from_fc_hdr(fc_hdr);
2957 	fctl = (fc_hdr->fh_f_ctl[0] << 16 |
2958 		fc_hdr->fh_f_ctl[1] << 8 |
2959 		fc_hdr->fh_f_ctl[2]);
2960 	size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
2961 
2962 	lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
2963 			 oxid, size, sid);
2964 
2965 	if (phba->pport->load_flag & FC_UNLOADING) {
2966 		failwhy = "Driver Unloading";
2967 	} else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
2968 		failwhy = "NVME FC4 Disabled";
2969 	} else if (!phba->nvmet_support && !phba->pport->localport) {
2970 		failwhy = "No Localport";
2971 	} else if (phba->nvmet_support && !phba->targetport) {
2972 		failwhy = "No Targetport";
2973 	} else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
2974 		failwhy = "Bad NVME LS R_CTL";
2975 	} else if (unlikely((fctl & 0x00FF0000) !=
2976 			(FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
2977 		failwhy = "Bad NVME LS F_CTL";
2978 	} else {
2979 		axchg = kzalloc(sizeof(*axchg), GFP_ATOMIC);
2980 		if (!axchg)
2981 			failwhy = "No CTX memory";
2982 	}
2983 
2984 	if (unlikely(failwhy)) {
2985 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2986 				"6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
2987 				sid, oxid, failwhy);
2988 		goto out_fail;
2989 	}
2990 
2991 	/* validate the source of the LS is logged in */
2992 	ndlp = lpfc_findnode_did(phba->pport, sid);
2993 	if (!ndlp ||
2994 	    ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
2995 	     (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
2996 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
2997 				"6216 NVME Unsol rcv: No ndlp: "
2998 				"NPort_ID x%x oxid x%x\n",
2999 				sid, oxid);
3000 		goto out_fail;
3001 	}
3002 
3003 	axchg->phba = phba;
3004 	axchg->ndlp = ndlp;
3005 	axchg->size = size;
3006 	axchg->oxid = oxid;
3007 	axchg->sid = sid;
3008 	axchg->wqeq = NULL;
3009 	axchg->state = LPFC_NVME_STE_LS_RCV;
3010 	axchg->entry_cnt = 1;
3011 	axchg->rqb_buffer = (void *)nvmebuf;
3012 	axchg->hdwq = &phba->sli4_hba.hdwq[0];
3013 	axchg->payload = nvmebuf->dbuf.virt;
3014 	INIT_LIST_HEAD(&axchg->list);
3015 
3016 	if (phba->nvmet_support) {
3017 		ret = lpfc_nvmet_handle_lsreq(phba, axchg);
3018 		spin_lock_irq(&ndlp->lock);
3019 		if (!ret && !(ndlp->fc4_xpt_flags & NLP_XPT_HAS_HH)) {
3020 			ndlp->fc4_xpt_flags |= NLP_XPT_HAS_HH;
3021 			spin_unlock_irq(&ndlp->lock);
3022 
3023 			/* This reference is a single occurrence to hold the
3024 			 * node valid until the nvmet transport calls
3025 			 * host_release.
3026 			 */
3027 			if (!lpfc_nlp_get(ndlp))
3028 				goto out_fail;
3029 
3030 			lpfc_printf_log(phba, KERN_ERR, LOG_NODE,
3031 					"6206 NVMET unsol ls_req ndlp x%px "
3032 					"DID x%x xflags x%x refcnt %d\n",
3033 					ndlp, ndlp->nlp_DID,
3034 					ndlp->fc4_xpt_flags,
3035 					kref_read(&ndlp->kref));
3036 		} else {
3037 			spin_unlock_irq(&ndlp->lock);
3038 		}
3039 	} else {
3040 		ret = lpfc_nvme_handle_lsreq(phba, axchg);
3041 	}
3042 
3043 	/* if zero, LS was successfully handled. If non-zero, LS not handled */
3044 	if (!ret)
3045 		return;
3046 
3047 out_fail:
3048 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3049 			"6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
3050 			"NVMe%s handler failed %d\n",
3051 			did, sid, oxid,
3052 			(phba->nvmet_support) ? "T" : "I", ret);
3053 
3054 	/* recycle receive buffer */
3055 	lpfc_in_buf_free(phba, &nvmebuf->dbuf);
3056 
3057 	/* If start of new exchange, abort it */
3058 	if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
3059 		ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
3060 
3061 	if (ret)
3062 		kfree(axchg);
3063 }
3064 
3065 /**
3066  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
3067  * @phba: Pointer to HBA context object.
3068  * @pring: Pointer to driver SLI ring object.
3069  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
3070  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
3071  * @fch_type: the type for the first frame of the sequence.
3072  *
3073  * This function is called with no lock held. This function uses the r_ctl and
3074  * type of the received sequence to find the correct callback function to call
3075  * to process the sequence.
3076  **/
3077 static int
3078 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3079 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
3080 			 uint32_t fch_type)
3081 {
3082 	int i;
3083 
3084 	switch (fch_type) {
3085 	case FC_TYPE_NVME:
3086 		lpfc_nvme_unsol_ls_handler(phba, saveq);
3087 		return 1;
3088 	default:
3089 		break;
3090 	}
3091 
3092 	/* unSolicited Responses */
3093 	if (pring->prt[0].profile) {
3094 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
3095 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
3096 									saveq);
3097 		return 1;
3098 	}
3099 	/* We must search, based on rctl / type
3100 	   for the right routine */
3101 	for (i = 0; i < pring->num_mask; i++) {
3102 		if ((pring->prt[i].rctl == fch_r_ctl) &&
3103 		    (pring->prt[i].type == fch_type)) {
3104 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
3105 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
3106 						(phba, pring, saveq);
3107 			return 1;
3108 		}
3109 	}
3110 	return 0;
3111 }
3112 
3113 /**
3114  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
3115  * @phba: Pointer to HBA context object.
3116  * @pring: Pointer to driver SLI ring object.
3117  * @saveq: Pointer to the unsolicited iocb.
3118  *
3119  * This function is called with no lock held by the ring event handler
3120  * when there is an unsolicited iocb posted to the response ring by the
3121  * firmware. This function gets the buffer associated with the iocbs
3122  * and calls the event handler for the ring. This function handles both
3123  * qring buffers and hbq buffers.
3124  * When the function returns 1 the caller can free the iocb object otherwise
3125  * upper layer functions will free the iocb objects.
3126  **/
3127 static int
3128 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3129 			    struct lpfc_iocbq *saveq)
3130 {
3131 	IOCB_t           * irsp;
3132 	WORD5            * w5p;
3133 	uint32_t           Rctl, Type;
3134 	struct lpfc_iocbq *iocbq;
3135 	struct lpfc_dmabuf *dmzbuf;
3136 
3137 	irsp = &(saveq->iocb);
3138 
3139 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
3140 		if (pring->lpfc_sli_rcv_async_status)
3141 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
3142 		else
3143 			lpfc_printf_log(phba,
3144 					KERN_WARNING,
3145 					LOG_SLI,
3146 					"0316 Ring %d handler: unexpected "
3147 					"ASYNC_STATUS iocb received evt_code "
3148 					"0x%x\n",
3149 					pring->ringno,
3150 					irsp->un.asyncstat.evt_code);
3151 		return 1;
3152 	}
3153 
3154 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3155 		(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3156 		if (irsp->ulpBdeCount > 0) {
3157 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3158 					irsp->un.ulpWord[3]);
3159 			lpfc_in_buf_free(phba, dmzbuf);
3160 		}
3161 
3162 		if (irsp->ulpBdeCount > 1) {
3163 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3164 					irsp->unsli3.sli3Words[3]);
3165 			lpfc_in_buf_free(phba, dmzbuf);
3166 		}
3167 
3168 		if (irsp->ulpBdeCount > 2) {
3169 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3170 				irsp->unsli3.sli3Words[7]);
3171 			lpfc_in_buf_free(phba, dmzbuf);
3172 		}
3173 
3174 		return 1;
3175 	}
3176 
3177 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3178 		if (irsp->ulpBdeCount != 0) {
3179 			saveq->context2 = lpfc_sli_get_buff(phba, pring,
3180 						irsp->un.ulpWord[3]);
3181 			if (!saveq->context2)
3182 				lpfc_printf_log(phba,
3183 					KERN_ERR,
3184 					LOG_SLI,
3185 					"0341 Ring %d Cannot find buffer for "
3186 					"an unsolicited iocb. tag 0x%x\n",
3187 					pring->ringno,
3188 					irsp->un.ulpWord[3]);
3189 		}
3190 		if (irsp->ulpBdeCount == 2) {
3191 			saveq->context3 = lpfc_sli_get_buff(phba, pring,
3192 						irsp->unsli3.sli3Words[7]);
3193 			if (!saveq->context3)
3194 				lpfc_printf_log(phba,
3195 					KERN_ERR,
3196 					LOG_SLI,
3197 					"0342 Ring %d Cannot find buffer for an"
3198 					" unsolicited iocb. tag 0x%x\n",
3199 					pring->ringno,
3200 					irsp->unsli3.sli3Words[7]);
3201 		}
3202 		list_for_each_entry(iocbq, &saveq->list, list) {
3203 			irsp = &(iocbq->iocb);
3204 			if (irsp->ulpBdeCount != 0) {
3205 				iocbq->context2 = lpfc_sli_get_buff(phba, pring,
3206 							irsp->un.ulpWord[3]);
3207 				if (!iocbq->context2)
3208 					lpfc_printf_log(phba,
3209 						KERN_ERR,
3210 						LOG_SLI,
3211 						"0343 Ring %d Cannot find "
3212 						"buffer for an unsolicited iocb"
3213 						". tag 0x%x\n", pring->ringno,
3214 						irsp->un.ulpWord[3]);
3215 			}
3216 			if (irsp->ulpBdeCount == 2) {
3217 				iocbq->context3 = lpfc_sli_get_buff(phba, pring,
3218 						irsp->unsli3.sli3Words[7]);
3219 				if (!iocbq->context3)
3220 					lpfc_printf_log(phba,
3221 						KERN_ERR,
3222 						LOG_SLI,
3223 						"0344 Ring %d Cannot find "
3224 						"buffer for an unsolicited "
3225 						"iocb. tag 0x%x\n",
3226 						pring->ringno,
3227 						irsp->unsli3.sli3Words[7]);
3228 			}
3229 		}
3230 	}
3231 	if (irsp->ulpBdeCount != 0 &&
3232 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3233 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3234 		int found = 0;
3235 
3236 		/* search continue save q for same XRI */
3237 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3238 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3239 				saveq->iocb.unsli3.rcvsli3.ox_id) {
3240 				list_add_tail(&saveq->list, &iocbq->list);
3241 				found = 1;
3242 				break;
3243 			}
3244 		}
3245 		if (!found)
3246 			list_add_tail(&saveq->clist,
3247 				      &pring->iocb_continue_saveq);
3248 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3249 			list_del_init(&iocbq->clist);
3250 			saveq = iocbq;
3251 			irsp = &(saveq->iocb);
3252 		} else
3253 			return 0;
3254 	}
3255 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3256 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3257 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3258 		Rctl = FC_RCTL_ELS_REQ;
3259 		Type = FC_TYPE_ELS;
3260 	} else {
3261 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3262 		Rctl = w5p->hcsw.Rctl;
3263 		Type = w5p->hcsw.Type;
3264 
3265 		/* Firmware Workaround */
3266 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3267 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3268 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3269 			Rctl = FC_RCTL_ELS_REQ;
3270 			Type = FC_TYPE_ELS;
3271 			w5p->hcsw.Rctl = Rctl;
3272 			w5p->hcsw.Type = Type;
3273 		}
3274 	}
3275 
3276 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3277 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3278 				"0313 Ring %d handler: unexpected Rctl x%x "
3279 				"Type x%x received\n",
3280 				pring->ringno, Rctl, Type);
3281 
3282 	return 1;
3283 }
3284 
3285 /**
3286  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3287  * @phba: Pointer to HBA context object.
3288  * @pring: Pointer to driver SLI ring object.
3289  * @prspiocb: Pointer to response iocb object.
3290  *
3291  * This function looks up the iocb_lookup table to get the command iocb
3292  * corresponding to the given response iocb using the iotag of the
3293  * response iocb. The driver calls this function with the hbalock held
3294  * for SLI3 ports or the ring lock held for SLI4 ports.
3295  * This function returns the command iocb object if it finds the command
3296  * iocb else returns NULL.
3297  **/
3298 static struct lpfc_iocbq *
3299 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3300 		      struct lpfc_sli_ring *pring,
3301 		      struct lpfc_iocbq *prspiocb)
3302 {
3303 	struct lpfc_iocbq *cmd_iocb = NULL;
3304 	uint16_t iotag;
3305 	spinlock_t *temp_lock = NULL;
3306 	unsigned long iflag = 0;
3307 
3308 	if (phba->sli_rev == LPFC_SLI_REV4)
3309 		temp_lock = &pring->ring_lock;
3310 	else
3311 		temp_lock = &phba->hbalock;
3312 
3313 	spin_lock_irqsave(temp_lock, iflag);
3314 	iotag = prspiocb->iocb.ulpIoTag;
3315 
3316 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3317 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3318 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3319 			/* remove from txcmpl queue list */
3320 			list_del_init(&cmd_iocb->list);
3321 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3322 			pring->txcmplq_cnt--;
3323 			spin_unlock_irqrestore(temp_lock, iflag);
3324 			return cmd_iocb;
3325 		}
3326 	}
3327 
3328 	spin_unlock_irqrestore(temp_lock, iflag);
3329 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3330 			"0317 iotag x%x is out of "
3331 			"range: max iotag x%x wd0 x%x\n",
3332 			iotag, phba->sli.last_iotag,
3333 			*(((uint32_t *) &prspiocb->iocb) + 7));
3334 	return NULL;
3335 }
3336 
3337 /**
3338  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3339  * @phba: Pointer to HBA context object.
3340  * @pring: Pointer to driver SLI ring object.
3341  * @iotag: IOCB tag.
3342  *
3343  * This function looks up the iocb_lookup table to get the command iocb
3344  * corresponding to the given iotag. The driver calls this function with
3345  * the ring lock held because this function is an SLI4 port only helper.
3346  * This function returns the command iocb object if it finds the command
3347  * iocb else returns NULL.
3348  **/
3349 static struct lpfc_iocbq *
3350 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3351 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3352 {
3353 	struct lpfc_iocbq *cmd_iocb = NULL;
3354 	spinlock_t *temp_lock = NULL;
3355 	unsigned long iflag = 0;
3356 
3357 	if (phba->sli_rev == LPFC_SLI_REV4)
3358 		temp_lock = &pring->ring_lock;
3359 	else
3360 		temp_lock = &phba->hbalock;
3361 
3362 	spin_lock_irqsave(temp_lock, iflag);
3363 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3364 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3365 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3366 			/* remove from txcmpl queue list */
3367 			list_del_init(&cmd_iocb->list);
3368 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3369 			pring->txcmplq_cnt--;
3370 			spin_unlock_irqrestore(temp_lock, iflag);
3371 			return cmd_iocb;
3372 		}
3373 	}
3374 
3375 	spin_unlock_irqrestore(temp_lock, iflag);
3376 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3377 			"0372 iotag x%x lookup error: max iotag (x%x) "
3378 			"iocb_flag x%x\n",
3379 			iotag, phba->sli.last_iotag,
3380 			cmd_iocb ? cmd_iocb->iocb_flag : 0xffff);
3381 	return NULL;
3382 }
3383 
3384 /**
3385  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3386  * @phba: Pointer to HBA context object.
3387  * @pring: Pointer to driver SLI ring object.
3388  * @saveq: Pointer to the response iocb to be processed.
3389  *
3390  * This function is called by the ring event handler for non-fcp
3391  * rings when there is a new response iocb in the response ring.
3392  * The caller is not required to hold any locks. This function
3393  * gets the command iocb associated with the response iocb and
3394  * calls the completion handler for the command iocb. If there
3395  * is no completion handler, the function will free the resources
3396  * associated with command iocb. If the response iocb is for
3397  * an already aborted command iocb, the status of the completion
3398  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3399  * This function always returns 1.
3400  **/
3401 static int
3402 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3403 			  struct lpfc_iocbq *saveq)
3404 {
3405 	struct lpfc_iocbq *cmdiocbp;
3406 	int rc = 1;
3407 	unsigned long iflag;
3408 
3409 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3410 	if (cmdiocbp) {
3411 		if (cmdiocbp->iocb_cmpl) {
3412 			/*
3413 			 * If an ELS command failed send an event to mgmt
3414 			 * application.
3415 			 */
3416 			if (saveq->iocb.ulpStatus &&
3417 			     (pring->ringno == LPFC_ELS_RING) &&
3418 			     (cmdiocbp->iocb.ulpCommand ==
3419 				CMD_ELS_REQUEST64_CR))
3420 				lpfc_send_els_failure_event(phba,
3421 					cmdiocbp, saveq);
3422 
3423 			/*
3424 			 * Post all ELS completions to the worker thread.
3425 			 * All other are passed to the completion callback.
3426 			 */
3427 			if (pring->ringno == LPFC_ELS_RING) {
3428 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3429 				    (cmdiocbp->iocb_flag &
3430 							LPFC_DRIVER_ABORTED)) {
3431 					spin_lock_irqsave(&phba->hbalock,
3432 							  iflag);
3433 					cmdiocbp->iocb_flag &=
3434 						~LPFC_DRIVER_ABORTED;
3435 					spin_unlock_irqrestore(&phba->hbalock,
3436 							       iflag);
3437 					saveq->iocb.ulpStatus =
3438 						IOSTAT_LOCAL_REJECT;
3439 					saveq->iocb.un.ulpWord[4] =
3440 						IOERR_SLI_ABORTED;
3441 
3442 					/* Firmware could still be in progress
3443 					 * of DMAing payload, so don't free data
3444 					 * buffer till after a hbeat.
3445 					 */
3446 					spin_lock_irqsave(&phba->hbalock,
3447 							  iflag);
3448 					saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
3449 					spin_unlock_irqrestore(&phba->hbalock,
3450 							       iflag);
3451 				}
3452 				if (phba->sli_rev == LPFC_SLI_REV4) {
3453 					if (saveq->iocb_flag &
3454 					    LPFC_EXCHANGE_BUSY) {
3455 						/* Set cmdiocb flag for the
3456 						 * exchange busy so sgl (xri)
3457 						 * will not be released until
3458 						 * the abort xri is received
3459 						 * from hba.
3460 						 */
3461 						spin_lock_irqsave(
3462 							&phba->hbalock, iflag);
3463 						cmdiocbp->iocb_flag |=
3464 							LPFC_EXCHANGE_BUSY;
3465 						spin_unlock_irqrestore(
3466 							&phba->hbalock, iflag);
3467 					}
3468 					if (cmdiocbp->iocb_flag &
3469 					    LPFC_DRIVER_ABORTED) {
3470 						/*
3471 						 * Clear LPFC_DRIVER_ABORTED
3472 						 * bit in case it was driver
3473 						 * initiated abort.
3474 						 */
3475 						spin_lock_irqsave(
3476 							&phba->hbalock, iflag);
3477 						cmdiocbp->iocb_flag &=
3478 							~LPFC_DRIVER_ABORTED;
3479 						spin_unlock_irqrestore(
3480 							&phba->hbalock, iflag);
3481 						cmdiocbp->iocb.ulpStatus =
3482 							IOSTAT_LOCAL_REJECT;
3483 						cmdiocbp->iocb.un.ulpWord[4] =
3484 							IOERR_ABORT_REQUESTED;
3485 						/*
3486 						 * For SLI4, irsiocb contains
3487 						 * NO_XRI in sli_xritag, it
3488 						 * shall not affect releasing
3489 						 * sgl (xri) process.
3490 						 */
3491 						saveq->iocb.ulpStatus =
3492 							IOSTAT_LOCAL_REJECT;
3493 						saveq->iocb.un.ulpWord[4] =
3494 							IOERR_SLI_ABORTED;
3495 						spin_lock_irqsave(
3496 							&phba->hbalock, iflag);
3497 						saveq->iocb_flag |=
3498 							LPFC_DELAY_MEM_FREE;
3499 						spin_unlock_irqrestore(
3500 							&phba->hbalock, iflag);
3501 					}
3502 				}
3503 			}
3504 			(cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
3505 		} else
3506 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3507 	} else {
3508 		/*
3509 		 * Unknown initiating command based on the response iotag.
3510 		 * This could be the case on the ELS ring because of
3511 		 * lpfc_els_abort().
3512 		 */
3513 		if (pring->ringno != LPFC_ELS_RING) {
3514 			/*
3515 			 * Ring <ringno> handler: unexpected completion IoTag
3516 			 * <IoTag>
3517 			 */
3518 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3519 					 "0322 Ring %d handler: "
3520 					 "unexpected completion IoTag x%x "
3521 					 "Data: x%x x%x x%x x%x\n",
3522 					 pring->ringno,
3523 					 saveq->iocb.ulpIoTag,
3524 					 saveq->iocb.ulpStatus,
3525 					 saveq->iocb.un.ulpWord[4],
3526 					 saveq->iocb.ulpCommand,
3527 					 saveq->iocb.ulpContext);
3528 		}
3529 	}
3530 
3531 	return rc;
3532 }
3533 
3534 /**
3535  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3536  * @phba: Pointer to HBA context object.
3537  * @pring: Pointer to driver SLI ring object.
3538  *
3539  * This function is called from the iocb ring event handlers when
3540  * put pointer is ahead of the get pointer for a ring. This function signal
3541  * an error attention condition to the worker thread and the worker
3542  * thread will transition the HBA to offline state.
3543  **/
3544 static void
3545 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3546 {
3547 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3548 	/*
3549 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3550 	 * rsp ring <portRspMax>
3551 	 */
3552 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3553 			"0312 Ring %d handler: portRspPut %d "
3554 			"is bigger than rsp ring %d\n",
3555 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3556 			pring->sli.sli3.numRiocb);
3557 
3558 	phba->link_state = LPFC_HBA_ERROR;
3559 
3560 	/*
3561 	 * All error attention handlers are posted to
3562 	 * worker thread
3563 	 */
3564 	phba->work_ha |= HA_ERATT;
3565 	phba->work_hs = HS_FFER3;
3566 
3567 	lpfc_worker_wake_up(phba);
3568 
3569 	return;
3570 }
3571 
3572 /**
3573  * lpfc_poll_eratt - Error attention polling timer timeout handler
3574  * @t: Context to fetch pointer to address of HBA context object from.
3575  *
3576  * This function is invoked by the Error Attention polling timer when the
3577  * timer times out. It will check the SLI Error Attention register for
3578  * possible attention events. If so, it will post an Error Attention event
3579  * and wake up worker thread to process it. Otherwise, it will set up the
3580  * Error Attention polling timer for the next poll.
3581  **/
3582 void lpfc_poll_eratt(struct timer_list *t)
3583 {
3584 	struct lpfc_hba *phba;
3585 	uint32_t eratt = 0;
3586 	uint64_t sli_intr, cnt;
3587 
3588 	phba = from_timer(phba, t, eratt_poll);
3589 
3590 	/* Here we will also keep track of interrupts per sec of the hba */
3591 	sli_intr = phba->sli.slistat.sli_intr;
3592 
3593 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3594 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3595 			sli_intr);
3596 	else
3597 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3598 
3599 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3600 	do_div(cnt, phba->eratt_poll_interval);
3601 	phba->sli.slistat.sli_ips = cnt;
3602 
3603 	phba->sli.slistat.sli_prev_intr = sli_intr;
3604 
3605 	/* Check chip HA register for error event */
3606 	eratt = lpfc_sli_check_eratt(phba);
3607 
3608 	if (eratt)
3609 		/* Tell the worker thread there is work to do */
3610 		lpfc_worker_wake_up(phba);
3611 	else
3612 		/* Restart the timer for next eratt poll */
3613 		mod_timer(&phba->eratt_poll,
3614 			  jiffies +
3615 			  msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3616 	return;
3617 }
3618 
3619 
3620 /**
3621  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3622  * @phba: Pointer to HBA context object.
3623  * @pring: Pointer to driver SLI ring object.
3624  * @mask: Host attention register mask for this ring.
3625  *
3626  * This function is called from the interrupt context when there is a ring
3627  * event for the fcp ring. The caller does not hold any lock.
3628  * The function processes each response iocb in the response ring until it
3629  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3630  * LE bit set. The function will call the completion handler of the command iocb
3631  * if the response iocb indicates a completion for a command iocb or it is
3632  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3633  * function if this is an unsolicited iocb.
3634  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3635  * to check it explicitly.
3636  */
3637 int
3638 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3639 				struct lpfc_sli_ring *pring, uint32_t mask)
3640 {
3641 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3642 	IOCB_t *irsp = NULL;
3643 	IOCB_t *entry = NULL;
3644 	struct lpfc_iocbq *cmdiocbq = NULL;
3645 	struct lpfc_iocbq rspiocbq;
3646 	uint32_t status;
3647 	uint32_t portRspPut, portRspMax;
3648 	int rc = 1;
3649 	lpfc_iocb_type type;
3650 	unsigned long iflag;
3651 	uint32_t rsp_cmpl = 0;
3652 
3653 	spin_lock_irqsave(&phba->hbalock, iflag);
3654 	pring->stats.iocb_event++;
3655 
3656 	/*
3657 	 * The next available response entry should never exceed the maximum
3658 	 * entries.  If it does, treat it as an adapter hardware error.
3659 	 */
3660 	portRspMax = pring->sli.sli3.numRiocb;
3661 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3662 	if (unlikely(portRspPut >= portRspMax)) {
3663 		lpfc_sli_rsp_pointers_error(phba, pring);
3664 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3665 		return 1;
3666 	}
3667 	if (phba->fcp_ring_in_use) {
3668 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3669 		return 1;
3670 	} else
3671 		phba->fcp_ring_in_use = 1;
3672 
3673 	rmb();
3674 	while (pring->sli.sli3.rspidx != portRspPut) {
3675 		/*
3676 		 * Fetch an entry off the ring and copy it into a local data
3677 		 * structure.  The copy involves a byte-swap since the
3678 		 * network byte order and pci byte orders are different.
3679 		 */
3680 		entry = lpfc_resp_iocb(phba, pring);
3681 		phba->last_completion_time = jiffies;
3682 
3683 		if (++pring->sli.sli3.rspidx >= portRspMax)
3684 			pring->sli.sli3.rspidx = 0;
3685 
3686 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3687 				      (uint32_t *) &rspiocbq.iocb,
3688 				      phba->iocb_rsp_size);
3689 		INIT_LIST_HEAD(&(rspiocbq.list));
3690 		irsp = &rspiocbq.iocb;
3691 
3692 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3693 		pring->stats.iocb_rsp++;
3694 		rsp_cmpl++;
3695 
3696 		if (unlikely(irsp->ulpStatus)) {
3697 			/*
3698 			 * If resource errors reported from HBA, reduce
3699 			 * queuedepths of the SCSI device.
3700 			 */
3701 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3702 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3703 			     IOERR_NO_RESOURCES)) {
3704 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3705 				phba->lpfc_rampdown_queue_depth(phba);
3706 				spin_lock_irqsave(&phba->hbalock, iflag);
3707 			}
3708 
3709 			/* Rsp ring <ringno> error: IOCB */
3710 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3711 					"0336 Rsp Ring %d error: IOCB Data: "
3712 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
3713 					pring->ringno,
3714 					irsp->un.ulpWord[0],
3715 					irsp->un.ulpWord[1],
3716 					irsp->un.ulpWord[2],
3717 					irsp->un.ulpWord[3],
3718 					irsp->un.ulpWord[4],
3719 					irsp->un.ulpWord[5],
3720 					*(uint32_t *)&irsp->un1,
3721 					*((uint32_t *)&irsp->un1 + 1));
3722 		}
3723 
3724 		switch (type) {
3725 		case LPFC_ABORT_IOCB:
3726 		case LPFC_SOL_IOCB:
3727 			/*
3728 			 * Idle exchange closed via ABTS from port.  No iocb
3729 			 * resources need to be recovered.
3730 			 */
3731 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3732 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3733 						"0333 IOCB cmd 0x%x"
3734 						" processed. Skipping"
3735 						" completion\n",
3736 						irsp->ulpCommand);
3737 				break;
3738 			}
3739 
3740 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3741 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3742 							 &rspiocbq);
3743 			spin_lock_irqsave(&phba->hbalock, iflag);
3744 			if (unlikely(!cmdiocbq))
3745 				break;
3746 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3747 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3748 			if (cmdiocbq->iocb_cmpl) {
3749 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3750 				(cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
3751 						      &rspiocbq);
3752 				spin_lock_irqsave(&phba->hbalock, iflag);
3753 			}
3754 			break;
3755 		case LPFC_UNSOL_IOCB:
3756 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3757 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
3758 			spin_lock_irqsave(&phba->hbalock, iflag);
3759 			break;
3760 		default:
3761 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3762 				char adaptermsg[LPFC_MAX_ADPTMSG];
3763 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3764 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
3765 				       MAX_MSG_DATA);
3766 				dev_warn(&((phba->pcidev)->dev),
3767 					 "lpfc%d: %s\n",
3768 					 phba->brd_no, adaptermsg);
3769 			} else {
3770 				/* Unknown IOCB command */
3771 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3772 						"0334 Unknown IOCB command "
3773 						"Data: x%x, x%x x%x x%x x%x\n",
3774 						type, irsp->ulpCommand,
3775 						irsp->ulpStatus,
3776 						irsp->ulpIoTag,
3777 						irsp->ulpContext);
3778 			}
3779 			break;
3780 		}
3781 
3782 		/*
3783 		 * The response IOCB has been processed.  Update the ring
3784 		 * pointer in SLIM.  If the port response put pointer has not
3785 		 * been updated, sync the pgp->rspPutInx and fetch the new port
3786 		 * response put pointer.
3787 		 */
3788 		writel(pring->sli.sli3.rspidx,
3789 			&phba->host_gp[pring->ringno].rspGetInx);
3790 
3791 		if (pring->sli.sli3.rspidx == portRspPut)
3792 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3793 	}
3794 
3795 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
3796 		pring->stats.iocb_rsp_full++;
3797 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3798 		writel(status, phba->CAregaddr);
3799 		readl(phba->CAregaddr);
3800 	}
3801 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3802 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3803 		pring->stats.iocb_cmd_empty++;
3804 
3805 		/* Force update of the local copy of cmdGetInx */
3806 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3807 		lpfc_sli_resume_iocb(phba, pring);
3808 
3809 		if ((pring->lpfc_sli_cmd_available))
3810 			(pring->lpfc_sli_cmd_available) (phba, pring);
3811 
3812 	}
3813 
3814 	phba->fcp_ring_in_use = 0;
3815 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3816 	return rc;
3817 }
3818 
3819 /**
3820  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
3821  * @phba: Pointer to HBA context object.
3822  * @pring: Pointer to driver SLI ring object.
3823  * @rspiocbp: Pointer to driver response IOCB object.
3824  *
3825  * This function is called from the worker thread when there is a slow-path
3826  * response IOCB to process. This function chains all the response iocbs until
3827  * seeing the iocb with the LE bit set. The function will call
3828  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
3829  * completion of a command iocb. The function will call the
3830  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
3831  * The function frees the resources or calls the completion handler if this
3832  * iocb is an abort completion. The function returns NULL when the response
3833  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
3834  * this function shall chain the iocb on to the iocb_continueq and return the
3835  * response iocb passed in.
3836  **/
3837 static struct lpfc_iocbq *
3838 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3839 			struct lpfc_iocbq *rspiocbp)
3840 {
3841 	struct lpfc_iocbq *saveq;
3842 	struct lpfc_iocbq *cmdiocbp;
3843 	struct lpfc_iocbq *next_iocb;
3844 	IOCB_t *irsp = NULL;
3845 	uint32_t free_saveq;
3846 	uint8_t iocb_cmd_type;
3847 	lpfc_iocb_type type;
3848 	unsigned long iflag;
3849 	int rc;
3850 
3851 	spin_lock_irqsave(&phba->hbalock, iflag);
3852 	/* First add the response iocb to the countinueq list */
3853 	list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
3854 	pring->iocb_continueq_cnt++;
3855 
3856 	/* Now, determine whether the list is completed for processing */
3857 	irsp = &rspiocbp->iocb;
3858 	if (irsp->ulpLe) {
3859 		/*
3860 		 * By default, the driver expects to free all resources
3861 		 * associated with this iocb completion.
3862 		 */
3863 		free_saveq = 1;
3864 		saveq = list_get_first(&pring->iocb_continueq,
3865 				       struct lpfc_iocbq, list);
3866 		irsp = &(saveq->iocb);
3867 		list_del_init(&pring->iocb_continueq);
3868 		pring->iocb_continueq_cnt = 0;
3869 
3870 		pring->stats.iocb_rsp++;
3871 
3872 		/*
3873 		 * If resource errors reported from HBA, reduce
3874 		 * queuedepths of the SCSI device.
3875 		 */
3876 		if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3877 		    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3878 		     IOERR_NO_RESOURCES)) {
3879 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3880 			phba->lpfc_rampdown_queue_depth(phba);
3881 			spin_lock_irqsave(&phba->hbalock, iflag);
3882 		}
3883 
3884 		if (irsp->ulpStatus) {
3885 			/* Rsp ring <ringno> error: IOCB */
3886 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3887 					"0328 Rsp Ring %d error: "
3888 					"IOCB Data: "
3889 					"x%x x%x x%x x%x "
3890 					"x%x x%x x%x x%x "
3891 					"x%x x%x x%x x%x "
3892 					"x%x x%x x%x x%x\n",
3893 					pring->ringno,
3894 					irsp->un.ulpWord[0],
3895 					irsp->un.ulpWord[1],
3896 					irsp->un.ulpWord[2],
3897 					irsp->un.ulpWord[3],
3898 					irsp->un.ulpWord[4],
3899 					irsp->un.ulpWord[5],
3900 					*(((uint32_t *) irsp) + 6),
3901 					*(((uint32_t *) irsp) + 7),
3902 					*(((uint32_t *) irsp) + 8),
3903 					*(((uint32_t *) irsp) + 9),
3904 					*(((uint32_t *) irsp) + 10),
3905 					*(((uint32_t *) irsp) + 11),
3906 					*(((uint32_t *) irsp) + 12),
3907 					*(((uint32_t *) irsp) + 13),
3908 					*(((uint32_t *) irsp) + 14),
3909 					*(((uint32_t *) irsp) + 15));
3910 		}
3911 
3912 		/*
3913 		 * Fetch the IOCB command type and call the correct completion
3914 		 * routine. Solicited and Unsolicited IOCBs on the ELS ring
3915 		 * get freed back to the lpfc_iocb_list by the discovery
3916 		 * kernel thread.
3917 		 */
3918 		iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
3919 		type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
3920 		switch (type) {
3921 		case LPFC_SOL_IOCB:
3922 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3923 			rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
3924 			spin_lock_irqsave(&phba->hbalock, iflag);
3925 			break;
3926 
3927 		case LPFC_UNSOL_IOCB:
3928 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3929 			rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
3930 			spin_lock_irqsave(&phba->hbalock, iflag);
3931 			if (!rc)
3932 				free_saveq = 0;
3933 			break;
3934 
3935 		case LPFC_ABORT_IOCB:
3936 			cmdiocbp = NULL;
3937 			if (irsp->ulpCommand != CMD_XRI_ABORTED_CX) {
3938 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3939 				cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
3940 								 saveq);
3941 				spin_lock_irqsave(&phba->hbalock, iflag);
3942 			}
3943 			if (cmdiocbp) {
3944 				/* Call the specified completion routine */
3945 				if (cmdiocbp->iocb_cmpl) {
3946 					spin_unlock_irqrestore(&phba->hbalock,
3947 							       iflag);
3948 					(cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
3949 							      saveq);
3950 					spin_lock_irqsave(&phba->hbalock,
3951 							  iflag);
3952 				} else
3953 					__lpfc_sli_release_iocbq(phba,
3954 								 cmdiocbp);
3955 			}
3956 			break;
3957 
3958 		case LPFC_UNKNOWN_IOCB:
3959 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3960 				char adaptermsg[LPFC_MAX_ADPTMSG];
3961 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3962 				memcpy(&adaptermsg[0], (uint8_t *)irsp,
3963 				       MAX_MSG_DATA);
3964 				dev_warn(&((phba->pcidev)->dev),
3965 					 "lpfc%d: %s\n",
3966 					 phba->brd_no, adaptermsg);
3967 			} else {
3968 				/* Unknown IOCB command */
3969 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3970 						"0335 Unknown IOCB "
3971 						"command Data: x%x "
3972 						"x%x x%x x%x\n",
3973 						irsp->ulpCommand,
3974 						irsp->ulpStatus,
3975 						irsp->ulpIoTag,
3976 						irsp->ulpContext);
3977 			}
3978 			break;
3979 		}
3980 
3981 		if (free_saveq) {
3982 			list_for_each_entry_safe(rspiocbp, next_iocb,
3983 						 &saveq->list, list) {
3984 				list_del_init(&rspiocbp->list);
3985 				__lpfc_sli_release_iocbq(phba, rspiocbp);
3986 			}
3987 			__lpfc_sli_release_iocbq(phba, saveq);
3988 		}
3989 		rspiocbp = NULL;
3990 	}
3991 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3992 	return rspiocbp;
3993 }
3994 
3995 /**
3996  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
3997  * @phba: Pointer to HBA context object.
3998  * @pring: Pointer to driver SLI ring object.
3999  * @mask: Host attention register mask for this ring.
4000  *
4001  * This routine wraps the actual slow_ring event process routine from the
4002  * API jump table function pointer from the lpfc_hba struct.
4003  **/
4004 void
4005 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
4006 				struct lpfc_sli_ring *pring, uint32_t mask)
4007 {
4008 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
4009 }
4010 
4011 /**
4012  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
4013  * @phba: Pointer to HBA context object.
4014  * @pring: Pointer to driver SLI ring object.
4015  * @mask: Host attention register mask for this ring.
4016  *
4017  * This function is called from the worker thread when there is a ring event
4018  * for non-fcp rings. The caller does not hold any lock. The function will
4019  * remove each response iocb in the response ring and calls the handle
4020  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4021  **/
4022 static void
4023 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
4024 				   struct lpfc_sli_ring *pring, uint32_t mask)
4025 {
4026 	struct lpfc_pgp *pgp;
4027 	IOCB_t *entry;
4028 	IOCB_t *irsp = NULL;
4029 	struct lpfc_iocbq *rspiocbp = NULL;
4030 	uint32_t portRspPut, portRspMax;
4031 	unsigned long iflag;
4032 	uint32_t status;
4033 
4034 	pgp = &phba->port_gp[pring->ringno];
4035 	spin_lock_irqsave(&phba->hbalock, iflag);
4036 	pring->stats.iocb_event++;
4037 
4038 	/*
4039 	 * The next available response entry should never exceed the maximum
4040 	 * entries.  If it does, treat it as an adapter hardware error.
4041 	 */
4042 	portRspMax = pring->sli.sli3.numRiocb;
4043 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4044 	if (portRspPut >= portRspMax) {
4045 		/*
4046 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
4047 		 * rsp ring <portRspMax>
4048 		 */
4049 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4050 				"0303 Ring %d handler: portRspPut %d "
4051 				"is bigger than rsp ring %d\n",
4052 				pring->ringno, portRspPut, portRspMax);
4053 
4054 		phba->link_state = LPFC_HBA_ERROR;
4055 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4056 
4057 		phba->work_hs = HS_FFER3;
4058 		lpfc_handle_eratt(phba);
4059 
4060 		return;
4061 	}
4062 
4063 	rmb();
4064 	while (pring->sli.sli3.rspidx != portRspPut) {
4065 		/*
4066 		 * Build a completion list and call the appropriate handler.
4067 		 * The process is to get the next available response iocb, get
4068 		 * a free iocb from the list, copy the response data into the
4069 		 * free iocb, insert to the continuation list, and update the
4070 		 * next response index to slim.  This process makes response
4071 		 * iocb's in the ring available to DMA as fast as possible but
4072 		 * pays a penalty for a copy operation.  Since the iocb is
4073 		 * only 32 bytes, this penalty is considered small relative to
4074 		 * the PCI reads for register values and a slim write.  When
4075 		 * the ulpLe field is set, the entire Command has been
4076 		 * received.
4077 		 */
4078 		entry = lpfc_resp_iocb(phba, pring);
4079 
4080 		phba->last_completion_time = jiffies;
4081 		rspiocbp = __lpfc_sli_get_iocbq(phba);
4082 		if (rspiocbp == NULL) {
4083 			printk(KERN_ERR "%s: out of buffers! Failing "
4084 			       "completion.\n", __func__);
4085 			break;
4086 		}
4087 
4088 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
4089 				      phba->iocb_rsp_size);
4090 		irsp = &rspiocbp->iocb;
4091 
4092 		if (++pring->sli.sli3.rspidx >= portRspMax)
4093 			pring->sli.sli3.rspidx = 0;
4094 
4095 		if (pring->ringno == LPFC_ELS_RING) {
4096 			lpfc_debugfs_slow_ring_trc(phba,
4097 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
4098 				*(((uint32_t *) irsp) + 4),
4099 				*(((uint32_t *) irsp) + 6),
4100 				*(((uint32_t *) irsp) + 7));
4101 		}
4102 
4103 		writel(pring->sli.sli3.rspidx,
4104 			&phba->host_gp[pring->ringno].rspGetInx);
4105 
4106 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4107 		/* Handle the response IOCB */
4108 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
4109 		spin_lock_irqsave(&phba->hbalock, iflag);
4110 
4111 		/*
4112 		 * If the port response put pointer has not been updated, sync
4113 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
4114 		 * response put pointer.
4115 		 */
4116 		if (pring->sli.sli3.rspidx == portRspPut) {
4117 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4118 		}
4119 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
4120 
4121 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
4122 		/* At least one response entry has been freed */
4123 		pring->stats.iocb_rsp_full++;
4124 		/* SET RxRE_RSP in Chip Att register */
4125 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4126 		writel(status, phba->CAregaddr);
4127 		readl(phba->CAregaddr); /* flush */
4128 	}
4129 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4130 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4131 		pring->stats.iocb_cmd_empty++;
4132 
4133 		/* Force update of the local copy of cmdGetInx */
4134 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4135 		lpfc_sli_resume_iocb(phba, pring);
4136 
4137 		if ((pring->lpfc_sli_cmd_available))
4138 			(pring->lpfc_sli_cmd_available) (phba, pring);
4139 
4140 	}
4141 
4142 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4143 	return;
4144 }
4145 
4146 /**
4147  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
4148  * @phba: Pointer to HBA context object.
4149  * @pring: Pointer to driver SLI ring object.
4150  * @mask: Host attention register mask for this ring.
4151  *
4152  * This function is called from the worker thread when there is a pending
4153  * ELS response iocb on the driver internal slow-path response iocb worker
4154  * queue. The caller does not hold any lock. The function will remove each
4155  * response iocb from the response worker queue and calls the handle
4156  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4157  **/
4158 static void
4159 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4160 				   struct lpfc_sli_ring *pring, uint32_t mask)
4161 {
4162 	struct lpfc_iocbq *irspiocbq;
4163 	struct hbq_dmabuf *dmabuf;
4164 	struct lpfc_cq_event *cq_event;
4165 	unsigned long iflag;
4166 	int count = 0;
4167 
4168 	spin_lock_irqsave(&phba->hbalock, iflag);
4169 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
4170 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4171 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4172 		/* Get the response iocb from the head of work queue */
4173 		spin_lock_irqsave(&phba->hbalock, iflag);
4174 		list_remove_head(&phba->sli4_hba.sp_queue_event,
4175 				 cq_event, struct lpfc_cq_event, list);
4176 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4177 
4178 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4179 		case CQE_CODE_COMPL_WQE:
4180 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4181 						 cq_event);
4182 			/* Translate ELS WCQE to response IOCBQ */
4183 			irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
4184 								   irspiocbq);
4185 			if (irspiocbq)
4186 				lpfc_sli_sp_handle_rspiocb(phba, pring,
4187 							   irspiocbq);
4188 			count++;
4189 			break;
4190 		case CQE_CODE_RECEIVE:
4191 		case CQE_CODE_RECEIVE_V1:
4192 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
4193 					      cq_event);
4194 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
4195 			count++;
4196 			break;
4197 		default:
4198 			break;
4199 		}
4200 
4201 		/* Limit the number of events to 64 to avoid soft lockups */
4202 		if (count == 64)
4203 			break;
4204 	}
4205 }
4206 
4207 /**
4208  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4209  * @phba: Pointer to HBA context object.
4210  * @pring: Pointer to driver SLI ring object.
4211  *
4212  * This function aborts all iocbs in the given ring and frees all the iocb
4213  * objects in txq. This function issues an abort iocb for all the iocb commands
4214  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4215  * the return of this function. The caller is not required to hold any locks.
4216  **/
4217 void
4218 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4219 {
4220 	LIST_HEAD(completions);
4221 	struct lpfc_iocbq *iocb, *next_iocb;
4222 
4223 	if (pring->ringno == LPFC_ELS_RING) {
4224 		lpfc_fabric_abort_hba(phba);
4225 	}
4226 
4227 	/* Error everything on txq and txcmplq
4228 	 * First do the txq.
4229 	 */
4230 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4231 		spin_lock_irq(&pring->ring_lock);
4232 		list_splice_init(&pring->txq, &completions);
4233 		pring->txq_cnt = 0;
4234 		spin_unlock_irq(&pring->ring_lock);
4235 
4236 		spin_lock_irq(&phba->hbalock);
4237 		/* Next issue ABTS for everything on the txcmplq */
4238 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4239 			lpfc_sli_issue_abort_iotag(phba, pring, iocb, NULL);
4240 		spin_unlock_irq(&phba->hbalock);
4241 	} else {
4242 		spin_lock_irq(&phba->hbalock);
4243 		list_splice_init(&pring->txq, &completions);
4244 		pring->txq_cnt = 0;
4245 
4246 		/* Next issue ABTS for everything on the txcmplq */
4247 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4248 			lpfc_sli_issue_abort_iotag(phba, pring, iocb, NULL);
4249 		spin_unlock_irq(&phba->hbalock);
4250 	}
4251 	/* Make sure HBA is alive */
4252 	lpfc_issue_hb_tmo(phba);
4253 
4254 	/* Cancel all the IOCBs from the completions list */
4255 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
4256 			      IOERR_SLI_ABORTED);
4257 }
4258 
4259 /**
4260  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4261  * @phba: Pointer to HBA context object.
4262  *
4263  * This function aborts all iocbs in FCP rings and frees all the iocb
4264  * objects in txq. This function issues an abort iocb for all the iocb commands
4265  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4266  * the return of this function. The caller is not required to hold any locks.
4267  **/
4268 void
4269 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4270 {
4271 	struct lpfc_sli *psli = &phba->sli;
4272 	struct lpfc_sli_ring  *pring;
4273 	uint32_t i;
4274 
4275 	/* Look on all the FCP Rings for the iotag */
4276 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4277 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4278 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4279 			lpfc_sli_abort_iocb_ring(phba, pring);
4280 		}
4281 	} else {
4282 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4283 		lpfc_sli_abort_iocb_ring(phba, pring);
4284 	}
4285 }
4286 
4287 /**
4288  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4289  * @phba: Pointer to HBA context object.
4290  *
4291  * This function flushes all iocbs in the IO ring and frees all the iocb
4292  * objects in txq and txcmplq. This function will not issue abort iocbs
4293  * for all the iocb commands in txcmplq, they will just be returned with
4294  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4295  * slot has been permanently disabled.
4296  **/
4297 void
4298 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4299 {
4300 	LIST_HEAD(txq);
4301 	LIST_HEAD(txcmplq);
4302 	struct lpfc_sli *psli = &phba->sli;
4303 	struct lpfc_sli_ring  *pring;
4304 	uint32_t i;
4305 	struct lpfc_iocbq *piocb, *next_iocb;
4306 
4307 	spin_lock_irq(&phba->hbalock);
4308 	if (phba->hba_flag & HBA_IOQ_FLUSH ||
4309 	    !phba->sli4_hba.hdwq) {
4310 		spin_unlock_irq(&phba->hbalock);
4311 		return;
4312 	}
4313 	/* Indicate the I/O queues are flushed */
4314 	phba->hba_flag |= HBA_IOQ_FLUSH;
4315 	spin_unlock_irq(&phba->hbalock);
4316 
4317 	/* Look on all the FCP Rings for the iotag */
4318 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4319 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4320 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4321 
4322 			spin_lock_irq(&pring->ring_lock);
4323 			/* Retrieve everything on txq */
4324 			list_splice_init(&pring->txq, &txq);
4325 			list_for_each_entry_safe(piocb, next_iocb,
4326 						 &pring->txcmplq, list)
4327 				piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4328 			/* Retrieve everything on the txcmplq */
4329 			list_splice_init(&pring->txcmplq, &txcmplq);
4330 			pring->txq_cnt = 0;
4331 			pring->txcmplq_cnt = 0;
4332 			spin_unlock_irq(&pring->ring_lock);
4333 
4334 			/* Flush the txq */
4335 			lpfc_sli_cancel_iocbs(phba, &txq,
4336 					      IOSTAT_LOCAL_REJECT,
4337 					      IOERR_SLI_DOWN);
4338 			/* Flush the txcmpq */
4339 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4340 					      IOSTAT_LOCAL_REJECT,
4341 					      IOERR_SLI_DOWN);
4342 		}
4343 	} else {
4344 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4345 
4346 		spin_lock_irq(&phba->hbalock);
4347 		/* Retrieve everything on txq */
4348 		list_splice_init(&pring->txq, &txq);
4349 		list_for_each_entry_safe(piocb, next_iocb,
4350 					 &pring->txcmplq, list)
4351 			piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4352 		/* Retrieve everything on the txcmplq */
4353 		list_splice_init(&pring->txcmplq, &txcmplq);
4354 		pring->txq_cnt = 0;
4355 		pring->txcmplq_cnt = 0;
4356 		spin_unlock_irq(&phba->hbalock);
4357 
4358 		/* Flush the txq */
4359 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4360 				      IOERR_SLI_DOWN);
4361 		/* Flush the txcmpq */
4362 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4363 				      IOERR_SLI_DOWN);
4364 	}
4365 }
4366 
4367 /**
4368  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4369  * @phba: Pointer to HBA context object.
4370  * @mask: Bit mask to be checked.
4371  *
4372  * This function reads the host status register and compares
4373  * with the provided bit mask to check if HBA completed
4374  * the restart. This function will wait in a loop for the
4375  * HBA to complete restart. If the HBA does not restart within
4376  * 15 iterations, the function will reset the HBA again. The
4377  * function returns 1 when HBA fail to restart otherwise returns
4378  * zero.
4379  **/
4380 static int
4381 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4382 {
4383 	uint32_t status;
4384 	int i = 0;
4385 	int retval = 0;
4386 
4387 	/* Read the HBA Host Status Register */
4388 	if (lpfc_readl(phba->HSregaddr, &status))
4389 		return 1;
4390 
4391 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4392 
4393 	/*
4394 	 * Check status register every 100ms for 5 retries, then every
4395 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4396 	 * every 2.5 sec for 4.
4397 	 * Break our of the loop if errors occurred during init.
4398 	 */
4399 	while (((status & mask) != mask) &&
4400 	       !(status & HS_FFERM) &&
4401 	       i++ < 20) {
4402 
4403 		if (i <= 5)
4404 			msleep(10);
4405 		else if (i <= 10)
4406 			msleep(500);
4407 		else
4408 			msleep(2500);
4409 
4410 		if (i == 15) {
4411 				/* Do post */
4412 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4413 			lpfc_sli_brdrestart(phba);
4414 		}
4415 		/* Read the HBA Host Status Register */
4416 		if (lpfc_readl(phba->HSregaddr, &status)) {
4417 			retval = 1;
4418 			break;
4419 		}
4420 	}
4421 
4422 	/* Check to see if any errors occurred during init */
4423 	if ((status & HS_FFERM) || (i >= 20)) {
4424 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4425 				"2751 Adapter failed to restart, "
4426 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4427 				status,
4428 				readl(phba->MBslimaddr + 0xa8),
4429 				readl(phba->MBslimaddr + 0xac));
4430 		phba->link_state = LPFC_HBA_ERROR;
4431 		retval = 1;
4432 	}
4433 
4434 	return retval;
4435 }
4436 
4437 /**
4438  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4439  * @phba: Pointer to HBA context object.
4440  * @mask: Bit mask to be checked.
4441  *
4442  * This function checks the host status register to check if HBA is
4443  * ready. This function will wait in a loop for the HBA to be ready
4444  * If the HBA is not ready , the function will will reset the HBA PCI
4445  * function again. The function returns 1 when HBA fail to be ready
4446  * otherwise returns zero.
4447  **/
4448 static int
4449 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4450 {
4451 	uint32_t status;
4452 	int retval = 0;
4453 
4454 	/* Read the HBA Host Status Register */
4455 	status = lpfc_sli4_post_status_check(phba);
4456 
4457 	if (status) {
4458 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4459 		lpfc_sli_brdrestart(phba);
4460 		status = lpfc_sli4_post_status_check(phba);
4461 	}
4462 
4463 	/* Check to see if any errors occurred during init */
4464 	if (status) {
4465 		phba->link_state = LPFC_HBA_ERROR;
4466 		retval = 1;
4467 	} else
4468 		phba->sli4_hba.intr_enable = 0;
4469 
4470 	return retval;
4471 }
4472 
4473 /**
4474  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4475  * @phba: Pointer to HBA context object.
4476  * @mask: Bit mask to be checked.
4477  *
4478  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4479  * from the API jump table function pointer from the lpfc_hba struct.
4480  **/
4481 int
4482 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4483 {
4484 	return phba->lpfc_sli_brdready(phba, mask);
4485 }
4486 
4487 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4488 
4489 /**
4490  * lpfc_reset_barrier - Make HBA ready for HBA reset
4491  * @phba: Pointer to HBA context object.
4492  *
4493  * This function is called before resetting an HBA. This function is called
4494  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4495  **/
4496 void lpfc_reset_barrier(struct lpfc_hba *phba)
4497 {
4498 	uint32_t __iomem *resp_buf;
4499 	uint32_t __iomem *mbox_buf;
4500 	volatile uint32_t mbox;
4501 	uint32_t hc_copy, ha_copy, resp_data;
4502 	int  i;
4503 	uint8_t hdrtype;
4504 
4505 	lockdep_assert_held(&phba->hbalock);
4506 
4507 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4508 	if (hdrtype != 0x80 ||
4509 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4510 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4511 		return;
4512 
4513 	/*
4514 	 * Tell the other part of the chip to suspend temporarily all
4515 	 * its DMA activity.
4516 	 */
4517 	resp_buf = phba->MBslimaddr;
4518 
4519 	/* Disable the error attention */
4520 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4521 		return;
4522 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4523 	readl(phba->HCregaddr); /* flush */
4524 	phba->link_flag |= LS_IGNORE_ERATT;
4525 
4526 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4527 		return;
4528 	if (ha_copy & HA_ERATT) {
4529 		/* Clear Chip error bit */
4530 		writel(HA_ERATT, phba->HAregaddr);
4531 		phba->pport->stopped = 1;
4532 	}
4533 
4534 	mbox = 0;
4535 	((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
4536 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
4537 
4538 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4539 	mbox_buf = phba->MBslimaddr;
4540 	writel(mbox, mbox_buf);
4541 
4542 	for (i = 0; i < 50; i++) {
4543 		if (lpfc_readl((resp_buf + 1), &resp_data))
4544 			return;
4545 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4546 			mdelay(1);
4547 		else
4548 			break;
4549 	}
4550 	resp_data = 0;
4551 	if (lpfc_readl((resp_buf + 1), &resp_data))
4552 		return;
4553 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4554 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4555 		    phba->pport->stopped)
4556 			goto restore_hc;
4557 		else
4558 			goto clear_errat;
4559 	}
4560 
4561 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
4562 	resp_data = 0;
4563 	for (i = 0; i < 500; i++) {
4564 		if (lpfc_readl(resp_buf, &resp_data))
4565 			return;
4566 		if (resp_data != mbox)
4567 			mdelay(1);
4568 		else
4569 			break;
4570 	}
4571 
4572 clear_errat:
4573 
4574 	while (++i < 500) {
4575 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4576 			return;
4577 		if (!(ha_copy & HA_ERATT))
4578 			mdelay(1);
4579 		else
4580 			break;
4581 	}
4582 
4583 	if (readl(phba->HAregaddr) & HA_ERATT) {
4584 		writel(HA_ERATT, phba->HAregaddr);
4585 		phba->pport->stopped = 1;
4586 	}
4587 
4588 restore_hc:
4589 	phba->link_flag &= ~LS_IGNORE_ERATT;
4590 	writel(hc_copy, phba->HCregaddr);
4591 	readl(phba->HCregaddr); /* flush */
4592 }
4593 
4594 /**
4595  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4596  * @phba: Pointer to HBA context object.
4597  *
4598  * This function issues a kill_board mailbox command and waits for
4599  * the error attention interrupt. This function is called for stopping
4600  * the firmware processing. The caller is not required to hold any
4601  * locks. This function calls lpfc_hba_down_post function to free
4602  * any pending commands after the kill. The function will return 1 when it
4603  * fails to kill the board else will return 0.
4604  **/
4605 int
4606 lpfc_sli_brdkill(struct lpfc_hba *phba)
4607 {
4608 	struct lpfc_sli *psli;
4609 	LPFC_MBOXQ_t *pmb;
4610 	uint32_t status;
4611 	uint32_t ha_copy;
4612 	int retval;
4613 	int i = 0;
4614 
4615 	psli = &phba->sli;
4616 
4617 	/* Kill HBA */
4618 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4619 			"0329 Kill HBA Data: x%x x%x\n",
4620 			phba->pport->port_state, psli->sli_flag);
4621 
4622 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4623 	if (!pmb)
4624 		return 1;
4625 
4626 	/* Disable the error attention */
4627 	spin_lock_irq(&phba->hbalock);
4628 	if (lpfc_readl(phba->HCregaddr, &status)) {
4629 		spin_unlock_irq(&phba->hbalock);
4630 		mempool_free(pmb, phba->mbox_mem_pool);
4631 		return 1;
4632 	}
4633 	status &= ~HC_ERINT_ENA;
4634 	writel(status, phba->HCregaddr);
4635 	readl(phba->HCregaddr); /* flush */
4636 	phba->link_flag |= LS_IGNORE_ERATT;
4637 	spin_unlock_irq(&phba->hbalock);
4638 
4639 	lpfc_kill_board(phba, pmb);
4640 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4641 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4642 
4643 	if (retval != MBX_SUCCESS) {
4644 		if (retval != MBX_BUSY)
4645 			mempool_free(pmb, phba->mbox_mem_pool);
4646 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4647 				"2752 KILL_BOARD command failed retval %d\n",
4648 				retval);
4649 		spin_lock_irq(&phba->hbalock);
4650 		phba->link_flag &= ~LS_IGNORE_ERATT;
4651 		spin_unlock_irq(&phba->hbalock);
4652 		return 1;
4653 	}
4654 
4655 	spin_lock_irq(&phba->hbalock);
4656 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
4657 	spin_unlock_irq(&phba->hbalock);
4658 
4659 	mempool_free(pmb, phba->mbox_mem_pool);
4660 
4661 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
4662 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
4663 	 * 3 seconds we still set HBA_ERROR state because the status of the
4664 	 * board is now undefined.
4665 	 */
4666 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4667 		return 1;
4668 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
4669 		mdelay(100);
4670 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4671 			return 1;
4672 	}
4673 
4674 	del_timer_sync(&psli->mbox_tmo);
4675 	if (ha_copy & HA_ERATT) {
4676 		writel(HA_ERATT, phba->HAregaddr);
4677 		phba->pport->stopped = 1;
4678 	}
4679 	spin_lock_irq(&phba->hbalock);
4680 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4681 	psli->mbox_active = NULL;
4682 	phba->link_flag &= ~LS_IGNORE_ERATT;
4683 	spin_unlock_irq(&phba->hbalock);
4684 
4685 	lpfc_hba_down_post(phba);
4686 	phba->link_state = LPFC_HBA_ERROR;
4687 
4688 	return ha_copy & HA_ERATT ? 0 : 1;
4689 }
4690 
4691 /**
4692  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
4693  * @phba: Pointer to HBA context object.
4694  *
4695  * This function resets the HBA by writing HC_INITFF to the control
4696  * register. After the HBA resets, this function resets all the iocb ring
4697  * indices. This function disables PCI layer parity checking during
4698  * the reset.
4699  * This function returns 0 always.
4700  * The caller is not required to hold any locks.
4701  **/
4702 int
4703 lpfc_sli_brdreset(struct lpfc_hba *phba)
4704 {
4705 	struct lpfc_sli *psli;
4706 	struct lpfc_sli_ring *pring;
4707 	uint16_t cfg_value;
4708 	int i;
4709 
4710 	psli = &phba->sli;
4711 
4712 	/* Reset HBA */
4713 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4714 			"0325 Reset HBA Data: x%x x%x\n",
4715 			(phba->pport) ? phba->pport->port_state : 0,
4716 			psli->sli_flag);
4717 
4718 	/* perform board reset */
4719 	phba->fc_eventTag = 0;
4720 	phba->link_events = 0;
4721 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4722 	if (phba->pport) {
4723 		phba->pport->fc_myDID = 0;
4724 		phba->pport->fc_prevDID = 0;
4725 	}
4726 
4727 	/* Turn off parity checking and serr during the physical reset */
4728 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
4729 		return -EIO;
4730 
4731 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
4732 			      (cfg_value &
4733 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4734 
4735 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4736 
4737 	/* Now toggle INITFF bit in the Host Control Register */
4738 	writel(HC_INITFF, phba->HCregaddr);
4739 	mdelay(1);
4740 	readl(phba->HCregaddr); /* flush */
4741 	writel(0, phba->HCregaddr);
4742 	readl(phba->HCregaddr); /* flush */
4743 
4744 	/* Restore PCI cmd register */
4745 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4746 
4747 	/* Initialize relevant SLI info */
4748 	for (i = 0; i < psli->num_rings; i++) {
4749 		pring = &psli->sli3_ring[i];
4750 		pring->flag = 0;
4751 		pring->sli.sli3.rspidx = 0;
4752 		pring->sli.sli3.next_cmdidx  = 0;
4753 		pring->sli.sli3.local_getidx = 0;
4754 		pring->sli.sli3.cmdidx = 0;
4755 		pring->missbufcnt = 0;
4756 	}
4757 
4758 	phba->link_state = LPFC_WARM_START;
4759 	return 0;
4760 }
4761 
4762 /**
4763  * lpfc_sli4_brdreset - Reset a sli-4 HBA
4764  * @phba: Pointer to HBA context object.
4765  *
4766  * This function resets a SLI4 HBA. This function disables PCI layer parity
4767  * checking during resets the device. The caller is not required to hold
4768  * any locks.
4769  *
4770  * This function returns 0 on success else returns negative error code.
4771  **/
4772 int
4773 lpfc_sli4_brdreset(struct lpfc_hba *phba)
4774 {
4775 	struct lpfc_sli *psli = &phba->sli;
4776 	uint16_t cfg_value;
4777 	int rc = 0;
4778 
4779 	/* Reset HBA */
4780 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4781 			"0295 Reset HBA Data: x%x x%x x%x\n",
4782 			phba->pport->port_state, psli->sli_flag,
4783 			phba->hba_flag);
4784 
4785 	/* perform board reset */
4786 	phba->fc_eventTag = 0;
4787 	phba->link_events = 0;
4788 	phba->pport->fc_myDID = 0;
4789 	phba->pport->fc_prevDID = 0;
4790 
4791 	spin_lock_irq(&phba->hbalock);
4792 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
4793 	phba->fcf.fcf_flag = 0;
4794 	spin_unlock_irq(&phba->hbalock);
4795 
4796 	/* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
4797 	if (phba->hba_flag & HBA_FW_DUMP_OP) {
4798 		phba->hba_flag &= ~HBA_FW_DUMP_OP;
4799 		return rc;
4800 	}
4801 
4802 	/* Now physically reset the device */
4803 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4804 			"0389 Performing PCI function reset!\n");
4805 
4806 	/* Turn off parity checking and serr during the physical reset */
4807 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
4808 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4809 				"3205 PCI read Config failed\n");
4810 		return -EIO;
4811 	}
4812 
4813 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
4814 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4815 
4816 	/* Perform FCoE PCI function reset before freeing queue memory */
4817 	rc = lpfc_pci_function_reset(phba);
4818 
4819 	/* Restore PCI cmd register */
4820 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4821 
4822 	return rc;
4823 }
4824 
4825 /**
4826  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
4827  * @phba: Pointer to HBA context object.
4828  *
4829  * This function is called in the SLI initialization code path to
4830  * restart the HBA. The caller is not required to hold any lock.
4831  * This function writes MBX_RESTART mailbox command to the SLIM and
4832  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
4833  * function to free any pending commands. The function enables
4834  * POST only during the first initialization. The function returns zero.
4835  * The function does not guarantee completion of MBX_RESTART mailbox
4836  * command before the return of this function.
4837  **/
4838 static int
4839 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
4840 {
4841 	MAILBOX_t *mb;
4842 	struct lpfc_sli *psli;
4843 	volatile uint32_t word0;
4844 	void __iomem *to_slim;
4845 	uint32_t hba_aer_enabled;
4846 
4847 	spin_lock_irq(&phba->hbalock);
4848 
4849 	/* Take PCIe device Advanced Error Reporting (AER) state */
4850 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4851 
4852 	psli = &phba->sli;
4853 
4854 	/* Restart HBA */
4855 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4856 			"0337 Restart HBA Data: x%x x%x\n",
4857 			(phba->pport) ? phba->pport->port_state : 0,
4858 			psli->sli_flag);
4859 
4860 	word0 = 0;
4861 	mb = (MAILBOX_t *) &word0;
4862 	mb->mbxCommand = MBX_RESTART;
4863 	mb->mbxHc = 1;
4864 
4865 	lpfc_reset_barrier(phba);
4866 
4867 	to_slim = phba->MBslimaddr;
4868 	writel(*(uint32_t *) mb, to_slim);
4869 	readl(to_slim); /* flush */
4870 
4871 	/* Only skip post after fc_ffinit is completed */
4872 	if (phba->pport && phba->pport->port_state)
4873 		word0 = 1;	/* This is really setting up word1 */
4874 	else
4875 		word0 = 0;	/* This is really setting up word1 */
4876 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
4877 	writel(*(uint32_t *) mb, to_slim);
4878 	readl(to_slim); /* flush */
4879 
4880 	lpfc_sli_brdreset(phba);
4881 	if (phba->pport)
4882 		phba->pport->stopped = 0;
4883 	phba->link_state = LPFC_INIT_START;
4884 	phba->hba_flag = 0;
4885 	spin_unlock_irq(&phba->hbalock);
4886 
4887 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4888 	psli->stats_start = ktime_get_seconds();
4889 
4890 	/* Give the INITFF and Post time to settle. */
4891 	mdelay(100);
4892 
4893 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4894 	if (hba_aer_enabled)
4895 		pci_disable_pcie_error_reporting(phba->pcidev);
4896 
4897 	lpfc_hba_down_post(phba);
4898 
4899 	return 0;
4900 }
4901 
4902 /**
4903  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
4904  * @phba: Pointer to HBA context object.
4905  *
4906  * This function is called in the SLI initialization code path to restart
4907  * a SLI4 HBA. The caller is not required to hold any lock.
4908  * At the end of the function, it calls lpfc_hba_down_post function to
4909  * free any pending commands.
4910  **/
4911 static int
4912 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
4913 {
4914 	struct lpfc_sli *psli = &phba->sli;
4915 	uint32_t hba_aer_enabled;
4916 	int rc;
4917 
4918 	/* Restart HBA */
4919 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4920 			"0296 Restart HBA Data: x%x x%x\n",
4921 			phba->pport->port_state, psli->sli_flag);
4922 
4923 	/* Take PCIe device Advanced Error Reporting (AER) state */
4924 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4925 
4926 	rc = lpfc_sli4_brdreset(phba);
4927 	if (rc) {
4928 		phba->link_state = LPFC_HBA_ERROR;
4929 		goto hba_down_queue;
4930 	}
4931 
4932 	spin_lock_irq(&phba->hbalock);
4933 	phba->pport->stopped = 0;
4934 	phba->link_state = LPFC_INIT_START;
4935 	phba->hba_flag = 0;
4936 	spin_unlock_irq(&phba->hbalock);
4937 
4938 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4939 	psli->stats_start = ktime_get_seconds();
4940 
4941 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4942 	if (hba_aer_enabled)
4943 		pci_disable_pcie_error_reporting(phba->pcidev);
4944 
4945 hba_down_queue:
4946 	lpfc_hba_down_post(phba);
4947 	lpfc_sli4_queue_destroy(phba);
4948 
4949 	return rc;
4950 }
4951 
4952 /**
4953  * lpfc_sli_brdrestart - Wrapper func for restarting hba
4954  * @phba: Pointer to HBA context object.
4955  *
4956  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
4957  * API jump table function pointer from the lpfc_hba struct.
4958 **/
4959 int
4960 lpfc_sli_brdrestart(struct lpfc_hba *phba)
4961 {
4962 	return phba->lpfc_sli_brdrestart(phba);
4963 }
4964 
4965 /**
4966  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
4967  * @phba: Pointer to HBA context object.
4968  *
4969  * This function is called after a HBA restart to wait for successful
4970  * restart of the HBA. Successful restart of the HBA is indicated by
4971  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
4972  * iteration, the function will restart the HBA again. The function returns
4973  * zero if HBA successfully restarted else returns negative error code.
4974  **/
4975 int
4976 lpfc_sli_chipset_init(struct lpfc_hba *phba)
4977 {
4978 	uint32_t status, i = 0;
4979 
4980 	/* Read the HBA Host Status Register */
4981 	if (lpfc_readl(phba->HSregaddr, &status))
4982 		return -EIO;
4983 
4984 	/* Check status register to see what current state is */
4985 	i = 0;
4986 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
4987 
4988 		/* Check every 10ms for 10 retries, then every 100ms for 90
4989 		 * retries, then every 1 sec for 50 retires for a total of
4990 		 * ~60 seconds before reset the board again and check every
4991 		 * 1 sec for 50 retries. The up to 60 seconds before the
4992 		 * board ready is required by the Falcon FIPS zeroization
4993 		 * complete, and any reset the board in between shall cause
4994 		 * restart of zeroization, further delay the board ready.
4995 		 */
4996 		if (i++ >= 200) {
4997 			/* Adapter failed to init, timeout, status reg
4998 			   <status> */
4999 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5000 					"0436 Adapter failed to init, "
5001 					"timeout, status reg x%x, "
5002 					"FW Data: A8 x%x AC x%x\n", status,
5003 					readl(phba->MBslimaddr + 0xa8),
5004 					readl(phba->MBslimaddr + 0xac));
5005 			phba->link_state = LPFC_HBA_ERROR;
5006 			return -ETIMEDOUT;
5007 		}
5008 
5009 		/* Check to see if any errors occurred during init */
5010 		if (status & HS_FFERM) {
5011 			/* ERROR: During chipset initialization */
5012 			/* Adapter failed to init, chipset, status reg
5013 			   <status> */
5014 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5015 					"0437 Adapter failed to init, "
5016 					"chipset, status reg x%x, "
5017 					"FW Data: A8 x%x AC x%x\n", status,
5018 					readl(phba->MBslimaddr + 0xa8),
5019 					readl(phba->MBslimaddr + 0xac));
5020 			phba->link_state = LPFC_HBA_ERROR;
5021 			return -EIO;
5022 		}
5023 
5024 		if (i <= 10)
5025 			msleep(10);
5026 		else if (i <= 100)
5027 			msleep(100);
5028 		else
5029 			msleep(1000);
5030 
5031 		if (i == 150) {
5032 			/* Do post */
5033 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5034 			lpfc_sli_brdrestart(phba);
5035 		}
5036 		/* Read the HBA Host Status Register */
5037 		if (lpfc_readl(phba->HSregaddr, &status))
5038 			return -EIO;
5039 	}
5040 
5041 	/* Check to see if any errors occurred during init */
5042 	if (status & HS_FFERM) {
5043 		/* ERROR: During chipset initialization */
5044 		/* Adapter failed to init, chipset, status reg <status> */
5045 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5046 				"0438 Adapter failed to init, chipset, "
5047 				"status reg x%x, "
5048 				"FW Data: A8 x%x AC x%x\n", status,
5049 				readl(phba->MBslimaddr + 0xa8),
5050 				readl(phba->MBslimaddr + 0xac));
5051 		phba->link_state = LPFC_HBA_ERROR;
5052 		return -EIO;
5053 	}
5054 
5055 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5056 
5057 	/* Clear all interrupt enable conditions */
5058 	writel(0, phba->HCregaddr);
5059 	readl(phba->HCregaddr); /* flush */
5060 
5061 	/* setup host attn register */
5062 	writel(0xffffffff, phba->HAregaddr);
5063 	readl(phba->HAregaddr); /* flush */
5064 	return 0;
5065 }
5066 
5067 /**
5068  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5069  *
5070  * This function calculates and returns the number of HBQs required to be
5071  * configured.
5072  **/
5073 int
5074 lpfc_sli_hbq_count(void)
5075 {
5076 	return ARRAY_SIZE(lpfc_hbq_defs);
5077 }
5078 
5079 /**
5080  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5081  *
5082  * This function adds the number of hbq entries in every HBQ to get
5083  * the total number of hbq entries required for the HBA and returns
5084  * the total count.
5085  **/
5086 static int
5087 lpfc_sli_hbq_entry_count(void)
5088 {
5089 	int  hbq_count = lpfc_sli_hbq_count();
5090 	int  count = 0;
5091 	int  i;
5092 
5093 	for (i = 0; i < hbq_count; ++i)
5094 		count += lpfc_hbq_defs[i]->entry_count;
5095 	return count;
5096 }
5097 
5098 /**
5099  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5100  *
5101  * This function calculates amount of memory required for all hbq entries
5102  * to be configured and returns the total memory required.
5103  **/
5104 int
5105 lpfc_sli_hbq_size(void)
5106 {
5107 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5108 }
5109 
5110 /**
5111  * lpfc_sli_hbq_setup - configure and initialize HBQs
5112  * @phba: Pointer to HBA context object.
5113  *
5114  * This function is called during the SLI initialization to configure
5115  * all the HBQs and post buffers to the HBQ. The caller is not
5116  * required to hold any locks. This function will return zero if successful
5117  * else it will return negative error code.
5118  **/
5119 static int
5120 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5121 {
5122 	int  hbq_count = lpfc_sli_hbq_count();
5123 	LPFC_MBOXQ_t *pmb;
5124 	MAILBOX_t *pmbox;
5125 	uint32_t hbqno;
5126 	uint32_t hbq_entry_index;
5127 
5128 				/* Get a Mailbox buffer to setup mailbox
5129 				 * commands for HBA initialization
5130 				 */
5131 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5132 
5133 	if (!pmb)
5134 		return -ENOMEM;
5135 
5136 	pmbox = &pmb->u.mb;
5137 
5138 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
5139 	phba->link_state = LPFC_INIT_MBX_CMDS;
5140 	phba->hbq_in_use = 1;
5141 
5142 	hbq_entry_index = 0;
5143 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5144 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
5145 		phba->hbqs[hbqno].hbqPutIdx      = 0;
5146 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5147 		phba->hbqs[hbqno].entry_count =
5148 			lpfc_hbq_defs[hbqno]->entry_count;
5149 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5150 			hbq_entry_index, pmb);
5151 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
5152 
5153 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5154 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5155 			   mbxStatus <status>, ring <num> */
5156 
5157 			lpfc_printf_log(phba, KERN_ERR,
5158 					LOG_SLI | LOG_VPORT,
5159 					"1805 Adapter failed to init. "
5160 					"Data: x%x x%x x%x\n",
5161 					pmbox->mbxCommand,
5162 					pmbox->mbxStatus, hbqno);
5163 
5164 			phba->link_state = LPFC_HBA_ERROR;
5165 			mempool_free(pmb, phba->mbox_mem_pool);
5166 			return -ENXIO;
5167 		}
5168 	}
5169 	phba->hbq_count = hbq_count;
5170 
5171 	mempool_free(pmb, phba->mbox_mem_pool);
5172 
5173 	/* Initially populate or replenish the HBQs */
5174 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5175 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5176 	return 0;
5177 }
5178 
5179 /**
5180  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5181  * @phba: Pointer to HBA context object.
5182  *
5183  * This function is called during the SLI initialization to configure
5184  * all the HBQs and post buffers to the HBQ. The caller is not
5185  * required to hold any locks. This function will return zero if successful
5186  * else it will return negative error code.
5187  **/
5188 static int
5189 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5190 {
5191 	phba->hbq_in_use = 1;
5192 	/**
5193 	 * Specific case when the MDS diagnostics is enabled and supported.
5194 	 * The receive buffer count is truncated to manage the incoming
5195 	 * traffic.
5196 	 **/
5197 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5198 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5199 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5200 	else
5201 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5202 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5203 	phba->hbq_count = 1;
5204 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5205 	/* Initially populate or replenish the HBQs */
5206 	return 0;
5207 }
5208 
5209 /**
5210  * lpfc_sli_config_port - Issue config port mailbox command
5211  * @phba: Pointer to HBA context object.
5212  * @sli_mode: sli mode - 2/3
5213  *
5214  * This function is called by the sli initialization code path
5215  * to issue config_port mailbox command. This function restarts the
5216  * HBA firmware and issues a config_port mailbox command to configure
5217  * the SLI interface in the sli mode specified by sli_mode
5218  * variable. The caller is not required to hold any locks.
5219  * The function returns 0 if successful, else returns negative error
5220  * code.
5221  **/
5222 int
5223 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5224 {
5225 	LPFC_MBOXQ_t *pmb;
5226 	uint32_t resetcount = 0, rc = 0, done = 0;
5227 
5228 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5229 	if (!pmb) {
5230 		phba->link_state = LPFC_HBA_ERROR;
5231 		return -ENOMEM;
5232 	}
5233 
5234 	phba->sli_rev = sli_mode;
5235 	while (resetcount < 2 && !done) {
5236 		spin_lock_irq(&phba->hbalock);
5237 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5238 		spin_unlock_irq(&phba->hbalock);
5239 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5240 		lpfc_sli_brdrestart(phba);
5241 		rc = lpfc_sli_chipset_init(phba);
5242 		if (rc)
5243 			break;
5244 
5245 		spin_lock_irq(&phba->hbalock);
5246 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5247 		spin_unlock_irq(&phba->hbalock);
5248 		resetcount++;
5249 
5250 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5251 		 * value of 0 means the call was successful.  Any other
5252 		 * nonzero value is a failure, but if ERESTART is returned,
5253 		 * the driver may reset the HBA and try again.
5254 		 */
5255 		rc = lpfc_config_port_prep(phba);
5256 		if (rc == -ERESTART) {
5257 			phba->link_state = LPFC_LINK_UNKNOWN;
5258 			continue;
5259 		} else if (rc)
5260 			break;
5261 
5262 		phba->link_state = LPFC_INIT_MBX_CMDS;
5263 		lpfc_config_port(phba, pmb);
5264 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5265 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5266 					LPFC_SLI3_HBQ_ENABLED |
5267 					LPFC_SLI3_CRP_ENABLED |
5268 					LPFC_SLI3_DSS_ENABLED);
5269 		if (rc != MBX_SUCCESS) {
5270 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5271 				"0442 Adapter failed to init, mbxCmd x%x "
5272 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5273 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5274 			spin_lock_irq(&phba->hbalock);
5275 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5276 			spin_unlock_irq(&phba->hbalock);
5277 			rc = -ENXIO;
5278 		} else {
5279 			/* Allow asynchronous mailbox command to go through */
5280 			spin_lock_irq(&phba->hbalock);
5281 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5282 			spin_unlock_irq(&phba->hbalock);
5283 			done = 1;
5284 
5285 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5286 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5287 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5288 					"3110 Port did not grant ASABT\n");
5289 		}
5290 	}
5291 	if (!done) {
5292 		rc = -EINVAL;
5293 		goto do_prep_failed;
5294 	}
5295 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5296 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5297 			rc = -ENXIO;
5298 			goto do_prep_failed;
5299 		}
5300 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5301 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5302 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5303 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5304 				phba->max_vpi : phba->max_vports;
5305 
5306 		} else
5307 			phba->max_vpi = 0;
5308 		if (pmb->u.mb.un.varCfgPort.gerbm)
5309 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5310 		if (pmb->u.mb.un.varCfgPort.gcrp)
5311 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5312 
5313 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5314 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5315 
5316 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5317 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5318 				phba->cfg_enable_bg = 0;
5319 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5320 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5321 						"0443 Adapter did not grant "
5322 						"BlockGuard\n");
5323 			}
5324 		}
5325 	} else {
5326 		phba->hbq_get = NULL;
5327 		phba->port_gp = phba->mbox->us.s2.port;
5328 		phba->max_vpi = 0;
5329 	}
5330 do_prep_failed:
5331 	mempool_free(pmb, phba->mbox_mem_pool);
5332 	return rc;
5333 }
5334 
5335 
5336 /**
5337  * lpfc_sli_hba_setup - SLI initialization function
5338  * @phba: Pointer to HBA context object.
5339  *
5340  * This function is the main SLI initialization function. This function
5341  * is called by the HBA initialization code, HBA reset code and HBA
5342  * error attention handler code. Caller is not required to hold any
5343  * locks. This function issues config_port mailbox command to configure
5344  * the SLI, setup iocb rings and HBQ rings. In the end the function
5345  * calls the config_port_post function to issue init_link mailbox
5346  * command and to start the discovery. The function will return zero
5347  * if successful, else it will return negative error code.
5348  **/
5349 int
5350 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5351 {
5352 	uint32_t rc;
5353 	int  i;
5354 	int longs;
5355 
5356 	/* Enable ISR already does config_port because of config_msi mbx */
5357 	if (phba->hba_flag & HBA_NEEDS_CFG_PORT) {
5358 		rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5359 		if (rc)
5360 			return -EIO;
5361 		phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
5362 	}
5363 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5364 
5365 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
5366 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
5367 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
5368 		if (!rc) {
5369 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5370 					"2709 This device supports "
5371 					"Advanced Error Reporting (AER)\n");
5372 			spin_lock_irq(&phba->hbalock);
5373 			phba->hba_flag |= HBA_AER_ENABLED;
5374 			spin_unlock_irq(&phba->hbalock);
5375 		} else {
5376 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5377 					"2708 This device does not support "
5378 					"Advanced Error Reporting (AER): %d\n",
5379 					rc);
5380 			phba->cfg_aer_support = 0;
5381 		}
5382 	}
5383 
5384 	if (phba->sli_rev == 3) {
5385 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5386 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5387 	} else {
5388 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5389 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5390 		phba->sli3_options = 0;
5391 	}
5392 
5393 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5394 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5395 			phba->sli_rev, phba->max_vpi);
5396 	rc = lpfc_sli_ring_map(phba);
5397 
5398 	if (rc)
5399 		goto lpfc_sli_hba_setup_error;
5400 
5401 	/* Initialize VPIs. */
5402 	if (phba->sli_rev == LPFC_SLI_REV3) {
5403 		/*
5404 		 * The VPI bitmask and physical ID array are allocated
5405 		 * and initialized once only - at driver load.  A port
5406 		 * reset doesn't need to reinitialize this memory.
5407 		 */
5408 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5409 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5410 			phba->vpi_bmask = kcalloc(longs,
5411 						  sizeof(unsigned long),
5412 						  GFP_KERNEL);
5413 			if (!phba->vpi_bmask) {
5414 				rc = -ENOMEM;
5415 				goto lpfc_sli_hba_setup_error;
5416 			}
5417 
5418 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5419 						sizeof(uint16_t),
5420 						GFP_KERNEL);
5421 			if (!phba->vpi_ids) {
5422 				kfree(phba->vpi_bmask);
5423 				rc = -ENOMEM;
5424 				goto lpfc_sli_hba_setup_error;
5425 			}
5426 			for (i = 0; i < phba->max_vpi; i++)
5427 				phba->vpi_ids[i] = i;
5428 		}
5429 	}
5430 
5431 	/* Init HBQs */
5432 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5433 		rc = lpfc_sli_hbq_setup(phba);
5434 		if (rc)
5435 			goto lpfc_sli_hba_setup_error;
5436 	}
5437 	spin_lock_irq(&phba->hbalock);
5438 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5439 	spin_unlock_irq(&phba->hbalock);
5440 
5441 	rc = lpfc_config_port_post(phba);
5442 	if (rc)
5443 		goto lpfc_sli_hba_setup_error;
5444 
5445 	return rc;
5446 
5447 lpfc_sli_hba_setup_error:
5448 	phba->link_state = LPFC_HBA_ERROR;
5449 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5450 			"0445 Firmware initialization failed\n");
5451 	return rc;
5452 }
5453 
5454 /**
5455  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5456  * @phba: Pointer to HBA context object.
5457  *
5458  * This function issue a dump mailbox command to read config region
5459  * 23 and parse the records in the region and populate driver
5460  * data structure.
5461  **/
5462 static int
5463 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5464 {
5465 	LPFC_MBOXQ_t *mboxq;
5466 	struct lpfc_dmabuf *mp;
5467 	struct lpfc_mqe *mqe;
5468 	uint32_t data_length;
5469 	int rc;
5470 
5471 	/* Program the default value of vlan_id and fc_map */
5472 	phba->valid_vlan = 0;
5473 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5474 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5475 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5476 
5477 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5478 	if (!mboxq)
5479 		return -ENOMEM;
5480 
5481 	mqe = &mboxq->u.mqe;
5482 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5483 		rc = -ENOMEM;
5484 		goto out_free_mboxq;
5485 	}
5486 
5487 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5488 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5489 
5490 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5491 			"(%d):2571 Mailbox cmd x%x Status x%x "
5492 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5493 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5494 			"CQ: x%x x%x x%x x%x\n",
5495 			mboxq->vport ? mboxq->vport->vpi : 0,
5496 			bf_get(lpfc_mqe_command, mqe),
5497 			bf_get(lpfc_mqe_status, mqe),
5498 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5499 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5500 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5501 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5502 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5503 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5504 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5505 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5506 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5507 			mboxq->mcqe.word0,
5508 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5509 			mboxq->mcqe.trailer);
5510 
5511 	if (rc) {
5512 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5513 		kfree(mp);
5514 		rc = -EIO;
5515 		goto out_free_mboxq;
5516 	}
5517 	data_length = mqe->un.mb_words[5];
5518 	if (data_length > DMP_RGN23_SIZE) {
5519 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5520 		kfree(mp);
5521 		rc = -EIO;
5522 		goto out_free_mboxq;
5523 	}
5524 
5525 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5526 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
5527 	kfree(mp);
5528 	rc = 0;
5529 
5530 out_free_mboxq:
5531 	mempool_free(mboxq, phba->mbox_mem_pool);
5532 	return rc;
5533 }
5534 
5535 /**
5536  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5537  * @phba: pointer to lpfc hba data structure.
5538  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5539  * @vpd: pointer to the memory to hold resulting port vpd data.
5540  * @vpd_size: On input, the number of bytes allocated to @vpd.
5541  *	      On output, the number of data bytes in @vpd.
5542  *
5543  * This routine executes a READ_REV SLI4 mailbox command.  In
5544  * addition, this routine gets the port vpd data.
5545  *
5546  * Return codes
5547  * 	0 - successful
5548  * 	-ENOMEM - could not allocated memory.
5549  **/
5550 static int
5551 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5552 		    uint8_t *vpd, uint32_t *vpd_size)
5553 {
5554 	int rc = 0;
5555 	uint32_t dma_size;
5556 	struct lpfc_dmabuf *dmabuf;
5557 	struct lpfc_mqe *mqe;
5558 
5559 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5560 	if (!dmabuf)
5561 		return -ENOMEM;
5562 
5563 	/*
5564 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5565 	 * mailbox command.
5566 	 */
5567 	dma_size = *vpd_size;
5568 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5569 					  &dmabuf->phys, GFP_KERNEL);
5570 	if (!dmabuf->virt) {
5571 		kfree(dmabuf);
5572 		return -ENOMEM;
5573 	}
5574 
5575 	/*
5576 	 * The SLI4 implementation of READ_REV conflicts at word1,
5577 	 * bits 31:16 and SLI4 adds vpd functionality not present
5578 	 * in SLI3.  This code corrects the conflicts.
5579 	 */
5580 	lpfc_read_rev(phba, mboxq);
5581 	mqe = &mboxq->u.mqe;
5582 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5583 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5584 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5585 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5586 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5587 
5588 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5589 	if (rc) {
5590 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5591 				  dmabuf->virt, dmabuf->phys);
5592 		kfree(dmabuf);
5593 		return -EIO;
5594 	}
5595 
5596 	/*
5597 	 * The available vpd length cannot be bigger than the
5598 	 * DMA buffer passed to the port.  Catch the less than
5599 	 * case and update the caller's size.
5600 	 */
5601 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5602 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5603 
5604 	memcpy(vpd, dmabuf->virt, *vpd_size);
5605 
5606 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5607 			  dmabuf->virt, dmabuf->phys);
5608 	kfree(dmabuf);
5609 	return 0;
5610 }
5611 
5612 /**
5613  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5614  * @phba: pointer to lpfc hba data structure.
5615  *
5616  * This routine retrieves SLI4 device physical port name this PCI function
5617  * is attached to.
5618  *
5619  * Return codes
5620  *      0 - successful
5621  *      otherwise - failed to retrieve controller attributes
5622  **/
5623 static int
5624 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5625 {
5626 	LPFC_MBOXQ_t *mboxq;
5627 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5628 	struct lpfc_controller_attribute *cntl_attr;
5629 	void *virtaddr = NULL;
5630 	uint32_t alloclen, reqlen;
5631 	uint32_t shdr_status, shdr_add_status;
5632 	union lpfc_sli4_cfg_shdr *shdr;
5633 	int rc;
5634 
5635 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5636 	if (!mboxq)
5637 		return -ENOMEM;
5638 
5639 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5640 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5641 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5642 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5643 			LPFC_SLI4_MBX_NEMBED);
5644 
5645 	if (alloclen < reqlen) {
5646 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5647 				"3084 Allocated DMA memory size (%d) is "
5648 				"less than the requested DMA memory size "
5649 				"(%d)\n", alloclen, reqlen);
5650 		rc = -ENOMEM;
5651 		goto out_free_mboxq;
5652 	}
5653 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5654 	virtaddr = mboxq->sge_array->addr[0];
5655 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5656 	shdr = &mbx_cntl_attr->cfg_shdr;
5657 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5658 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5659 	if (shdr_status || shdr_add_status || rc) {
5660 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5661 				"3085 Mailbox x%x (x%x/x%x) failed, "
5662 				"rc:x%x, status:x%x, add_status:x%x\n",
5663 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5664 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5665 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5666 				rc, shdr_status, shdr_add_status);
5667 		rc = -ENXIO;
5668 		goto out_free_mboxq;
5669 	}
5670 
5671 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5672 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5673 	phba->sli4_hba.lnk_info.lnk_tp =
5674 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5675 	phba->sli4_hba.lnk_info.lnk_no =
5676 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5677 
5678 	memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
5679 	strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
5680 		sizeof(phba->BIOSVersion));
5681 
5682 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5683 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s\n",
5684 			phba->sli4_hba.lnk_info.lnk_tp,
5685 			phba->sli4_hba.lnk_info.lnk_no,
5686 			phba->BIOSVersion);
5687 out_free_mboxq:
5688 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5689 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
5690 	else
5691 		mempool_free(mboxq, phba->mbox_mem_pool);
5692 	return rc;
5693 }
5694 
5695 /**
5696  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
5697  * @phba: pointer to lpfc hba data structure.
5698  *
5699  * This routine retrieves SLI4 device physical port name this PCI function
5700  * is attached to.
5701  *
5702  * Return codes
5703  *      0 - successful
5704  *      otherwise - failed to retrieve physical port name
5705  **/
5706 static int
5707 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
5708 {
5709 	LPFC_MBOXQ_t *mboxq;
5710 	struct lpfc_mbx_get_port_name *get_port_name;
5711 	uint32_t shdr_status, shdr_add_status;
5712 	union lpfc_sli4_cfg_shdr *shdr;
5713 	char cport_name = 0;
5714 	int rc;
5715 
5716 	/* We assume nothing at this point */
5717 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5718 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
5719 
5720 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5721 	if (!mboxq)
5722 		return -ENOMEM;
5723 	/* obtain link type and link number via READ_CONFIG */
5724 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5725 	lpfc_sli4_read_config(phba);
5726 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
5727 		goto retrieve_ppname;
5728 
5729 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
5730 	rc = lpfc_sli4_get_ctl_attr(phba);
5731 	if (rc)
5732 		goto out_free_mboxq;
5733 
5734 retrieve_ppname:
5735 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5736 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
5737 		sizeof(struct lpfc_mbx_get_port_name) -
5738 		sizeof(struct lpfc_sli4_cfg_mhdr),
5739 		LPFC_SLI4_MBX_EMBED);
5740 	get_port_name = &mboxq->u.mqe.un.get_port_name;
5741 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5742 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
5743 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
5744 		phba->sli4_hba.lnk_info.lnk_tp);
5745 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5746 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5747 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5748 	if (shdr_status || shdr_add_status || rc) {
5749 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5750 				"3087 Mailbox x%x (x%x/x%x) failed: "
5751 				"rc:x%x, status:x%x, add_status:x%x\n",
5752 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5753 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5754 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5755 				rc, shdr_status, shdr_add_status);
5756 		rc = -ENXIO;
5757 		goto out_free_mboxq;
5758 	}
5759 	switch (phba->sli4_hba.lnk_info.lnk_no) {
5760 	case LPFC_LINK_NUMBER_0:
5761 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
5762 				&get_port_name->u.response);
5763 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5764 		break;
5765 	case LPFC_LINK_NUMBER_1:
5766 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
5767 				&get_port_name->u.response);
5768 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5769 		break;
5770 	case LPFC_LINK_NUMBER_2:
5771 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
5772 				&get_port_name->u.response);
5773 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5774 		break;
5775 	case LPFC_LINK_NUMBER_3:
5776 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
5777 				&get_port_name->u.response);
5778 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5779 		break;
5780 	default:
5781 		break;
5782 	}
5783 
5784 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
5785 		phba->Port[0] = cport_name;
5786 		phba->Port[1] = '\0';
5787 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5788 				"3091 SLI get port name: %s\n", phba->Port);
5789 	}
5790 
5791 out_free_mboxq:
5792 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5793 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
5794 	else
5795 		mempool_free(mboxq, phba->mbox_mem_pool);
5796 	return rc;
5797 }
5798 
5799 /**
5800  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
5801  * @phba: pointer to lpfc hba data structure.
5802  *
5803  * This routine is called to explicitly arm the SLI4 device's completion and
5804  * event queues
5805  **/
5806 static void
5807 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
5808 {
5809 	int qidx;
5810 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
5811 	struct lpfc_sli4_hdw_queue *qp;
5812 	struct lpfc_queue *eq;
5813 
5814 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
5815 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
5816 	if (sli4_hba->nvmels_cq)
5817 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
5818 					   LPFC_QUEUE_REARM);
5819 
5820 	if (sli4_hba->hdwq) {
5821 		/* Loop thru all Hardware Queues */
5822 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
5823 			qp = &sli4_hba->hdwq[qidx];
5824 			/* ARM the corresponding CQ */
5825 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
5826 						LPFC_QUEUE_REARM);
5827 		}
5828 
5829 		/* Loop thru all IRQ vectors */
5830 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
5831 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
5832 			/* ARM the corresponding EQ */
5833 			sli4_hba->sli4_write_eq_db(phba, eq,
5834 						   0, LPFC_QUEUE_REARM);
5835 		}
5836 	}
5837 
5838 	if (phba->nvmet_support) {
5839 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
5840 			sli4_hba->sli4_write_cq_db(phba,
5841 				sli4_hba->nvmet_cqset[qidx], 0,
5842 				LPFC_QUEUE_REARM);
5843 		}
5844 	}
5845 }
5846 
5847 /**
5848  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
5849  * @phba: Pointer to HBA context object.
5850  * @type: The resource extent type.
5851  * @extnt_count: buffer to hold port available extent count.
5852  * @extnt_size: buffer to hold element count per extent.
5853  *
5854  * This function calls the port and retrievs the number of available
5855  * extents and their size for a particular extent type.
5856  *
5857  * Returns: 0 if successful.  Nonzero otherwise.
5858  **/
5859 int
5860 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
5861 			       uint16_t *extnt_count, uint16_t *extnt_size)
5862 {
5863 	int rc = 0;
5864 	uint32_t length;
5865 	uint32_t mbox_tmo;
5866 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
5867 	LPFC_MBOXQ_t *mbox;
5868 
5869 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5870 	if (!mbox)
5871 		return -ENOMEM;
5872 
5873 	/* Find out how many extents are available for this resource type */
5874 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
5875 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5876 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5877 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
5878 			 length, LPFC_SLI4_MBX_EMBED);
5879 
5880 	/* Send an extents count of 0 - the GET doesn't use it. */
5881 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5882 					LPFC_SLI4_MBX_EMBED);
5883 	if (unlikely(rc)) {
5884 		rc = -EIO;
5885 		goto err_exit;
5886 	}
5887 
5888 	if (!phba->sli4_hba.intr_enable)
5889 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5890 	else {
5891 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5892 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5893 	}
5894 	if (unlikely(rc)) {
5895 		rc = -EIO;
5896 		goto err_exit;
5897 	}
5898 
5899 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
5900 	if (bf_get(lpfc_mbox_hdr_status,
5901 		   &rsrc_info->header.cfg_shdr.response)) {
5902 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5903 				"2930 Failed to get resource extents "
5904 				"Status 0x%x Add'l Status 0x%x\n",
5905 				bf_get(lpfc_mbox_hdr_status,
5906 				       &rsrc_info->header.cfg_shdr.response),
5907 				bf_get(lpfc_mbox_hdr_add_status,
5908 				       &rsrc_info->header.cfg_shdr.response));
5909 		rc = -EIO;
5910 		goto err_exit;
5911 	}
5912 
5913 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
5914 			      &rsrc_info->u.rsp);
5915 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
5916 			     &rsrc_info->u.rsp);
5917 
5918 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5919 			"3162 Retrieved extents type-%d from port: count:%d, "
5920 			"size:%d\n", type, *extnt_count, *extnt_size);
5921 
5922 err_exit:
5923 	mempool_free(mbox, phba->mbox_mem_pool);
5924 	return rc;
5925 }
5926 
5927 /**
5928  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
5929  * @phba: Pointer to HBA context object.
5930  * @type: The extent type to check.
5931  *
5932  * This function reads the current available extents from the port and checks
5933  * if the extent count or extent size has changed since the last access.
5934  * Callers use this routine post port reset to understand if there is a
5935  * extent reprovisioning requirement.
5936  *
5937  * Returns:
5938  *   -Error: error indicates problem.
5939  *   1: Extent count or size has changed.
5940  *   0: No changes.
5941  **/
5942 static int
5943 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
5944 {
5945 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
5946 	uint16_t size_diff, rsrc_ext_size;
5947 	int rc = 0;
5948 	struct lpfc_rsrc_blks *rsrc_entry;
5949 	struct list_head *rsrc_blk_list = NULL;
5950 
5951 	size_diff = 0;
5952 	curr_ext_cnt = 0;
5953 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5954 					    &rsrc_ext_cnt,
5955 					    &rsrc_ext_size);
5956 	if (unlikely(rc))
5957 		return -EIO;
5958 
5959 	switch (type) {
5960 	case LPFC_RSC_TYPE_FCOE_RPI:
5961 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5962 		break;
5963 	case LPFC_RSC_TYPE_FCOE_VPI:
5964 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
5965 		break;
5966 	case LPFC_RSC_TYPE_FCOE_XRI:
5967 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5968 		break;
5969 	case LPFC_RSC_TYPE_FCOE_VFI:
5970 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5971 		break;
5972 	default:
5973 		break;
5974 	}
5975 
5976 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
5977 		curr_ext_cnt++;
5978 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
5979 			size_diff++;
5980 	}
5981 
5982 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
5983 		rc = 1;
5984 
5985 	return rc;
5986 }
5987 
5988 /**
5989  * lpfc_sli4_cfg_post_extnts -
5990  * @phba: Pointer to HBA context object.
5991  * @extnt_cnt: number of available extents.
5992  * @type: the extent type (rpi, xri, vfi, vpi).
5993  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
5994  * @mbox: pointer to the caller's allocated mailbox structure.
5995  *
5996  * This function executes the extents allocation request.  It also
5997  * takes care of the amount of memory needed to allocate or get the
5998  * allocated extents. It is the caller's responsibility to evaluate
5999  * the response.
6000  *
6001  * Returns:
6002  *   -Error:  Error value describes the condition found.
6003  *   0: if successful
6004  **/
6005 static int
6006 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6007 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6008 {
6009 	int rc = 0;
6010 	uint32_t req_len;
6011 	uint32_t emb_len;
6012 	uint32_t alloc_len, mbox_tmo;
6013 
6014 	/* Calculate the total requested length of the dma memory */
6015 	req_len = extnt_cnt * sizeof(uint16_t);
6016 
6017 	/*
6018 	 * Calculate the size of an embedded mailbox.  The uint32_t
6019 	 * accounts for extents-specific word.
6020 	 */
6021 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6022 		sizeof(uint32_t);
6023 
6024 	/*
6025 	 * Presume the allocation and response will fit into an embedded
6026 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6027 	 */
6028 	*emb = LPFC_SLI4_MBX_EMBED;
6029 	if (req_len > emb_len) {
6030 		req_len = extnt_cnt * sizeof(uint16_t) +
6031 			sizeof(union lpfc_sli4_cfg_shdr) +
6032 			sizeof(uint32_t);
6033 		*emb = LPFC_SLI4_MBX_NEMBED;
6034 	}
6035 
6036 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6037 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6038 				     req_len, *emb);
6039 	if (alloc_len < req_len) {
6040 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6041 			"2982 Allocated DMA memory size (x%x) is "
6042 			"less than the requested DMA memory "
6043 			"size (x%x)\n", alloc_len, req_len);
6044 		return -ENOMEM;
6045 	}
6046 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6047 	if (unlikely(rc))
6048 		return -EIO;
6049 
6050 	if (!phba->sli4_hba.intr_enable)
6051 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6052 	else {
6053 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6054 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6055 	}
6056 
6057 	if (unlikely(rc))
6058 		rc = -EIO;
6059 	return rc;
6060 }
6061 
6062 /**
6063  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6064  * @phba: Pointer to HBA context object.
6065  * @type:  The resource extent type to allocate.
6066  *
6067  * This function allocates the number of elements for the specified
6068  * resource type.
6069  **/
6070 static int
6071 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6072 {
6073 	bool emb = false;
6074 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6075 	uint16_t rsrc_id, rsrc_start, j, k;
6076 	uint16_t *ids;
6077 	int i, rc;
6078 	unsigned long longs;
6079 	unsigned long *bmask;
6080 	struct lpfc_rsrc_blks *rsrc_blks;
6081 	LPFC_MBOXQ_t *mbox;
6082 	uint32_t length;
6083 	struct lpfc_id_range *id_array = NULL;
6084 	void *virtaddr = NULL;
6085 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6086 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6087 	struct list_head *ext_blk_list;
6088 
6089 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6090 					    &rsrc_cnt,
6091 					    &rsrc_size);
6092 	if (unlikely(rc))
6093 		return -EIO;
6094 
6095 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6096 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6097 			"3009 No available Resource Extents "
6098 			"for resource type 0x%x: Count: 0x%x, "
6099 			"Size 0x%x\n", type, rsrc_cnt,
6100 			rsrc_size);
6101 		return -ENOMEM;
6102 	}
6103 
6104 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6105 			"2903 Post resource extents type-0x%x: "
6106 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6107 
6108 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6109 	if (!mbox)
6110 		return -ENOMEM;
6111 
6112 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6113 	if (unlikely(rc)) {
6114 		rc = -EIO;
6115 		goto err_exit;
6116 	}
6117 
6118 	/*
6119 	 * Figure out where the response is located.  Then get local pointers
6120 	 * to the response data.  The port does not guarantee to respond to
6121 	 * all extents counts request so update the local variable with the
6122 	 * allocated count from the port.
6123 	 */
6124 	if (emb == LPFC_SLI4_MBX_EMBED) {
6125 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6126 		id_array = &rsrc_ext->u.rsp.id[0];
6127 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6128 	} else {
6129 		virtaddr = mbox->sge_array->addr[0];
6130 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6131 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6132 		id_array = &n_rsrc->id;
6133 	}
6134 
6135 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6136 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6137 
6138 	/*
6139 	 * Based on the resource size and count, correct the base and max
6140 	 * resource values.
6141 	 */
6142 	length = sizeof(struct lpfc_rsrc_blks);
6143 	switch (type) {
6144 	case LPFC_RSC_TYPE_FCOE_RPI:
6145 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6146 						   sizeof(unsigned long),
6147 						   GFP_KERNEL);
6148 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6149 			rc = -ENOMEM;
6150 			goto err_exit;
6151 		}
6152 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6153 						 sizeof(uint16_t),
6154 						 GFP_KERNEL);
6155 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6156 			kfree(phba->sli4_hba.rpi_bmask);
6157 			rc = -ENOMEM;
6158 			goto err_exit;
6159 		}
6160 
6161 		/*
6162 		 * The next_rpi was initialized with the maximum available
6163 		 * count but the port may allocate a smaller number.  Catch
6164 		 * that case and update the next_rpi.
6165 		 */
6166 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6167 
6168 		/* Initialize local ptrs for common extent processing later. */
6169 		bmask = phba->sli4_hba.rpi_bmask;
6170 		ids = phba->sli4_hba.rpi_ids;
6171 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6172 		break;
6173 	case LPFC_RSC_TYPE_FCOE_VPI:
6174 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6175 					  GFP_KERNEL);
6176 		if (unlikely(!phba->vpi_bmask)) {
6177 			rc = -ENOMEM;
6178 			goto err_exit;
6179 		}
6180 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6181 					 GFP_KERNEL);
6182 		if (unlikely(!phba->vpi_ids)) {
6183 			kfree(phba->vpi_bmask);
6184 			rc = -ENOMEM;
6185 			goto err_exit;
6186 		}
6187 
6188 		/* Initialize local ptrs for common extent processing later. */
6189 		bmask = phba->vpi_bmask;
6190 		ids = phba->vpi_ids;
6191 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6192 		break;
6193 	case LPFC_RSC_TYPE_FCOE_XRI:
6194 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6195 						   sizeof(unsigned long),
6196 						   GFP_KERNEL);
6197 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6198 			rc = -ENOMEM;
6199 			goto err_exit;
6200 		}
6201 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6202 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6203 						 sizeof(uint16_t),
6204 						 GFP_KERNEL);
6205 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6206 			kfree(phba->sli4_hba.xri_bmask);
6207 			rc = -ENOMEM;
6208 			goto err_exit;
6209 		}
6210 
6211 		/* Initialize local ptrs for common extent processing later. */
6212 		bmask = phba->sli4_hba.xri_bmask;
6213 		ids = phba->sli4_hba.xri_ids;
6214 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6215 		break;
6216 	case LPFC_RSC_TYPE_FCOE_VFI:
6217 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6218 						   sizeof(unsigned long),
6219 						   GFP_KERNEL);
6220 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6221 			rc = -ENOMEM;
6222 			goto err_exit;
6223 		}
6224 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6225 						 sizeof(uint16_t),
6226 						 GFP_KERNEL);
6227 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6228 			kfree(phba->sli4_hba.vfi_bmask);
6229 			rc = -ENOMEM;
6230 			goto err_exit;
6231 		}
6232 
6233 		/* Initialize local ptrs for common extent processing later. */
6234 		bmask = phba->sli4_hba.vfi_bmask;
6235 		ids = phba->sli4_hba.vfi_ids;
6236 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6237 		break;
6238 	default:
6239 		/* Unsupported Opcode.  Fail call. */
6240 		id_array = NULL;
6241 		bmask = NULL;
6242 		ids = NULL;
6243 		ext_blk_list = NULL;
6244 		goto err_exit;
6245 	}
6246 
6247 	/*
6248 	 * Complete initializing the extent configuration with the
6249 	 * allocated ids assigned to this function.  The bitmask serves
6250 	 * as an index into the array and manages the available ids.  The
6251 	 * array just stores the ids communicated to the port via the wqes.
6252 	 */
6253 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6254 		if ((i % 2) == 0)
6255 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6256 					 &id_array[k]);
6257 		else
6258 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6259 					 &id_array[k]);
6260 
6261 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6262 		if (unlikely(!rsrc_blks)) {
6263 			rc = -ENOMEM;
6264 			kfree(bmask);
6265 			kfree(ids);
6266 			goto err_exit;
6267 		}
6268 		rsrc_blks->rsrc_start = rsrc_id;
6269 		rsrc_blks->rsrc_size = rsrc_size;
6270 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6271 		rsrc_start = rsrc_id;
6272 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6273 			phba->sli4_hba.io_xri_start = rsrc_start +
6274 				lpfc_sli4_get_iocb_cnt(phba);
6275 		}
6276 
6277 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6278 			ids[j] = rsrc_id;
6279 			rsrc_id++;
6280 			j++;
6281 		}
6282 		/* Entire word processed.  Get next word.*/
6283 		if ((i % 2) == 1)
6284 			k++;
6285 	}
6286  err_exit:
6287 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6288 	return rc;
6289 }
6290 
6291 
6292 
6293 /**
6294  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6295  * @phba: Pointer to HBA context object.
6296  * @type: the extent's type.
6297  *
6298  * This function deallocates all extents of a particular resource type.
6299  * SLI4 does not allow for deallocating a particular extent range.  It
6300  * is the caller's responsibility to release all kernel memory resources.
6301  **/
6302 static int
6303 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6304 {
6305 	int rc;
6306 	uint32_t length, mbox_tmo = 0;
6307 	LPFC_MBOXQ_t *mbox;
6308 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6309 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6310 
6311 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6312 	if (!mbox)
6313 		return -ENOMEM;
6314 
6315 	/*
6316 	 * This function sends an embedded mailbox because it only sends the
6317 	 * the resource type.  All extents of this type are released by the
6318 	 * port.
6319 	 */
6320 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6321 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6322 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6323 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6324 			 length, LPFC_SLI4_MBX_EMBED);
6325 
6326 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6327 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6328 					LPFC_SLI4_MBX_EMBED);
6329 	if (unlikely(rc)) {
6330 		rc = -EIO;
6331 		goto out_free_mbox;
6332 	}
6333 	if (!phba->sli4_hba.intr_enable)
6334 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6335 	else {
6336 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6337 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6338 	}
6339 	if (unlikely(rc)) {
6340 		rc = -EIO;
6341 		goto out_free_mbox;
6342 	}
6343 
6344 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6345 	if (bf_get(lpfc_mbox_hdr_status,
6346 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6347 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6348 				"2919 Failed to release resource extents "
6349 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6350 				"Resource memory not released.\n",
6351 				type,
6352 				bf_get(lpfc_mbox_hdr_status,
6353 				    &dealloc_rsrc->header.cfg_shdr.response),
6354 				bf_get(lpfc_mbox_hdr_add_status,
6355 				    &dealloc_rsrc->header.cfg_shdr.response));
6356 		rc = -EIO;
6357 		goto out_free_mbox;
6358 	}
6359 
6360 	/* Release kernel memory resources for the specific type. */
6361 	switch (type) {
6362 	case LPFC_RSC_TYPE_FCOE_VPI:
6363 		kfree(phba->vpi_bmask);
6364 		kfree(phba->vpi_ids);
6365 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6366 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6367 				    &phba->lpfc_vpi_blk_list, list) {
6368 			list_del_init(&rsrc_blk->list);
6369 			kfree(rsrc_blk);
6370 		}
6371 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6372 		break;
6373 	case LPFC_RSC_TYPE_FCOE_XRI:
6374 		kfree(phba->sli4_hba.xri_bmask);
6375 		kfree(phba->sli4_hba.xri_ids);
6376 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6377 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6378 			list_del_init(&rsrc_blk->list);
6379 			kfree(rsrc_blk);
6380 		}
6381 		break;
6382 	case LPFC_RSC_TYPE_FCOE_VFI:
6383 		kfree(phba->sli4_hba.vfi_bmask);
6384 		kfree(phba->sli4_hba.vfi_ids);
6385 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6386 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6387 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6388 			list_del_init(&rsrc_blk->list);
6389 			kfree(rsrc_blk);
6390 		}
6391 		break;
6392 	case LPFC_RSC_TYPE_FCOE_RPI:
6393 		/* RPI bitmask and physical id array are cleaned up earlier. */
6394 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6395 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6396 			list_del_init(&rsrc_blk->list);
6397 			kfree(rsrc_blk);
6398 		}
6399 		break;
6400 	default:
6401 		break;
6402 	}
6403 
6404 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6405 
6406  out_free_mbox:
6407 	mempool_free(mbox, phba->mbox_mem_pool);
6408 	return rc;
6409 }
6410 
6411 static void
6412 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6413 		  uint32_t feature)
6414 {
6415 	uint32_t len;
6416 
6417 	len = sizeof(struct lpfc_mbx_set_feature) -
6418 		sizeof(struct lpfc_sli4_cfg_mhdr);
6419 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6420 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6421 			 LPFC_SLI4_MBX_EMBED);
6422 
6423 	switch (feature) {
6424 	case LPFC_SET_UE_RECOVERY:
6425 		bf_set(lpfc_mbx_set_feature_UER,
6426 		       &mbox->u.mqe.un.set_feature, 1);
6427 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6428 		mbox->u.mqe.un.set_feature.param_len = 8;
6429 		break;
6430 	case LPFC_SET_MDS_DIAGS:
6431 		bf_set(lpfc_mbx_set_feature_mds,
6432 		       &mbox->u.mqe.un.set_feature, 1);
6433 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6434 		       &mbox->u.mqe.un.set_feature, 1);
6435 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6436 		mbox->u.mqe.un.set_feature.param_len = 8;
6437 		break;
6438 	case LPFC_SET_DUAL_DUMP:
6439 		bf_set(lpfc_mbx_set_feature_dd,
6440 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6441 		bf_set(lpfc_mbx_set_feature_ddquery,
6442 		       &mbox->u.mqe.un.set_feature, 0);
6443 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6444 		mbox->u.mqe.un.set_feature.param_len = 4;
6445 		break;
6446 	}
6447 
6448 	return;
6449 }
6450 
6451 /**
6452  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6453  * @phba: Pointer to HBA context object.
6454  *
6455  * Disable FW logging into host memory on the adapter. To
6456  * be done before reading logs from the host memory.
6457  **/
6458 void
6459 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6460 {
6461 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6462 
6463 	spin_lock_irq(&phba->hbalock);
6464 	ras_fwlog->state = INACTIVE;
6465 	spin_unlock_irq(&phba->hbalock);
6466 
6467 	/* Disable FW logging to host memory */
6468 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6469 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6470 
6471 	/* Wait 10ms for firmware to stop using DMA buffer */
6472 	usleep_range(10 * 1000, 20 * 1000);
6473 }
6474 
6475 /**
6476  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6477  * @phba: Pointer to HBA context object.
6478  *
6479  * This function is called to free memory allocated for RAS FW logging
6480  * support in the driver.
6481  **/
6482 void
6483 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6484 {
6485 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6486 	struct lpfc_dmabuf *dmabuf, *next;
6487 
6488 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6489 		list_for_each_entry_safe(dmabuf, next,
6490 				    &ras_fwlog->fwlog_buff_list,
6491 				    list) {
6492 			list_del(&dmabuf->list);
6493 			dma_free_coherent(&phba->pcidev->dev,
6494 					  LPFC_RAS_MAX_ENTRY_SIZE,
6495 					  dmabuf->virt, dmabuf->phys);
6496 			kfree(dmabuf);
6497 		}
6498 	}
6499 
6500 	if (ras_fwlog->lwpd.virt) {
6501 		dma_free_coherent(&phba->pcidev->dev,
6502 				  sizeof(uint32_t) * 2,
6503 				  ras_fwlog->lwpd.virt,
6504 				  ras_fwlog->lwpd.phys);
6505 		ras_fwlog->lwpd.virt = NULL;
6506 	}
6507 
6508 	spin_lock_irq(&phba->hbalock);
6509 	ras_fwlog->state = INACTIVE;
6510 	spin_unlock_irq(&phba->hbalock);
6511 }
6512 
6513 /**
6514  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6515  * @phba: Pointer to HBA context object.
6516  * @fwlog_buff_count: Count of buffers to be created.
6517  *
6518  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6519  * to update FW log is posted to the adapter.
6520  * Buffer count is calculated based on module param ras_fwlog_buffsize
6521  * Size of each buffer posted to FW is 64K.
6522  **/
6523 
6524 static int
6525 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6526 			uint32_t fwlog_buff_count)
6527 {
6528 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6529 	struct lpfc_dmabuf *dmabuf;
6530 	int rc = 0, i = 0;
6531 
6532 	/* Initialize List */
6533 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6534 
6535 	/* Allocate memory for the LWPD */
6536 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6537 					    sizeof(uint32_t) * 2,
6538 					    &ras_fwlog->lwpd.phys,
6539 					    GFP_KERNEL);
6540 	if (!ras_fwlog->lwpd.virt) {
6541 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6542 				"6185 LWPD Memory Alloc Failed\n");
6543 
6544 		return -ENOMEM;
6545 	}
6546 
6547 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6548 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6549 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6550 				 GFP_KERNEL);
6551 		if (!dmabuf) {
6552 			rc = -ENOMEM;
6553 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6554 					"6186 Memory Alloc failed FW logging");
6555 			goto free_mem;
6556 		}
6557 
6558 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6559 						  LPFC_RAS_MAX_ENTRY_SIZE,
6560 						  &dmabuf->phys, GFP_KERNEL);
6561 		if (!dmabuf->virt) {
6562 			kfree(dmabuf);
6563 			rc = -ENOMEM;
6564 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6565 					"6187 DMA Alloc Failed FW logging");
6566 			goto free_mem;
6567 		}
6568 		dmabuf->buffer_tag = i;
6569 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6570 	}
6571 
6572 free_mem:
6573 	if (rc)
6574 		lpfc_sli4_ras_dma_free(phba);
6575 
6576 	return rc;
6577 }
6578 
6579 /**
6580  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6581  * @phba: pointer to lpfc hba data structure.
6582  * @pmb: pointer to the driver internal queue element for mailbox command.
6583  *
6584  * Completion handler for driver's RAS MBX command to the device.
6585  **/
6586 static void
6587 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6588 {
6589 	MAILBOX_t *mb;
6590 	union lpfc_sli4_cfg_shdr *shdr;
6591 	uint32_t shdr_status, shdr_add_status;
6592 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6593 
6594 	mb = &pmb->u.mb;
6595 
6596 	shdr = (union lpfc_sli4_cfg_shdr *)
6597 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6598 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6599 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6600 
6601 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6602 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6603 				"6188 FW LOG mailbox "
6604 				"completed with status x%x add_status x%x,"
6605 				" mbx status x%x\n",
6606 				shdr_status, shdr_add_status, mb->mbxStatus);
6607 
6608 		ras_fwlog->ras_hwsupport = false;
6609 		goto disable_ras;
6610 	}
6611 
6612 	spin_lock_irq(&phba->hbalock);
6613 	ras_fwlog->state = ACTIVE;
6614 	spin_unlock_irq(&phba->hbalock);
6615 	mempool_free(pmb, phba->mbox_mem_pool);
6616 
6617 	return;
6618 
6619 disable_ras:
6620 	/* Free RAS DMA memory */
6621 	lpfc_sli4_ras_dma_free(phba);
6622 	mempool_free(pmb, phba->mbox_mem_pool);
6623 }
6624 
6625 /**
6626  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
6627  * @phba: pointer to lpfc hba data structure.
6628  * @fwlog_level: Logging verbosity level.
6629  * @fwlog_enable: Enable/Disable logging.
6630  *
6631  * Initialize memory and post mailbox command to enable FW logging in host
6632  * memory.
6633  **/
6634 int
6635 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
6636 			 uint32_t fwlog_level,
6637 			 uint32_t fwlog_enable)
6638 {
6639 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6640 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
6641 	struct lpfc_dmabuf *dmabuf;
6642 	LPFC_MBOXQ_t *mbox;
6643 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
6644 	int rc = 0;
6645 
6646 	spin_lock_irq(&phba->hbalock);
6647 	ras_fwlog->state = INACTIVE;
6648 	spin_unlock_irq(&phba->hbalock);
6649 
6650 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
6651 			  phba->cfg_ras_fwlog_buffsize);
6652 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
6653 
6654 	/*
6655 	 * If re-enabling FW logging support use earlier allocated
6656 	 * DMA buffers while posting MBX command.
6657 	 **/
6658 	if (!ras_fwlog->lwpd.virt) {
6659 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
6660 		if (rc) {
6661 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6662 					"6189 FW Log Memory Allocation Failed");
6663 			return rc;
6664 		}
6665 	}
6666 
6667 	/* Setup Mailbox command */
6668 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6669 	if (!mbox) {
6670 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6671 				"6190 RAS MBX Alloc Failed");
6672 		rc = -ENOMEM;
6673 		goto mem_free;
6674 	}
6675 
6676 	ras_fwlog->fw_loglevel = fwlog_level;
6677 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
6678 		sizeof(struct lpfc_sli4_cfg_mhdr));
6679 
6680 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
6681 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
6682 			 len, LPFC_SLI4_MBX_EMBED);
6683 
6684 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
6685 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
6686 	       fwlog_enable);
6687 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
6688 	       ras_fwlog->fw_loglevel);
6689 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
6690 	       ras_fwlog->fw_buffcount);
6691 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
6692 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
6693 
6694 	/* Update DMA buffer address */
6695 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
6696 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
6697 
6698 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
6699 			putPaddrLow(dmabuf->phys);
6700 
6701 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
6702 			putPaddrHigh(dmabuf->phys);
6703 	}
6704 
6705 	/* Update LPWD address */
6706 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
6707 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
6708 
6709 	spin_lock_irq(&phba->hbalock);
6710 	ras_fwlog->state = REG_INPROGRESS;
6711 	spin_unlock_irq(&phba->hbalock);
6712 	mbox->vport = phba->pport;
6713 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
6714 
6715 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
6716 
6717 	if (rc == MBX_NOT_FINISHED) {
6718 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6719 				"6191 FW-Log Mailbox failed. "
6720 				"status %d mbxStatus : x%x", rc,
6721 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
6722 		mempool_free(mbox, phba->mbox_mem_pool);
6723 		rc = -EIO;
6724 		goto mem_free;
6725 	} else
6726 		rc = 0;
6727 mem_free:
6728 	if (rc)
6729 		lpfc_sli4_ras_dma_free(phba);
6730 
6731 	return rc;
6732 }
6733 
6734 /**
6735  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
6736  * @phba: Pointer to HBA context object.
6737  *
6738  * Check if RAS is supported on the adapter and initialize it.
6739  **/
6740 void
6741 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
6742 {
6743 	/* Check RAS FW Log needs to be enabled or not */
6744 	if (lpfc_check_fwlog_support(phba))
6745 		return;
6746 
6747 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
6748 				 LPFC_RAS_ENABLE_LOGGING);
6749 }
6750 
6751 /**
6752  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
6753  * @phba: Pointer to HBA context object.
6754  *
6755  * This function allocates all SLI4 resource identifiers.
6756  **/
6757 int
6758 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
6759 {
6760 	int i, rc, error = 0;
6761 	uint16_t count, base;
6762 	unsigned long longs;
6763 
6764 	if (!phba->sli4_hba.rpi_hdrs_in_use)
6765 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
6766 	if (phba->sli4_hba.extents_in_use) {
6767 		/*
6768 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
6769 		 * resource extent count must be read and allocated before
6770 		 * provisioning the resource id arrays.
6771 		 */
6772 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6773 		    LPFC_IDX_RSRC_RDY) {
6774 			/*
6775 			 * Extent-based resources are set - the driver could
6776 			 * be in a port reset. Figure out if any corrective
6777 			 * actions need to be taken.
6778 			 */
6779 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6780 						 LPFC_RSC_TYPE_FCOE_VFI);
6781 			if (rc != 0)
6782 				error++;
6783 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6784 						 LPFC_RSC_TYPE_FCOE_VPI);
6785 			if (rc != 0)
6786 				error++;
6787 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6788 						 LPFC_RSC_TYPE_FCOE_XRI);
6789 			if (rc != 0)
6790 				error++;
6791 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6792 						 LPFC_RSC_TYPE_FCOE_RPI);
6793 			if (rc != 0)
6794 				error++;
6795 
6796 			/*
6797 			 * It's possible that the number of resources
6798 			 * provided to this port instance changed between
6799 			 * resets.  Detect this condition and reallocate
6800 			 * resources.  Otherwise, there is no action.
6801 			 */
6802 			if (error) {
6803 				lpfc_printf_log(phba, KERN_INFO,
6804 						LOG_MBOX | LOG_INIT,
6805 						"2931 Detected extent resource "
6806 						"change.  Reallocating all "
6807 						"extents.\n");
6808 				rc = lpfc_sli4_dealloc_extent(phba,
6809 						 LPFC_RSC_TYPE_FCOE_VFI);
6810 				rc = lpfc_sli4_dealloc_extent(phba,
6811 						 LPFC_RSC_TYPE_FCOE_VPI);
6812 				rc = lpfc_sli4_dealloc_extent(phba,
6813 						 LPFC_RSC_TYPE_FCOE_XRI);
6814 				rc = lpfc_sli4_dealloc_extent(phba,
6815 						 LPFC_RSC_TYPE_FCOE_RPI);
6816 			} else
6817 				return 0;
6818 		}
6819 
6820 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6821 		if (unlikely(rc))
6822 			goto err_exit;
6823 
6824 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6825 		if (unlikely(rc))
6826 			goto err_exit;
6827 
6828 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6829 		if (unlikely(rc))
6830 			goto err_exit;
6831 
6832 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6833 		if (unlikely(rc))
6834 			goto err_exit;
6835 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6836 		       LPFC_IDX_RSRC_RDY);
6837 		return rc;
6838 	} else {
6839 		/*
6840 		 * The port does not support resource extents.  The XRI, VPI,
6841 		 * VFI, RPI resource ids were determined from READ_CONFIG.
6842 		 * Just allocate the bitmasks and provision the resource id
6843 		 * arrays.  If a port reset is active, the resources don't
6844 		 * need any action - just exit.
6845 		 */
6846 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6847 		    LPFC_IDX_RSRC_RDY) {
6848 			lpfc_sli4_dealloc_resource_identifiers(phba);
6849 			lpfc_sli4_remove_rpis(phba);
6850 		}
6851 		/* RPIs. */
6852 		count = phba->sli4_hba.max_cfg_param.max_rpi;
6853 		if (count <= 0) {
6854 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6855 					"3279 Invalid provisioning of "
6856 					"rpi:%d\n", count);
6857 			rc = -EINVAL;
6858 			goto err_exit;
6859 		}
6860 		base = phba->sli4_hba.max_cfg_param.rpi_base;
6861 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6862 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6863 						   sizeof(unsigned long),
6864 						   GFP_KERNEL);
6865 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6866 			rc = -ENOMEM;
6867 			goto err_exit;
6868 		}
6869 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
6870 						 GFP_KERNEL);
6871 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6872 			rc = -ENOMEM;
6873 			goto free_rpi_bmask;
6874 		}
6875 
6876 		for (i = 0; i < count; i++)
6877 			phba->sli4_hba.rpi_ids[i] = base + i;
6878 
6879 		/* VPIs. */
6880 		count = phba->sli4_hba.max_cfg_param.max_vpi;
6881 		if (count <= 0) {
6882 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6883 					"3280 Invalid provisioning of "
6884 					"vpi:%d\n", count);
6885 			rc = -EINVAL;
6886 			goto free_rpi_ids;
6887 		}
6888 		base = phba->sli4_hba.max_cfg_param.vpi_base;
6889 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6890 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6891 					  GFP_KERNEL);
6892 		if (unlikely(!phba->vpi_bmask)) {
6893 			rc = -ENOMEM;
6894 			goto free_rpi_ids;
6895 		}
6896 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
6897 					GFP_KERNEL);
6898 		if (unlikely(!phba->vpi_ids)) {
6899 			rc = -ENOMEM;
6900 			goto free_vpi_bmask;
6901 		}
6902 
6903 		for (i = 0; i < count; i++)
6904 			phba->vpi_ids[i] = base + i;
6905 
6906 		/* XRIs. */
6907 		count = phba->sli4_hba.max_cfg_param.max_xri;
6908 		if (count <= 0) {
6909 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6910 					"3281 Invalid provisioning of "
6911 					"xri:%d\n", count);
6912 			rc = -EINVAL;
6913 			goto free_vpi_ids;
6914 		}
6915 		base = phba->sli4_hba.max_cfg_param.xri_base;
6916 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6917 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6918 						   sizeof(unsigned long),
6919 						   GFP_KERNEL);
6920 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6921 			rc = -ENOMEM;
6922 			goto free_vpi_ids;
6923 		}
6924 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6925 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
6926 						 GFP_KERNEL);
6927 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6928 			rc = -ENOMEM;
6929 			goto free_xri_bmask;
6930 		}
6931 
6932 		for (i = 0; i < count; i++)
6933 			phba->sli4_hba.xri_ids[i] = base + i;
6934 
6935 		/* VFIs. */
6936 		count = phba->sli4_hba.max_cfg_param.max_vfi;
6937 		if (count <= 0) {
6938 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6939 					"3282 Invalid provisioning of "
6940 					"vfi:%d\n", count);
6941 			rc = -EINVAL;
6942 			goto free_xri_ids;
6943 		}
6944 		base = phba->sli4_hba.max_cfg_param.vfi_base;
6945 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6946 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6947 						   sizeof(unsigned long),
6948 						   GFP_KERNEL);
6949 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6950 			rc = -ENOMEM;
6951 			goto free_xri_ids;
6952 		}
6953 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
6954 						 GFP_KERNEL);
6955 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6956 			rc = -ENOMEM;
6957 			goto free_vfi_bmask;
6958 		}
6959 
6960 		for (i = 0; i < count; i++)
6961 			phba->sli4_hba.vfi_ids[i] = base + i;
6962 
6963 		/*
6964 		 * Mark all resources ready.  An HBA reset doesn't need
6965 		 * to reset the initialization.
6966 		 */
6967 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6968 		       LPFC_IDX_RSRC_RDY);
6969 		return 0;
6970 	}
6971 
6972  free_vfi_bmask:
6973 	kfree(phba->sli4_hba.vfi_bmask);
6974 	phba->sli4_hba.vfi_bmask = NULL;
6975  free_xri_ids:
6976 	kfree(phba->sli4_hba.xri_ids);
6977 	phba->sli4_hba.xri_ids = NULL;
6978  free_xri_bmask:
6979 	kfree(phba->sli4_hba.xri_bmask);
6980 	phba->sli4_hba.xri_bmask = NULL;
6981  free_vpi_ids:
6982 	kfree(phba->vpi_ids);
6983 	phba->vpi_ids = NULL;
6984  free_vpi_bmask:
6985 	kfree(phba->vpi_bmask);
6986 	phba->vpi_bmask = NULL;
6987  free_rpi_ids:
6988 	kfree(phba->sli4_hba.rpi_ids);
6989 	phba->sli4_hba.rpi_ids = NULL;
6990  free_rpi_bmask:
6991 	kfree(phba->sli4_hba.rpi_bmask);
6992 	phba->sli4_hba.rpi_bmask = NULL;
6993  err_exit:
6994 	return rc;
6995 }
6996 
6997 /**
6998  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
6999  * @phba: Pointer to HBA context object.
7000  *
7001  * This function allocates the number of elements for the specified
7002  * resource type.
7003  **/
7004 int
7005 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7006 {
7007 	if (phba->sli4_hba.extents_in_use) {
7008 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7009 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7010 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7011 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7012 	} else {
7013 		kfree(phba->vpi_bmask);
7014 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
7015 		kfree(phba->vpi_ids);
7016 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7017 		kfree(phba->sli4_hba.xri_bmask);
7018 		kfree(phba->sli4_hba.xri_ids);
7019 		kfree(phba->sli4_hba.vfi_bmask);
7020 		kfree(phba->sli4_hba.vfi_ids);
7021 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7022 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7023 	}
7024 
7025 	return 0;
7026 }
7027 
7028 /**
7029  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7030  * @phba: Pointer to HBA context object.
7031  * @type: The resource extent type.
7032  * @extnt_cnt: buffer to hold port extent count response
7033  * @extnt_size: buffer to hold port extent size response.
7034  *
7035  * This function calls the port to read the host allocated extents
7036  * for a particular type.
7037  **/
7038 int
7039 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7040 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
7041 {
7042 	bool emb;
7043 	int rc = 0;
7044 	uint16_t curr_blks = 0;
7045 	uint32_t req_len, emb_len;
7046 	uint32_t alloc_len, mbox_tmo;
7047 	struct list_head *blk_list_head;
7048 	struct lpfc_rsrc_blks *rsrc_blk;
7049 	LPFC_MBOXQ_t *mbox;
7050 	void *virtaddr = NULL;
7051 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7052 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7053 	union  lpfc_sli4_cfg_shdr *shdr;
7054 
7055 	switch (type) {
7056 	case LPFC_RSC_TYPE_FCOE_VPI:
7057 		blk_list_head = &phba->lpfc_vpi_blk_list;
7058 		break;
7059 	case LPFC_RSC_TYPE_FCOE_XRI:
7060 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7061 		break;
7062 	case LPFC_RSC_TYPE_FCOE_VFI:
7063 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7064 		break;
7065 	case LPFC_RSC_TYPE_FCOE_RPI:
7066 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7067 		break;
7068 	default:
7069 		return -EIO;
7070 	}
7071 
7072 	/* Count the number of extents currently allocatd for this type. */
7073 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
7074 		if (curr_blks == 0) {
7075 			/*
7076 			 * The GET_ALLOCATED mailbox does not return the size,
7077 			 * just the count.  The size should be just the size
7078 			 * stored in the current allocated block and all sizes
7079 			 * for an extent type are the same so set the return
7080 			 * value now.
7081 			 */
7082 			*extnt_size = rsrc_blk->rsrc_size;
7083 		}
7084 		curr_blks++;
7085 	}
7086 
7087 	/*
7088 	 * Calculate the size of an embedded mailbox.  The uint32_t
7089 	 * accounts for extents-specific word.
7090 	 */
7091 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7092 		sizeof(uint32_t);
7093 
7094 	/*
7095 	 * Presume the allocation and response will fit into an embedded
7096 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7097 	 */
7098 	emb = LPFC_SLI4_MBX_EMBED;
7099 	req_len = emb_len;
7100 	if (req_len > emb_len) {
7101 		req_len = curr_blks * sizeof(uint16_t) +
7102 			sizeof(union lpfc_sli4_cfg_shdr) +
7103 			sizeof(uint32_t);
7104 		emb = LPFC_SLI4_MBX_NEMBED;
7105 	}
7106 
7107 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7108 	if (!mbox)
7109 		return -ENOMEM;
7110 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7111 
7112 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7113 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7114 				     req_len, emb);
7115 	if (alloc_len < req_len) {
7116 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7117 			"2983 Allocated DMA memory size (x%x) is "
7118 			"less than the requested DMA memory "
7119 			"size (x%x)\n", alloc_len, req_len);
7120 		rc = -ENOMEM;
7121 		goto err_exit;
7122 	}
7123 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7124 	if (unlikely(rc)) {
7125 		rc = -EIO;
7126 		goto err_exit;
7127 	}
7128 
7129 	if (!phba->sli4_hba.intr_enable)
7130 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7131 	else {
7132 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7133 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7134 	}
7135 
7136 	if (unlikely(rc)) {
7137 		rc = -EIO;
7138 		goto err_exit;
7139 	}
7140 
7141 	/*
7142 	 * Figure out where the response is located.  Then get local pointers
7143 	 * to the response data.  The port does not guarantee to respond to
7144 	 * all extents counts request so update the local variable with the
7145 	 * allocated count from the port.
7146 	 */
7147 	if (emb == LPFC_SLI4_MBX_EMBED) {
7148 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7149 		shdr = &rsrc_ext->header.cfg_shdr;
7150 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7151 	} else {
7152 		virtaddr = mbox->sge_array->addr[0];
7153 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7154 		shdr = &n_rsrc->cfg_shdr;
7155 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7156 	}
7157 
7158 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7159 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7160 			"2984 Failed to read allocated resources "
7161 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7162 			type,
7163 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7164 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7165 		rc = -EIO;
7166 		goto err_exit;
7167 	}
7168  err_exit:
7169 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7170 	return rc;
7171 }
7172 
7173 /**
7174  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7175  * @phba: pointer to lpfc hba data structure.
7176  * @sgl_list: linked link of sgl buffers to post
7177  * @cnt: number of linked list buffers
7178  *
7179  * This routine walks the list of buffers that have been allocated and
7180  * repost them to the port by using SGL block post. This is needed after a
7181  * pci_function_reset/warm_start or start. It attempts to construct blocks
7182  * of buffer sgls which contains contiguous xris and uses the non-embedded
7183  * SGL block post mailbox commands to post them to the port. For single
7184  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7185  * mailbox command for posting.
7186  *
7187  * Returns: 0 = success, non-zero failure.
7188  **/
7189 static int
7190 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7191 			  struct list_head *sgl_list, int cnt)
7192 {
7193 	struct lpfc_sglq *sglq_entry = NULL;
7194 	struct lpfc_sglq *sglq_entry_next = NULL;
7195 	struct lpfc_sglq *sglq_entry_first = NULL;
7196 	int status, total_cnt;
7197 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7198 	int last_xritag = NO_XRI;
7199 	LIST_HEAD(prep_sgl_list);
7200 	LIST_HEAD(blck_sgl_list);
7201 	LIST_HEAD(allc_sgl_list);
7202 	LIST_HEAD(post_sgl_list);
7203 	LIST_HEAD(free_sgl_list);
7204 
7205 	spin_lock_irq(&phba->hbalock);
7206 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7207 	list_splice_init(sgl_list, &allc_sgl_list);
7208 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7209 	spin_unlock_irq(&phba->hbalock);
7210 
7211 	total_cnt = cnt;
7212 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7213 				 &allc_sgl_list, list) {
7214 		list_del_init(&sglq_entry->list);
7215 		block_cnt++;
7216 		if ((last_xritag != NO_XRI) &&
7217 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7218 			/* a hole in xri block, form a sgl posting block */
7219 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7220 			post_cnt = block_cnt - 1;
7221 			/* prepare list for next posting block */
7222 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7223 			block_cnt = 1;
7224 		} else {
7225 			/* prepare list for next posting block */
7226 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7227 			/* enough sgls for non-embed sgl mbox command */
7228 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7229 				list_splice_init(&prep_sgl_list,
7230 						 &blck_sgl_list);
7231 				post_cnt = block_cnt;
7232 				block_cnt = 0;
7233 			}
7234 		}
7235 		num_posted++;
7236 
7237 		/* keep track of last sgl's xritag */
7238 		last_xritag = sglq_entry->sli4_xritag;
7239 
7240 		/* end of repost sgl list condition for buffers */
7241 		if (num_posted == total_cnt) {
7242 			if (post_cnt == 0) {
7243 				list_splice_init(&prep_sgl_list,
7244 						 &blck_sgl_list);
7245 				post_cnt = block_cnt;
7246 			} else if (block_cnt == 1) {
7247 				status = lpfc_sli4_post_sgl(phba,
7248 						sglq_entry->phys, 0,
7249 						sglq_entry->sli4_xritag);
7250 				if (!status) {
7251 					/* successful, put sgl to posted list */
7252 					list_add_tail(&sglq_entry->list,
7253 						      &post_sgl_list);
7254 				} else {
7255 					/* Failure, put sgl to free list */
7256 					lpfc_printf_log(phba, KERN_WARNING,
7257 						LOG_SLI,
7258 						"3159 Failed to post "
7259 						"sgl, xritag:x%x\n",
7260 						sglq_entry->sli4_xritag);
7261 					list_add_tail(&sglq_entry->list,
7262 						      &free_sgl_list);
7263 					total_cnt--;
7264 				}
7265 			}
7266 		}
7267 
7268 		/* continue until a nembed page worth of sgls */
7269 		if (post_cnt == 0)
7270 			continue;
7271 
7272 		/* post the buffer list sgls as a block */
7273 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7274 						 post_cnt);
7275 
7276 		if (!status) {
7277 			/* success, put sgl list to posted sgl list */
7278 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7279 		} else {
7280 			/* Failure, put sgl list to free sgl list */
7281 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7282 							    struct lpfc_sglq,
7283 							    list);
7284 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7285 					"3160 Failed to post sgl-list, "
7286 					"xritag:x%x-x%x\n",
7287 					sglq_entry_first->sli4_xritag,
7288 					(sglq_entry_first->sli4_xritag +
7289 					 post_cnt - 1));
7290 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7291 			total_cnt -= post_cnt;
7292 		}
7293 
7294 		/* don't reset xirtag due to hole in xri block */
7295 		if (block_cnt == 0)
7296 			last_xritag = NO_XRI;
7297 
7298 		/* reset sgl post count for next round of posting */
7299 		post_cnt = 0;
7300 	}
7301 
7302 	/* free the sgls failed to post */
7303 	lpfc_free_sgl_list(phba, &free_sgl_list);
7304 
7305 	/* push sgls posted to the available list */
7306 	if (!list_empty(&post_sgl_list)) {
7307 		spin_lock_irq(&phba->hbalock);
7308 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7309 		list_splice_init(&post_sgl_list, sgl_list);
7310 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7311 		spin_unlock_irq(&phba->hbalock);
7312 	} else {
7313 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7314 				"3161 Failure to post sgl to port.\n");
7315 		return -EIO;
7316 	}
7317 
7318 	/* return the number of XRIs actually posted */
7319 	return total_cnt;
7320 }
7321 
7322 /**
7323  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7324  * @phba: pointer to lpfc hba data structure.
7325  *
7326  * This routine walks the list of nvme buffers that have been allocated and
7327  * repost them to the port by using SGL block post. This is needed after a
7328  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7329  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7330  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7331  *
7332  * Returns: 0 = success, non-zero failure.
7333  **/
7334 static int
7335 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7336 {
7337 	LIST_HEAD(post_nblist);
7338 	int num_posted, rc = 0;
7339 
7340 	/* get all NVME buffers need to repost to a local list */
7341 	lpfc_io_buf_flush(phba, &post_nblist);
7342 
7343 	/* post the list of nvme buffer sgls to port if available */
7344 	if (!list_empty(&post_nblist)) {
7345 		num_posted = lpfc_sli4_post_io_sgl_list(
7346 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7347 		/* failed to post any nvme buffer, return error */
7348 		if (num_posted == 0)
7349 			rc = -EIO;
7350 	}
7351 	return rc;
7352 }
7353 
7354 static void
7355 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7356 {
7357 	uint32_t len;
7358 
7359 	len = sizeof(struct lpfc_mbx_set_host_data) -
7360 		sizeof(struct lpfc_sli4_cfg_mhdr);
7361 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7362 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7363 			 LPFC_SLI4_MBX_EMBED);
7364 
7365 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7366 	mbox->u.mqe.un.set_host_data.param_len =
7367 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7368 	snprintf(mbox->u.mqe.un.set_host_data.data,
7369 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7370 		 "Linux %s v"LPFC_DRIVER_VERSION,
7371 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7372 }
7373 
7374 int
7375 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7376 		    struct lpfc_queue *drq, int count, int idx)
7377 {
7378 	int rc, i;
7379 	struct lpfc_rqe hrqe;
7380 	struct lpfc_rqe drqe;
7381 	struct lpfc_rqb *rqbp;
7382 	unsigned long flags;
7383 	struct rqb_dmabuf *rqb_buffer;
7384 	LIST_HEAD(rqb_buf_list);
7385 
7386 	rqbp = hrq->rqbp;
7387 	for (i = 0; i < count; i++) {
7388 		spin_lock_irqsave(&phba->hbalock, flags);
7389 		/* IF RQ is already full, don't bother */
7390 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7391 			spin_unlock_irqrestore(&phba->hbalock, flags);
7392 			break;
7393 		}
7394 		spin_unlock_irqrestore(&phba->hbalock, flags);
7395 
7396 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7397 		if (!rqb_buffer)
7398 			break;
7399 		rqb_buffer->hrq = hrq;
7400 		rqb_buffer->drq = drq;
7401 		rqb_buffer->idx = idx;
7402 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7403 	}
7404 
7405 	spin_lock_irqsave(&phba->hbalock, flags);
7406 	while (!list_empty(&rqb_buf_list)) {
7407 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7408 				 hbuf.list);
7409 
7410 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7411 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7412 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7413 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7414 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7415 		if (rc < 0) {
7416 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7417 					"6421 Cannot post to HRQ %d: %x %x %x "
7418 					"DRQ %x %x\n",
7419 					hrq->queue_id,
7420 					hrq->host_index,
7421 					hrq->hba_index,
7422 					hrq->entry_count,
7423 					drq->host_index,
7424 					drq->hba_index);
7425 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7426 		} else {
7427 			list_add_tail(&rqb_buffer->hbuf.list,
7428 				      &rqbp->rqb_buffer_list);
7429 			rqbp->buffer_count++;
7430 		}
7431 	}
7432 	spin_unlock_irqrestore(&phba->hbalock, flags);
7433 	return 1;
7434 }
7435 
7436 /**
7437  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7438  * @phba: pointer to lpfc hba data structure.
7439  *
7440  * This routine initializes the per-cq idle_stat to dynamically dictate
7441  * polling decisions.
7442  *
7443  * Return codes:
7444  *   None
7445  **/
7446 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
7447 {
7448 	int i;
7449 	struct lpfc_sli4_hdw_queue *hdwq;
7450 	struct lpfc_queue *cq;
7451 	struct lpfc_idle_stat *idle_stat;
7452 	u64 wall;
7453 
7454 	for_each_present_cpu(i) {
7455 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
7456 		cq = hdwq->io_cq;
7457 
7458 		/* Skip if we've already handled this cq's primary CPU */
7459 		if (cq->chann != i)
7460 			continue;
7461 
7462 		idle_stat = &phba->sli4_hba.idle_stat[i];
7463 
7464 		idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
7465 		idle_stat->prev_wall = wall;
7466 
7467 		if (phba->nvmet_support)
7468 			cq->poll_mode = LPFC_QUEUE_WORK;
7469 		else
7470 			cq->poll_mode = LPFC_IRQ_POLL;
7471 	}
7472 
7473 	if (!phba->nvmet_support)
7474 		schedule_delayed_work(&phba->idle_stat_delay_work,
7475 				      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
7476 }
7477 
7478 static void lpfc_sli4_dip(struct lpfc_hba *phba)
7479 {
7480 	uint32_t if_type;
7481 
7482 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
7483 	if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
7484 	    if_type == LPFC_SLI_INTF_IF_TYPE_6) {
7485 		struct lpfc_register reg_data;
7486 
7487 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
7488 			       &reg_data.word0))
7489 			return;
7490 
7491 		if (bf_get(lpfc_sliport_status_dip, &reg_data))
7492 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7493 					"2904 Firmware Dump Image Present"
7494 					" on Adapter");
7495 	}
7496 }
7497 
7498 /**
7499  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
7500  * @phba: Pointer to HBA context object.
7501  *
7502  * This function is the main SLI4 device initialization PCI function. This
7503  * function is called by the HBA initialization code, HBA reset code and
7504  * HBA error attention handler code. Caller is not required to hold any
7505  * locks.
7506  **/
7507 int
7508 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
7509 {
7510 	int rc, i, cnt, len, dd;
7511 	LPFC_MBOXQ_t *mboxq;
7512 	struct lpfc_mqe *mqe;
7513 	uint8_t *vpd;
7514 	uint32_t vpd_size;
7515 	uint32_t ftr_rsp = 0;
7516 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
7517 	struct lpfc_vport *vport = phba->pport;
7518 	struct lpfc_dmabuf *mp;
7519 	struct lpfc_rqb *rqbp;
7520 
7521 	/* Perform a PCI function reset to start from clean */
7522 	rc = lpfc_pci_function_reset(phba);
7523 	if (unlikely(rc))
7524 		return -ENODEV;
7525 
7526 	/* Check the HBA Host Status Register for readyness */
7527 	rc = lpfc_sli4_post_status_check(phba);
7528 	if (unlikely(rc))
7529 		return -ENODEV;
7530 	else {
7531 		spin_lock_irq(&phba->hbalock);
7532 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
7533 		spin_unlock_irq(&phba->hbalock);
7534 	}
7535 
7536 	lpfc_sli4_dip(phba);
7537 
7538 	/*
7539 	 * Allocate a single mailbox container for initializing the
7540 	 * port.
7541 	 */
7542 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7543 	if (!mboxq)
7544 		return -ENOMEM;
7545 
7546 	/* Issue READ_REV to collect vpd and FW information. */
7547 	vpd_size = SLI4_PAGE_SIZE;
7548 	vpd = kzalloc(vpd_size, GFP_KERNEL);
7549 	if (!vpd) {
7550 		rc = -ENOMEM;
7551 		goto out_free_mbox;
7552 	}
7553 
7554 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
7555 	if (unlikely(rc)) {
7556 		kfree(vpd);
7557 		goto out_free_mbox;
7558 	}
7559 
7560 	mqe = &mboxq->u.mqe;
7561 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
7562 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
7563 		phba->hba_flag |= HBA_FCOE_MODE;
7564 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
7565 	} else {
7566 		phba->hba_flag &= ~HBA_FCOE_MODE;
7567 	}
7568 
7569 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
7570 		LPFC_DCBX_CEE_MODE)
7571 		phba->hba_flag |= HBA_FIP_SUPPORT;
7572 	else
7573 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
7574 
7575 	phba->hba_flag &= ~HBA_IOQ_FLUSH;
7576 
7577 	if (phba->sli_rev != LPFC_SLI_REV4) {
7578 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7579 			"0376 READ_REV Error. SLI Level %d "
7580 			"FCoE enabled %d\n",
7581 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
7582 		rc = -EIO;
7583 		kfree(vpd);
7584 		goto out_free_mbox;
7585 	}
7586 
7587 	/*
7588 	 * Continue initialization with default values even if driver failed
7589 	 * to read FCoE param config regions, only read parameters if the
7590 	 * board is FCoE
7591 	 */
7592 	if (phba->hba_flag & HBA_FCOE_MODE &&
7593 	    lpfc_sli4_read_fcoe_params(phba))
7594 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
7595 			"2570 Failed to read FCoE parameters\n");
7596 
7597 	/*
7598 	 * Retrieve sli4 device physical port name, failure of doing it
7599 	 * is considered as non-fatal.
7600 	 */
7601 	rc = lpfc_sli4_retrieve_pport_name(phba);
7602 	if (!rc)
7603 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7604 				"3080 Successful retrieving SLI4 device "
7605 				"physical port name: %s.\n", phba->Port);
7606 
7607 	rc = lpfc_sli4_get_ctl_attr(phba);
7608 	if (!rc)
7609 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7610 				"8351 Successful retrieving SLI4 device "
7611 				"CTL ATTR\n");
7612 
7613 	/*
7614 	 * Evaluate the read rev and vpd data. Populate the driver
7615 	 * state with the results. If this routine fails, the failure
7616 	 * is not fatal as the driver will use generic values.
7617 	 */
7618 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
7619 	if (unlikely(!rc)) {
7620 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7621 				"0377 Error %d parsing vpd. "
7622 				"Using defaults.\n", rc);
7623 		rc = 0;
7624 	}
7625 	kfree(vpd);
7626 
7627 	/* Save information as VPD data */
7628 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
7629 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
7630 
7631 	/*
7632 	 * This is because first G7 ASIC doesn't support the standard
7633 	 * 0x5a NVME cmd descriptor type/subtype
7634 	 */
7635 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7636 			LPFC_SLI_INTF_IF_TYPE_6) &&
7637 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
7638 	    (phba->vpd.rev.smRev == 0) &&
7639 	    (phba->cfg_nvme_embed_cmd == 1))
7640 		phba->cfg_nvme_embed_cmd = 0;
7641 
7642 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
7643 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
7644 					 &mqe->un.read_rev);
7645 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
7646 				       &mqe->un.read_rev);
7647 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
7648 					    &mqe->un.read_rev);
7649 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
7650 					   &mqe->un.read_rev);
7651 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
7652 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
7653 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
7654 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
7655 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
7656 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
7657 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7658 			"(%d):0380 READ_REV Status x%x "
7659 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
7660 			mboxq->vport ? mboxq->vport->vpi : 0,
7661 			bf_get(lpfc_mqe_status, mqe),
7662 			phba->vpd.rev.opFwName,
7663 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
7664 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
7665 
7666 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7667 	    LPFC_SLI_INTF_IF_TYPE_0) {
7668 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
7669 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7670 		if (rc == MBX_SUCCESS) {
7671 			phba->hba_flag |= HBA_RECOVERABLE_UE;
7672 			/* Set 1Sec interval to detect UE */
7673 			phba->eratt_poll_interval = 1;
7674 			phba->sli4_hba.ue_to_sr = bf_get(
7675 					lpfc_mbx_set_feature_UESR,
7676 					&mboxq->u.mqe.un.set_feature);
7677 			phba->sli4_hba.ue_to_rp = bf_get(
7678 					lpfc_mbx_set_feature_UERP,
7679 					&mboxq->u.mqe.un.set_feature);
7680 		}
7681 	}
7682 
7683 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
7684 		/* Enable MDS Diagnostics only if the SLI Port supports it */
7685 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
7686 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7687 		if (rc != MBX_SUCCESS)
7688 			phba->mds_diags_support = 0;
7689 	}
7690 
7691 	/*
7692 	 * Discover the port's supported feature set and match it against the
7693 	 * hosts requests.
7694 	 */
7695 	lpfc_request_features(phba, mboxq);
7696 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7697 	if (unlikely(rc)) {
7698 		rc = -EIO;
7699 		goto out_free_mbox;
7700 	}
7701 
7702 	/*
7703 	 * The port must support FCP initiator mode as this is the
7704 	 * only mode running in the host.
7705 	 */
7706 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
7707 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7708 				"0378 No support for fcpi mode.\n");
7709 		ftr_rsp++;
7710 	}
7711 
7712 	/* Performance Hints are ONLY for FCoE */
7713 	if (phba->hba_flag & HBA_FCOE_MODE) {
7714 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
7715 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
7716 		else
7717 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
7718 	}
7719 
7720 	/*
7721 	 * If the port cannot support the host's requested features
7722 	 * then turn off the global config parameters to disable the
7723 	 * feature in the driver.  This is not a fatal error.
7724 	 */
7725 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
7726 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
7727 			phba->cfg_enable_bg = 0;
7728 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
7729 			ftr_rsp++;
7730 		}
7731 	}
7732 
7733 	if (phba->max_vpi && phba->cfg_enable_npiv &&
7734 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7735 		ftr_rsp++;
7736 
7737 	if (ftr_rsp) {
7738 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7739 				"0379 Feature Mismatch Data: x%08x %08x "
7740 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
7741 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
7742 				phba->cfg_enable_npiv, phba->max_vpi);
7743 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
7744 			phba->cfg_enable_bg = 0;
7745 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7746 			phba->cfg_enable_npiv = 0;
7747 	}
7748 
7749 	/* These SLI3 features are assumed in SLI4 */
7750 	spin_lock_irq(&phba->hbalock);
7751 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
7752 	spin_unlock_irq(&phba->hbalock);
7753 
7754 	/* Always try to enable dual dump feature if we can */
7755 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
7756 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7757 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
7758 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
7759 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7760 				"6448 Dual Dump is enabled\n");
7761 	else
7762 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
7763 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
7764 				"rc:x%x dd:x%x\n",
7765 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7766 				lpfc_sli_config_mbox_subsys_get(
7767 					phba, mboxq),
7768 				lpfc_sli_config_mbox_opcode_get(
7769 					phba, mboxq),
7770 				rc, dd);
7771 	/*
7772 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
7773 	 * calls depends on these resources to complete port setup.
7774 	 */
7775 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
7776 	if (rc) {
7777 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7778 				"2920 Failed to alloc Resource IDs "
7779 				"rc = x%x\n", rc);
7780 		goto out_free_mbox;
7781 	}
7782 
7783 	lpfc_set_host_data(phba, mboxq);
7784 
7785 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7786 	if (rc) {
7787 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7788 				"2134 Failed to set host os driver version %x",
7789 				rc);
7790 	}
7791 
7792 	/* Read the port's service parameters. */
7793 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
7794 	if (rc) {
7795 		phba->link_state = LPFC_HBA_ERROR;
7796 		rc = -ENOMEM;
7797 		goto out_free_mbox;
7798 	}
7799 
7800 	mboxq->vport = vport;
7801 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7802 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
7803 	if (rc == MBX_SUCCESS) {
7804 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
7805 		rc = 0;
7806 	}
7807 
7808 	/*
7809 	 * This memory was allocated by the lpfc_read_sparam routine. Release
7810 	 * it to the mbuf pool.
7811 	 */
7812 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
7813 	kfree(mp);
7814 	mboxq->ctx_buf = NULL;
7815 	if (unlikely(rc)) {
7816 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7817 				"0382 READ_SPARAM command failed "
7818 				"status %d, mbxStatus x%x\n",
7819 				rc, bf_get(lpfc_mqe_status, mqe));
7820 		phba->link_state = LPFC_HBA_ERROR;
7821 		rc = -EIO;
7822 		goto out_free_mbox;
7823 	}
7824 
7825 	lpfc_update_vport_wwn(vport);
7826 
7827 	/* Update the fc_host data structures with new wwn. */
7828 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
7829 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
7830 
7831 	/* Create all the SLI4 queues */
7832 	rc = lpfc_sli4_queue_create(phba);
7833 	if (rc) {
7834 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7835 				"3089 Failed to allocate queues\n");
7836 		rc = -ENODEV;
7837 		goto out_free_mbox;
7838 	}
7839 	/* Set up all the queues to the device */
7840 	rc = lpfc_sli4_queue_setup(phba);
7841 	if (unlikely(rc)) {
7842 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7843 				"0381 Error %d during queue setup.\n ", rc);
7844 		goto out_stop_timers;
7845 	}
7846 	/* Initialize the driver internal SLI layer lists. */
7847 	lpfc_sli4_setup(phba);
7848 	lpfc_sli4_queue_init(phba);
7849 
7850 	/* update host els xri-sgl sizes and mappings */
7851 	rc = lpfc_sli4_els_sgl_update(phba);
7852 	if (unlikely(rc)) {
7853 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7854 				"1400 Failed to update xri-sgl size and "
7855 				"mapping: %d\n", rc);
7856 		goto out_destroy_queue;
7857 	}
7858 
7859 	/* register the els sgl pool to the port */
7860 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
7861 				       phba->sli4_hba.els_xri_cnt);
7862 	if (unlikely(rc < 0)) {
7863 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7864 				"0582 Error %d during els sgl post "
7865 				"operation\n", rc);
7866 		rc = -ENODEV;
7867 		goto out_destroy_queue;
7868 	}
7869 	phba->sli4_hba.els_xri_cnt = rc;
7870 
7871 	if (phba->nvmet_support) {
7872 		/* update host nvmet xri-sgl sizes and mappings */
7873 		rc = lpfc_sli4_nvmet_sgl_update(phba);
7874 		if (unlikely(rc)) {
7875 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7876 					"6308 Failed to update nvmet-sgl size "
7877 					"and mapping: %d\n", rc);
7878 			goto out_destroy_queue;
7879 		}
7880 
7881 		/* register the nvmet sgl pool to the port */
7882 		rc = lpfc_sli4_repost_sgl_list(
7883 			phba,
7884 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
7885 			phba->sli4_hba.nvmet_xri_cnt);
7886 		if (unlikely(rc < 0)) {
7887 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7888 					"3117 Error %d during nvmet "
7889 					"sgl post\n", rc);
7890 			rc = -ENODEV;
7891 			goto out_destroy_queue;
7892 		}
7893 		phba->sli4_hba.nvmet_xri_cnt = rc;
7894 
7895 		/* We allocate an iocbq for every receive context SGL.
7896 		 * The additional allocation is for abort and ls handling.
7897 		 */
7898 		cnt = phba->sli4_hba.nvmet_xri_cnt +
7899 			phba->sli4_hba.max_cfg_param.max_xri;
7900 	} else {
7901 		/* update host common xri-sgl sizes and mappings */
7902 		rc = lpfc_sli4_io_sgl_update(phba);
7903 		if (unlikely(rc)) {
7904 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7905 					"6082 Failed to update nvme-sgl size "
7906 					"and mapping: %d\n", rc);
7907 			goto out_destroy_queue;
7908 		}
7909 
7910 		/* register the allocated common sgl pool to the port */
7911 		rc = lpfc_sli4_repost_io_sgl_list(phba);
7912 		if (unlikely(rc)) {
7913 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7914 					"6116 Error %d during nvme sgl post "
7915 					"operation\n", rc);
7916 			/* Some NVME buffers were moved to abort nvme list */
7917 			/* A pci function reset will repost them */
7918 			rc = -ENODEV;
7919 			goto out_destroy_queue;
7920 		}
7921 		/* Each lpfc_io_buf job structure has an iocbq element.
7922 		 * This cnt provides for abort, els, ct and ls requests.
7923 		 */
7924 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
7925 	}
7926 
7927 	if (!phba->sli.iocbq_lookup) {
7928 		/* Initialize and populate the iocb list per host */
7929 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7930 				"2821 initialize iocb list with %d entries\n",
7931 				cnt);
7932 		rc = lpfc_init_iocb_list(phba, cnt);
7933 		if (rc) {
7934 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7935 					"1413 Failed to init iocb list.\n");
7936 			goto out_destroy_queue;
7937 		}
7938 	}
7939 
7940 	if (phba->nvmet_support)
7941 		lpfc_nvmet_create_targetport(phba);
7942 
7943 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
7944 		/* Post initial buffers to all RQs created */
7945 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
7946 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
7947 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
7948 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
7949 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
7950 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
7951 			rqbp->buffer_count = 0;
7952 
7953 			lpfc_post_rq_buffer(
7954 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
7955 				phba->sli4_hba.nvmet_mrq_data[i],
7956 				phba->cfg_nvmet_mrq_post, i);
7957 		}
7958 	}
7959 
7960 	/* Post the rpi header region to the device. */
7961 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
7962 	if (unlikely(rc)) {
7963 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7964 				"0393 Error %d during rpi post operation\n",
7965 				rc);
7966 		rc = -ENODEV;
7967 		goto out_free_iocblist;
7968 	}
7969 	lpfc_sli4_node_prep(phba);
7970 
7971 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
7972 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
7973 			/*
7974 			 * The FC Port needs to register FCFI (index 0)
7975 			 */
7976 			lpfc_reg_fcfi(phba, mboxq);
7977 			mboxq->vport = phba->pport;
7978 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7979 			if (rc != MBX_SUCCESS)
7980 				goto out_unset_queue;
7981 			rc = 0;
7982 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
7983 						&mboxq->u.mqe.un.reg_fcfi);
7984 		} else {
7985 			/* We are a NVME Target mode with MRQ > 1 */
7986 
7987 			/* First register the FCFI */
7988 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
7989 			mboxq->vport = phba->pport;
7990 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7991 			if (rc != MBX_SUCCESS)
7992 				goto out_unset_queue;
7993 			rc = 0;
7994 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
7995 						&mboxq->u.mqe.un.reg_fcfi_mrq);
7996 
7997 			/* Next register the MRQs */
7998 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
7999 			mboxq->vport = phba->pport;
8000 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8001 			if (rc != MBX_SUCCESS)
8002 				goto out_unset_queue;
8003 			rc = 0;
8004 		}
8005 		/* Check if the port is configured to be disabled */
8006 		lpfc_sli_read_link_ste(phba);
8007 	}
8008 
8009 	/* Don't post more new bufs if repost already recovered
8010 	 * the nvme sgls.
8011 	 */
8012 	if (phba->nvmet_support == 0) {
8013 		if (phba->sli4_hba.io_xri_cnt == 0) {
8014 			len = lpfc_new_io_buf(
8015 					      phba, phba->sli4_hba.io_xri_max);
8016 			if (len == 0) {
8017 				rc = -ENOMEM;
8018 				goto out_unset_queue;
8019 			}
8020 
8021 			if (phba->cfg_xri_rebalancing)
8022 				lpfc_create_multixri_pools(phba);
8023 		}
8024 	} else {
8025 		phba->cfg_xri_rebalancing = 0;
8026 	}
8027 
8028 	/* Allow asynchronous mailbox command to go through */
8029 	spin_lock_irq(&phba->hbalock);
8030 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8031 	spin_unlock_irq(&phba->hbalock);
8032 
8033 	/* Post receive buffers to the device */
8034 	lpfc_sli4_rb_setup(phba);
8035 
8036 	/* Reset HBA FCF states after HBA reset */
8037 	phba->fcf.fcf_flag = 0;
8038 	phba->fcf.current_rec.flag = 0;
8039 
8040 	/* Start the ELS watchdog timer */
8041 	mod_timer(&vport->els_tmofunc,
8042 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
8043 
8044 	/* Start heart beat timer */
8045 	mod_timer(&phba->hb_tmofunc,
8046 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
8047 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
8048 	phba->last_completion_time = jiffies;
8049 
8050 	/* start eq_delay heartbeat */
8051 	if (phba->cfg_auto_imax)
8052 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
8053 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
8054 
8055 	/* start per phba idle_stat_delay heartbeat */
8056 	lpfc_init_idle_stat_hb(phba);
8057 
8058 	/* Start error attention (ERATT) polling timer */
8059 	mod_timer(&phba->eratt_poll,
8060 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
8061 
8062 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
8063 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
8064 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
8065 		if (!rc) {
8066 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8067 					"2829 This device supports "
8068 					"Advanced Error Reporting (AER)\n");
8069 			spin_lock_irq(&phba->hbalock);
8070 			phba->hba_flag |= HBA_AER_ENABLED;
8071 			spin_unlock_irq(&phba->hbalock);
8072 		} else {
8073 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8074 					"2830 This device does not support "
8075 					"Advanced Error Reporting (AER)\n");
8076 			phba->cfg_aer_support = 0;
8077 		}
8078 		rc = 0;
8079 	}
8080 
8081 	/*
8082 	 * The port is ready, set the host's link state to LINK_DOWN
8083 	 * in preparation for link interrupts.
8084 	 */
8085 	spin_lock_irq(&phba->hbalock);
8086 	phba->link_state = LPFC_LINK_DOWN;
8087 
8088 	/* Check if physical ports are trunked */
8089 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
8090 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
8091 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
8092 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
8093 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
8094 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
8095 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
8096 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
8097 	spin_unlock_irq(&phba->hbalock);
8098 
8099 	/* Arm the CQs and then EQs on device */
8100 	lpfc_sli4_arm_cqeq_intr(phba);
8101 
8102 	/* Indicate device interrupt mode */
8103 	phba->sli4_hba.intr_enable = 1;
8104 
8105 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
8106 	    (phba->hba_flag & LINK_DISABLED)) {
8107 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8108 				"3103 Adapter Link is disabled.\n");
8109 		lpfc_down_link(phba, mboxq);
8110 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8111 		if (rc != MBX_SUCCESS) {
8112 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8113 					"3104 Adapter failed to issue "
8114 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
8115 			goto out_io_buff_free;
8116 		}
8117 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
8118 		/* don't perform init_link on SLI4 FC port loopback test */
8119 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
8120 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
8121 			if (rc)
8122 				goto out_io_buff_free;
8123 		}
8124 	}
8125 	mempool_free(mboxq, phba->mbox_mem_pool);
8126 	return rc;
8127 out_io_buff_free:
8128 	/* Free allocated IO Buffers */
8129 	lpfc_io_free(phba);
8130 out_unset_queue:
8131 	/* Unset all the queues set up in this routine when error out */
8132 	lpfc_sli4_queue_unset(phba);
8133 out_free_iocblist:
8134 	lpfc_free_iocb_list(phba);
8135 out_destroy_queue:
8136 	lpfc_sli4_queue_destroy(phba);
8137 out_stop_timers:
8138 	lpfc_stop_hba_timers(phba);
8139 out_free_mbox:
8140 	mempool_free(mboxq, phba->mbox_mem_pool);
8141 	return rc;
8142 }
8143 
8144 /**
8145  * lpfc_mbox_timeout - Timeout call back function for mbox timer
8146  * @t: Context to fetch pointer to hba structure from.
8147  *
8148  * This is the callback function for mailbox timer. The mailbox
8149  * timer is armed when a new mailbox command is issued and the timer
8150  * is deleted when the mailbox complete. The function is called by
8151  * the kernel timer code when a mailbox does not complete within
8152  * expected time. This function wakes up the worker thread to
8153  * process the mailbox timeout and returns. All the processing is
8154  * done by the worker thread function lpfc_mbox_timeout_handler.
8155  **/
8156 void
8157 lpfc_mbox_timeout(struct timer_list *t)
8158 {
8159 	struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
8160 	unsigned long iflag;
8161 	uint32_t tmo_posted;
8162 
8163 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
8164 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
8165 	if (!tmo_posted)
8166 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
8167 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
8168 
8169 	if (!tmo_posted)
8170 		lpfc_worker_wake_up(phba);
8171 	return;
8172 }
8173 
8174 /**
8175  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
8176  *                                    are pending
8177  * @phba: Pointer to HBA context object.
8178  *
8179  * This function checks if any mailbox completions are present on the mailbox
8180  * completion queue.
8181  **/
8182 static bool
8183 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
8184 {
8185 
8186 	uint32_t idx;
8187 	struct lpfc_queue *mcq;
8188 	struct lpfc_mcqe *mcqe;
8189 	bool pending_completions = false;
8190 	uint8_t	qe_valid;
8191 
8192 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8193 		return false;
8194 
8195 	/* Check for completions on mailbox completion queue */
8196 
8197 	mcq = phba->sli4_hba.mbx_cq;
8198 	idx = mcq->hba_index;
8199 	qe_valid = mcq->qe_valid;
8200 	while (bf_get_le32(lpfc_cqe_valid,
8201 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
8202 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
8203 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
8204 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
8205 			pending_completions = true;
8206 			break;
8207 		}
8208 		idx = (idx + 1) % mcq->entry_count;
8209 		if (mcq->hba_index == idx)
8210 			break;
8211 
8212 		/* if the index wrapped around, toggle the valid bit */
8213 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
8214 			qe_valid = (qe_valid) ? 0 : 1;
8215 	}
8216 	return pending_completions;
8217 
8218 }
8219 
8220 /**
8221  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
8222  *					      that were missed.
8223  * @phba: Pointer to HBA context object.
8224  *
8225  * For sli4, it is possible to miss an interrupt. As such mbox completions
8226  * maybe missed causing erroneous mailbox timeouts to occur. This function
8227  * checks to see if mbox completions are on the mailbox completion queue
8228  * and will process all the completions associated with the eq for the
8229  * mailbox completion queue.
8230  **/
8231 static bool
8232 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
8233 {
8234 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
8235 	uint32_t eqidx;
8236 	struct lpfc_queue *fpeq = NULL;
8237 	struct lpfc_queue *eq;
8238 	bool mbox_pending;
8239 
8240 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8241 		return false;
8242 
8243 	/* Find the EQ associated with the mbox CQ */
8244 	if (sli4_hba->hdwq) {
8245 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
8246 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
8247 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
8248 				fpeq = eq;
8249 				break;
8250 			}
8251 		}
8252 	}
8253 	if (!fpeq)
8254 		return false;
8255 
8256 	/* Turn off interrupts from this EQ */
8257 
8258 	sli4_hba->sli4_eq_clr_intr(fpeq);
8259 
8260 	/* Check to see if a mbox completion is pending */
8261 
8262 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
8263 
8264 	/*
8265 	 * If a mbox completion is pending, process all the events on EQ
8266 	 * associated with the mbox completion queue (this could include
8267 	 * mailbox commands, async events, els commands, receive queue data
8268 	 * and fcp commands)
8269 	 */
8270 
8271 	if (mbox_pending)
8272 		/* process and rearm the EQ */
8273 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
8274 	else
8275 		/* Always clear and re-arm the EQ */
8276 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
8277 
8278 	return mbox_pending;
8279 
8280 }
8281 
8282 /**
8283  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
8284  * @phba: Pointer to HBA context object.
8285  *
8286  * This function is called from worker thread when a mailbox command times out.
8287  * The caller is not required to hold any locks. This function will reset the
8288  * HBA and recover all the pending commands.
8289  **/
8290 void
8291 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
8292 {
8293 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
8294 	MAILBOX_t *mb = NULL;
8295 
8296 	struct lpfc_sli *psli = &phba->sli;
8297 
8298 	/* If the mailbox completed, process the completion */
8299 	lpfc_sli4_process_missed_mbox_completions(phba);
8300 
8301 	if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
8302 		return;
8303 
8304 	if (pmbox != NULL)
8305 		mb = &pmbox->u.mb;
8306 	/* Check the pmbox pointer first.  There is a race condition
8307 	 * between the mbox timeout handler getting executed in the
8308 	 * worklist and the mailbox actually completing. When this
8309 	 * race condition occurs, the mbox_active will be NULL.
8310 	 */
8311 	spin_lock_irq(&phba->hbalock);
8312 	if (pmbox == NULL) {
8313 		lpfc_printf_log(phba, KERN_WARNING,
8314 				LOG_MBOX | LOG_SLI,
8315 				"0353 Active Mailbox cleared - mailbox timeout "
8316 				"exiting\n");
8317 		spin_unlock_irq(&phba->hbalock);
8318 		return;
8319 	}
8320 
8321 	/* Mbox cmd <mbxCommand> timeout */
8322 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8323 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
8324 			mb->mbxCommand,
8325 			phba->pport->port_state,
8326 			phba->sli.sli_flag,
8327 			phba->sli.mbox_active);
8328 	spin_unlock_irq(&phba->hbalock);
8329 
8330 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
8331 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
8332 	 * it to fail all outstanding SCSI IO.
8333 	 */
8334 	spin_lock_irq(&phba->pport->work_port_lock);
8335 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
8336 	spin_unlock_irq(&phba->pport->work_port_lock);
8337 	spin_lock_irq(&phba->hbalock);
8338 	phba->link_state = LPFC_LINK_UNKNOWN;
8339 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
8340 	spin_unlock_irq(&phba->hbalock);
8341 
8342 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8343 			"0345 Resetting board due to mailbox timeout\n");
8344 
8345 	/* Reset the HBA device */
8346 	lpfc_reset_hba(phba);
8347 }
8348 
8349 /**
8350  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
8351  * @phba: Pointer to HBA context object.
8352  * @pmbox: Pointer to mailbox object.
8353  * @flag: Flag indicating how the mailbox need to be processed.
8354  *
8355  * This function is called by discovery code and HBA management code
8356  * to submit a mailbox command to firmware with SLI-3 interface spec. This
8357  * function gets the hbalock to protect the data structures.
8358  * The mailbox command can be submitted in polling mode, in which case
8359  * this function will wait in a polling loop for the completion of the
8360  * mailbox.
8361  * If the mailbox is submitted in no_wait mode (not polling) the
8362  * function will submit the command and returns immediately without waiting
8363  * for the mailbox completion. The no_wait is supported only when HBA
8364  * is in SLI2/SLI3 mode - interrupts are enabled.
8365  * The SLI interface allows only one mailbox pending at a time. If the
8366  * mailbox is issued in polling mode and there is already a mailbox
8367  * pending, then the function will return an error. If the mailbox is issued
8368  * in NO_WAIT mode and there is a mailbox pending already, the function
8369  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
8370  * The sli layer owns the mailbox object until the completion of mailbox
8371  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
8372  * return codes the caller owns the mailbox command after the return of
8373  * the function.
8374  **/
8375 static int
8376 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
8377 		       uint32_t flag)
8378 {
8379 	MAILBOX_t *mbx;
8380 	struct lpfc_sli *psli = &phba->sli;
8381 	uint32_t status, evtctr;
8382 	uint32_t ha_copy, hc_copy;
8383 	int i;
8384 	unsigned long timeout;
8385 	unsigned long drvr_flag = 0;
8386 	uint32_t word0, ldata;
8387 	void __iomem *to_slim;
8388 	int processing_queue = 0;
8389 
8390 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
8391 	if (!pmbox) {
8392 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8393 		/* processing mbox queue from intr_handler */
8394 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8395 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8396 			return MBX_SUCCESS;
8397 		}
8398 		processing_queue = 1;
8399 		pmbox = lpfc_mbox_get(phba);
8400 		if (!pmbox) {
8401 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8402 			return MBX_SUCCESS;
8403 		}
8404 	}
8405 
8406 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
8407 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
8408 		if(!pmbox->vport) {
8409 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8410 			lpfc_printf_log(phba, KERN_ERR,
8411 					LOG_MBOX | LOG_VPORT,
8412 					"1806 Mbox x%x failed. No vport\n",
8413 					pmbox->u.mb.mbxCommand);
8414 			dump_stack();
8415 			goto out_not_finished;
8416 		}
8417 	}
8418 
8419 	/* If the PCI channel is in offline state, do not post mbox. */
8420 	if (unlikely(pci_channel_offline(phba->pcidev))) {
8421 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8422 		goto out_not_finished;
8423 	}
8424 
8425 	/* If HBA has a deferred error attention, fail the iocb. */
8426 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
8427 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8428 		goto out_not_finished;
8429 	}
8430 
8431 	psli = &phba->sli;
8432 
8433 	mbx = &pmbox->u.mb;
8434 	status = MBX_SUCCESS;
8435 
8436 	if (phba->link_state == LPFC_HBA_ERROR) {
8437 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8438 
8439 		/* Mbox command <mbxCommand> cannot issue */
8440 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8441 				"(%d):0311 Mailbox command x%x cannot "
8442 				"issue Data: x%x x%x\n",
8443 				pmbox->vport ? pmbox->vport->vpi : 0,
8444 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8445 		goto out_not_finished;
8446 	}
8447 
8448 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
8449 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
8450 			!(hc_copy & HC_MBINT_ENA)) {
8451 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8452 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8453 				"(%d):2528 Mailbox command x%x cannot "
8454 				"issue Data: x%x x%x\n",
8455 				pmbox->vport ? pmbox->vport->vpi : 0,
8456 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8457 			goto out_not_finished;
8458 		}
8459 	}
8460 
8461 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8462 		/* Polling for a mbox command when another one is already active
8463 		 * is not allowed in SLI. Also, the driver must have established
8464 		 * SLI2 mode to queue and process multiple mbox commands.
8465 		 */
8466 
8467 		if (flag & MBX_POLL) {
8468 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8469 
8470 			/* Mbox command <mbxCommand> cannot issue */
8471 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8472 					"(%d):2529 Mailbox command x%x "
8473 					"cannot issue Data: x%x x%x\n",
8474 					pmbox->vport ? pmbox->vport->vpi : 0,
8475 					pmbox->u.mb.mbxCommand,
8476 					psli->sli_flag, flag);
8477 			goto out_not_finished;
8478 		}
8479 
8480 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
8481 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8482 			/* Mbox command <mbxCommand> cannot issue */
8483 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8484 					"(%d):2530 Mailbox command x%x "
8485 					"cannot issue Data: x%x x%x\n",
8486 					pmbox->vport ? pmbox->vport->vpi : 0,
8487 					pmbox->u.mb.mbxCommand,
8488 					psli->sli_flag, flag);
8489 			goto out_not_finished;
8490 		}
8491 
8492 		/* Another mailbox command is still being processed, queue this
8493 		 * command to be processed later.
8494 		 */
8495 		lpfc_mbox_put(phba, pmbox);
8496 
8497 		/* Mbox cmd issue - BUSY */
8498 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8499 				"(%d):0308 Mbox cmd issue - BUSY Data: "
8500 				"x%x x%x x%x x%x\n",
8501 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
8502 				mbx->mbxCommand,
8503 				phba->pport ? phba->pport->port_state : 0xff,
8504 				psli->sli_flag, flag);
8505 
8506 		psli->slistat.mbox_busy++;
8507 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8508 
8509 		if (pmbox->vport) {
8510 			lpfc_debugfs_disc_trc(pmbox->vport,
8511 				LPFC_DISC_TRC_MBOX_VPORT,
8512 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
8513 				(uint32_t)mbx->mbxCommand,
8514 				mbx->un.varWords[0], mbx->un.varWords[1]);
8515 		}
8516 		else {
8517 			lpfc_debugfs_disc_trc(phba->pport,
8518 				LPFC_DISC_TRC_MBOX,
8519 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
8520 				(uint32_t)mbx->mbxCommand,
8521 				mbx->un.varWords[0], mbx->un.varWords[1]);
8522 		}
8523 
8524 		return MBX_BUSY;
8525 	}
8526 
8527 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8528 
8529 	/* If we are not polling, we MUST be in SLI2 mode */
8530 	if (flag != MBX_POLL) {
8531 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
8532 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
8533 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8534 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8535 			/* Mbox command <mbxCommand> cannot issue */
8536 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8537 					"(%d):2531 Mailbox command x%x "
8538 					"cannot issue Data: x%x x%x\n",
8539 					pmbox->vport ? pmbox->vport->vpi : 0,
8540 					pmbox->u.mb.mbxCommand,
8541 					psli->sli_flag, flag);
8542 			goto out_not_finished;
8543 		}
8544 		/* timeout active mbox command */
8545 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8546 					   1000);
8547 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
8548 	}
8549 
8550 	/* Mailbox cmd <cmd> issue */
8551 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8552 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
8553 			"x%x\n",
8554 			pmbox->vport ? pmbox->vport->vpi : 0,
8555 			mbx->mbxCommand,
8556 			phba->pport ? phba->pport->port_state : 0xff,
8557 			psli->sli_flag, flag);
8558 
8559 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
8560 		if (pmbox->vport) {
8561 			lpfc_debugfs_disc_trc(pmbox->vport,
8562 				LPFC_DISC_TRC_MBOX_VPORT,
8563 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
8564 				(uint32_t)mbx->mbxCommand,
8565 				mbx->un.varWords[0], mbx->un.varWords[1]);
8566 		}
8567 		else {
8568 			lpfc_debugfs_disc_trc(phba->pport,
8569 				LPFC_DISC_TRC_MBOX,
8570 				"MBOX Send:       cmd:x%x mb:x%x x%x",
8571 				(uint32_t)mbx->mbxCommand,
8572 				mbx->un.varWords[0], mbx->un.varWords[1]);
8573 		}
8574 	}
8575 
8576 	psli->slistat.mbox_cmd++;
8577 	evtctr = psli->slistat.mbox_event;
8578 
8579 	/* next set own bit for the adapter and copy over command word */
8580 	mbx->mbxOwner = OWN_CHIP;
8581 
8582 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8583 		/* Populate mbox extension offset word. */
8584 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
8585 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8586 				= (uint8_t *)phba->mbox_ext
8587 				  - (uint8_t *)phba->mbox;
8588 		}
8589 
8590 		/* Copy the mailbox extension data */
8591 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
8592 			lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
8593 					      (uint8_t *)phba->mbox_ext,
8594 					      pmbox->in_ext_byte_len);
8595 		}
8596 		/* Copy command data to host SLIM area */
8597 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
8598 	} else {
8599 		/* Populate mbox extension offset word. */
8600 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
8601 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8602 				= MAILBOX_HBA_EXT_OFFSET;
8603 
8604 		/* Copy the mailbox extension data */
8605 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
8606 			lpfc_memcpy_to_slim(phba->MBslimaddr +
8607 				MAILBOX_HBA_EXT_OFFSET,
8608 				pmbox->ctx_buf, pmbox->in_ext_byte_len);
8609 
8610 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8611 			/* copy command data into host mbox for cmpl */
8612 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
8613 					      MAILBOX_CMD_SIZE);
8614 
8615 		/* First copy mbox command data to HBA SLIM, skip past first
8616 		   word */
8617 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
8618 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
8619 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
8620 
8621 		/* Next copy over first word, with mbxOwner set */
8622 		ldata = *((uint32_t *)mbx);
8623 		to_slim = phba->MBslimaddr;
8624 		writel(ldata, to_slim);
8625 		readl(to_slim); /* flush */
8626 
8627 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8628 			/* switch over to host mailbox */
8629 			psli->sli_flag |= LPFC_SLI_ACTIVE;
8630 	}
8631 
8632 	wmb();
8633 
8634 	switch (flag) {
8635 	case MBX_NOWAIT:
8636 		/* Set up reference to mailbox command */
8637 		psli->mbox_active = pmbox;
8638 		/* Interrupt board to do it */
8639 		writel(CA_MBATT, phba->CAregaddr);
8640 		readl(phba->CAregaddr); /* flush */
8641 		/* Don't wait for it to finish, just return */
8642 		break;
8643 
8644 	case MBX_POLL:
8645 		/* Set up null reference to mailbox command */
8646 		psli->mbox_active = NULL;
8647 		/* Interrupt board to do it */
8648 		writel(CA_MBATT, phba->CAregaddr);
8649 		readl(phba->CAregaddr); /* flush */
8650 
8651 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8652 			/* First read mbox status word */
8653 			word0 = *((uint32_t *)phba->mbox);
8654 			word0 = le32_to_cpu(word0);
8655 		} else {
8656 			/* First read mbox status word */
8657 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
8658 				spin_unlock_irqrestore(&phba->hbalock,
8659 						       drvr_flag);
8660 				goto out_not_finished;
8661 			}
8662 		}
8663 
8664 		/* Read the HBA Host Attention Register */
8665 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8666 			spin_unlock_irqrestore(&phba->hbalock,
8667 						       drvr_flag);
8668 			goto out_not_finished;
8669 		}
8670 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8671 							1000) + jiffies;
8672 		i = 0;
8673 		/* Wait for command to complete */
8674 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
8675 		       (!(ha_copy & HA_MBATT) &&
8676 			(phba->link_state > LPFC_WARM_START))) {
8677 			if (time_after(jiffies, timeout)) {
8678 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8679 				spin_unlock_irqrestore(&phba->hbalock,
8680 						       drvr_flag);
8681 				goto out_not_finished;
8682 			}
8683 
8684 			/* Check if we took a mbox interrupt while we were
8685 			   polling */
8686 			if (((word0 & OWN_CHIP) != OWN_CHIP)
8687 			    && (evtctr != psli->slistat.mbox_event))
8688 				break;
8689 
8690 			if (i++ > 10) {
8691 				spin_unlock_irqrestore(&phba->hbalock,
8692 						       drvr_flag);
8693 				msleep(1);
8694 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
8695 			}
8696 
8697 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8698 				/* First copy command data */
8699 				word0 = *((uint32_t *)phba->mbox);
8700 				word0 = le32_to_cpu(word0);
8701 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
8702 					MAILBOX_t *slimmb;
8703 					uint32_t slimword0;
8704 					/* Check real SLIM for any errors */
8705 					slimword0 = readl(phba->MBslimaddr);
8706 					slimmb = (MAILBOX_t *) & slimword0;
8707 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
8708 					    && slimmb->mbxStatus) {
8709 						psli->sli_flag &=
8710 						    ~LPFC_SLI_ACTIVE;
8711 						word0 = slimword0;
8712 					}
8713 				}
8714 			} else {
8715 				/* First copy command data */
8716 				word0 = readl(phba->MBslimaddr);
8717 			}
8718 			/* Read the HBA Host Attention Register */
8719 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8720 				spin_unlock_irqrestore(&phba->hbalock,
8721 						       drvr_flag);
8722 				goto out_not_finished;
8723 			}
8724 		}
8725 
8726 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8727 			/* copy results back to user */
8728 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
8729 						MAILBOX_CMD_SIZE);
8730 			/* Copy the mailbox extension data */
8731 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8732 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
8733 						      pmbox->ctx_buf,
8734 						      pmbox->out_ext_byte_len);
8735 			}
8736 		} else {
8737 			/* First copy command data */
8738 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
8739 						MAILBOX_CMD_SIZE);
8740 			/* Copy the mailbox extension data */
8741 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8742 				lpfc_memcpy_from_slim(
8743 					pmbox->ctx_buf,
8744 					phba->MBslimaddr +
8745 					MAILBOX_HBA_EXT_OFFSET,
8746 					pmbox->out_ext_byte_len);
8747 			}
8748 		}
8749 
8750 		writel(HA_MBATT, phba->HAregaddr);
8751 		readl(phba->HAregaddr); /* flush */
8752 
8753 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8754 		status = mbx->mbxStatus;
8755 	}
8756 
8757 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8758 	return status;
8759 
8760 out_not_finished:
8761 	if (processing_queue) {
8762 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
8763 		lpfc_mbox_cmpl_put(phba, pmbox);
8764 	}
8765 	return MBX_NOT_FINISHED;
8766 }
8767 
8768 /**
8769  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
8770  * @phba: Pointer to HBA context object.
8771  *
8772  * The function blocks the posting of SLI4 asynchronous mailbox commands from
8773  * the driver internal pending mailbox queue. It will then try to wait out the
8774  * possible outstanding mailbox command before return.
8775  *
8776  * Returns:
8777  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
8778  * 	the outstanding mailbox command timed out.
8779  **/
8780 static int
8781 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
8782 {
8783 	struct lpfc_sli *psli = &phba->sli;
8784 	int rc = 0;
8785 	unsigned long timeout = 0;
8786 
8787 	/* Mark the asynchronous mailbox command posting as blocked */
8788 	spin_lock_irq(&phba->hbalock);
8789 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
8790 	/* Determine how long we might wait for the active mailbox
8791 	 * command to be gracefully completed by firmware.
8792 	 */
8793 	if (phba->sli.mbox_active)
8794 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
8795 						phba->sli.mbox_active) *
8796 						1000) + jiffies;
8797 	spin_unlock_irq(&phba->hbalock);
8798 
8799 	/* Make sure the mailbox is really active */
8800 	if (timeout)
8801 		lpfc_sli4_process_missed_mbox_completions(phba);
8802 
8803 	/* Wait for the outstnading mailbox command to complete */
8804 	while (phba->sli.mbox_active) {
8805 		/* Check active mailbox complete status every 2ms */
8806 		msleep(2);
8807 		if (time_after(jiffies, timeout)) {
8808 			/* Timeout, marked the outstanding cmd not complete */
8809 			rc = 1;
8810 			break;
8811 		}
8812 	}
8813 
8814 	/* Can not cleanly block async mailbox command, fails it */
8815 	if (rc) {
8816 		spin_lock_irq(&phba->hbalock);
8817 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8818 		spin_unlock_irq(&phba->hbalock);
8819 	}
8820 	return rc;
8821 }
8822 
8823 /**
8824  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
8825  * @phba: Pointer to HBA context object.
8826  *
8827  * The function unblocks and resume posting of SLI4 asynchronous mailbox
8828  * commands from the driver internal pending mailbox queue. It makes sure
8829  * that there is no outstanding mailbox command before resuming posting
8830  * asynchronous mailbox commands. If, for any reason, there is outstanding
8831  * mailbox command, it will try to wait it out before resuming asynchronous
8832  * mailbox command posting.
8833  **/
8834 static void
8835 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
8836 {
8837 	struct lpfc_sli *psli = &phba->sli;
8838 
8839 	spin_lock_irq(&phba->hbalock);
8840 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8841 		/* Asynchronous mailbox posting is not blocked, do nothing */
8842 		spin_unlock_irq(&phba->hbalock);
8843 		return;
8844 	}
8845 
8846 	/* Outstanding synchronous mailbox command is guaranteed to be done,
8847 	 * successful or timeout, after timing-out the outstanding mailbox
8848 	 * command shall always be removed, so just unblock posting async
8849 	 * mailbox command and resume
8850 	 */
8851 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8852 	spin_unlock_irq(&phba->hbalock);
8853 
8854 	/* wake up worker thread to post asynchronous mailbox command */
8855 	lpfc_worker_wake_up(phba);
8856 }
8857 
8858 /**
8859  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
8860  * @phba: Pointer to HBA context object.
8861  * @mboxq: Pointer to mailbox object.
8862  *
8863  * The function waits for the bootstrap mailbox register ready bit from
8864  * port for twice the regular mailbox command timeout value.
8865  *
8866  *      0 - no timeout on waiting for bootstrap mailbox register ready.
8867  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
8868  **/
8869 static int
8870 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8871 {
8872 	uint32_t db_ready;
8873 	unsigned long timeout;
8874 	struct lpfc_register bmbx_reg;
8875 
8876 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
8877 				   * 1000) + jiffies;
8878 
8879 	do {
8880 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
8881 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
8882 		if (!db_ready)
8883 			mdelay(2);
8884 
8885 		if (time_after(jiffies, timeout))
8886 			return MBXERR_ERROR;
8887 	} while (!db_ready);
8888 
8889 	return 0;
8890 }
8891 
8892 /**
8893  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
8894  * @phba: Pointer to HBA context object.
8895  * @mboxq: Pointer to mailbox object.
8896  *
8897  * The function posts a mailbox to the port.  The mailbox is expected
8898  * to be comletely filled in and ready for the port to operate on it.
8899  * This routine executes a synchronous completion operation on the
8900  * mailbox by polling for its completion.
8901  *
8902  * The caller must not be holding any locks when calling this routine.
8903  *
8904  * Returns:
8905  *	MBX_SUCCESS - mailbox posted successfully
8906  *	Any of the MBX error values.
8907  **/
8908 static int
8909 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8910 {
8911 	int rc = MBX_SUCCESS;
8912 	unsigned long iflag;
8913 	uint32_t mcqe_status;
8914 	uint32_t mbx_cmnd;
8915 	struct lpfc_sli *psli = &phba->sli;
8916 	struct lpfc_mqe *mb = &mboxq->u.mqe;
8917 	struct lpfc_bmbx_create *mbox_rgn;
8918 	struct dma_address *dma_address;
8919 
8920 	/*
8921 	 * Only one mailbox can be active to the bootstrap mailbox region
8922 	 * at a time and there is no queueing provided.
8923 	 */
8924 	spin_lock_irqsave(&phba->hbalock, iflag);
8925 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8926 		spin_unlock_irqrestore(&phba->hbalock, iflag);
8927 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8928 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
8929 				"cannot issue Data: x%x x%x\n",
8930 				mboxq->vport ? mboxq->vport->vpi : 0,
8931 				mboxq->u.mb.mbxCommand,
8932 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8933 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8934 				psli->sli_flag, MBX_POLL);
8935 		return MBXERR_ERROR;
8936 	}
8937 	/* The server grabs the token and owns it until release */
8938 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8939 	phba->sli.mbox_active = mboxq;
8940 	spin_unlock_irqrestore(&phba->hbalock, iflag);
8941 
8942 	/* wait for bootstrap mbox register for readyness */
8943 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8944 	if (rc)
8945 		goto exit;
8946 	/*
8947 	 * Initialize the bootstrap memory region to avoid stale data areas
8948 	 * in the mailbox post.  Then copy the caller's mailbox contents to
8949 	 * the bmbx mailbox region.
8950 	 */
8951 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
8952 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
8953 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
8954 			       sizeof(struct lpfc_mqe));
8955 
8956 	/* Post the high mailbox dma address to the port and wait for ready. */
8957 	dma_address = &phba->sli4_hba.bmbx.dma_address;
8958 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
8959 
8960 	/* wait for bootstrap mbox register for hi-address write done */
8961 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8962 	if (rc)
8963 		goto exit;
8964 
8965 	/* Post the low mailbox dma address to the port. */
8966 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
8967 
8968 	/* wait for bootstrap mbox register for low address write done */
8969 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8970 	if (rc)
8971 		goto exit;
8972 
8973 	/*
8974 	 * Read the CQ to ensure the mailbox has completed.
8975 	 * If so, update the mailbox status so that the upper layers
8976 	 * can complete the request normally.
8977 	 */
8978 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
8979 			       sizeof(struct lpfc_mqe));
8980 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
8981 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
8982 			       sizeof(struct lpfc_mcqe));
8983 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
8984 	/*
8985 	 * When the CQE status indicates a failure and the mailbox status
8986 	 * indicates success then copy the CQE status into the mailbox status
8987 	 * (and prefix it with x4000).
8988 	 */
8989 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
8990 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
8991 			bf_set(lpfc_mqe_status, mb,
8992 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
8993 		rc = MBXERR_ERROR;
8994 	} else
8995 		lpfc_sli4_swap_str(phba, mboxq);
8996 
8997 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8998 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
8999 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
9000 			" x%x x%x CQ: x%x x%x x%x x%x\n",
9001 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
9002 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9003 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9004 			bf_get(lpfc_mqe_status, mb),
9005 			mb->un.mb_words[0], mb->un.mb_words[1],
9006 			mb->un.mb_words[2], mb->un.mb_words[3],
9007 			mb->un.mb_words[4], mb->un.mb_words[5],
9008 			mb->un.mb_words[6], mb->un.mb_words[7],
9009 			mb->un.mb_words[8], mb->un.mb_words[9],
9010 			mb->un.mb_words[10], mb->un.mb_words[11],
9011 			mb->un.mb_words[12], mboxq->mcqe.word0,
9012 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
9013 			mboxq->mcqe.trailer);
9014 exit:
9015 	/* We are holding the token, no needed for lock when release */
9016 	spin_lock_irqsave(&phba->hbalock, iflag);
9017 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9018 	phba->sli.mbox_active = NULL;
9019 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9020 	return rc;
9021 }
9022 
9023 /**
9024  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
9025  * @phba: Pointer to HBA context object.
9026  * @mboxq: Pointer to mailbox object.
9027  * @flag: Flag indicating how the mailbox need to be processed.
9028  *
9029  * This function is called by discovery code and HBA management code to submit
9030  * a mailbox command to firmware with SLI-4 interface spec.
9031  *
9032  * Return codes the caller owns the mailbox command after the return of the
9033  * function.
9034  **/
9035 static int
9036 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
9037 		       uint32_t flag)
9038 {
9039 	struct lpfc_sli *psli = &phba->sli;
9040 	unsigned long iflags;
9041 	int rc;
9042 
9043 	/* dump from issue mailbox command if setup */
9044 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
9045 
9046 	rc = lpfc_mbox_dev_check(phba);
9047 	if (unlikely(rc)) {
9048 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9049 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
9050 				"cannot issue Data: x%x x%x\n",
9051 				mboxq->vport ? mboxq->vport->vpi : 0,
9052 				mboxq->u.mb.mbxCommand,
9053 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9054 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9055 				psli->sli_flag, flag);
9056 		goto out_not_finished;
9057 	}
9058 
9059 	/* Detect polling mode and jump to a handler */
9060 	if (!phba->sli4_hba.intr_enable) {
9061 		if (flag == MBX_POLL)
9062 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
9063 		else
9064 			rc = -EIO;
9065 		if (rc != MBX_SUCCESS)
9066 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
9067 					"(%d):2541 Mailbox command x%x "
9068 					"(x%x/x%x) failure: "
9069 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
9070 					"Data: x%x x%x\n,",
9071 					mboxq->vport ? mboxq->vport->vpi : 0,
9072 					mboxq->u.mb.mbxCommand,
9073 					lpfc_sli_config_mbox_subsys_get(phba,
9074 									mboxq),
9075 					lpfc_sli_config_mbox_opcode_get(phba,
9076 									mboxq),
9077 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
9078 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
9079 					bf_get(lpfc_mcqe_ext_status,
9080 					       &mboxq->mcqe),
9081 					psli->sli_flag, flag);
9082 		return rc;
9083 	} else if (flag == MBX_POLL) {
9084 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
9085 				"(%d):2542 Try to issue mailbox command "
9086 				"x%x (x%x/x%x) synchronously ahead of async "
9087 				"mailbox command queue: x%x x%x\n",
9088 				mboxq->vport ? mboxq->vport->vpi : 0,
9089 				mboxq->u.mb.mbxCommand,
9090 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9091 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9092 				psli->sli_flag, flag);
9093 		/* Try to block the asynchronous mailbox posting */
9094 		rc = lpfc_sli4_async_mbox_block(phba);
9095 		if (!rc) {
9096 			/* Successfully blocked, now issue sync mbox cmd */
9097 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
9098 			if (rc != MBX_SUCCESS)
9099 				lpfc_printf_log(phba, KERN_WARNING,
9100 					LOG_MBOX | LOG_SLI,
9101 					"(%d):2597 Sync Mailbox command "
9102 					"x%x (x%x/x%x) failure: "
9103 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
9104 					"Data: x%x x%x\n,",
9105 					mboxq->vport ? mboxq->vport->vpi : 0,
9106 					mboxq->u.mb.mbxCommand,
9107 					lpfc_sli_config_mbox_subsys_get(phba,
9108 									mboxq),
9109 					lpfc_sli_config_mbox_opcode_get(phba,
9110 									mboxq),
9111 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
9112 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
9113 					bf_get(lpfc_mcqe_ext_status,
9114 					       &mboxq->mcqe),
9115 					psli->sli_flag, flag);
9116 			/* Unblock the async mailbox posting afterward */
9117 			lpfc_sli4_async_mbox_unblock(phba);
9118 		}
9119 		return rc;
9120 	}
9121 
9122 	/* Now, interrupt mode asynchronous mailbox command */
9123 	rc = lpfc_mbox_cmd_check(phba, mboxq);
9124 	if (rc) {
9125 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9126 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
9127 				"cannot issue Data: x%x x%x\n",
9128 				mboxq->vport ? mboxq->vport->vpi : 0,
9129 				mboxq->u.mb.mbxCommand,
9130 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9131 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9132 				psli->sli_flag, flag);
9133 		goto out_not_finished;
9134 	}
9135 
9136 	/* Put the mailbox command to the driver internal FIFO */
9137 	psli->slistat.mbox_busy++;
9138 	spin_lock_irqsave(&phba->hbalock, iflags);
9139 	lpfc_mbox_put(phba, mboxq);
9140 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9141 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9142 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
9143 			"x%x (x%x/x%x) x%x x%x x%x\n",
9144 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
9145 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
9146 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9147 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9148 			phba->pport->port_state,
9149 			psli->sli_flag, MBX_NOWAIT);
9150 	/* Wake up worker thread to transport mailbox command from head */
9151 	lpfc_worker_wake_up(phba);
9152 
9153 	return MBX_BUSY;
9154 
9155 out_not_finished:
9156 	return MBX_NOT_FINISHED;
9157 }
9158 
9159 /**
9160  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
9161  * @phba: Pointer to HBA context object.
9162  *
9163  * This function is called by worker thread to send a mailbox command to
9164  * SLI4 HBA firmware.
9165  *
9166  **/
9167 int
9168 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
9169 {
9170 	struct lpfc_sli *psli = &phba->sli;
9171 	LPFC_MBOXQ_t *mboxq;
9172 	int rc = MBX_SUCCESS;
9173 	unsigned long iflags;
9174 	struct lpfc_mqe *mqe;
9175 	uint32_t mbx_cmnd;
9176 
9177 	/* Check interrupt mode before post async mailbox command */
9178 	if (unlikely(!phba->sli4_hba.intr_enable))
9179 		return MBX_NOT_FINISHED;
9180 
9181 	/* Check for mailbox command service token */
9182 	spin_lock_irqsave(&phba->hbalock, iflags);
9183 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9184 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9185 		return MBX_NOT_FINISHED;
9186 	}
9187 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9188 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9189 		return MBX_NOT_FINISHED;
9190 	}
9191 	if (unlikely(phba->sli.mbox_active)) {
9192 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9193 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9194 				"0384 There is pending active mailbox cmd\n");
9195 		return MBX_NOT_FINISHED;
9196 	}
9197 	/* Take the mailbox command service token */
9198 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9199 
9200 	/* Get the next mailbox command from head of queue */
9201 	mboxq = lpfc_mbox_get(phba);
9202 
9203 	/* If no more mailbox command waiting for post, we're done */
9204 	if (!mboxq) {
9205 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9206 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9207 		return MBX_SUCCESS;
9208 	}
9209 	phba->sli.mbox_active = mboxq;
9210 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9211 
9212 	/* Check device readiness for posting mailbox command */
9213 	rc = lpfc_mbox_dev_check(phba);
9214 	if (unlikely(rc))
9215 		/* Driver clean routine will clean up pending mailbox */
9216 		goto out_not_finished;
9217 
9218 	/* Prepare the mbox command to be posted */
9219 	mqe = &mboxq->u.mqe;
9220 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
9221 
9222 	/* Start timer for the mbox_tmo and log some mailbox post messages */
9223 	mod_timer(&psli->mbox_tmo, (jiffies +
9224 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
9225 
9226 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9227 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
9228 			"x%x x%x\n",
9229 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
9230 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9231 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9232 			phba->pport->port_state, psli->sli_flag);
9233 
9234 	if (mbx_cmnd != MBX_HEARTBEAT) {
9235 		if (mboxq->vport) {
9236 			lpfc_debugfs_disc_trc(mboxq->vport,
9237 				LPFC_DISC_TRC_MBOX_VPORT,
9238 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9239 				mbx_cmnd, mqe->un.mb_words[0],
9240 				mqe->un.mb_words[1]);
9241 		} else {
9242 			lpfc_debugfs_disc_trc(phba->pport,
9243 				LPFC_DISC_TRC_MBOX,
9244 				"MBOX Send: cmd:x%x mb:x%x x%x",
9245 				mbx_cmnd, mqe->un.mb_words[0],
9246 				mqe->un.mb_words[1]);
9247 		}
9248 	}
9249 	psli->slistat.mbox_cmd++;
9250 
9251 	/* Post the mailbox command to the port */
9252 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
9253 	if (rc != MBX_SUCCESS) {
9254 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9255 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
9256 				"cannot issue Data: x%x x%x\n",
9257 				mboxq->vport ? mboxq->vport->vpi : 0,
9258 				mboxq->u.mb.mbxCommand,
9259 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9260 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9261 				psli->sli_flag, MBX_NOWAIT);
9262 		goto out_not_finished;
9263 	}
9264 
9265 	return rc;
9266 
9267 out_not_finished:
9268 	spin_lock_irqsave(&phba->hbalock, iflags);
9269 	if (phba->sli.mbox_active) {
9270 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
9271 		__lpfc_mbox_cmpl_put(phba, mboxq);
9272 		/* Release the token */
9273 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9274 		phba->sli.mbox_active = NULL;
9275 	}
9276 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9277 
9278 	return MBX_NOT_FINISHED;
9279 }
9280 
9281 /**
9282  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
9283  * @phba: Pointer to HBA context object.
9284  * @pmbox: Pointer to mailbox object.
9285  * @flag: Flag indicating how the mailbox need to be processed.
9286  *
9287  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
9288  * the API jump table function pointer from the lpfc_hba struct.
9289  *
9290  * Return codes the caller owns the mailbox command after the return of the
9291  * function.
9292  **/
9293 int
9294 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
9295 {
9296 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
9297 }
9298 
9299 /**
9300  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
9301  * @phba: The hba struct for which this call is being executed.
9302  * @dev_grp: The HBA PCI-Device group number.
9303  *
9304  * This routine sets up the mbox interface API function jump table in @phba
9305  * struct.
9306  * Returns: 0 - success, -ENODEV - failure.
9307  **/
9308 int
9309 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
9310 {
9311 
9312 	switch (dev_grp) {
9313 	case LPFC_PCI_DEV_LP:
9314 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
9315 		phba->lpfc_sli_handle_slow_ring_event =
9316 				lpfc_sli_handle_slow_ring_event_s3;
9317 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
9318 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
9319 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
9320 		break;
9321 	case LPFC_PCI_DEV_OC:
9322 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
9323 		phba->lpfc_sli_handle_slow_ring_event =
9324 				lpfc_sli_handle_slow_ring_event_s4;
9325 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
9326 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
9327 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
9328 		break;
9329 	default:
9330 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9331 				"1420 Invalid HBA PCI-device group: 0x%x\n",
9332 				dev_grp);
9333 		return -ENODEV;
9334 	}
9335 	return 0;
9336 }
9337 
9338 /**
9339  * __lpfc_sli_ringtx_put - Add an iocb to the txq
9340  * @phba: Pointer to HBA context object.
9341  * @pring: Pointer to driver SLI ring object.
9342  * @piocb: Pointer to address of newly added command iocb.
9343  *
9344  * This function is called with hbalock held for SLI3 ports or
9345  * the ring lock held for SLI4 ports to add a command
9346  * iocb to the txq when SLI layer cannot submit the command iocb
9347  * to the ring.
9348  **/
9349 void
9350 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9351 		    struct lpfc_iocbq *piocb)
9352 {
9353 	if (phba->sli_rev == LPFC_SLI_REV4)
9354 		lockdep_assert_held(&pring->ring_lock);
9355 	else
9356 		lockdep_assert_held(&phba->hbalock);
9357 	/* Insert the caller's iocb in the txq tail for later processing. */
9358 	list_add_tail(&piocb->list, &pring->txq);
9359 }
9360 
9361 /**
9362  * lpfc_sli_next_iocb - Get the next iocb in the txq
9363  * @phba: Pointer to HBA context object.
9364  * @pring: Pointer to driver SLI ring object.
9365  * @piocb: Pointer to address of newly added command iocb.
9366  *
9367  * This function is called with hbalock held before a new
9368  * iocb is submitted to the firmware. This function checks
9369  * txq to flush the iocbs in txq to Firmware before
9370  * submitting new iocbs to the Firmware.
9371  * If there are iocbs in the txq which need to be submitted
9372  * to firmware, lpfc_sli_next_iocb returns the first element
9373  * of the txq after dequeuing it from txq.
9374  * If there is no iocb in the txq then the function will return
9375  * *piocb and *piocb is set to NULL. Caller needs to check
9376  * *piocb to find if there are more commands in the txq.
9377  **/
9378 static struct lpfc_iocbq *
9379 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9380 		   struct lpfc_iocbq **piocb)
9381 {
9382 	struct lpfc_iocbq * nextiocb;
9383 
9384 	lockdep_assert_held(&phba->hbalock);
9385 
9386 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
9387 	if (!nextiocb) {
9388 		nextiocb = *piocb;
9389 		*piocb = NULL;
9390 	}
9391 
9392 	return nextiocb;
9393 }
9394 
9395 /**
9396  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
9397  * @phba: Pointer to HBA context object.
9398  * @ring_number: SLI ring number to issue iocb on.
9399  * @piocb: Pointer to command iocb.
9400  * @flag: Flag indicating if this command can be put into txq.
9401  *
9402  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
9403  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
9404  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
9405  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
9406  * this function allows only iocbs for posting buffers. This function finds
9407  * next available slot in the command ring and posts the command to the
9408  * available slot and writes the port attention register to request HBA start
9409  * processing new iocb. If there is no slot available in the ring and
9410  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
9411  * the function returns IOCB_BUSY.
9412  *
9413  * This function is called with hbalock held. The function will return success
9414  * after it successfully submit the iocb to firmware or after adding to the
9415  * txq.
9416  **/
9417 static int
9418 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
9419 		    struct lpfc_iocbq *piocb, uint32_t flag)
9420 {
9421 	struct lpfc_iocbq *nextiocb;
9422 	IOCB_t *iocb;
9423 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
9424 
9425 	lockdep_assert_held(&phba->hbalock);
9426 
9427 	if (piocb->iocb_cmpl && (!piocb->vport) &&
9428 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
9429 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
9430 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9431 				"1807 IOCB x%x failed. No vport\n",
9432 				piocb->iocb.ulpCommand);
9433 		dump_stack();
9434 		return IOCB_ERROR;
9435 	}
9436 
9437 
9438 	/* If the PCI channel is in offline state, do not post iocbs. */
9439 	if (unlikely(pci_channel_offline(phba->pcidev)))
9440 		return IOCB_ERROR;
9441 
9442 	/* If HBA has a deferred error attention, fail the iocb. */
9443 	if (unlikely(phba->hba_flag & DEFER_ERATT))
9444 		return IOCB_ERROR;
9445 
9446 	/*
9447 	 * We should never get an IOCB if we are in a < LINK_DOWN state
9448 	 */
9449 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
9450 		return IOCB_ERROR;
9451 
9452 	/*
9453 	 * Check to see if we are blocking IOCB processing because of a
9454 	 * outstanding event.
9455 	 */
9456 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
9457 		goto iocb_busy;
9458 
9459 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
9460 		/*
9461 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
9462 		 * can be issued if the link is not up.
9463 		 */
9464 		switch (piocb->iocb.ulpCommand) {
9465 		case CMD_GEN_REQUEST64_CR:
9466 		case CMD_GEN_REQUEST64_CX:
9467 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
9468 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
9469 					FC_RCTL_DD_UNSOL_CMD) ||
9470 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
9471 					MENLO_TRANSPORT_TYPE))
9472 
9473 				goto iocb_busy;
9474 			break;
9475 		case CMD_QUE_RING_BUF_CN:
9476 		case CMD_QUE_RING_BUF64_CN:
9477 			/*
9478 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
9479 			 * completion, iocb_cmpl MUST be 0.
9480 			 */
9481 			if (piocb->iocb_cmpl)
9482 				piocb->iocb_cmpl = NULL;
9483 			fallthrough;
9484 		case CMD_CREATE_XRI_CR:
9485 		case CMD_CLOSE_XRI_CN:
9486 		case CMD_CLOSE_XRI_CX:
9487 			break;
9488 		default:
9489 			goto iocb_busy;
9490 		}
9491 
9492 	/*
9493 	 * For FCP commands, we must be in a state where we can process link
9494 	 * attention events.
9495 	 */
9496 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
9497 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
9498 		goto iocb_busy;
9499 	}
9500 
9501 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
9502 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
9503 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
9504 
9505 	if (iocb)
9506 		lpfc_sli_update_ring(phba, pring);
9507 	else
9508 		lpfc_sli_update_full_ring(phba, pring);
9509 
9510 	if (!piocb)
9511 		return IOCB_SUCCESS;
9512 
9513 	goto out_busy;
9514 
9515  iocb_busy:
9516 	pring->stats.iocb_cmd_delay++;
9517 
9518  out_busy:
9519 
9520 	if (!(flag & SLI_IOCB_RET_IOCB)) {
9521 		__lpfc_sli_ringtx_put(phba, pring, piocb);
9522 		return IOCB_SUCCESS;
9523 	}
9524 
9525 	return IOCB_BUSY;
9526 }
9527 
9528 /**
9529  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
9530  * @phba: Pointer to HBA context object.
9531  * @piocbq: Pointer to command iocb.
9532  * @sglq: Pointer to the scatter gather queue object.
9533  *
9534  * This routine converts the bpl or bde that is in the IOCB
9535  * to a sgl list for the sli4 hardware. The physical address
9536  * of the bpl/bde is converted back to a virtual address.
9537  * If the IOCB contains a BPL then the list of BDE's is
9538  * converted to sli4_sge's. If the IOCB contains a single
9539  * BDE then it is converted to a single sli_sge.
9540  * The IOCB is still in cpu endianess so the contents of
9541  * the bpl can be used without byte swapping.
9542  *
9543  * Returns valid XRI = Success, NO_XRI = Failure.
9544 **/
9545 static uint16_t
9546 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
9547 		struct lpfc_sglq *sglq)
9548 {
9549 	uint16_t xritag = NO_XRI;
9550 	struct ulp_bde64 *bpl = NULL;
9551 	struct ulp_bde64 bde;
9552 	struct sli4_sge *sgl  = NULL;
9553 	struct lpfc_dmabuf *dmabuf;
9554 	IOCB_t *icmd;
9555 	int numBdes = 0;
9556 	int i = 0;
9557 	uint32_t offset = 0; /* accumulated offset in the sg request list */
9558 	int inbound = 0; /* number of sg reply entries inbound from firmware */
9559 
9560 	if (!piocbq || !sglq)
9561 		return xritag;
9562 
9563 	sgl  = (struct sli4_sge *)sglq->sgl;
9564 	icmd = &piocbq->iocb;
9565 	if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
9566 		return sglq->sli4_xritag;
9567 	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9568 		numBdes = icmd->un.genreq64.bdl.bdeSize /
9569 				sizeof(struct ulp_bde64);
9570 		/* The addrHigh and addrLow fields within the IOCB
9571 		 * have not been byteswapped yet so there is no
9572 		 * need to swap them back.
9573 		 */
9574 		if (piocbq->context3)
9575 			dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
9576 		else
9577 			return xritag;
9578 
9579 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
9580 		if (!bpl)
9581 			return xritag;
9582 
9583 		for (i = 0; i < numBdes; i++) {
9584 			/* Should already be byte swapped. */
9585 			sgl->addr_hi = bpl->addrHigh;
9586 			sgl->addr_lo = bpl->addrLow;
9587 
9588 			sgl->word2 = le32_to_cpu(sgl->word2);
9589 			if ((i+1) == numBdes)
9590 				bf_set(lpfc_sli4_sge_last, sgl, 1);
9591 			else
9592 				bf_set(lpfc_sli4_sge_last, sgl, 0);
9593 			/* swap the size field back to the cpu so we
9594 			 * can assign it to the sgl.
9595 			 */
9596 			bde.tus.w = le32_to_cpu(bpl->tus.w);
9597 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
9598 			/* The offsets in the sgl need to be accumulated
9599 			 * separately for the request and reply lists.
9600 			 * The request is always first, the reply follows.
9601 			 */
9602 			if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
9603 				/* add up the reply sg entries */
9604 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
9605 					inbound++;
9606 				/* first inbound? reset the offset */
9607 				if (inbound == 1)
9608 					offset = 0;
9609 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
9610 				bf_set(lpfc_sli4_sge_type, sgl,
9611 					LPFC_SGE_TYPE_DATA);
9612 				offset += bde.tus.f.bdeSize;
9613 			}
9614 			sgl->word2 = cpu_to_le32(sgl->word2);
9615 			bpl++;
9616 			sgl++;
9617 		}
9618 	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
9619 			/* The addrHigh and addrLow fields of the BDE have not
9620 			 * been byteswapped yet so they need to be swapped
9621 			 * before putting them in the sgl.
9622 			 */
9623 			sgl->addr_hi =
9624 				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
9625 			sgl->addr_lo =
9626 				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
9627 			sgl->word2 = le32_to_cpu(sgl->word2);
9628 			bf_set(lpfc_sli4_sge_last, sgl, 1);
9629 			sgl->word2 = cpu_to_le32(sgl->word2);
9630 			sgl->sge_len =
9631 				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
9632 	}
9633 	return sglq->sli4_xritag;
9634 }
9635 
9636 /**
9637  * lpfc_sli4_iocb2wqe - Convert the IOCB to a work queue entry.
9638  * @phba: Pointer to HBA context object.
9639  * @iocbq: Pointer to command iocb.
9640  * @wqe: Pointer to the work queue entry.
9641  *
9642  * This routine converts the iocb command to its Work Queue Entry
9643  * equivalent. The wqe pointer should not have any fields set when
9644  * this routine is called because it will memcpy over them.
9645  * This routine does not set the CQ_ID or the WQEC bits in the
9646  * wqe.
9647  *
9648  * Returns: 0 = Success, IOCB_ERROR = Failure.
9649  **/
9650 static int
9651 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
9652 		union lpfc_wqe128 *wqe)
9653 {
9654 	uint32_t xmit_len = 0, total_len = 0;
9655 	uint8_t ct = 0;
9656 	uint32_t fip;
9657 	uint32_t abort_tag;
9658 	uint8_t command_type = ELS_COMMAND_NON_FIP;
9659 	uint8_t cmnd;
9660 	uint16_t xritag;
9661 	uint16_t abrt_iotag;
9662 	struct lpfc_iocbq *abrtiocbq;
9663 	struct ulp_bde64 *bpl = NULL;
9664 	uint32_t els_id = LPFC_ELS_ID_DEFAULT;
9665 	int numBdes, i;
9666 	struct ulp_bde64 bde;
9667 	struct lpfc_nodelist *ndlp;
9668 	uint32_t *pcmd;
9669 	uint32_t if_type;
9670 
9671 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
9672 	/* The fcp commands will set command type */
9673 	if (iocbq->iocb_flag &  LPFC_IO_FCP)
9674 		command_type = FCP_COMMAND;
9675 	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
9676 		command_type = ELS_COMMAND_FIP;
9677 	else
9678 		command_type = ELS_COMMAND_NON_FIP;
9679 
9680 	if (phba->fcp_embed_io)
9681 		memset(wqe, 0, sizeof(union lpfc_wqe128));
9682 	/* Some of the fields are in the right position already */
9683 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
9684 	/* The ct field has moved so reset */
9685 	wqe->generic.wqe_com.word7 = 0;
9686 	wqe->generic.wqe_com.word10 = 0;
9687 
9688 	abort_tag = (uint32_t) iocbq->iotag;
9689 	xritag = iocbq->sli4_xritag;
9690 	/* words0-2 bpl convert bde */
9691 	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9692 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
9693 				sizeof(struct ulp_bde64);
9694 		bpl  = (struct ulp_bde64 *)
9695 			((struct lpfc_dmabuf *)iocbq->context3)->virt;
9696 		if (!bpl)
9697 			return IOCB_ERROR;
9698 
9699 		/* Should already be byte swapped. */
9700 		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
9701 		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
9702 		/* swap the size field back to the cpu so we
9703 		 * can assign it to the sgl.
9704 		 */
9705 		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
9706 		xmit_len = wqe->generic.bde.tus.f.bdeSize;
9707 		total_len = 0;
9708 		for (i = 0; i < numBdes; i++) {
9709 			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
9710 			total_len += bde.tus.f.bdeSize;
9711 		}
9712 	} else
9713 		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
9714 
9715 	iocbq->iocb.ulpIoTag = iocbq->iotag;
9716 	cmnd = iocbq->iocb.ulpCommand;
9717 
9718 	switch (iocbq->iocb.ulpCommand) {
9719 	case CMD_ELS_REQUEST64_CR:
9720 		if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
9721 			ndlp = iocbq->context_un.ndlp;
9722 		else
9723 			ndlp = (struct lpfc_nodelist *)iocbq->context1;
9724 		if (!iocbq->iocb.ulpLe) {
9725 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9726 				"2007 Only Limited Edition cmd Format"
9727 				" supported 0x%x\n",
9728 				iocbq->iocb.ulpCommand);
9729 			return IOCB_ERROR;
9730 		}
9731 
9732 		wqe->els_req.payload_len = xmit_len;
9733 		/* Els_reguest64 has a TMO */
9734 		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
9735 			iocbq->iocb.ulpTimeout);
9736 		/* Need a VF for word 4 set the vf bit*/
9737 		bf_set(els_req64_vf, &wqe->els_req, 0);
9738 		/* And a VFID for word 12 */
9739 		bf_set(els_req64_vfid, &wqe->els_req, 0);
9740 		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
9741 		bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9742 		       iocbq->iocb.ulpContext);
9743 		bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
9744 		bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
9745 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
9746 		if (command_type == ELS_COMMAND_FIP)
9747 			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
9748 					>> LPFC_FIP_ELS_ID_SHIFT);
9749 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9750 					iocbq->context2)->virt);
9751 		if_type = bf_get(lpfc_sli_intf_if_type,
9752 					&phba->sli4_hba.sli_intf);
9753 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9754 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
9755 				*pcmd == ELS_CMD_SCR ||
9756 				*pcmd == ELS_CMD_RDF ||
9757 				*pcmd == ELS_CMD_RSCN_XMT ||
9758 				*pcmd == ELS_CMD_FDISC ||
9759 				*pcmd == ELS_CMD_LOGO ||
9760 				*pcmd == ELS_CMD_PLOGI)) {
9761 				bf_set(els_req64_sp, &wqe->els_req, 1);
9762 				bf_set(els_req64_sid, &wqe->els_req,
9763 					iocbq->vport->fc_myDID);
9764 				if ((*pcmd == ELS_CMD_FLOGI) &&
9765 					!(phba->fc_topology ==
9766 						LPFC_TOPOLOGY_LOOP))
9767 					bf_set(els_req64_sid, &wqe->els_req, 0);
9768 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
9769 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9770 					phba->vpi_ids[iocbq->vport->vpi]);
9771 			} else if (pcmd && iocbq->context1) {
9772 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
9773 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9774 					phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9775 			}
9776 		}
9777 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
9778 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9779 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
9780 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
9781 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
9782 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
9783 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
9784 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
9785 		wqe->els_req.max_response_payload_len = total_len - xmit_len;
9786 		break;
9787 	case CMD_XMIT_SEQUENCE64_CX:
9788 		bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
9789 		       iocbq->iocb.un.ulpWord[3]);
9790 		bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
9791 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
9792 		/* The entire sequence is transmitted for this IOCB */
9793 		xmit_len = total_len;
9794 		cmnd = CMD_XMIT_SEQUENCE64_CR;
9795 		if (phba->link_flag & LS_LOOPBACK_MODE)
9796 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
9797 		fallthrough;
9798 	case CMD_XMIT_SEQUENCE64_CR:
9799 		/* word3 iocb=io_tag32 wqe=reserved */
9800 		wqe->xmit_sequence.rsvd3 = 0;
9801 		/* word4 relative_offset memcpy */
9802 		/* word5 r_ctl/df_ctl memcpy */
9803 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
9804 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
9805 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
9806 		       LPFC_WQE_IOD_WRITE);
9807 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
9808 		       LPFC_WQE_LENLOC_WORD12);
9809 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
9810 		wqe->xmit_sequence.xmit_len = xmit_len;
9811 		command_type = OTHER_COMMAND;
9812 		break;
9813 	case CMD_XMIT_BCAST64_CN:
9814 		/* word3 iocb=iotag32 wqe=seq_payload_len */
9815 		wqe->xmit_bcast64.seq_payload_len = xmit_len;
9816 		/* word4 iocb=rsvd wqe=rsvd */
9817 		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
9818 		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
9819 		bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
9820 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9821 		bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
9822 		bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
9823 		bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
9824 		       LPFC_WQE_LENLOC_WORD3);
9825 		bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
9826 		break;
9827 	case CMD_FCP_IWRITE64_CR:
9828 		command_type = FCP_COMMAND_DATA_OUT;
9829 		/* word3 iocb=iotag wqe=payload_offset_len */
9830 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9831 		bf_set(payload_offset_len, &wqe->fcp_iwrite,
9832 		       xmit_len + sizeof(struct fcp_rsp));
9833 		bf_set(cmd_buff_len, &wqe->fcp_iwrite,
9834 		       0);
9835 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9836 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9837 		bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
9838 		       iocbq->iocb.ulpFCP2Rcvy);
9839 		bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
9840 		/* Always open the exchange */
9841 		bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
9842 		bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
9843 		       LPFC_WQE_LENLOC_WORD4);
9844 		bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
9845 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
9846 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9847 			bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
9848 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
9849 			if (iocbq->priority) {
9850 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9851 				       (iocbq->priority << 1));
9852 			} else {
9853 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9854 				       (phba->cfg_XLanePriority << 1));
9855 			}
9856 		}
9857 		/* Note, word 10 is already initialized to 0 */
9858 
9859 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9860 		if (phba->cfg_enable_pbde)
9861 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 1);
9862 		else
9863 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
9864 
9865 		if (phba->fcp_embed_io) {
9866 			struct lpfc_io_buf *lpfc_cmd;
9867 			struct sli4_sge *sgl;
9868 			struct fcp_cmnd *fcp_cmnd;
9869 			uint32_t *ptr;
9870 
9871 			/* 128 byte wqe support here */
9872 
9873 			lpfc_cmd = iocbq->context1;
9874 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9875 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9876 
9877 			/* Word 0-2 - FCP_CMND */
9878 			wqe->generic.bde.tus.f.bdeFlags =
9879 				BUFF_TYPE_BDE_IMMED;
9880 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9881 			wqe->generic.bde.addrHigh = 0;
9882 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9883 
9884 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
9885 			bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
9886 
9887 			/* Word 22-29  FCP CMND Payload */
9888 			ptr = &wqe->words[22];
9889 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9890 		}
9891 		break;
9892 	case CMD_FCP_IREAD64_CR:
9893 		/* word3 iocb=iotag wqe=payload_offset_len */
9894 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9895 		bf_set(payload_offset_len, &wqe->fcp_iread,
9896 		       xmit_len + sizeof(struct fcp_rsp));
9897 		bf_set(cmd_buff_len, &wqe->fcp_iread,
9898 		       0);
9899 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9900 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9901 		bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
9902 		       iocbq->iocb.ulpFCP2Rcvy);
9903 		bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
9904 		/* Always open the exchange */
9905 		bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
9906 		bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
9907 		       LPFC_WQE_LENLOC_WORD4);
9908 		bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
9909 		bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
9910 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9911 			bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
9912 			bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
9913 			if (iocbq->priority) {
9914 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9915 				       (iocbq->priority << 1));
9916 			} else {
9917 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9918 				       (phba->cfg_XLanePriority << 1));
9919 			}
9920 		}
9921 		/* Note, word 10 is already initialized to 0 */
9922 
9923 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9924 		if (phba->cfg_enable_pbde)
9925 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 1);
9926 		else
9927 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
9928 
9929 		if (phba->fcp_embed_io) {
9930 			struct lpfc_io_buf *lpfc_cmd;
9931 			struct sli4_sge *sgl;
9932 			struct fcp_cmnd *fcp_cmnd;
9933 			uint32_t *ptr;
9934 
9935 			/* 128 byte wqe support here */
9936 
9937 			lpfc_cmd = iocbq->context1;
9938 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9939 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9940 
9941 			/* Word 0-2 - FCP_CMND */
9942 			wqe->generic.bde.tus.f.bdeFlags =
9943 				BUFF_TYPE_BDE_IMMED;
9944 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9945 			wqe->generic.bde.addrHigh = 0;
9946 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9947 
9948 			bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
9949 			bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
9950 
9951 			/* Word 22-29  FCP CMND Payload */
9952 			ptr = &wqe->words[22];
9953 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9954 		}
9955 		break;
9956 	case CMD_FCP_ICMND64_CR:
9957 		/* word3 iocb=iotag wqe=payload_offset_len */
9958 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9959 		bf_set(payload_offset_len, &wqe->fcp_icmd,
9960 		       xmit_len + sizeof(struct fcp_rsp));
9961 		bf_set(cmd_buff_len, &wqe->fcp_icmd,
9962 		       0);
9963 		/* word3 iocb=IO_TAG wqe=reserved */
9964 		bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
9965 		/* Always open the exchange */
9966 		bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
9967 		bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
9968 		bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
9969 		bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
9970 		       LPFC_WQE_LENLOC_NONE);
9971 		bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
9972 		       iocbq->iocb.ulpFCP2Rcvy);
9973 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9974 			bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
9975 			bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
9976 			if (iocbq->priority) {
9977 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9978 				       (iocbq->priority << 1));
9979 			} else {
9980 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9981 				       (phba->cfg_XLanePriority << 1));
9982 			}
9983 		}
9984 		/* Note, word 10 is already initialized to 0 */
9985 
9986 		if (phba->fcp_embed_io) {
9987 			struct lpfc_io_buf *lpfc_cmd;
9988 			struct sli4_sge *sgl;
9989 			struct fcp_cmnd *fcp_cmnd;
9990 			uint32_t *ptr;
9991 
9992 			/* 128 byte wqe support here */
9993 
9994 			lpfc_cmd = iocbq->context1;
9995 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9996 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9997 
9998 			/* Word 0-2 - FCP_CMND */
9999 			wqe->generic.bde.tus.f.bdeFlags =
10000 				BUFF_TYPE_BDE_IMMED;
10001 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10002 			wqe->generic.bde.addrHigh = 0;
10003 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
10004 
10005 			bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
10006 			bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
10007 
10008 			/* Word 22-29  FCP CMND Payload */
10009 			ptr = &wqe->words[22];
10010 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10011 		}
10012 		break;
10013 	case CMD_GEN_REQUEST64_CR:
10014 		/* For this command calculate the xmit length of the
10015 		 * request bde.
10016 		 */
10017 		xmit_len = 0;
10018 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
10019 			sizeof(struct ulp_bde64);
10020 		for (i = 0; i < numBdes; i++) {
10021 			bde.tus.w = le32_to_cpu(bpl[i].tus.w);
10022 			if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
10023 				break;
10024 			xmit_len += bde.tus.f.bdeSize;
10025 		}
10026 		/* word3 iocb=IO_TAG wqe=request_payload_len */
10027 		wqe->gen_req.request_payload_len = xmit_len;
10028 		/* word4 iocb=parameter wqe=relative_offset memcpy */
10029 		/* word5 [rctl, type, df_ctl, la] copied in memcpy */
10030 		/* word6 context tag copied in memcpy */
10031 		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
10032 			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
10033 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10034 				"2015 Invalid CT %x command 0x%x\n",
10035 				ct, iocbq->iocb.ulpCommand);
10036 			return IOCB_ERROR;
10037 		}
10038 		bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
10039 		bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
10040 		bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
10041 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
10042 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
10043 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
10044 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
10045 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
10046 		wqe->gen_req.max_response_payload_len = total_len - xmit_len;
10047 		command_type = OTHER_COMMAND;
10048 		break;
10049 	case CMD_XMIT_ELS_RSP64_CX:
10050 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
10051 		/* words0-2 BDE memcpy */
10052 		/* word3 iocb=iotag32 wqe=response_payload_len */
10053 		wqe->xmit_els_rsp.response_payload_len = xmit_len;
10054 		/* word4 */
10055 		wqe->xmit_els_rsp.word4 = 0;
10056 		/* word5 iocb=rsvd wge=did */
10057 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
10058 			 iocbq->iocb.un.xseq64.xmit_els_remoteID);
10059 
10060 		if_type = bf_get(lpfc_sli_intf_if_type,
10061 					&phba->sli4_hba.sli_intf);
10062 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10063 			if (iocbq->vport->fc_flag & FC_PT2PT) {
10064 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
10065 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
10066 					iocbq->vport->fc_myDID);
10067 				if (iocbq->vport->fc_myDID == Fabric_DID) {
10068 					bf_set(wqe_els_did,
10069 						&wqe->xmit_els_rsp.wqe_dest, 0);
10070 				}
10071 			}
10072 		}
10073 		bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
10074 		       ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
10075 		bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
10076 		bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
10077 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
10078 		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
10079 			bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
10080 			       phba->vpi_ids[iocbq->vport->vpi]);
10081 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
10082 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
10083 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
10084 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
10085 		       LPFC_WQE_LENLOC_WORD3);
10086 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
10087 		bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
10088 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
10089 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
10090 					iocbq->context2)->virt);
10091 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
10092 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
10093 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
10094 					iocbq->vport->fc_myDID);
10095 				bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
10096 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
10097 					phba->vpi_ids[phba->pport->vpi]);
10098 		}
10099 		command_type = OTHER_COMMAND;
10100 		break;
10101 	case CMD_CLOSE_XRI_CN:
10102 	case CMD_ABORT_XRI_CN:
10103 	case CMD_ABORT_XRI_CX:
10104 		/* words 0-2 memcpy should be 0 rserved */
10105 		/* port will send abts */
10106 		abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
10107 		if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
10108 			abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
10109 			fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
10110 		} else
10111 			fip = 0;
10112 
10113 		if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
10114 			/*
10115 			 * The link is down, or the command was ELS_FIP
10116 			 * so the fw does not need to send abts
10117 			 * on the wire.
10118 			 */
10119 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
10120 		else
10121 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
10122 		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
10123 		/* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
10124 		wqe->abort_cmd.rsrvd5 = 0;
10125 		bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
10126 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
10127 		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
10128 		/*
10129 		 * The abort handler will send us CMD_ABORT_XRI_CN or
10130 		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
10131 		 */
10132 		bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
10133 		bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
10134 		bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
10135 		       LPFC_WQE_LENLOC_NONE);
10136 		cmnd = CMD_ABORT_XRI_CX;
10137 		command_type = OTHER_COMMAND;
10138 		xritag = 0;
10139 		break;
10140 	case CMD_XMIT_BLS_RSP64_CX:
10141 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
10142 		/* As BLS ABTS RSP WQE is very different from other WQEs,
10143 		 * we re-construct this WQE here based on information in
10144 		 * iocbq from scratch.
10145 		 */
10146 		memset(wqe, 0, sizeof(*wqe));
10147 		/* OX_ID is invariable to who sent ABTS to CT exchange */
10148 		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
10149 		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
10150 		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
10151 		    LPFC_ABTS_UNSOL_INT) {
10152 			/* ABTS sent by initiator to CT exchange, the
10153 			 * RX_ID field will be filled with the newly
10154 			 * allocated responder XRI.
10155 			 */
10156 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10157 			       iocbq->sli4_xritag);
10158 		} else {
10159 			/* ABTS sent by responder to CT exchange, the
10160 			 * RX_ID field will be filled with the responder
10161 			 * RX_ID from ABTS.
10162 			 */
10163 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10164 			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
10165 		}
10166 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
10167 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
10168 
10169 		/* Use CT=VPI */
10170 		bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
10171 			ndlp->nlp_DID);
10172 		bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
10173 			iocbq->iocb.ulpContext);
10174 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
10175 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
10176 			phba->vpi_ids[phba->pport->vpi]);
10177 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
10178 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
10179 		       LPFC_WQE_LENLOC_NONE);
10180 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
10181 		command_type = OTHER_COMMAND;
10182 		if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
10183 			bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
10184 			       bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
10185 			bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
10186 			       bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
10187 			bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
10188 			       bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
10189 		}
10190 
10191 		break;
10192 	case CMD_SEND_FRAME:
10193 		bf_set(wqe_cmnd, &wqe->generic.wqe_com, CMD_SEND_FRAME);
10194 		bf_set(wqe_sof, &wqe->generic.wqe_com, 0x2E); /* SOF byte */
10195 		bf_set(wqe_eof, &wqe->generic.wqe_com, 0x41); /* EOF byte */
10196 		bf_set(wqe_lenloc, &wqe->generic.wqe_com, 1);
10197 		bf_set(wqe_xbl, &wqe->generic.wqe_com, 1);
10198 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10199 		bf_set(wqe_xc, &wqe->generic.wqe_com, 1);
10200 		bf_set(wqe_cmd_type, &wqe->generic.wqe_com, 0xA);
10201 		bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10202 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10203 		bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10204 		return 0;
10205 	case CMD_XRI_ABORTED_CX:
10206 	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
10207 	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
10208 	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
10209 	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
10210 	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
10211 	default:
10212 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10213 				"2014 Invalid command 0x%x\n",
10214 				iocbq->iocb.ulpCommand);
10215 		return IOCB_ERROR;
10216 	}
10217 
10218 	if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
10219 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
10220 	else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
10221 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
10222 	else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
10223 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
10224 	iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
10225 			      LPFC_IO_DIF_INSERT);
10226 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10227 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10228 	wqe->generic.wqe_com.abort_tag = abort_tag;
10229 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
10230 	bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
10231 	bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
10232 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10233 	return 0;
10234 }
10235 
10236 /**
10237  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10238  * @phba: Pointer to HBA context object.
10239  * @ring_number: SLI ring number to issue wqe on.
10240  * @piocb: Pointer to command iocb.
10241  * @flag: Flag indicating if this command can be put into txq.
10242  *
10243  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10244  * send  an iocb command to an HBA with SLI-4 interface spec.
10245  *
10246  * This function takes the hbalock before invoking the lockless version.
10247  * The function will return success after it successfully submit the wqe to
10248  * firmware or after adding to the txq.
10249  **/
10250 static int
10251 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10252 			   struct lpfc_iocbq *piocb, uint32_t flag)
10253 {
10254 	unsigned long iflags;
10255 	int rc;
10256 
10257 	spin_lock_irqsave(&phba->hbalock, iflags);
10258 	rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10259 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10260 
10261 	return rc;
10262 }
10263 
10264 /**
10265  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10266  * @phba: Pointer to HBA context object.
10267  * @ring_number: SLI ring number to issue wqe on.
10268  * @piocb: Pointer to command iocb.
10269  * @flag: Flag indicating if this command can be put into txq.
10270  *
10271  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10272  * an wqe command to an HBA with SLI-4 interface spec.
10273  *
10274  * This function is a lockless version. The function will return success
10275  * after it successfully submit the wqe to firmware or after adding to the
10276  * txq.
10277  **/
10278 static int
10279 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10280 			   struct lpfc_iocbq *piocb, uint32_t flag)
10281 {
10282 	int rc;
10283 	struct lpfc_io_buf *lpfc_cmd =
10284 		(struct lpfc_io_buf *)piocb->context1;
10285 	union lpfc_wqe128 *wqe = &piocb->wqe;
10286 	struct sli4_sge *sgl;
10287 
10288 	/* 128 byte wqe support here */
10289 	sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10290 
10291 	if (phba->fcp_embed_io) {
10292 		struct fcp_cmnd *fcp_cmnd;
10293 		u32 *ptr;
10294 
10295 		fcp_cmnd = lpfc_cmd->fcp_cmnd;
10296 
10297 		/* Word 0-2 - FCP_CMND */
10298 		wqe->generic.bde.tus.f.bdeFlags =
10299 			BUFF_TYPE_BDE_IMMED;
10300 		wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10301 		wqe->generic.bde.addrHigh = 0;
10302 		wqe->generic.bde.addrLow =  88;  /* Word 22 */
10303 
10304 		bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10305 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10306 
10307 		/* Word 22-29  FCP CMND Payload */
10308 		ptr = &wqe->words[22];
10309 		memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10310 	} else {
10311 		/* Word 0-2 - Inline BDE */
10312 		wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
10313 		wqe->generic.bde.tus.f.bdeSize = sizeof(struct fcp_cmnd);
10314 		wqe->generic.bde.addrHigh = sgl->addr_hi;
10315 		wqe->generic.bde.addrLow =  sgl->addr_lo;
10316 
10317 		/* Word 10 */
10318 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10319 		bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
10320 	}
10321 
10322 	rc = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
10323 	return rc;
10324 }
10325 
10326 /**
10327  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10328  * @phba: Pointer to HBA context object.
10329  * @ring_number: SLI ring number to issue iocb on.
10330  * @piocb: Pointer to command iocb.
10331  * @flag: Flag indicating if this command can be put into txq.
10332  *
10333  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10334  * an iocb command to an HBA with SLI-4 interface spec.
10335  *
10336  * This function is called with ringlock held. The function will return success
10337  * after it successfully submit the iocb to firmware or after adding to the
10338  * txq.
10339  **/
10340 static int
10341 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10342 			 struct lpfc_iocbq *piocb, uint32_t flag)
10343 {
10344 	struct lpfc_sglq *sglq;
10345 	union lpfc_wqe128 wqe;
10346 	struct lpfc_queue *wq;
10347 	struct lpfc_sli_ring *pring;
10348 
10349 	/* Get the WQ */
10350 	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
10351 	    (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
10352 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10353 	} else {
10354 		wq = phba->sli4_hba.els_wq;
10355 	}
10356 
10357 	/* Get corresponding ring */
10358 	pring = wq->pring;
10359 
10360 	/*
10361 	 * The WQE can be either 64 or 128 bytes,
10362 	 */
10363 
10364 	lockdep_assert_held(&pring->ring_lock);
10365 
10366 	if (piocb->sli4_xritag == NO_XRI) {
10367 		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
10368 		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
10369 			sglq = NULL;
10370 		else {
10371 			if (!list_empty(&pring->txq)) {
10372 				if (!(flag & SLI_IOCB_RET_IOCB)) {
10373 					__lpfc_sli_ringtx_put(phba,
10374 						pring, piocb);
10375 					return IOCB_SUCCESS;
10376 				} else {
10377 					return IOCB_BUSY;
10378 				}
10379 			} else {
10380 				sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10381 				if (!sglq) {
10382 					if (!(flag & SLI_IOCB_RET_IOCB)) {
10383 						__lpfc_sli_ringtx_put(phba,
10384 								pring,
10385 								piocb);
10386 						return IOCB_SUCCESS;
10387 					} else
10388 						return IOCB_BUSY;
10389 				}
10390 			}
10391 		}
10392 	} else if (piocb->iocb_flag &  LPFC_IO_FCP) {
10393 		/* These IO's already have an XRI and a mapped sgl. */
10394 		sglq = NULL;
10395 	}
10396 	else {
10397 		/*
10398 		 * This is a continuation of a commandi,(CX) so this
10399 		 * sglq is on the active list
10400 		 */
10401 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10402 		if (!sglq)
10403 			return IOCB_ERROR;
10404 	}
10405 
10406 	if (sglq) {
10407 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10408 		piocb->sli4_xritag = sglq->sli4_xritag;
10409 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
10410 			return IOCB_ERROR;
10411 	}
10412 
10413 	if (lpfc_sli4_iocb2wqe(phba, piocb, &wqe))
10414 		return IOCB_ERROR;
10415 
10416 	if (lpfc_sli4_wq_put(wq, &wqe))
10417 		return IOCB_ERROR;
10418 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10419 
10420 	return 0;
10421 }
10422 
10423 /*
10424  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
10425  *
10426  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
10427  * or IOCB for sli-3  function.
10428  * pointer from the lpfc_hba struct.
10429  *
10430  * Return codes:
10431  * IOCB_ERROR - Error
10432  * IOCB_SUCCESS - Success
10433  * IOCB_BUSY - Busy
10434  **/
10435 int
10436 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
10437 		      struct lpfc_iocbq *piocb, uint32_t flag)
10438 {
10439 	return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
10440 }
10441 
10442 /*
10443  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10444  *
10445  * This routine wraps the actual lockless version for issusing IOCB function
10446  * pointer from the lpfc_hba struct.
10447  *
10448  * Return codes:
10449  * IOCB_ERROR - Error
10450  * IOCB_SUCCESS - Success
10451  * IOCB_BUSY - Busy
10452  **/
10453 int
10454 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10455 		struct lpfc_iocbq *piocb, uint32_t flag)
10456 {
10457 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10458 }
10459 
10460 /**
10461  * lpfc_sli_api_table_setup - Set up sli api function jump table
10462  * @phba: The hba struct for which this call is being executed.
10463  * @dev_grp: The HBA PCI-Device group number.
10464  *
10465  * This routine sets up the SLI interface API function jump table in @phba
10466  * struct.
10467  * Returns: 0 - success, -ENODEV - failure.
10468  **/
10469 int
10470 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10471 {
10472 
10473 	switch (dev_grp) {
10474 	case LPFC_PCI_DEV_LP:
10475 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
10476 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
10477 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
10478 		break;
10479 	case LPFC_PCI_DEV_OC:
10480 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
10481 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
10482 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
10483 		break;
10484 	default:
10485 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10486 				"1419 Invalid HBA PCI-device group: 0x%x\n",
10487 				dev_grp);
10488 		return -ENODEV;
10489 	}
10490 	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
10491 	return 0;
10492 }
10493 
10494 /**
10495  * lpfc_sli4_calc_ring - Calculates which ring to use
10496  * @phba: Pointer to HBA context object.
10497  * @piocb: Pointer to command iocb.
10498  *
10499  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
10500  * hba_wqidx, thus we need to calculate the corresponding ring.
10501  * Since ABORTS must go on the same WQ of the command they are
10502  * aborting, we use command's hba_wqidx.
10503  */
10504 struct lpfc_sli_ring *
10505 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
10506 {
10507 	struct lpfc_io_buf *lpfc_cmd;
10508 
10509 	if (piocb->iocb_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
10510 		if (unlikely(!phba->sli4_hba.hdwq))
10511 			return NULL;
10512 		/*
10513 		 * for abort iocb hba_wqidx should already
10514 		 * be setup based on what work queue we used.
10515 		 */
10516 		if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
10517 			lpfc_cmd = (struct lpfc_io_buf *)piocb->context1;
10518 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
10519 		}
10520 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
10521 	} else {
10522 		if (unlikely(!phba->sli4_hba.els_wq))
10523 			return NULL;
10524 		piocb->hba_wqidx = 0;
10525 		return phba->sli4_hba.els_wq->pring;
10526 	}
10527 }
10528 
10529 /**
10530  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
10531  * @phba: Pointer to HBA context object.
10532  * @ring_number: Ring number
10533  * @piocb: Pointer to command iocb.
10534  * @flag: Flag indicating if this command can be put into txq.
10535  *
10536  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
10537  * function. This function gets the hbalock and calls
10538  * __lpfc_sli_issue_iocb function and will return the error returned
10539  * by __lpfc_sli_issue_iocb function. This wrapper is used by
10540  * functions which do not hold hbalock.
10541  **/
10542 int
10543 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10544 		    struct lpfc_iocbq *piocb, uint32_t flag)
10545 {
10546 	struct lpfc_sli_ring *pring;
10547 	struct lpfc_queue *eq;
10548 	unsigned long iflags;
10549 	int rc;
10550 
10551 	if (phba->sli_rev == LPFC_SLI_REV4) {
10552 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
10553 
10554 		pring = lpfc_sli4_calc_ring(phba, piocb);
10555 		if (unlikely(pring == NULL))
10556 			return IOCB_ERROR;
10557 
10558 		spin_lock_irqsave(&pring->ring_lock, iflags);
10559 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10560 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
10561 
10562 		lpfc_sli4_poll_eq(eq, LPFC_POLL_FASTPATH);
10563 	} else {
10564 		/* For now, SLI2/3 will still use hbalock */
10565 		spin_lock_irqsave(&phba->hbalock, iflags);
10566 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10567 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10568 	}
10569 	return rc;
10570 }
10571 
10572 /**
10573  * lpfc_extra_ring_setup - Extra ring setup function
10574  * @phba: Pointer to HBA context object.
10575  *
10576  * This function is called while driver attaches with the
10577  * HBA to setup the extra ring. The extra ring is used
10578  * only when driver needs to support target mode functionality
10579  * or IP over FC functionalities.
10580  *
10581  * This function is called with no lock held. SLI3 only.
10582  **/
10583 static int
10584 lpfc_extra_ring_setup( struct lpfc_hba *phba)
10585 {
10586 	struct lpfc_sli *psli;
10587 	struct lpfc_sli_ring *pring;
10588 
10589 	psli = &phba->sli;
10590 
10591 	/* Adjust cmd/rsp ring iocb entries more evenly */
10592 
10593 	/* Take some away from the FCP ring */
10594 	pring = &psli->sli3_ring[LPFC_FCP_RING];
10595 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10596 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10597 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10598 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10599 
10600 	/* and give them to the extra ring */
10601 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
10602 
10603 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10604 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10605 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10606 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10607 
10608 	/* Setup default profile for this ring */
10609 	pring->iotag_max = 4096;
10610 	pring->num_mask = 1;
10611 	pring->prt[0].profile = 0;      /* Mask 0 */
10612 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
10613 	pring->prt[0].type = phba->cfg_multi_ring_type;
10614 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
10615 	return 0;
10616 }
10617 
10618 static void
10619 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
10620 			     struct lpfc_nodelist *ndlp)
10621 {
10622 	unsigned long iflags;
10623 	struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
10624 
10625 	spin_lock_irqsave(&phba->hbalock, iflags);
10626 	if (!list_empty(&evtp->evt_listp)) {
10627 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10628 		return;
10629 	}
10630 
10631 	/* Incrementing the reference count until the queued work is done. */
10632 	evtp->evt_arg1  = lpfc_nlp_get(ndlp);
10633 	if (!evtp->evt_arg1) {
10634 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10635 		return;
10636 	}
10637 	evtp->evt = LPFC_EVT_RECOVER_PORT;
10638 	list_add_tail(&evtp->evt_listp, &phba->work_list);
10639 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10640 
10641 	lpfc_worker_wake_up(phba);
10642 }
10643 
10644 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
10645  * @phba: Pointer to HBA context object.
10646  * @iocbq: Pointer to iocb object.
10647  *
10648  * The async_event handler calls this routine when it receives
10649  * an ASYNC_STATUS_CN event from the port.  The port generates
10650  * this event when an Abort Sequence request to an rport fails
10651  * twice in succession.  The abort could be originated by the
10652  * driver or by the port.  The ABTS could have been for an ELS
10653  * or FCP IO.  The port only generates this event when an ABTS
10654  * fails to complete after one retry.
10655  */
10656 static void
10657 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
10658 			  struct lpfc_iocbq *iocbq)
10659 {
10660 	struct lpfc_nodelist *ndlp = NULL;
10661 	uint16_t rpi = 0, vpi = 0;
10662 	struct lpfc_vport *vport = NULL;
10663 
10664 	/* The rpi in the ulpContext is vport-sensitive. */
10665 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
10666 	rpi = iocbq->iocb.ulpContext;
10667 
10668 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10669 			"3092 Port generated ABTS async event "
10670 			"on vpi %d rpi %d status 0x%x\n",
10671 			vpi, rpi, iocbq->iocb.ulpStatus);
10672 
10673 	vport = lpfc_find_vport_by_vpid(phba, vpi);
10674 	if (!vport)
10675 		goto err_exit;
10676 	ndlp = lpfc_findnode_rpi(vport, rpi);
10677 	if (!ndlp)
10678 		goto err_exit;
10679 
10680 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
10681 		lpfc_sli_abts_recover_port(vport, ndlp);
10682 	return;
10683 
10684  err_exit:
10685 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10686 			"3095 Event Context not found, no "
10687 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
10688 			iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
10689 			vpi, rpi);
10690 }
10691 
10692 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
10693  * @phba: pointer to HBA context object.
10694  * @ndlp: nodelist pointer for the impacted rport.
10695  * @axri: pointer to the wcqe containing the failed exchange.
10696  *
10697  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
10698  * port.  The port generates this event when an abort exchange request to an
10699  * rport fails twice in succession with no reply.  The abort could be originated
10700  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
10701  */
10702 void
10703 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
10704 			   struct lpfc_nodelist *ndlp,
10705 			   struct sli4_wcqe_xri_aborted *axri)
10706 {
10707 	uint32_t ext_status = 0;
10708 
10709 	if (!ndlp) {
10710 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10711 				"3115 Node Context not found, driver "
10712 				"ignoring abts err event\n");
10713 		return;
10714 	}
10715 
10716 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10717 			"3116 Port generated FCP XRI ABORT event on "
10718 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
10719 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
10720 			bf_get(lpfc_wcqe_xa_xri, axri),
10721 			bf_get(lpfc_wcqe_xa_status, axri),
10722 			axri->parameter);
10723 
10724 	/*
10725 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
10726 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
10727 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
10728 	 */
10729 	ext_status = axri->parameter & IOERR_PARAM_MASK;
10730 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
10731 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
10732 		lpfc_sli_post_recovery_event(phba, ndlp);
10733 }
10734 
10735 /**
10736  * lpfc_sli_async_event_handler - ASYNC iocb handler function
10737  * @phba: Pointer to HBA context object.
10738  * @pring: Pointer to driver SLI ring object.
10739  * @iocbq: Pointer to iocb object.
10740  *
10741  * This function is called by the slow ring event handler
10742  * function when there is an ASYNC event iocb in the ring.
10743  * This function is called with no lock held.
10744  * Currently this function handles only temperature related
10745  * ASYNC events. The function decodes the temperature sensor
10746  * event message and posts events for the management applications.
10747  **/
10748 static void
10749 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
10750 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
10751 {
10752 	IOCB_t *icmd;
10753 	uint16_t evt_code;
10754 	struct temp_event temp_event_data;
10755 	struct Scsi_Host *shost;
10756 	uint32_t *iocb_w;
10757 
10758 	icmd = &iocbq->iocb;
10759 	evt_code = icmd->un.asyncstat.evt_code;
10760 
10761 	switch (evt_code) {
10762 	case ASYNC_TEMP_WARN:
10763 	case ASYNC_TEMP_SAFE:
10764 		temp_event_data.data = (uint32_t) icmd->ulpContext;
10765 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
10766 		if (evt_code == ASYNC_TEMP_WARN) {
10767 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
10768 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10769 				"0347 Adapter is very hot, please take "
10770 				"corrective action. temperature : %d Celsius\n",
10771 				(uint32_t) icmd->ulpContext);
10772 		} else {
10773 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
10774 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10775 				"0340 Adapter temperature is OK now. "
10776 				"temperature : %d Celsius\n",
10777 				(uint32_t) icmd->ulpContext);
10778 		}
10779 
10780 		/* Send temperature change event to applications */
10781 		shost = lpfc_shost_from_vport(phba->pport);
10782 		fc_host_post_vendor_event(shost, fc_get_event_number(),
10783 			sizeof(temp_event_data), (char *) &temp_event_data,
10784 			LPFC_NL_VENDOR_ID);
10785 		break;
10786 	case ASYNC_STATUS_CN:
10787 		lpfc_sli_abts_err_handler(phba, iocbq);
10788 		break;
10789 	default:
10790 		iocb_w = (uint32_t *) icmd;
10791 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10792 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
10793 			" evt_code 0x%x\n"
10794 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
10795 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
10796 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
10797 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
10798 			pring->ringno, icmd->un.asyncstat.evt_code,
10799 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
10800 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
10801 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
10802 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
10803 
10804 		break;
10805 	}
10806 }
10807 
10808 
10809 /**
10810  * lpfc_sli4_setup - SLI ring setup function
10811  * @phba: Pointer to HBA context object.
10812  *
10813  * lpfc_sli_setup sets up rings of the SLI interface with
10814  * number of iocbs per ring and iotags. This function is
10815  * called while driver attach to the HBA and before the
10816  * interrupts are enabled. So there is no need for locking.
10817  *
10818  * This function always returns 0.
10819  **/
10820 int
10821 lpfc_sli4_setup(struct lpfc_hba *phba)
10822 {
10823 	struct lpfc_sli_ring *pring;
10824 
10825 	pring = phba->sli4_hba.els_wq->pring;
10826 	pring->num_mask = LPFC_MAX_RING_MASK;
10827 	pring->prt[0].profile = 0;	/* Mask 0 */
10828 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10829 	pring->prt[0].type = FC_TYPE_ELS;
10830 	pring->prt[0].lpfc_sli_rcv_unsol_event =
10831 	    lpfc_els_unsol_event;
10832 	pring->prt[1].profile = 0;	/* Mask 1 */
10833 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
10834 	pring->prt[1].type = FC_TYPE_ELS;
10835 	pring->prt[1].lpfc_sli_rcv_unsol_event =
10836 	    lpfc_els_unsol_event;
10837 	pring->prt[2].profile = 0;	/* Mask 2 */
10838 	/* NameServer Inquiry */
10839 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10840 	/* NameServer */
10841 	pring->prt[2].type = FC_TYPE_CT;
10842 	pring->prt[2].lpfc_sli_rcv_unsol_event =
10843 	    lpfc_ct_unsol_event;
10844 	pring->prt[3].profile = 0;	/* Mask 3 */
10845 	/* NameServer response */
10846 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10847 	/* NameServer */
10848 	pring->prt[3].type = FC_TYPE_CT;
10849 	pring->prt[3].lpfc_sli_rcv_unsol_event =
10850 	    lpfc_ct_unsol_event;
10851 	return 0;
10852 }
10853 
10854 /**
10855  * lpfc_sli_setup - SLI ring setup function
10856  * @phba: Pointer to HBA context object.
10857  *
10858  * lpfc_sli_setup sets up rings of the SLI interface with
10859  * number of iocbs per ring and iotags. This function is
10860  * called while driver attach to the HBA and before the
10861  * interrupts are enabled. So there is no need for locking.
10862  *
10863  * This function always returns 0. SLI3 only.
10864  **/
10865 int
10866 lpfc_sli_setup(struct lpfc_hba *phba)
10867 {
10868 	int i, totiocbsize = 0;
10869 	struct lpfc_sli *psli = &phba->sli;
10870 	struct lpfc_sli_ring *pring;
10871 
10872 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
10873 	psli->sli_flag = 0;
10874 
10875 	psli->iocbq_lookup = NULL;
10876 	psli->iocbq_lookup_len = 0;
10877 	psli->last_iotag = 0;
10878 
10879 	for (i = 0; i < psli->num_rings; i++) {
10880 		pring = &psli->sli3_ring[i];
10881 		switch (i) {
10882 		case LPFC_FCP_RING:	/* ring 0 - FCP */
10883 			/* numCiocb and numRiocb are used in config_port */
10884 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
10885 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
10886 			pring->sli.sli3.numCiocb +=
10887 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10888 			pring->sli.sli3.numRiocb +=
10889 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10890 			pring->sli.sli3.numCiocb +=
10891 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10892 			pring->sli.sli3.numRiocb +=
10893 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10894 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10895 							SLI3_IOCB_CMD_SIZE :
10896 							SLI2_IOCB_CMD_SIZE;
10897 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10898 							SLI3_IOCB_RSP_SIZE :
10899 							SLI2_IOCB_RSP_SIZE;
10900 			pring->iotag_ctr = 0;
10901 			pring->iotag_max =
10902 			    (phba->cfg_hba_queue_depth * 2);
10903 			pring->fast_iotag = pring->iotag_max;
10904 			pring->num_mask = 0;
10905 			break;
10906 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
10907 			/* numCiocb and numRiocb are used in config_port */
10908 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
10909 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
10910 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10911 							SLI3_IOCB_CMD_SIZE :
10912 							SLI2_IOCB_CMD_SIZE;
10913 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10914 							SLI3_IOCB_RSP_SIZE :
10915 							SLI2_IOCB_RSP_SIZE;
10916 			pring->iotag_max = phba->cfg_hba_queue_depth;
10917 			pring->num_mask = 0;
10918 			break;
10919 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
10920 			/* numCiocb and numRiocb are used in config_port */
10921 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
10922 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
10923 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10924 							SLI3_IOCB_CMD_SIZE :
10925 							SLI2_IOCB_CMD_SIZE;
10926 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10927 							SLI3_IOCB_RSP_SIZE :
10928 							SLI2_IOCB_RSP_SIZE;
10929 			pring->fast_iotag = 0;
10930 			pring->iotag_ctr = 0;
10931 			pring->iotag_max = 4096;
10932 			pring->lpfc_sli_rcv_async_status =
10933 				lpfc_sli_async_event_handler;
10934 			pring->num_mask = LPFC_MAX_RING_MASK;
10935 			pring->prt[0].profile = 0;	/* Mask 0 */
10936 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10937 			pring->prt[0].type = FC_TYPE_ELS;
10938 			pring->prt[0].lpfc_sli_rcv_unsol_event =
10939 			    lpfc_els_unsol_event;
10940 			pring->prt[1].profile = 0;	/* Mask 1 */
10941 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
10942 			pring->prt[1].type = FC_TYPE_ELS;
10943 			pring->prt[1].lpfc_sli_rcv_unsol_event =
10944 			    lpfc_els_unsol_event;
10945 			pring->prt[2].profile = 0;	/* Mask 2 */
10946 			/* NameServer Inquiry */
10947 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10948 			/* NameServer */
10949 			pring->prt[2].type = FC_TYPE_CT;
10950 			pring->prt[2].lpfc_sli_rcv_unsol_event =
10951 			    lpfc_ct_unsol_event;
10952 			pring->prt[3].profile = 0;	/* Mask 3 */
10953 			/* NameServer response */
10954 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10955 			/* NameServer */
10956 			pring->prt[3].type = FC_TYPE_CT;
10957 			pring->prt[3].lpfc_sli_rcv_unsol_event =
10958 			    lpfc_ct_unsol_event;
10959 			break;
10960 		}
10961 		totiocbsize += (pring->sli.sli3.numCiocb *
10962 			pring->sli.sli3.sizeCiocb) +
10963 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
10964 	}
10965 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
10966 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
10967 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
10968 		       "SLI2 SLIM Data: x%x x%lx\n",
10969 		       phba->brd_no, totiocbsize,
10970 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
10971 	}
10972 	if (phba->cfg_multi_ring_support == 2)
10973 		lpfc_extra_ring_setup(phba);
10974 
10975 	return 0;
10976 }
10977 
10978 /**
10979  * lpfc_sli4_queue_init - Queue initialization function
10980  * @phba: Pointer to HBA context object.
10981  *
10982  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
10983  * ring. This function also initializes ring indices of each ring.
10984  * This function is called during the initialization of the SLI
10985  * interface of an HBA.
10986  * This function is called with no lock held and always returns
10987  * 1.
10988  **/
10989 void
10990 lpfc_sli4_queue_init(struct lpfc_hba *phba)
10991 {
10992 	struct lpfc_sli *psli;
10993 	struct lpfc_sli_ring *pring;
10994 	int i;
10995 
10996 	psli = &phba->sli;
10997 	spin_lock_irq(&phba->hbalock);
10998 	INIT_LIST_HEAD(&psli->mboxq);
10999 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11000 	/* Initialize list headers for txq and txcmplq as double linked lists */
11001 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
11002 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
11003 		pring->flag = 0;
11004 		pring->ringno = LPFC_FCP_RING;
11005 		pring->txcmplq_cnt = 0;
11006 		INIT_LIST_HEAD(&pring->txq);
11007 		INIT_LIST_HEAD(&pring->txcmplq);
11008 		INIT_LIST_HEAD(&pring->iocb_continueq);
11009 		spin_lock_init(&pring->ring_lock);
11010 	}
11011 	pring = phba->sli4_hba.els_wq->pring;
11012 	pring->flag = 0;
11013 	pring->ringno = LPFC_ELS_RING;
11014 	pring->txcmplq_cnt = 0;
11015 	INIT_LIST_HEAD(&pring->txq);
11016 	INIT_LIST_HEAD(&pring->txcmplq);
11017 	INIT_LIST_HEAD(&pring->iocb_continueq);
11018 	spin_lock_init(&pring->ring_lock);
11019 
11020 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11021 		pring = phba->sli4_hba.nvmels_wq->pring;
11022 		pring->flag = 0;
11023 		pring->ringno = LPFC_ELS_RING;
11024 		pring->txcmplq_cnt = 0;
11025 		INIT_LIST_HEAD(&pring->txq);
11026 		INIT_LIST_HEAD(&pring->txcmplq);
11027 		INIT_LIST_HEAD(&pring->iocb_continueq);
11028 		spin_lock_init(&pring->ring_lock);
11029 	}
11030 
11031 	spin_unlock_irq(&phba->hbalock);
11032 }
11033 
11034 /**
11035  * lpfc_sli_queue_init - Queue initialization function
11036  * @phba: Pointer to HBA context object.
11037  *
11038  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11039  * ring. This function also initializes ring indices of each ring.
11040  * This function is called during the initialization of the SLI
11041  * interface of an HBA.
11042  * This function is called with no lock held and always returns
11043  * 1.
11044  **/
11045 void
11046 lpfc_sli_queue_init(struct lpfc_hba *phba)
11047 {
11048 	struct lpfc_sli *psli;
11049 	struct lpfc_sli_ring *pring;
11050 	int i;
11051 
11052 	psli = &phba->sli;
11053 	spin_lock_irq(&phba->hbalock);
11054 	INIT_LIST_HEAD(&psli->mboxq);
11055 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11056 	/* Initialize list headers for txq and txcmplq as double linked lists */
11057 	for (i = 0; i < psli->num_rings; i++) {
11058 		pring = &psli->sli3_ring[i];
11059 		pring->ringno = i;
11060 		pring->sli.sli3.next_cmdidx  = 0;
11061 		pring->sli.sli3.local_getidx = 0;
11062 		pring->sli.sli3.cmdidx = 0;
11063 		INIT_LIST_HEAD(&pring->iocb_continueq);
11064 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11065 		INIT_LIST_HEAD(&pring->postbufq);
11066 		pring->flag = 0;
11067 		INIT_LIST_HEAD(&pring->txq);
11068 		INIT_LIST_HEAD(&pring->txcmplq);
11069 		spin_lock_init(&pring->ring_lock);
11070 	}
11071 	spin_unlock_irq(&phba->hbalock);
11072 }
11073 
11074 /**
11075  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11076  * @phba: Pointer to HBA context object.
11077  *
11078  * This routine flushes the mailbox command subsystem. It will unconditionally
11079  * flush all the mailbox commands in the three possible stages in the mailbox
11080  * command sub-system: pending mailbox command queue; the outstanding mailbox
11081  * command; and completed mailbox command queue. It is caller's responsibility
11082  * to make sure that the driver is in the proper state to flush the mailbox
11083  * command sub-system. Namely, the posting of mailbox commands into the
11084  * pending mailbox command queue from the various clients must be stopped;
11085  * either the HBA is in a state that it will never works on the outstanding
11086  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11087  * mailbox command has been completed.
11088  **/
11089 static void
11090 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11091 {
11092 	LIST_HEAD(completions);
11093 	struct lpfc_sli *psli = &phba->sli;
11094 	LPFC_MBOXQ_t *pmb;
11095 	unsigned long iflag;
11096 
11097 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11098 	local_bh_disable();
11099 
11100 	/* Flush all the mailbox commands in the mbox system */
11101 	spin_lock_irqsave(&phba->hbalock, iflag);
11102 
11103 	/* The pending mailbox command queue */
11104 	list_splice_init(&phba->sli.mboxq, &completions);
11105 	/* The outstanding active mailbox command */
11106 	if (psli->mbox_active) {
11107 		list_add_tail(&psli->mbox_active->list, &completions);
11108 		psli->mbox_active = NULL;
11109 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11110 	}
11111 	/* The completed mailbox command queue */
11112 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11113 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11114 
11115 	/* Enable softirqs again, done with phba->hbalock */
11116 	local_bh_enable();
11117 
11118 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11119 	while (!list_empty(&completions)) {
11120 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11121 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11122 		if (pmb->mbox_cmpl)
11123 			pmb->mbox_cmpl(phba, pmb);
11124 	}
11125 }
11126 
11127 /**
11128  * lpfc_sli_host_down - Vport cleanup function
11129  * @vport: Pointer to virtual port object.
11130  *
11131  * lpfc_sli_host_down is called to clean up the resources
11132  * associated with a vport before destroying virtual
11133  * port data structures.
11134  * This function does following operations:
11135  * - Free discovery resources associated with this virtual
11136  *   port.
11137  * - Free iocbs associated with this virtual port in
11138  *   the txq.
11139  * - Send abort for all iocb commands associated with this
11140  *   vport in txcmplq.
11141  *
11142  * This function is called with no lock held and always returns 1.
11143  **/
11144 int
11145 lpfc_sli_host_down(struct lpfc_vport *vport)
11146 {
11147 	LIST_HEAD(completions);
11148 	struct lpfc_hba *phba = vport->phba;
11149 	struct lpfc_sli *psli = &phba->sli;
11150 	struct lpfc_queue *qp = NULL;
11151 	struct lpfc_sli_ring *pring;
11152 	struct lpfc_iocbq *iocb, *next_iocb;
11153 	int i;
11154 	unsigned long flags = 0;
11155 	uint16_t prev_pring_flag;
11156 
11157 	lpfc_cleanup_discovery_resources(vport);
11158 
11159 	spin_lock_irqsave(&phba->hbalock, flags);
11160 
11161 	/*
11162 	 * Error everything on the txq since these iocbs
11163 	 * have not been given to the FW yet.
11164 	 * Also issue ABTS for everything on the txcmplq
11165 	 */
11166 	if (phba->sli_rev != LPFC_SLI_REV4) {
11167 		for (i = 0; i < psli->num_rings; i++) {
11168 			pring = &psli->sli3_ring[i];
11169 			prev_pring_flag = pring->flag;
11170 			/* Only slow rings */
11171 			if (pring->ringno == LPFC_ELS_RING) {
11172 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11173 				/* Set the lpfc data pending flag */
11174 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11175 			}
11176 			list_for_each_entry_safe(iocb, next_iocb,
11177 						 &pring->txq, list) {
11178 				if (iocb->vport != vport)
11179 					continue;
11180 				list_move_tail(&iocb->list, &completions);
11181 			}
11182 			list_for_each_entry_safe(iocb, next_iocb,
11183 						 &pring->txcmplq, list) {
11184 				if (iocb->vport != vport)
11185 					continue;
11186 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11187 							   NULL);
11188 			}
11189 			pring->flag = prev_pring_flag;
11190 		}
11191 	} else {
11192 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11193 			pring = qp->pring;
11194 			if (!pring)
11195 				continue;
11196 			if (pring == phba->sli4_hba.els_wq->pring) {
11197 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11198 				/* Set the lpfc data pending flag */
11199 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11200 			}
11201 			prev_pring_flag = pring->flag;
11202 			spin_lock(&pring->ring_lock);
11203 			list_for_each_entry_safe(iocb, next_iocb,
11204 						 &pring->txq, list) {
11205 				if (iocb->vport != vport)
11206 					continue;
11207 				list_move_tail(&iocb->list, &completions);
11208 			}
11209 			spin_unlock(&pring->ring_lock);
11210 			list_for_each_entry_safe(iocb, next_iocb,
11211 						 &pring->txcmplq, list) {
11212 				if (iocb->vport != vport)
11213 					continue;
11214 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11215 							   NULL);
11216 			}
11217 			pring->flag = prev_pring_flag;
11218 		}
11219 	}
11220 	spin_unlock_irqrestore(&phba->hbalock, flags);
11221 
11222 	/* Make sure HBA is alive */
11223 	lpfc_issue_hb_tmo(phba);
11224 
11225 	/* Cancel all the IOCBs from the completions list */
11226 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11227 			      IOERR_SLI_DOWN);
11228 	return 1;
11229 }
11230 
11231 /**
11232  * lpfc_sli_hba_down - Resource cleanup function for the HBA
11233  * @phba: Pointer to HBA context object.
11234  *
11235  * This function cleans up all iocb, buffers, mailbox commands
11236  * while shutting down the HBA. This function is called with no
11237  * lock held and always returns 1.
11238  * This function does the following to cleanup driver resources:
11239  * - Free discovery resources for each virtual port
11240  * - Cleanup any pending fabric iocbs
11241  * - Iterate through the iocb txq and free each entry
11242  *   in the list.
11243  * - Free up any buffer posted to the HBA
11244  * - Free mailbox commands in the mailbox queue.
11245  **/
11246 int
11247 lpfc_sli_hba_down(struct lpfc_hba *phba)
11248 {
11249 	LIST_HEAD(completions);
11250 	struct lpfc_sli *psli = &phba->sli;
11251 	struct lpfc_queue *qp = NULL;
11252 	struct lpfc_sli_ring *pring;
11253 	struct lpfc_dmabuf *buf_ptr;
11254 	unsigned long flags = 0;
11255 	int i;
11256 
11257 	/* Shutdown the mailbox command sub-system */
11258 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
11259 
11260 	lpfc_hba_down_prep(phba);
11261 
11262 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11263 	local_bh_disable();
11264 
11265 	lpfc_fabric_abort_hba(phba);
11266 
11267 	spin_lock_irqsave(&phba->hbalock, flags);
11268 
11269 	/*
11270 	 * Error everything on the txq since these iocbs
11271 	 * have not been given to the FW yet.
11272 	 */
11273 	if (phba->sli_rev != LPFC_SLI_REV4) {
11274 		for (i = 0; i < psli->num_rings; i++) {
11275 			pring = &psli->sli3_ring[i];
11276 			/* Only slow rings */
11277 			if (pring->ringno == LPFC_ELS_RING) {
11278 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11279 				/* Set the lpfc data pending flag */
11280 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11281 			}
11282 			list_splice_init(&pring->txq, &completions);
11283 		}
11284 	} else {
11285 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11286 			pring = qp->pring;
11287 			if (!pring)
11288 				continue;
11289 			spin_lock(&pring->ring_lock);
11290 			list_splice_init(&pring->txq, &completions);
11291 			spin_unlock(&pring->ring_lock);
11292 			if (pring == phba->sli4_hba.els_wq->pring) {
11293 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11294 				/* Set the lpfc data pending flag */
11295 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11296 			}
11297 		}
11298 	}
11299 	spin_unlock_irqrestore(&phba->hbalock, flags);
11300 
11301 	/* Cancel all the IOCBs from the completions list */
11302 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11303 			      IOERR_SLI_DOWN);
11304 
11305 	spin_lock_irqsave(&phba->hbalock, flags);
11306 	list_splice_init(&phba->elsbuf, &completions);
11307 	phba->elsbuf_cnt = 0;
11308 	phba->elsbuf_prev_cnt = 0;
11309 	spin_unlock_irqrestore(&phba->hbalock, flags);
11310 
11311 	while (!list_empty(&completions)) {
11312 		list_remove_head(&completions, buf_ptr,
11313 			struct lpfc_dmabuf, list);
11314 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
11315 		kfree(buf_ptr);
11316 	}
11317 
11318 	/* Enable softirqs again, done with phba->hbalock */
11319 	local_bh_enable();
11320 
11321 	/* Return any active mbox cmds */
11322 	del_timer_sync(&psli->mbox_tmo);
11323 
11324 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
11325 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
11326 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
11327 
11328 	return 1;
11329 }
11330 
11331 /**
11332  * lpfc_sli_pcimem_bcopy - SLI memory copy function
11333  * @srcp: Source memory pointer.
11334  * @destp: Destination memory pointer.
11335  * @cnt: Number of words required to be copied.
11336  *
11337  * This function is used for copying data between driver memory
11338  * and the SLI memory. This function also changes the endianness
11339  * of each word if native endianness is different from SLI
11340  * endianness. This function can be called with or without
11341  * lock.
11342  **/
11343 void
11344 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
11345 {
11346 	uint32_t *src = srcp;
11347 	uint32_t *dest = destp;
11348 	uint32_t ldata;
11349 	int i;
11350 
11351 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
11352 		ldata = *src;
11353 		ldata = le32_to_cpu(ldata);
11354 		*dest = ldata;
11355 		src++;
11356 		dest++;
11357 	}
11358 }
11359 
11360 
11361 /**
11362  * lpfc_sli_bemem_bcopy - SLI memory copy function
11363  * @srcp: Source memory pointer.
11364  * @destp: Destination memory pointer.
11365  * @cnt: Number of words required to be copied.
11366  *
11367  * This function is used for copying data between a data structure
11368  * with big endian representation to local endianness.
11369  * This function can be called with or without lock.
11370  **/
11371 void
11372 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
11373 {
11374 	uint32_t *src = srcp;
11375 	uint32_t *dest = destp;
11376 	uint32_t ldata;
11377 	int i;
11378 
11379 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
11380 		ldata = *src;
11381 		ldata = be32_to_cpu(ldata);
11382 		*dest = ldata;
11383 		src++;
11384 		dest++;
11385 	}
11386 }
11387 
11388 /**
11389  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
11390  * @phba: Pointer to HBA context object.
11391  * @pring: Pointer to driver SLI ring object.
11392  * @mp: Pointer to driver buffer object.
11393  *
11394  * This function is called with no lock held.
11395  * It always return zero after adding the buffer to the postbufq
11396  * buffer list.
11397  **/
11398 int
11399 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11400 			 struct lpfc_dmabuf *mp)
11401 {
11402 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
11403 	   later */
11404 	spin_lock_irq(&phba->hbalock);
11405 	list_add_tail(&mp->list, &pring->postbufq);
11406 	pring->postbufq_cnt++;
11407 	spin_unlock_irq(&phba->hbalock);
11408 	return 0;
11409 }
11410 
11411 /**
11412  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
11413  * @phba: Pointer to HBA context object.
11414  *
11415  * When HBQ is enabled, buffers are searched based on tags. This function
11416  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
11417  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
11418  * does not conflict with tags of buffer posted for unsolicited events.
11419  * The function returns the allocated tag. The function is called with
11420  * no locks held.
11421  **/
11422 uint32_t
11423 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
11424 {
11425 	spin_lock_irq(&phba->hbalock);
11426 	phba->buffer_tag_count++;
11427 	/*
11428 	 * Always set the QUE_BUFTAG_BIT to distiguish between
11429 	 * a tag assigned by HBQ.
11430 	 */
11431 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
11432 	spin_unlock_irq(&phba->hbalock);
11433 	return phba->buffer_tag_count;
11434 }
11435 
11436 /**
11437  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
11438  * @phba: Pointer to HBA context object.
11439  * @pring: Pointer to driver SLI ring object.
11440  * @tag: Buffer tag.
11441  *
11442  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
11443  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
11444  * iocb is posted to the response ring with the tag of the buffer.
11445  * This function searches the pring->postbufq list using the tag
11446  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
11447  * iocb. If the buffer is found then lpfc_dmabuf object of the
11448  * buffer is returned to the caller else NULL is returned.
11449  * This function is called with no lock held.
11450  **/
11451 struct lpfc_dmabuf *
11452 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11453 			uint32_t tag)
11454 {
11455 	struct lpfc_dmabuf *mp, *next_mp;
11456 	struct list_head *slp = &pring->postbufq;
11457 
11458 	/* Search postbufq, from the beginning, looking for a match on tag */
11459 	spin_lock_irq(&phba->hbalock);
11460 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11461 		if (mp->buffer_tag == tag) {
11462 			list_del_init(&mp->list);
11463 			pring->postbufq_cnt--;
11464 			spin_unlock_irq(&phba->hbalock);
11465 			return mp;
11466 		}
11467 	}
11468 
11469 	spin_unlock_irq(&phba->hbalock);
11470 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11471 			"0402 Cannot find virtual addr for buffer tag on "
11472 			"ring %d Data x%lx x%px x%px x%x\n",
11473 			pring->ringno, (unsigned long) tag,
11474 			slp->next, slp->prev, pring->postbufq_cnt);
11475 
11476 	return NULL;
11477 }
11478 
11479 /**
11480  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
11481  * @phba: Pointer to HBA context object.
11482  * @pring: Pointer to driver SLI ring object.
11483  * @phys: DMA address of the buffer.
11484  *
11485  * This function searches the buffer list using the dma_address
11486  * of unsolicited event to find the driver's lpfc_dmabuf object
11487  * corresponding to the dma_address. The function returns the
11488  * lpfc_dmabuf object if a buffer is found else it returns NULL.
11489  * This function is called by the ct and els unsolicited event
11490  * handlers to get the buffer associated with the unsolicited
11491  * event.
11492  *
11493  * This function is called with no lock held.
11494  **/
11495 struct lpfc_dmabuf *
11496 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11497 			 dma_addr_t phys)
11498 {
11499 	struct lpfc_dmabuf *mp, *next_mp;
11500 	struct list_head *slp = &pring->postbufq;
11501 
11502 	/* Search postbufq, from the beginning, looking for a match on phys */
11503 	spin_lock_irq(&phba->hbalock);
11504 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11505 		if (mp->phys == phys) {
11506 			list_del_init(&mp->list);
11507 			pring->postbufq_cnt--;
11508 			spin_unlock_irq(&phba->hbalock);
11509 			return mp;
11510 		}
11511 	}
11512 
11513 	spin_unlock_irq(&phba->hbalock);
11514 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11515 			"0410 Cannot find virtual addr for mapped buf on "
11516 			"ring %d Data x%llx x%px x%px x%x\n",
11517 			pring->ringno, (unsigned long long)phys,
11518 			slp->next, slp->prev, pring->postbufq_cnt);
11519 	return NULL;
11520 }
11521 
11522 /**
11523  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
11524  * @phba: Pointer to HBA context object.
11525  * @cmdiocb: Pointer to driver command iocb object.
11526  * @rspiocb: Pointer to driver response iocb object.
11527  *
11528  * This function is the completion handler for the abort iocbs for
11529  * ELS commands. This function is called from the ELS ring event
11530  * handler with no lock held. This function frees memory resources
11531  * associated with the abort iocb.
11532  **/
11533 static void
11534 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11535 			struct lpfc_iocbq *rspiocb)
11536 {
11537 	IOCB_t *irsp = &rspiocb->iocb;
11538 	uint16_t abort_iotag, abort_context;
11539 	struct lpfc_iocbq *abort_iocb = NULL;
11540 
11541 	if (irsp->ulpStatus) {
11542 
11543 		/*
11544 		 * Assume that the port already completed and returned, or
11545 		 * will return the iocb. Just Log the message.
11546 		 */
11547 		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
11548 		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
11549 
11550 		spin_lock_irq(&phba->hbalock);
11551 		if (phba->sli_rev < LPFC_SLI_REV4) {
11552 			if (irsp->ulpCommand == CMD_ABORT_XRI_CX &&
11553 			    irsp->ulpStatus == IOSTAT_LOCAL_REJECT &&
11554 			    irsp->un.ulpWord[4] == IOERR_ABORT_REQUESTED) {
11555 				spin_unlock_irq(&phba->hbalock);
11556 				goto release_iocb;
11557 			}
11558 			if (abort_iotag != 0 &&
11559 				abort_iotag <= phba->sli.last_iotag)
11560 				abort_iocb =
11561 					phba->sli.iocbq_lookup[abort_iotag];
11562 		} else
11563 			/* For sli4 the abort_tag is the XRI,
11564 			 * so the abort routine puts the iotag  of the iocb
11565 			 * being aborted in the context field of the abort
11566 			 * IOCB.
11567 			 */
11568 			abort_iocb = phba->sli.iocbq_lookup[abort_context];
11569 
11570 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
11571 				"0327 Cannot abort els iocb x%px "
11572 				"with tag %x context %x, abort status %x, "
11573 				"abort code %x\n",
11574 				abort_iocb, abort_iotag, abort_context,
11575 				irsp->ulpStatus, irsp->un.ulpWord[4]);
11576 
11577 		spin_unlock_irq(&phba->hbalock);
11578 	}
11579 release_iocb:
11580 	lpfc_sli_release_iocbq(phba, cmdiocb);
11581 	return;
11582 }
11583 
11584 /**
11585  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
11586  * @phba: Pointer to HBA context object.
11587  * @cmdiocb: Pointer to driver command iocb object.
11588  * @rspiocb: Pointer to driver response iocb object.
11589  *
11590  * The function is called from SLI ring event handler with no
11591  * lock held. This function is the completion handler for ELS commands
11592  * which are aborted. The function frees memory resources used for
11593  * the aborted ELS commands.
11594  **/
11595 void
11596 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11597 		     struct lpfc_iocbq *rspiocb)
11598 {
11599 	IOCB_t *irsp = &rspiocb->iocb;
11600 
11601 	/* ELS cmd tag <ulpIoTag> completes */
11602 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
11603 			"0139 Ignoring ELS cmd tag x%x completion Data: "
11604 			"x%x x%x x%x\n",
11605 			irsp->ulpIoTag, irsp->ulpStatus,
11606 			irsp->un.ulpWord[4], irsp->ulpTimeout);
11607 	lpfc_nlp_put((struct lpfc_nodelist *)cmdiocb->context1);
11608 	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
11609 		lpfc_ct_free_iocb(phba, cmdiocb);
11610 	else
11611 		lpfc_els_free_iocb(phba, cmdiocb);
11612 }
11613 
11614 /**
11615  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
11616  * @phba: Pointer to HBA context object.
11617  * @pring: Pointer to driver SLI ring object.
11618  * @cmdiocb: Pointer to driver command iocb object.
11619  * @cmpl: completion function.
11620  *
11621  * This function issues an abort iocb for the provided command iocb. In case
11622  * of unloading, the abort iocb will not be issued to commands on the ELS
11623  * ring. Instead, the callback function shall be changed to those commands
11624  * so that nothing happens when them finishes. This function is called with
11625  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
11626  * when the command iocb is an abort request.
11627  *
11628  **/
11629 int
11630 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11631 			   struct lpfc_iocbq *cmdiocb, void *cmpl)
11632 {
11633 	struct lpfc_vport *vport = cmdiocb->vport;
11634 	struct lpfc_iocbq *abtsiocbp;
11635 	IOCB_t *icmd = NULL;
11636 	IOCB_t *iabt = NULL;
11637 	int retval = IOCB_ERROR;
11638 	unsigned long iflags;
11639 	struct lpfc_nodelist *ndlp;
11640 
11641 	/*
11642 	 * There are certain command types we don't want to abort.  And we
11643 	 * don't want to abort commands that are already in the process of
11644 	 * being aborted.
11645 	 */
11646 	icmd = &cmdiocb->iocb;
11647 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11648 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
11649 	    cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED)
11650 		return IOCB_ABORTING;
11651 
11652 	if (!pring) {
11653 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11654 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11655 		else
11656 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11657 		return retval;
11658 	}
11659 
11660 	/*
11661 	 * If we're unloading, don't abort iocb on the ELS ring, but change
11662 	 * the callback so that nothing happens when it finishes.
11663 	 */
11664 	if ((vport->load_flag & FC_UNLOADING) &&
11665 	    pring->ringno == LPFC_ELS_RING) {
11666 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11667 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11668 		else
11669 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11670 		return retval;
11671 	}
11672 
11673 	/* issue ABTS for this IOCB based on iotag */
11674 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
11675 	if (abtsiocbp == NULL)
11676 		return IOCB_NORESOURCE;
11677 
11678 	/* This signals the response to set the correct status
11679 	 * before calling the completion handler
11680 	 */
11681 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
11682 
11683 	iabt = &abtsiocbp->iocb;
11684 	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
11685 	iabt->un.acxri.abortContextTag = icmd->ulpContext;
11686 	if (phba->sli_rev == LPFC_SLI_REV4) {
11687 		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
11688 		if (pring->ringno == LPFC_ELS_RING)
11689 			iabt->un.acxri.abortContextTag = cmdiocb->iotag;
11690 	} else {
11691 		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
11692 		if (pring->ringno == LPFC_ELS_RING) {
11693 			ndlp = (struct lpfc_nodelist *)(cmdiocb->context1);
11694 			iabt->un.acxri.abortContextTag = ndlp->nlp_rpi;
11695 		}
11696 	}
11697 	iabt->ulpLe = 1;
11698 	iabt->ulpClass = icmd->ulpClass;
11699 
11700 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11701 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
11702 	if (cmdiocb->iocb_flag & LPFC_IO_FCP) {
11703 		abtsiocbp->iocb_flag |= LPFC_IO_FCP;
11704 		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
11705 	}
11706 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
11707 		abtsiocbp->iocb_flag |= LPFC_IO_FOF;
11708 
11709 	if (phba->link_state >= LPFC_LINK_UP)
11710 		iabt->ulpCommand = CMD_ABORT_XRI_CN;
11711 	else
11712 		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
11713 
11714 	if (cmpl)
11715 		abtsiocbp->iocb_cmpl = cmpl;
11716 	else
11717 		abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
11718 	abtsiocbp->vport = vport;
11719 
11720 	if (phba->sli_rev == LPFC_SLI_REV4) {
11721 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
11722 		if (unlikely(pring == NULL))
11723 			goto abort_iotag_exit;
11724 		/* Note: both hbalock and ring_lock need to be set here */
11725 		spin_lock_irqsave(&pring->ring_lock, iflags);
11726 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11727 			abtsiocbp, 0);
11728 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11729 	} else {
11730 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11731 			abtsiocbp, 0);
11732 	}
11733 
11734 abort_iotag_exit:
11735 
11736 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
11737 			 "0339 Abort xri x%x, original iotag x%x, "
11738 			 "abort cmd iotag x%x retval x%x\n",
11739 			 iabt->un.acxri.abortIoTag,
11740 			 iabt->un.acxri.abortContextTag,
11741 			 abtsiocbp->iotag, retval);
11742 
11743 	if (retval) {
11744 		cmdiocb->iocb_flag &= ~LPFC_DRIVER_ABORTED;
11745 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
11746 	}
11747 
11748 	/*
11749 	 * Caller to this routine should check for IOCB_ERROR
11750 	 * and handle it properly.  This routine no longer removes
11751 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
11752 	 */
11753 	return retval;
11754 }
11755 
11756 /**
11757  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
11758  * @phba: pointer to lpfc HBA data structure.
11759  *
11760  * This routine will abort all pending and outstanding iocbs to an HBA.
11761  **/
11762 void
11763 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
11764 {
11765 	struct lpfc_sli *psli = &phba->sli;
11766 	struct lpfc_sli_ring *pring;
11767 	struct lpfc_queue *qp = NULL;
11768 	int i;
11769 
11770 	if (phba->sli_rev != LPFC_SLI_REV4) {
11771 		for (i = 0; i < psli->num_rings; i++) {
11772 			pring = &psli->sli3_ring[i];
11773 			lpfc_sli_abort_iocb_ring(phba, pring);
11774 		}
11775 		return;
11776 	}
11777 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11778 		pring = qp->pring;
11779 		if (!pring)
11780 			continue;
11781 		lpfc_sli_abort_iocb_ring(phba, pring);
11782 	}
11783 }
11784 
11785 /**
11786  * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
11787  * @iocbq: Pointer to driver iocb object.
11788  * @vport: Pointer to driver virtual port object.
11789  * @tgt_id: SCSI ID of the target.
11790  * @lun_id: LUN ID of the scsi device.
11791  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
11792  *
11793  * This function acts as an iocb filter for functions which abort or count
11794  * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
11795  * 0 if the filtering criteria is met for the given iocb and will return
11796  * 1 if the filtering criteria is not met.
11797  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
11798  * given iocb is for the SCSI device specified by vport, tgt_id and
11799  * lun_id parameter.
11800  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
11801  * given iocb is for the SCSI target specified by vport and tgt_id
11802  * parameters.
11803  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
11804  * given iocb is for the SCSI host associated with the given vport.
11805  * This function is called with no locks held.
11806  **/
11807 static int
11808 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
11809 			   uint16_t tgt_id, uint64_t lun_id,
11810 			   lpfc_ctx_cmd ctx_cmd)
11811 {
11812 	struct lpfc_io_buf *lpfc_cmd;
11813 	IOCB_t *icmd = NULL;
11814 	int rc = 1;
11815 
11816 	if (!iocbq || iocbq->vport != vport)
11817 		return rc;
11818 
11819 	if (!(iocbq->iocb_flag & LPFC_IO_FCP) ||
11820 	    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ) ||
11821 	      iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
11822 		return rc;
11823 
11824 	icmd = &iocbq->iocb;
11825 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11826 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN)
11827 		return rc;
11828 
11829 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
11830 
11831 	if (lpfc_cmd->pCmd == NULL)
11832 		return rc;
11833 
11834 	switch (ctx_cmd) {
11835 	case LPFC_CTX_LUN:
11836 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11837 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
11838 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
11839 			rc = 0;
11840 		break;
11841 	case LPFC_CTX_TGT:
11842 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11843 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
11844 			rc = 0;
11845 		break;
11846 	case LPFC_CTX_HOST:
11847 		rc = 0;
11848 		break;
11849 	default:
11850 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
11851 			__func__, ctx_cmd);
11852 		break;
11853 	}
11854 
11855 	return rc;
11856 }
11857 
11858 /**
11859  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
11860  * @vport: Pointer to virtual port.
11861  * @tgt_id: SCSI ID of the target.
11862  * @lun_id: LUN ID of the scsi device.
11863  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11864  *
11865  * This function returns number of FCP commands pending for the vport.
11866  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
11867  * commands pending on the vport associated with SCSI device specified
11868  * by tgt_id and lun_id parameters.
11869  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
11870  * commands pending on the vport associated with SCSI target specified
11871  * by tgt_id parameter.
11872  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
11873  * commands pending on the vport.
11874  * This function returns the number of iocbs which satisfy the filter.
11875  * This function is called without any lock held.
11876  **/
11877 int
11878 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
11879 		  lpfc_ctx_cmd ctx_cmd)
11880 {
11881 	struct lpfc_hba *phba = vport->phba;
11882 	struct lpfc_iocbq *iocbq;
11883 	int sum, i;
11884 
11885 	spin_lock_irq(&phba->hbalock);
11886 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
11887 		iocbq = phba->sli.iocbq_lookup[i];
11888 
11889 		if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
11890 						ctx_cmd) == 0)
11891 			sum++;
11892 	}
11893 	spin_unlock_irq(&phba->hbalock);
11894 
11895 	return sum;
11896 }
11897 
11898 /**
11899  * lpfc_sli4_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
11900  * @phba: Pointer to HBA context object
11901  * @cmdiocb: Pointer to command iocb object.
11902  * @wcqe: pointer to the complete wcqe
11903  *
11904  * This function is called when an aborted FCP iocb completes. This
11905  * function is called by the ring event handler with no lock held.
11906  * This function frees the iocb. It is called for sli-4 adapters.
11907  **/
11908 void
11909 lpfc_sli4_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11910 			 struct lpfc_wcqe_complete *wcqe)
11911 {
11912 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11913 			"3017 ABORT_XRI_CN completing on rpi x%x "
11914 			"original iotag x%x, abort cmd iotag x%x "
11915 			"status 0x%x, reason 0x%x\n",
11916 			cmdiocb->iocb.un.acxri.abortContextTag,
11917 			cmdiocb->iocb.un.acxri.abortIoTag,
11918 			cmdiocb->iotag,
11919 			(bf_get(lpfc_wcqe_c_status, wcqe)
11920 			& LPFC_IOCB_STATUS_MASK),
11921 			wcqe->parameter);
11922 	lpfc_sli_release_iocbq(phba, cmdiocb);
11923 }
11924 
11925 /**
11926  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
11927  * @phba: Pointer to HBA context object
11928  * @cmdiocb: Pointer to command iocb object.
11929  * @rspiocb: Pointer to response iocb object.
11930  *
11931  * This function is called when an aborted FCP iocb completes. This
11932  * function is called by the ring event handler with no lock held.
11933  * This function frees the iocb.
11934  **/
11935 void
11936 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11937 			struct lpfc_iocbq *rspiocb)
11938 {
11939 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11940 			"3096 ABORT_XRI_CN completing on rpi x%x "
11941 			"original iotag x%x, abort cmd iotag x%x "
11942 			"status 0x%x, reason 0x%x\n",
11943 			cmdiocb->iocb.un.acxri.abortContextTag,
11944 			cmdiocb->iocb.un.acxri.abortIoTag,
11945 			cmdiocb->iotag, rspiocb->iocb.ulpStatus,
11946 			rspiocb->iocb.un.ulpWord[4]);
11947 	lpfc_sli_release_iocbq(phba, cmdiocb);
11948 	return;
11949 }
11950 
11951 /**
11952  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
11953  * @vport: Pointer to virtual port.
11954  * @tgt_id: SCSI ID of the target.
11955  * @lun_id: LUN ID of the scsi device.
11956  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11957  *
11958  * This function sends an abort command for every SCSI command
11959  * associated with the given virtual port pending on the ring
11960  * filtered by lpfc_sli_validate_fcp_iocb function.
11961  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
11962  * FCP iocbs associated with lun specified by tgt_id and lun_id
11963  * parameters
11964  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
11965  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
11966  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
11967  * FCP iocbs associated with virtual port.
11968  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
11969  * lpfc_sli4_calc_ring is used.
11970  * This function returns number of iocbs it failed to abort.
11971  * This function is called with no locks held.
11972  **/
11973 int
11974 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
11975 		    lpfc_ctx_cmd abort_cmd)
11976 {
11977 	struct lpfc_hba *phba = vport->phba;
11978 	struct lpfc_sli_ring *pring = NULL;
11979 	struct lpfc_iocbq *iocbq;
11980 	int errcnt = 0, ret_val = 0;
11981 	unsigned long iflags;
11982 	int i;
11983 	void *fcp_cmpl = NULL;
11984 
11985 	/* all I/Os are in process of being flushed */
11986 	if (phba->hba_flag & HBA_IOQ_FLUSH)
11987 		return errcnt;
11988 
11989 	for (i = 1; i <= phba->sli.last_iotag; i++) {
11990 		iocbq = phba->sli.iocbq_lookup[i];
11991 
11992 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
11993 					       abort_cmd) != 0)
11994 			continue;
11995 
11996 		spin_lock_irqsave(&phba->hbalock, iflags);
11997 		if (phba->sli_rev == LPFC_SLI_REV3) {
11998 			pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
11999 			fcp_cmpl = lpfc_sli_abort_fcp_cmpl;
12000 		} else if (phba->sli_rev == LPFC_SLI_REV4) {
12001 			pring = lpfc_sli4_calc_ring(phba, iocbq);
12002 			fcp_cmpl = lpfc_sli4_abort_fcp_cmpl;
12003 		}
12004 		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
12005 						     fcp_cmpl);
12006 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12007 		if (ret_val != IOCB_SUCCESS)
12008 			errcnt++;
12009 	}
12010 
12011 	return errcnt;
12012 }
12013 
12014 /**
12015  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12016  * @vport: Pointer to virtual port.
12017  * @pring: Pointer to driver SLI ring object.
12018  * @tgt_id: SCSI ID of the target.
12019  * @lun_id: LUN ID of the scsi device.
12020  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12021  *
12022  * This function sends an abort command for every SCSI command
12023  * associated with the given virtual port pending on the ring
12024  * filtered by lpfc_sli_validate_fcp_iocb function.
12025  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12026  * FCP iocbs associated with lun specified by tgt_id and lun_id
12027  * parameters
12028  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12029  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12030  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12031  * FCP iocbs associated with virtual port.
12032  * This function returns number of iocbs it aborted .
12033  * This function is called with no locks held right after a taskmgmt
12034  * command is sent.
12035  **/
12036 int
12037 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12038 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12039 {
12040 	struct lpfc_hba *phba = vport->phba;
12041 	struct lpfc_io_buf *lpfc_cmd;
12042 	struct lpfc_iocbq *abtsiocbq;
12043 	struct lpfc_nodelist *ndlp;
12044 	struct lpfc_iocbq *iocbq;
12045 	IOCB_t *icmd;
12046 	int sum, i, ret_val;
12047 	unsigned long iflags;
12048 	struct lpfc_sli_ring *pring_s4 = NULL;
12049 
12050 	spin_lock_irqsave(&phba->hbalock, iflags);
12051 
12052 	/* all I/Os are in process of being flushed */
12053 	if (phba->hba_flag & HBA_IOQ_FLUSH) {
12054 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12055 		return 0;
12056 	}
12057 	sum = 0;
12058 
12059 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12060 		iocbq = phba->sli.iocbq_lookup[i];
12061 
12062 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12063 					       cmd) != 0)
12064 			continue;
12065 
12066 		/* Guard against IO completion being called at same time */
12067 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12068 		spin_lock(&lpfc_cmd->buf_lock);
12069 
12070 		if (!lpfc_cmd->pCmd) {
12071 			spin_unlock(&lpfc_cmd->buf_lock);
12072 			continue;
12073 		}
12074 
12075 		if (phba->sli_rev == LPFC_SLI_REV4) {
12076 			pring_s4 =
12077 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12078 			if (!pring_s4) {
12079 				spin_unlock(&lpfc_cmd->buf_lock);
12080 				continue;
12081 			}
12082 			/* Note: both hbalock and ring_lock must be set here */
12083 			spin_lock(&pring_s4->ring_lock);
12084 		}
12085 
12086 		/*
12087 		 * If the iocbq is already being aborted, don't take a second
12088 		 * action, but do count it.
12089 		 */
12090 		if ((iocbq->iocb_flag & LPFC_DRIVER_ABORTED) ||
12091 		    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ)) {
12092 			if (phba->sli_rev == LPFC_SLI_REV4)
12093 				spin_unlock(&pring_s4->ring_lock);
12094 			spin_unlock(&lpfc_cmd->buf_lock);
12095 			continue;
12096 		}
12097 
12098 		/* issue ABTS for this IOCB based on iotag */
12099 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
12100 		if (!abtsiocbq) {
12101 			if (phba->sli_rev == LPFC_SLI_REV4)
12102 				spin_unlock(&pring_s4->ring_lock);
12103 			spin_unlock(&lpfc_cmd->buf_lock);
12104 			continue;
12105 		}
12106 
12107 		icmd = &iocbq->iocb;
12108 		abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
12109 		abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
12110 		if (phba->sli_rev == LPFC_SLI_REV4)
12111 			abtsiocbq->iocb.un.acxri.abortIoTag =
12112 							 iocbq->sli4_xritag;
12113 		else
12114 			abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
12115 		abtsiocbq->iocb.ulpLe = 1;
12116 		abtsiocbq->iocb.ulpClass = icmd->ulpClass;
12117 		abtsiocbq->vport = vport;
12118 
12119 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12120 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12121 		if (iocbq->iocb_flag & LPFC_IO_FCP)
12122 			abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
12123 		if (iocbq->iocb_flag & LPFC_IO_FOF)
12124 			abtsiocbq->iocb_flag |= LPFC_IO_FOF;
12125 
12126 		ndlp = lpfc_cmd->rdata->pnode;
12127 
12128 		if (lpfc_is_link_up(phba) &&
12129 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
12130 			abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
12131 		else
12132 			abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
12133 
12134 		/* Setup callback routine and issue the command. */
12135 		abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
12136 
12137 		/*
12138 		 * Indicate the IO is being aborted by the driver and set
12139 		 * the caller's flag into the aborted IO.
12140 		 */
12141 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
12142 
12143 		if (phba->sli_rev == LPFC_SLI_REV4) {
12144 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
12145 							abtsiocbq, 0);
12146 			spin_unlock(&pring_s4->ring_lock);
12147 		} else {
12148 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
12149 							abtsiocbq, 0);
12150 		}
12151 
12152 		spin_unlock(&lpfc_cmd->buf_lock);
12153 
12154 		if (ret_val == IOCB_ERROR)
12155 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
12156 		else
12157 			sum++;
12158 	}
12159 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12160 	return sum;
12161 }
12162 
12163 /**
12164  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
12165  * @phba: Pointer to HBA context object.
12166  * @cmdiocbq: Pointer to command iocb.
12167  * @rspiocbq: Pointer to response iocb.
12168  *
12169  * This function is the completion handler for iocbs issued using
12170  * lpfc_sli_issue_iocb_wait function. This function is called by the
12171  * ring event handler function without any lock held. This function
12172  * can be called from both worker thread context and interrupt
12173  * context. This function also can be called from other thread which
12174  * cleans up the SLI layer objects.
12175  * This function copy the contents of the response iocb to the
12176  * response iocb memory object provided by the caller of
12177  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
12178  * sleeps for the iocb completion.
12179  **/
12180 static void
12181 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
12182 			struct lpfc_iocbq *cmdiocbq,
12183 			struct lpfc_iocbq *rspiocbq)
12184 {
12185 	wait_queue_head_t *pdone_q;
12186 	unsigned long iflags;
12187 	struct lpfc_io_buf *lpfc_cmd;
12188 
12189 	spin_lock_irqsave(&phba->hbalock, iflags);
12190 	if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
12191 
12192 		/*
12193 		 * A time out has occurred for the iocb.  If a time out
12194 		 * completion handler has been supplied, call it.  Otherwise,
12195 		 * just free the iocbq.
12196 		 */
12197 
12198 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12199 		cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
12200 		cmdiocbq->wait_iocb_cmpl = NULL;
12201 		if (cmdiocbq->iocb_cmpl)
12202 			(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
12203 		else
12204 			lpfc_sli_release_iocbq(phba, cmdiocbq);
12205 		return;
12206 	}
12207 
12208 	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
12209 	if (cmdiocbq->context2 && rspiocbq)
12210 		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
12211 		       &rspiocbq->iocb, sizeof(IOCB_t));
12212 
12213 	/* Set the exchange busy flag for task management commands */
12214 	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
12215 		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
12216 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
12217 			cur_iocbq);
12218 		if (rspiocbq && (rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY))
12219 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
12220 		else
12221 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
12222 	}
12223 
12224 	pdone_q = cmdiocbq->context_un.wait_queue;
12225 	if (pdone_q)
12226 		wake_up(pdone_q);
12227 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12228 	return;
12229 }
12230 
12231 /**
12232  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
12233  * @phba: Pointer to HBA context object..
12234  * @piocbq: Pointer to command iocb.
12235  * @flag: Flag to test.
12236  *
12237  * This routine grabs the hbalock and then test the iocb_flag to
12238  * see if the passed in flag is set.
12239  * Returns:
12240  * 1 if flag is set.
12241  * 0 if flag is not set.
12242  **/
12243 static int
12244 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
12245 		 struct lpfc_iocbq *piocbq, uint32_t flag)
12246 {
12247 	unsigned long iflags;
12248 	int ret;
12249 
12250 	spin_lock_irqsave(&phba->hbalock, iflags);
12251 	ret = piocbq->iocb_flag & flag;
12252 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12253 	return ret;
12254 
12255 }
12256 
12257 /**
12258  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
12259  * @phba: Pointer to HBA context object..
12260  * @ring_number: Ring number
12261  * @piocb: Pointer to command iocb.
12262  * @prspiocbq: Pointer to response iocb.
12263  * @timeout: Timeout in number of seconds.
12264  *
12265  * This function issues the iocb to firmware and waits for the
12266  * iocb to complete. The iocb_cmpl field of the shall be used
12267  * to handle iocbs which time out. If the field is NULL, the
12268  * function shall free the iocbq structure.  If more clean up is
12269  * needed, the caller is expected to provide a completion function
12270  * that will provide the needed clean up.  If the iocb command is
12271  * not completed within timeout seconds, the function will either
12272  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
12273  * completion function set in the iocb_cmpl field and then return
12274  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
12275  * resources if this function returns IOCB_TIMEDOUT.
12276  * The function waits for the iocb completion using an
12277  * non-interruptible wait.
12278  * This function will sleep while waiting for iocb completion.
12279  * So, this function should not be called from any context which
12280  * does not allow sleeping. Due to the same reason, this function
12281  * cannot be called with interrupt disabled.
12282  * This function assumes that the iocb completions occur while
12283  * this function sleep. So, this function cannot be called from
12284  * the thread which process iocb completion for this ring.
12285  * This function clears the iocb_flag of the iocb object before
12286  * issuing the iocb and the iocb completion handler sets this
12287  * flag and wakes this thread when the iocb completes.
12288  * The contents of the response iocb will be copied to prspiocbq
12289  * by the completion handler when the command completes.
12290  * This function returns IOCB_SUCCESS when success.
12291  * This function is called with no lock held.
12292  **/
12293 int
12294 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
12295 			 uint32_t ring_number,
12296 			 struct lpfc_iocbq *piocb,
12297 			 struct lpfc_iocbq *prspiocbq,
12298 			 uint32_t timeout)
12299 {
12300 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
12301 	long timeleft, timeout_req = 0;
12302 	int retval = IOCB_SUCCESS;
12303 	uint32_t creg_val;
12304 	struct lpfc_iocbq *iocb;
12305 	int txq_cnt = 0;
12306 	int txcmplq_cnt = 0;
12307 	struct lpfc_sli_ring *pring;
12308 	unsigned long iflags;
12309 	bool iocb_completed = true;
12310 
12311 	if (phba->sli_rev >= LPFC_SLI_REV4)
12312 		pring = lpfc_sli4_calc_ring(phba, piocb);
12313 	else
12314 		pring = &phba->sli.sli3_ring[ring_number];
12315 	/*
12316 	 * If the caller has provided a response iocbq buffer, then context2
12317 	 * is NULL or its an error.
12318 	 */
12319 	if (prspiocbq) {
12320 		if (piocb->context2)
12321 			return IOCB_ERROR;
12322 		piocb->context2 = prspiocbq;
12323 	}
12324 
12325 	piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
12326 	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
12327 	piocb->context_un.wait_queue = &done_q;
12328 	piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
12329 
12330 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12331 		if (lpfc_readl(phba->HCregaddr, &creg_val))
12332 			return IOCB_ERROR;
12333 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
12334 		writel(creg_val, phba->HCregaddr);
12335 		readl(phba->HCregaddr); /* flush */
12336 	}
12337 
12338 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
12339 				     SLI_IOCB_RET_IOCB);
12340 	if (retval == IOCB_SUCCESS) {
12341 		timeout_req = msecs_to_jiffies(timeout * 1000);
12342 		timeleft = wait_event_timeout(done_q,
12343 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
12344 				timeout_req);
12345 		spin_lock_irqsave(&phba->hbalock, iflags);
12346 		if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
12347 
12348 			/*
12349 			 * IOCB timed out.  Inform the wake iocb wait
12350 			 * completion function and set local status
12351 			 */
12352 
12353 			iocb_completed = false;
12354 			piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
12355 		}
12356 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12357 		if (iocb_completed) {
12358 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12359 					"0331 IOCB wake signaled\n");
12360 			/* Note: we are not indicating if the IOCB has a success
12361 			 * status or not - that's for the caller to check.
12362 			 * IOCB_SUCCESS means just that the command was sent and
12363 			 * completed. Not that it completed successfully.
12364 			 * */
12365 		} else if (timeleft == 0) {
12366 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12367 					"0338 IOCB wait timeout error - no "
12368 					"wake response Data x%x\n", timeout);
12369 			retval = IOCB_TIMEDOUT;
12370 		} else {
12371 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12372 					"0330 IOCB wake NOT set, "
12373 					"Data x%x x%lx\n",
12374 					timeout, (timeleft / jiffies));
12375 			retval = IOCB_TIMEDOUT;
12376 		}
12377 	} else if (retval == IOCB_BUSY) {
12378 		if (phba->cfg_log_verbose & LOG_SLI) {
12379 			list_for_each_entry(iocb, &pring->txq, list) {
12380 				txq_cnt++;
12381 			}
12382 			list_for_each_entry(iocb, &pring->txcmplq, list) {
12383 				txcmplq_cnt++;
12384 			}
12385 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12386 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
12387 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
12388 		}
12389 		return retval;
12390 	} else {
12391 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12392 				"0332 IOCB wait issue failed, Data x%x\n",
12393 				retval);
12394 		retval = IOCB_ERROR;
12395 	}
12396 
12397 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12398 		if (lpfc_readl(phba->HCregaddr, &creg_val))
12399 			return IOCB_ERROR;
12400 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
12401 		writel(creg_val, phba->HCregaddr);
12402 		readl(phba->HCregaddr); /* flush */
12403 	}
12404 
12405 	if (prspiocbq)
12406 		piocb->context2 = NULL;
12407 
12408 	piocb->context_un.wait_queue = NULL;
12409 	piocb->iocb_cmpl = NULL;
12410 	return retval;
12411 }
12412 
12413 /**
12414  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
12415  * @phba: Pointer to HBA context object.
12416  * @pmboxq: Pointer to driver mailbox object.
12417  * @timeout: Timeout in number of seconds.
12418  *
12419  * This function issues the mailbox to firmware and waits for the
12420  * mailbox command to complete. If the mailbox command is not
12421  * completed within timeout seconds, it returns MBX_TIMEOUT.
12422  * The function waits for the mailbox completion using an
12423  * interruptible wait. If the thread is woken up due to a
12424  * signal, MBX_TIMEOUT error is returned to the caller. Caller
12425  * should not free the mailbox resources, if this function returns
12426  * MBX_TIMEOUT.
12427  * This function will sleep while waiting for mailbox completion.
12428  * So, this function should not be called from any context which
12429  * does not allow sleeping. Due to the same reason, this function
12430  * cannot be called with interrupt disabled.
12431  * This function assumes that the mailbox completion occurs while
12432  * this function sleep. So, this function cannot be called from
12433  * the worker thread which processes mailbox completion.
12434  * This function is called in the context of HBA management
12435  * applications.
12436  * This function returns MBX_SUCCESS when successful.
12437  * This function is called with no lock held.
12438  **/
12439 int
12440 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
12441 			 uint32_t timeout)
12442 {
12443 	struct completion mbox_done;
12444 	int retval;
12445 	unsigned long flag;
12446 
12447 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
12448 	/* setup wake call as IOCB callback */
12449 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
12450 
12451 	/* setup context3 field to pass wait_queue pointer to wake function  */
12452 	init_completion(&mbox_done);
12453 	pmboxq->context3 = &mbox_done;
12454 	/* now issue the command */
12455 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
12456 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
12457 		wait_for_completion_timeout(&mbox_done,
12458 					    msecs_to_jiffies(timeout * 1000));
12459 
12460 		spin_lock_irqsave(&phba->hbalock, flag);
12461 		pmboxq->context3 = NULL;
12462 		/*
12463 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
12464 		 * else do not free the resources.
12465 		 */
12466 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
12467 			retval = MBX_SUCCESS;
12468 		} else {
12469 			retval = MBX_TIMEOUT;
12470 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
12471 		}
12472 		spin_unlock_irqrestore(&phba->hbalock, flag);
12473 	}
12474 	return retval;
12475 }
12476 
12477 /**
12478  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
12479  * @phba: Pointer to HBA context.
12480  * @mbx_action: Mailbox shutdown options.
12481  *
12482  * This function is called to shutdown the driver's mailbox sub-system.
12483  * It first marks the mailbox sub-system is in a block state to prevent
12484  * the asynchronous mailbox command from issued off the pending mailbox
12485  * command queue. If the mailbox command sub-system shutdown is due to
12486  * HBA error conditions such as EEH or ERATT, this routine shall invoke
12487  * the mailbox sub-system flush routine to forcefully bring down the
12488  * mailbox sub-system. Otherwise, if it is due to normal condition (such
12489  * as with offline or HBA function reset), this routine will wait for the
12490  * outstanding mailbox command to complete before invoking the mailbox
12491  * sub-system flush routine to gracefully bring down mailbox sub-system.
12492  **/
12493 void
12494 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
12495 {
12496 	struct lpfc_sli *psli = &phba->sli;
12497 	unsigned long timeout;
12498 
12499 	if (mbx_action == LPFC_MBX_NO_WAIT) {
12500 		/* delay 100ms for port state */
12501 		msleep(100);
12502 		lpfc_sli_mbox_sys_flush(phba);
12503 		return;
12504 	}
12505 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
12506 
12507 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12508 	local_bh_disable();
12509 
12510 	spin_lock_irq(&phba->hbalock);
12511 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
12512 
12513 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
12514 		/* Determine how long we might wait for the active mailbox
12515 		 * command to be gracefully completed by firmware.
12516 		 */
12517 		if (phba->sli.mbox_active)
12518 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
12519 						phba->sli.mbox_active) *
12520 						1000) + jiffies;
12521 		spin_unlock_irq(&phba->hbalock);
12522 
12523 		/* Enable softirqs again, done with phba->hbalock */
12524 		local_bh_enable();
12525 
12526 		while (phba->sli.mbox_active) {
12527 			/* Check active mailbox complete status every 2ms */
12528 			msleep(2);
12529 			if (time_after(jiffies, timeout))
12530 				/* Timeout, let the mailbox flush routine to
12531 				 * forcefully release active mailbox command
12532 				 */
12533 				break;
12534 		}
12535 	} else {
12536 		spin_unlock_irq(&phba->hbalock);
12537 
12538 		/* Enable softirqs again, done with phba->hbalock */
12539 		local_bh_enable();
12540 	}
12541 
12542 	lpfc_sli_mbox_sys_flush(phba);
12543 }
12544 
12545 /**
12546  * lpfc_sli_eratt_read - read sli-3 error attention events
12547  * @phba: Pointer to HBA context.
12548  *
12549  * This function is called to read the SLI3 device error attention registers
12550  * for possible error attention events. The caller must hold the hostlock
12551  * with spin_lock_irq().
12552  *
12553  * This function returns 1 when there is Error Attention in the Host Attention
12554  * Register and returns 0 otherwise.
12555  **/
12556 static int
12557 lpfc_sli_eratt_read(struct lpfc_hba *phba)
12558 {
12559 	uint32_t ha_copy;
12560 
12561 	/* Read chip Host Attention (HA) register */
12562 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
12563 		goto unplug_err;
12564 
12565 	if (ha_copy & HA_ERATT) {
12566 		/* Read host status register to retrieve error event */
12567 		if (lpfc_sli_read_hs(phba))
12568 			goto unplug_err;
12569 
12570 		/* Check if there is a deferred error condition is active */
12571 		if ((HS_FFER1 & phba->work_hs) &&
12572 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12573 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
12574 			phba->hba_flag |= DEFER_ERATT;
12575 			/* Clear all interrupt enable conditions */
12576 			writel(0, phba->HCregaddr);
12577 			readl(phba->HCregaddr);
12578 		}
12579 
12580 		/* Set the driver HA work bitmap */
12581 		phba->work_ha |= HA_ERATT;
12582 		/* Indicate polling handles this ERATT */
12583 		phba->hba_flag |= HBA_ERATT_HANDLED;
12584 		return 1;
12585 	}
12586 	return 0;
12587 
12588 unplug_err:
12589 	/* Set the driver HS work bitmap */
12590 	phba->work_hs |= UNPLUG_ERR;
12591 	/* Set the driver HA work bitmap */
12592 	phba->work_ha |= HA_ERATT;
12593 	/* Indicate polling handles this ERATT */
12594 	phba->hba_flag |= HBA_ERATT_HANDLED;
12595 	return 1;
12596 }
12597 
12598 /**
12599  * lpfc_sli4_eratt_read - read sli-4 error attention events
12600  * @phba: Pointer to HBA context.
12601  *
12602  * This function is called to read the SLI4 device error attention registers
12603  * for possible error attention events. The caller must hold the hostlock
12604  * with spin_lock_irq().
12605  *
12606  * This function returns 1 when there is Error Attention in the Host Attention
12607  * Register and returns 0 otherwise.
12608  **/
12609 static int
12610 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
12611 {
12612 	uint32_t uerr_sta_hi, uerr_sta_lo;
12613 	uint32_t if_type, portsmphr;
12614 	struct lpfc_register portstat_reg;
12615 
12616 	/*
12617 	 * For now, use the SLI4 device internal unrecoverable error
12618 	 * registers for error attention. This can be changed later.
12619 	 */
12620 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12621 	switch (if_type) {
12622 	case LPFC_SLI_INTF_IF_TYPE_0:
12623 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
12624 			&uerr_sta_lo) ||
12625 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
12626 			&uerr_sta_hi)) {
12627 			phba->work_hs |= UNPLUG_ERR;
12628 			phba->work_ha |= HA_ERATT;
12629 			phba->hba_flag |= HBA_ERATT_HANDLED;
12630 			return 1;
12631 		}
12632 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
12633 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
12634 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12635 					"1423 HBA Unrecoverable error: "
12636 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
12637 					"ue_mask_lo_reg=0x%x, "
12638 					"ue_mask_hi_reg=0x%x\n",
12639 					uerr_sta_lo, uerr_sta_hi,
12640 					phba->sli4_hba.ue_mask_lo,
12641 					phba->sli4_hba.ue_mask_hi);
12642 			phba->work_status[0] = uerr_sta_lo;
12643 			phba->work_status[1] = uerr_sta_hi;
12644 			phba->work_ha |= HA_ERATT;
12645 			phba->hba_flag |= HBA_ERATT_HANDLED;
12646 			return 1;
12647 		}
12648 		break;
12649 	case LPFC_SLI_INTF_IF_TYPE_2:
12650 	case LPFC_SLI_INTF_IF_TYPE_6:
12651 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
12652 			&portstat_reg.word0) ||
12653 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
12654 			&portsmphr)){
12655 			phba->work_hs |= UNPLUG_ERR;
12656 			phba->work_ha |= HA_ERATT;
12657 			phba->hba_flag |= HBA_ERATT_HANDLED;
12658 			return 1;
12659 		}
12660 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
12661 			phba->work_status[0] =
12662 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
12663 			phba->work_status[1] =
12664 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
12665 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12666 					"2885 Port Status Event: "
12667 					"port status reg 0x%x, "
12668 					"port smphr reg 0x%x, "
12669 					"error 1=0x%x, error 2=0x%x\n",
12670 					portstat_reg.word0,
12671 					portsmphr,
12672 					phba->work_status[0],
12673 					phba->work_status[1]);
12674 			phba->work_ha |= HA_ERATT;
12675 			phba->hba_flag |= HBA_ERATT_HANDLED;
12676 			return 1;
12677 		}
12678 		break;
12679 	case LPFC_SLI_INTF_IF_TYPE_1:
12680 	default:
12681 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12682 				"2886 HBA Error Attention on unsupported "
12683 				"if type %d.", if_type);
12684 		return 1;
12685 	}
12686 
12687 	return 0;
12688 }
12689 
12690 /**
12691  * lpfc_sli_check_eratt - check error attention events
12692  * @phba: Pointer to HBA context.
12693  *
12694  * This function is called from timer soft interrupt context to check HBA's
12695  * error attention register bit for error attention events.
12696  *
12697  * This function returns 1 when there is Error Attention in the Host Attention
12698  * Register and returns 0 otherwise.
12699  **/
12700 int
12701 lpfc_sli_check_eratt(struct lpfc_hba *phba)
12702 {
12703 	uint32_t ha_copy;
12704 
12705 	/* If somebody is waiting to handle an eratt, don't process it
12706 	 * here. The brdkill function will do this.
12707 	 */
12708 	if (phba->link_flag & LS_IGNORE_ERATT)
12709 		return 0;
12710 
12711 	/* Check if interrupt handler handles this ERATT */
12712 	spin_lock_irq(&phba->hbalock);
12713 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
12714 		/* Interrupt handler has handled ERATT */
12715 		spin_unlock_irq(&phba->hbalock);
12716 		return 0;
12717 	}
12718 
12719 	/*
12720 	 * If there is deferred error attention, do not check for error
12721 	 * attention
12722 	 */
12723 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12724 		spin_unlock_irq(&phba->hbalock);
12725 		return 0;
12726 	}
12727 
12728 	/* If PCI channel is offline, don't process it */
12729 	if (unlikely(pci_channel_offline(phba->pcidev))) {
12730 		spin_unlock_irq(&phba->hbalock);
12731 		return 0;
12732 	}
12733 
12734 	switch (phba->sli_rev) {
12735 	case LPFC_SLI_REV2:
12736 	case LPFC_SLI_REV3:
12737 		/* Read chip Host Attention (HA) register */
12738 		ha_copy = lpfc_sli_eratt_read(phba);
12739 		break;
12740 	case LPFC_SLI_REV4:
12741 		/* Read device Uncoverable Error (UERR) registers */
12742 		ha_copy = lpfc_sli4_eratt_read(phba);
12743 		break;
12744 	default:
12745 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12746 				"0299 Invalid SLI revision (%d)\n",
12747 				phba->sli_rev);
12748 		ha_copy = 0;
12749 		break;
12750 	}
12751 	spin_unlock_irq(&phba->hbalock);
12752 
12753 	return ha_copy;
12754 }
12755 
12756 /**
12757  * lpfc_intr_state_check - Check device state for interrupt handling
12758  * @phba: Pointer to HBA context.
12759  *
12760  * This inline routine checks whether a device or its PCI slot is in a state
12761  * that the interrupt should be handled.
12762  *
12763  * This function returns 0 if the device or the PCI slot is in a state that
12764  * interrupt should be handled, otherwise -EIO.
12765  */
12766 static inline int
12767 lpfc_intr_state_check(struct lpfc_hba *phba)
12768 {
12769 	/* If the pci channel is offline, ignore all the interrupts */
12770 	if (unlikely(pci_channel_offline(phba->pcidev)))
12771 		return -EIO;
12772 
12773 	/* Update device level interrupt statistics */
12774 	phba->sli.slistat.sli_intr++;
12775 
12776 	/* Ignore all interrupts during initialization. */
12777 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
12778 		return -EIO;
12779 
12780 	return 0;
12781 }
12782 
12783 /**
12784  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
12785  * @irq: Interrupt number.
12786  * @dev_id: The device context pointer.
12787  *
12788  * This function is directly called from the PCI layer as an interrupt
12789  * service routine when device with SLI-3 interface spec is enabled with
12790  * MSI-X multi-message interrupt mode and there are slow-path events in
12791  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
12792  * interrupt mode, this function is called as part of the device-level
12793  * interrupt handler. When the PCI slot is in error recovery or the HBA
12794  * is undergoing initialization, the interrupt handler will not process
12795  * the interrupt. The link attention and ELS ring attention events are
12796  * handled by the worker thread. The interrupt handler signals the worker
12797  * thread and returns for these events. This function is called without
12798  * any lock held. It gets the hbalock to access and update SLI data
12799  * structures.
12800  *
12801  * This function returns IRQ_HANDLED when interrupt is handled else it
12802  * returns IRQ_NONE.
12803  **/
12804 irqreturn_t
12805 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
12806 {
12807 	struct lpfc_hba  *phba;
12808 	uint32_t ha_copy, hc_copy;
12809 	uint32_t work_ha_copy;
12810 	unsigned long status;
12811 	unsigned long iflag;
12812 	uint32_t control;
12813 
12814 	MAILBOX_t *mbox, *pmbox;
12815 	struct lpfc_vport *vport;
12816 	struct lpfc_nodelist *ndlp;
12817 	struct lpfc_dmabuf *mp;
12818 	LPFC_MBOXQ_t *pmb;
12819 	int rc;
12820 
12821 	/*
12822 	 * Get the driver's phba structure from the dev_id and
12823 	 * assume the HBA is not interrupting.
12824 	 */
12825 	phba = (struct lpfc_hba *)dev_id;
12826 
12827 	if (unlikely(!phba))
12828 		return IRQ_NONE;
12829 
12830 	/*
12831 	 * Stuff needs to be attented to when this function is invoked as an
12832 	 * individual interrupt handler in MSI-X multi-message interrupt mode
12833 	 */
12834 	if (phba->intr_type == MSIX) {
12835 		/* Check device state for handling interrupt */
12836 		if (lpfc_intr_state_check(phba))
12837 			return IRQ_NONE;
12838 		/* Need to read HA REG for slow-path events */
12839 		spin_lock_irqsave(&phba->hbalock, iflag);
12840 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
12841 			goto unplug_error;
12842 		/* If somebody is waiting to handle an eratt don't process it
12843 		 * here. The brdkill function will do this.
12844 		 */
12845 		if (phba->link_flag & LS_IGNORE_ERATT)
12846 			ha_copy &= ~HA_ERATT;
12847 		/* Check the need for handling ERATT in interrupt handler */
12848 		if (ha_copy & HA_ERATT) {
12849 			if (phba->hba_flag & HBA_ERATT_HANDLED)
12850 				/* ERATT polling has handled ERATT */
12851 				ha_copy &= ~HA_ERATT;
12852 			else
12853 				/* Indicate interrupt handler handles ERATT */
12854 				phba->hba_flag |= HBA_ERATT_HANDLED;
12855 		}
12856 
12857 		/*
12858 		 * If there is deferred error attention, do not check for any
12859 		 * interrupt.
12860 		 */
12861 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12862 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12863 			return IRQ_NONE;
12864 		}
12865 
12866 		/* Clear up only attention source related to slow-path */
12867 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
12868 			goto unplug_error;
12869 
12870 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
12871 			HC_LAINT_ENA | HC_ERINT_ENA),
12872 			phba->HCregaddr);
12873 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
12874 			phba->HAregaddr);
12875 		writel(hc_copy, phba->HCregaddr);
12876 		readl(phba->HAregaddr); /* flush */
12877 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12878 	} else
12879 		ha_copy = phba->ha_copy;
12880 
12881 	work_ha_copy = ha_copy & phba->work_ha_mask;
12882 
12883 	if (work_ha_copy) {
12884 		if (work_ha_copy & HA_LATT) {
12885 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
12886 				/*
12887 				 * Turn off Link Attention interrupts
12888 				 * until CLEAR_LA done
12889 				 */
12890 				spin_lock_irqsave(&phba->hbalock, iflag);
12891 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
12892 				if (lpfc_readl(phba->HCregaddr, &control))
12893 					goto unplug_error;
12894 				control &= ~HC_LAINT_ENA;
12895 				writel(control, phba->HCregaddr);
12896 				readl(phba->HCregaddr); /* flush */
12897 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12898 			}
12899 			else
12900 				work_ha_copy &= ~HA_LATT;
12901 		}
12902 
12903 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
12904 			/*
12905 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
12906 			 * the only slow ring.
12907 			 */
12908 			status = (work_ha_copy &
12909 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
12910 			status >>= (4*LPFC_ELS_RING);
12911 			if (status & HA_RXMASK) {
12912 				spin_lock_irqsave(&phba->hbalock, iflag);
12913 				if (lpfc_readl(phba->HCregaddr, &control))
12914 					goto unplug_error;
12915 
12916 				lpfc_debugfs_slow_ring_trc(phba,
12917 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
12918 				control, status,
12919 				(uint32_t)phba->sli.slistat.sli_intr);
12920 
12921 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
12922 					lpfc_debugfs_slow_ring_trc(phba,
12923 						"ISR Disable ring:"
12924 						"pwork:x%x hawork:x%x wait:x%x",
12925 						phba->work_ha, work_ha_copy,
12926 						(uint32_t)((unsigned long)
12927 						&phba->work_waitq));
12928 
12929 					control &=
12930 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
12931 					writel(control, phba->HCregaddr);
12932 					readl(phba->HCregaddr); /* flush */
12933 				}
12934 				else {
12935 					lpfc_debugfs_slow_ring_trc(phba,
12936 						"ISR slow ring:   pwork:"
12937 						"x%x hawork:x%x wait:x%x",
12938 						phba->work_ha, work_ha_copy,
12939 						(uint32_t)((unsigned long)
12940 						&phba->work_waitq));
12941 				}
12942 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12943 			}
12944 		}
12945 		spin_lock_irqsave(&phba->hbalock, iflag);
12946 		if (work_ha_copy & HA_ERATT) {
12947 			if (lpfc_sli_read_hs(phba))
12948 				goto unplug_error;
12949 			/*
12950 			 * Check if there is a deferred error condition
12951 			 * is active
12952 			 */
12953 			if ((HS_FFER1 & phba->work_hs) &&
12954 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12955 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
12956 				  phba->work_hs)) {
12957 				phba->hba_flag |= DEFER_ERATT;
12958 				/* Clear all interrupt enable conditions */
12959 				writel(0, phba->HCregaddr);
12960 				readl(phba->HCregaddr);
12961 			}
12962 		}
12963 
12964 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
12965 			pmb = phba->sli.mbox_active;
12966 			pmbox = &pmb->u.mb;
12967 			mbox = phba->mbox;
12968 			vport = pmb->vport;
12969 
12970 			/* First check out the status word */
12971 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
12972 			if (pmbox->mbxOwner != OWN_HOST) {
12973 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12974 				/*
12975 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
12976 				 * mbxStatus <status>
12977 				 */
12978 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12979 						"(%d):0304 Stray Mailbox "
12980 						"Interrupt mbxCommand x%x "
12981 						"mbxStatus x%x\n",
12982 						(vport ? vport->vpi : 0),
12983 						pmbox->mbxCommand,
12984 						pmbox->mbxStatus);
12985 				/* clear mailbox attention bit */
12986 				work_ha_copy &= ~HA_MBATT;
12987 			} else {
12988 				phba->sli.mbox_active = NULL;
12989 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12990 				phba->last_completion_time = jiffies;
12991 				del_timer(&phba->sli.mbox_tmo);
12992 				if (pmb->mbox_cmpl) {
12993 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
12994 							MAILBOX_CMD_SIZE);
12995 					if (pmb->out_ext_byte_len &&
12996 						pmb->ctx_buf)
12997 						lpfc_sli_pcimem_bcopy(
12998 						phba->mbox_ext,
12999 						pmb->ctx_buf,
13000 						pmb->out_ext_byte_len);
13001 				}
13002 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13003 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13004 
13005 					lpfc_debugfs_disc_trc(vport,
13006 						LPFC_DISC_TRC_MBOX_VPORT,
13007 						"MBOX dflt rpi: : "
13008 						"status:x%x rpi:x%x",
13009 						(uint32_t)pmbox->mbxStatus,
13010 						pmbox->un.varWords[0], 0);
13011 
13012 					if (!pmbox->mbxStatus) {
13013 						mp = (struct lpfc_dmabuf *)
13014 							(pmb->ctx_buf);
13015 						ndlp = (struct lpfc_nodelist *)
13016 							pmb->ctx_ndlp;
13017 
13018 						/* Reg_LOGIN of dflt RPI was
13019 						 * successful. new lets get
13020 						 * rid of the RPI using the
13021 						 * same mbox buffer.
13022 						 */
13023 						lpfc_unreg_login(phba,
13024 							vport->vpi,
13025 							pmbox->un.varWords[0],
13026 							pmb);
13027 						pmb->mbox_cmpl =
13028 							lpfc_mbx_cmpl_dflt_rpi;
13029 						pmb->ctx_buf = mp;
13030 						pmb->ctx_ndlp = ndlp;
13031 						pmb->vport = vport;
13032 						rc = lpfc_sli_issue_mbox(phba,
13033 								pmb,
13034 								MBX_NOWAIT);
13035 						if (rc != MBX_BUSY)
13036 							lpfc_printf_log(phba,
13037 							KERN_ERR,
13038 							LOG_TRACE_EVENT,
13039 							"0350 rc should have"
13040 							"been MBX_BUSY\n");
13041 						if (rc != MBX_NOT_FINISHED)
13042 							goto send_current_mbox;
13043 					}
13044 				}
13045 				spin_lock_irqsave(
13046 						&phba->pport->work_port_lock,
13047 						iflag);
13048 				phba->pport->work_port_events &=
13049 					~WORKER_MBOX_TMO;
13050 				spin_unlock_irqrestore(
13051 						&phba->pport->work_port_lock,
13052 						iflag);
13053 
13054 				/* Do NOT queue MBX_HEARTBEAT to the worker
13055 				 * thread for processing.
13056 				 */
13057 				if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13058 					/* Process mbox now */
13059 					phba->sli.mbox_active = NULL;
13060 					phba->sli.sli_flag &=
13061 						~LPFC_SLI_MBOX_ACTIVE;
13062 					if (pmb->mbox_cmpl)
13063 						pmb->mbox_cmpl(phba, pmb);
13064 				} else {
13065 					/* Queue to worker thread to process */
13066 					lpfc_mbox_cmpl_put(phba, pmb);
13067 				}
13068 			}
13069 		} else
13070 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13071 
13072 		if ((work_ha_copy & HA_MBATT) &&
13073 		    (phba->sli.mbox_active == NULL)) {
13074 send_current_mbox:
13075 			/* Process next mailbox command if there is one */
13076 			do {
13077 				rc = lpfc_sli_issue_mbox(phba, NULL,
13078 							 MBX_NOWAIT);
13079 			} while (rc == MBX_NOT_FINISHED);
13080 			if (rc != MBX_SUCCESS)
13081 				lpfc_printf_log(phba, KERN_ERR,
13082 						LOG_TRACE_EVENT,
13083 						"0349 rc should be "
13084 						"MBX_SUCCESS\n");
13085 		}
13086 
13087 		spin_lock_irqsave(&phba->hbalock, iflag);
13088 		phba->work_ha |= work_ha_copy;
13089 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13090 		lpfc_worker_wake_up(phba);
13091 	}
13092 	return IRQ_HANDLED;
13093 unplug_error:
13094 	spin_unlock_irqrestore(&phba->hbalock, iflag);
13095 	return IRQ_HANDLED;
13096 
13097 } /* lpfc_sli_sp_intr_handler */
13098 
13099 /**
13100  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13101  * @irq: Interrupt number.
13102  * @dev_id: The device context pointer.
13103  *
13104  * This function is directly called from the PCI layer as an interrupt
13105  * service routine when device with SLI-3 interface spec is enabled with
13106  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13107  * ring event in the HBA. However, when the device is enabled with either
13108  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13109  * device-level interrupt handler. When the PCI slot is in error recovery
13110  * or the HBA is undergoing initialization, the interrupt handler will not
13111  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13112  * the intrrupt context. This function is called without any lock held.
13113  * It gets the hbalock to access and update SLI data structures.
13114  *
13115  * This function returns IRQ_HANDLED when interrupt is handled else it
13116  * returns IRQ_NONE.
13117  **/
13118 irqreturn_t
13119 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13120 {
13121 	struct lpfc_hba  *phba;
13122 	uint32_t ha_copy;
13123 	unsigned long status;
13124 	unsigned long iflag;
13125 	struct lpfc_sli_ring *pring;
13126 
13127 	/* Get the driver's phba structure from the dev_id and
13128 	 * assume the HBA is not interrupting.
13129 	 */
13130 	phba = (struct lpfc_hba *) dev_id;
13131 
13132 	if (unlikely(!phba))
13133 		return IRQ_NONE;
13134 
13135 	/*
13136 	 * Stuff needs to be attented to when this function is invoked as an
13137 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13138 	 */
13139 	if (phba->intr_type == MSIX) {
13140 		/* Check device state for handling interrupt */
13141 		if (lpfc_intr_state_check(phba))
13142 			return IRQ_NONE;
13143 		/* Need to read HA REG for FCP ring and other ring events */
13144 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13145 			return IRQ_HANDLED;
13146 		/* Clear up only attention source related to fast-path */
13147 		spin_lock_irqsave(&phba->hbalock, iflag);
13148 		/*
13149 		 * If there is deferred error attention, do not check for
13150 		 * any interrupt.
13151 		 */
13152 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13153 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13154 			return IRQ_NONE;
13155 		}
13156 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
13157 			phba->HAregaddr);
13158 		readl(phba->HAregaddr); /* flush */
13159 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13160 	} else
13161 		ha_copy = phba->ha_copy;
13162 
13163 	/*
13164 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
13165 	 */
13166 	ha_copy &= ~(phba->work_ha_mask);
13167 
13168 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13169 	status >>= (4*LPFC_FCP_RING);
13170 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
13171 	if (status & HA_RXMASK)
13172 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
13173 
13174 	if (phba->cfg_multi_ring_support == 2) {
13175 		/*
13176 		 * Process all events on extra ring. Take the optimized path
13177 		 * for extra ring IO.
13178 		 */
13179 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13180 		status >>= (4*LPFC_EXTRA_RING);
13181 		if (status & HA_RXMASK) {
13182 			lpfc_sli_handle_fast_ring_event(phba,
13183 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
13184 					status);
13185 		}
13186 	}
13187 	return IRQ_HANDLED;
13188 }  /* lpfc_sli_fp_intr_handler */
13189 
13190 /**
13191  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
13192  * @irq: Interrupt number.
13193  * @dev_id: The device context pointer.
13194  *
13195  * This function is the HBA device-level interrupt handler to device with
13196  * SLI-3 interface spec, called from the PCI layer when either MSI or
13197  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
13198  * requires driver attention. This function invokes the slow-path interrupt
13199  * attention handling function and fast-path interrupt attention handling
13200  * function in turn to process the relevant HBA attention events. This
13201  * function is called without any lock held. It gets the hbalock to access
13202  * and update SLI data structures.
13203  *
13204  * This function returns IRQ_HANDLED when interrupt is handled, else it
13205  * returns IRQ_NONE.
13206  **/
13207 irqreturn_t
13208 lpfc_sli_intr_handler(int irq, void *dev_id)
13209 {
13210 	struct lpfc_hba  *phba;
13211 	irqreturn_t sp_irq_rc, fp_irq_rc;
13212 	unsigned long status1, status2;
13213 	uint32_t hc_copy;
13214 
13215 	/*
13216 	 * Get the driver's phba structure from the dev_id and
13217 	 * assume the HBA is not interrupting.
13218 	 */
13219 	phba = (struct lpfc_hba *) dev_id;
13220 
13221 	if (unlikely(!phba))
13222 		return IRQ_NONE;
13223 
13224 	/* Check device state for handling interrupt */
13225 	if (lpfc_intr_state_check(phba))
13226 		return IRQ_NONE;
13227 
13228 	spin_lock(&phba->hbalock);
13229 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
13230 		spin_unlock(&phba->hbalock);
13231 		return IRQ_HANDLED;
13232 	}
13233 
13234 	if (unlikely(!phba->ha_copy)) {
13235 		spin_unlock(&phba->hbalock);
13236 		return IRQ_NONE;
13237 	} else if (phba->ha_copy & HA_ERATT) {
13238 		if (phba->hba_flag & HBA_ERATT_HANDLED)
13239 			/* ERATT polling has handled ERATT */
13240 			phba->ha_copy &= ~HA_ERATT;
13241 		else
13242 			/* Indicate interrupt handler handles ERATT */
13243 			phba->hba_flag |= HBA_ERATT_HANDLED;
13244 	}
13245 
13246 	/*
13247 	 * If there is deferred error attention, do not check for any interrupt.
13248 	 */
13249 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13250 		spin_unlock(&phba->hbalock);
13251 		return IRQ_NONE;
13252 	}
13253 
13254 	/* Clear attention sources except link and error attentions */
13255 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
13256 		spin_unlock(&phba->hbalock);
13257 		return IRQ_HANDLED;
13258 	}
13259 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
13260 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
13261 		phba->HCregaddr);
13262 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
13263 	writel(hc_copy, phba->HCregaddr);
13264 	readl(phba->HAregaddr); /* flush */
13265 	spin_unlock(&phba->hbalock);
13266 
13267 	/*
13268 	 * Invokes slow-path host attention interrupt handling as appropriate.
13269 	 */
13270 
13271 	/* status of events with mailbox and link attention */
13272 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
13273 
13274 	/* status of events with ELS ring */
13275 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
13276 	status2 >>= (4*LPFC_ELS_RING);
13277 
13278 	if (status1 || (status2 & HA_RXMASK))
13279 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
13280 	else
13281 		sp_irq_rc = IRQ_NONE;
13282 
13283 	/*
13284 	 * Invoke fast-path host attention interrupt handling as appropriate.
13285 	 */
13286 
13287 	/* status of events with FCP ring */
13288 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13289 	status1 >>= (4*LPFC_FCP_RING);
13290 
13291 	/* status of events with extra ring */
13292 	if (phba->cfg_multi_ring_support == 2) {
13293 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13294 		status2 >>= (4*LPFC_EXTRA_RING);
13295 	} else
13296 		status2 = 0;
13297 
13298 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
13299 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
13300 	else
13301 		fp_irq_rc = IRQ_NONE;
13302 
13303 	/* Return device-level interrupt handling status */
13304 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
13305 }  /* lpfc_sli_intr_handler */
13306 
13307 /**
13308  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
13309  * @phba: pointer to lpfc hba data structure.
13310  *
13311  * This routine is invoked by the worker thread to process all the pending
13312  * SLI4 els abort xri events.
13313  **/
13314 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
13315 {
13316 	struct lpfc_cq_event *cq_event;
13317 	unsigned long iflags;
13318 
13319 	/* First, declare the els xri abort event has been handled */
13320 	spin_lock_irqsave(&phba->hbalock, iflags);
13321 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
13322 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13323 
13324 	/* Now, handle all the els xri abort events */
13325 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
13326 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
13327 		/* Get the first event from the head of the event queue */
13328 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
13329 				 cq_event, struct lpfc_cq_event, list);
13330 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
13331 				       iflags);
13332 		/* Notify aborted XRI for ELS work queue */
13333 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
13334 
13335 		/* Free the event processed back to the free pool */
13336 		lpfc_sli4_cq_event_release(phba, cq_event);
13337 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
13338 				  iflags);
13339 	}
13340 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
13341 }
13342 
13343 /**
13344  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
13345  * @phba: pointer to lpfc hba data structure
13346  * @pIocbIn: pointer to the rspiocbq
13347  * @pIocbOut: pointer to the cmdiocbq
13348  * @wcqe: pointer to the complete wcqe
13349  *
13350  * This routine transfers the fields of a command iocbq to a response iocbq
13351  * by copying all the IOCB fields from command iocbq and transferring the
13352  * completion status information from the complete wcqe.
13353  **/
13354 static void
13355 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
13356 			      struct lpfc_iocbq *pIocbIn,
13357 			      struct lpfc_iocbq *pIocbOut,
13358 			      struct lpfc_wcqe_complete *wcqe)
13359 {
13360 	int numBdes, i;
13361 	unsigned long iflags;
13362 	uint32_t status, max_response;
13363 	struct lpfc_dmabuf *dmabuf;
13364 	struct ulp_bde64 *bpl, bde;
13365 	size_t offset = offsetof(struct lpfc_iocbq, iocb);
13366 
13367 	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
13368 	       sizeof(struct lpfc_iocbq) - offset);
13369 	/* Map WCQE parameters into irspiocb parameters */
13370 	status = bf_get(lpfc_wcqe_c_status, wcqe);
13371 	pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
13372 	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
13373 		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
13374 			pIocbIn->iocb.un.fcpi.fcpi_parm =
13375 					pIocbOut->iocb.un.fcpi.fcpi_parm -
13376 					wcqe->total_data_placed;
13377 		else
13378 			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
13379 	else {
13380 		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
13381 		switch (pIocbOut->iocb.ulpCommand) {
13382 		case CMD_ELS_REQUEST64_CR:
13383 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
13384 			bpl  = (struct ulp_bde64 *)dmabuf->virt;
13385 			bde.tus.w = le32_to_cpu(bpl[1].tus.w);
13386 			max_response = bde.tus.f.bdeSize;
13387 			break;
13388 		case CMD_GEN_REQUEST64_CR:
13389 			max_response = 0;
13390 			if (!pIocbOut->context3)
13391 				break;
13392 			numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
13393 					sizeof(struct ulp_bde64);
13394 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
13395 			bpl = (struct ulp_bde64 *)dmabuf->virt;
13396 			for (i = 0; i < numBdes; i++) {
13397 				bde.tus.w = le32_to_cpu(bpl[i].tus.w);
13398 				if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
13399 					max_response += bde.tus.f.bdeSize;
13400 			}
13401 			break;
13402 		default:
13403 			max_response = wcqe->total_data_placed;
13404 			break;
13405 		}
13406 		if (max_response < wcqe->total_data_placed)
13407 			pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
13408 		else
13409 			pIocbIn->iocb.un.genreq64.bdl.bdeSize =
13410 				wcqe->total_data_placed;
13411 	}
13412 
13413 	/* Convert BG errors for completion status */
13414 	if (status == CQE_STATUS_DI_ERROR) {
13415 		pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
13416 
13417 		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
13418 			pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
13419 		else
13420 			pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
13421 
13422 		pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
13423 		if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
13424 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13425 				BGS_GUARD_ERR_MASK;
13426 		if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
13427 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13428 				BGS_APPTAG_ERR_MASK;
13429 		if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
13430 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13431 				BGS_REFTAG_ERR_MASK;
13432 
13433 		/* Check to see if there was any good data before the error */
13434 		if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
13435 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13436 				BGS_HI_WATER_MARK_PRESENT_MASK;
13437 			pIocbIn->iocb.unsli3.sli3_bg.bghm =
13438 				wcqe->total_data_placed;
13439 		}
13440 
13441 		/*
13442 		* Set ALL the error bits to indicate we don't know what
13443 		* type of error it is.
13444 		*/
13445 		if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
13446 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13447 				(BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
13448 				BGS_GUARD_ERR_MASK);
13449 	}
13450 
13451 	/* Pick up HBA exchange busy condition */
13452 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
13453 		spin_lock_irqsave(&phba->hbalock, iflags);
13454 		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
13455 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13456 	}
13457 }
13458 
13459 /**
13460  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
13461  * @phba: Pointer to HBA context object.
13462  * @irspiocbq: Pointer to work-queue completion queue entry.
13463  *
13464  * This routine handles an ELS work-queue completion event and construct
13465  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
13466  * discovery engine to handle.
13467  *
13468  * Return: Pointer to the receive IOCBQ, NULL otherwise.
13469  **/
13470 static struct lpfc_iocbq *
13471 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
13472 			       struct lpfc_iocbq *irspiocbq)
13473 {
13474 	struct lpfc_sli_ring *pring;
13475 	struct lpfc_iocbq *cmdiocbq;
13476 	struct lpfc_wcqe_complete *wcqe;
13477 	unsigned long iflags;
13478 
13479 	pring = lpfc_phba_elsring(phba);
13480 	if (unlikely(!pring))
13481 		return NULL;
13482 
13483 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
13484 	pring->stats.iocb_event++;
13485 	/* Look up the ELS command IOCB and create pseudo response IOCB */
13486 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
13487 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13488 	if (unlikely(!cmdiocbq)) {
13489 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13490 				"0386 ELS complete with no corresponding "
13491 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
13492 				wcqe->word0, wcqe->total_data_placed,
13493 				wcqe->parameter, wcqe->word3);
13494 		lpfc_sli_release_iocbq(phba, irspiocbq);
13495 		return NULL;
13496 	}
13497 
13498 	spin_lock_irqsave(&pring->ring_lock, iflags);
13499 	/* Put the iocb back on the txcmplq */
13500 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
13501 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
13502 
13503 	/* Fake the irspiocbq and copy necessary response information */
13504 	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
13505 
13506 	return irspiocbq;
13507 }
13508 
13509 inline struct lpfc_cq_event *
13510 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
13511 {
13512 	struct lpfc_cq_event *cq_event;
13513 
13514 	/* Allocate a new internal CQ_EVENT entry */
13515 	cq_event = lpfc_sli4_cq_event_alloc(phba);
13516 	if (!cq_event) {
13517 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13518 				"0602 Failed to alloc CQ_EVENT entry\n");
13519 		return NULL;
13520 	}
13521 
13522 	/* Move the CQE into the event */
13523 	memcpy(&cq_event->cqe, entry, size);
13524 	return cq_event;
13525 }
13526 
13527 /**
13528  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
13529  * @phba: Pointer to HBA context object.
13530  * @mcqe: Pointer to mailbox completion queue entry.
13531  *
13532  * This routine process a mailbox completion queue entry with asynchronous
13533  * event.
13534  *
13535  * Return: true if work posted to worker thread, otherwise false.
13536  **/
13537 static bool
13538 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13539 {
13540 	struct lpfc_cq_event *cq_event;
13541 	unsigned long iflags;
13542 
13543 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13544 			"0392 Async Event: word0:x%x, word1:x%x, "
13545 			"word2:x%x, word3:x%x\n", mcqe->word0,
13546 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
13547 
13548 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
13549 	if (!cq_event)
13550 		return false;
13551 
13552 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
13553 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
13554 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
13555 
13556 	/* Set the async event flag */
13557 	spin_lock_irqsave(&phba->hbalock, iflags);
13558 	phba->hba_flag |= ASYNC_EVENT;
13559 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13560 
13561 	return true;
13562 }
13563 
13564 /**
13565  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
13566  * @phba: Pointer to HBA context object.
13567  * @mcqe: Pointer to mailbox completion queue entry.
13568  *
13569  * This routine process a mailbox completion queue entry with mailbox
13570  * completion event.
13571  *
13572  * Return: true if work posted to worker thread, otherwise false.
13573  **/
13574 static bool
13575 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13576 {
13577 	uint32_t mcqe_status;
13578 	MAILBOX_t *mbox, *pmbox;
13579 	struct lpfc_mqe *mqe;
13580 	struct lpfc_vport *vport;
13581 	struct lpfc_nodelist *ndlp;
13582 	struct lpfc_dmabuf *mp;
13583 	unsigned long iflags;
13584 	LPFC_MBOXQ_t *pmb;
13585 	bool workposted = false;
13586 	int rc;
13587 
13588 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
13589 	if (!bf_get(lpfc_trailer_completed, mcqe))
13590 		goto out_no_mqe_complete;
13591 
13592 	/* Get the reference to the active mbox command */
13593 	spin_lock_irqsave(&phba->hbalock, iflags);
13594 	pmb = phba->sli.mbox_active;
13595 	if (unlikely(!pmb)) {
13596 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13597 				"1832 No pending MBOX command to handle\n");
13598 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13599 		goto out_no_mqe_complete;
13600 	}
13601 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13602 	mqe = &pmb->u.mqe;
13603 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
13604 	mbox = phba->mbox;
13605 	vport = pmb->vport;
13606 
13607 	/* Reset heartbeat timer */
13608 	phba->last_completion_time = jiffies;
13609 	del_timer(&phba->sli.mbox_tmo);
13610 
13611 	/* Move mbox data to caller's mailbox region, do endian swapping */
13612 	if (pmb->mbox_cmpl && mbox)
13613 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
13614 
13615 	/*
13616 	 * For mcqe errors, conditionally move a modified error code to
13617 	 * the mbox so that the error will not be missed.
13618 	 */
13619 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
13620 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
13621 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
13622 			bf_set(lpfc_mqe_status, mqe,
13623 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
13624 	}
13625 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13626 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13627 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
13628 				      "MBOX dflt rpi: status:x%x rpi:x%x",
13629 				      mcqe_status,
13630 				      pmbox->un.varWords[0], 0);
13631 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
13632 			mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
13633 			ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
13634 
13635 			/* Reg_LOGIN of dflt RPI was successful. Mark the
13636 			 * node as having an UNREG_LOGIN in progress to stop
13637 			 * an unsolicited PLOGI from the same NPortId from
13638 			 * starting another mailbox transaction.
13639 			 */
13640 			spin_lock_irqsave(&ndlp->lock, iflags);
13641 			ndlp->nlp_flag |= NLP_UNREG_INP;
13642 			spin_unlock_irqrestore(&ndlp->lock, iflags);
13643 			lpfc_unreg_login(phba, vport->vpi,
13644 					 pmbox->un.varWords[0], pmb);
13645 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
13646 			pmb->ctx_buf = mp;
13647 
13648 			/* No reference taken here.  This is a default
13649 			 * RPI reg/immediate unreg cycle. The reference was
13650 			 * taken in the reg rpi path and is released when
13651 			 * this mailbox completes.
13652 			 */
13653 			pmb->ctx_ndlp = ndlp;
13654 			pmb->vport = vport;
13655 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
13656 			if (rc != MBX_BUSY)
13657 				lpfc_printf_log(phba, KERN_ERR,
13658 						LOG_TRACE_EVENT,
13659 						"0385 rc should "
13660 						"have been MBX_BUSY\n");
13661 			if (rc != MBX_NOT_FINISHED)
13662 				goto send_current_mbox;
13663 		}
13664 	}
13665 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
13666 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
13667 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
13668 
13669 	/* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
13670 	if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13671 		spin_lock_irqsave(&phba->hbalock, iflags);
13672 		/* Release the mailbox command posting token */
13673 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13674 		phba->sli.mbox_active = NULL;
13675 		if (bf_get(lpfc_trailer_consumed, mcqe))
13676 			lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13677 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13678 
13679 		/* Post the next mbox command, if there is one */
13680 		lpfc_sli4_post_async_mbox(phba);
13681 
13682 		/* Process cmpl now */
13683 		if (pmb->mbox_cmpl)
13684 			pmb->mbox_cmpl(phba, pmb);
13685 		return false;
13686 	}
13687 
13688 	/* There is mailbox completion work to queue to the worker thread */
13689 	spin_lock_irqsave(&phba->hbalock, iflags);
13690 	__lpfc_mbox_cmpl_put(phba, pmb);
13691 	phba->work_ha |= HA_MBATT;
13692 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13693 	workposted = true;
13694 
13695 send_current_mbox:
13696 	spin_lock_irqsave(&phba->hbalock, iflags);
13697 	/* Release the mailbox command posting token */
13698 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13699 	/* Setting active mailbox pointer need to be in sync to flag clear */
13700 	phba->sli.mbox_active = NULL;
13701 	if (bf_get(lpfc_trailer_consumed, mcqe))
13702 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13703 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13704 	/* Wake up worker thread to post the next pending mailbox command */
13705 	lpfc_worker_wake_up(phba);
13706 	return workposted;
13707 
13708 out_no_mqe_complete:
13709 	spin_lock_irqsave(&phba->hbalock, iflags);
13710 	if (bf_get(lpfc_trailer_consumed, mcqe))
13711 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13712 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13713 	return false;
13714 }
13715 
13716 /**
13717  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
13718  * @phba: Pointer to HBA context object.
13719  * @cq: Pointer to associated CQ
13720  * @cqe: Pointer to mailbox completion queue entry.
13721  *
13722  * This routine process a mailbox completion queue entry, it invokes the
13723  * proper mailbox complete handling or asynchronous event handling routine
13724  * according to the MCQE's async bit.
13725  *
13726  * Return: true if work posted to worker thread, otherwise false.
13727  **/
13728 static bool
13729 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13730 			 struct lpfc_cqe *cqe)
13731 {
13732 	struct lpfc_mcqe mcqe;
13733 	bool workposted;
13734 
13735 	cq->CQ_mbox++;
13736 
13737 	/* Copy the mailbox MCQE and convert endian order as needed */
13738 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
13739 
13740 	/* Invoke the proper event handling routine */
13741 	if (!bf_get(lpfc_trailer_async, &mcqe))
13742 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
13743 	else
13744 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
13745 	return workposted;
13746 }
13747 
13748 /**
13749  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
13750  * @phba: Pointer to HBA context object.
13751  * @cq: Pointer to associated CQ
13752  * @wcqe: Pointer to work-queue completion queue entry.
13753  *
13754  * This routine handles an ELS work-queue completion event.
13755  *
13756  * Return: true if work posted to worker thread, otherwise false.
13757  **/
13758 static bool
13759 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13760 			     struct lpfc_wcqe_complete *wcqe)
13761 {
13762 	struct lpfc_iocbq *irspiocbq;
13763 	unsigned long iflags;
13764 	struct lpfc_sli_ring *pring = cq->pring;
13765 	int txq_cnt = 0;
13766 	int txcmplq_cnt = 0;
13767 
13768 	/* Check for response status */
13769 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
13770 		/* Log the error status */
13771 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13772 				"0357 ELS CQE error: status=x%x: "
13773 				"CQE: %08x %08x %08x %08x\n",
13774 				bf_get(lpfc_wcqe_c_status, wcqe),
13775 				wcqe->word0, wcqe->total_data_placed,
13776 				wcqe->parameter, wcqe->word3);
13777 	}
13778 
13779 	/* Get an irspiocbq for later ELS response processing use */
13780 	irspiocbq = lpfc_sli_get_iocbq(phba);
13781 	if (!irspiocbq) {
13782 		if (!list_empty(&pring->txq))
13783 			txq_cnt++;
13784 		if (!list_empty(&pring->txcmplq))
13785 			txcmplq_cnt++;
13786 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13787 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
13788 			"els_txcmplq_cnt=%d\n",
13789 			txq_cnt, phba->iocb_cnt,
13790 			txcmplq_cnt);
13791 		return false;
13792 	}
13793 
13794 	/* Save off the slow-path queue event for work thread to process */
13795 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
13796 	spin_lock_irqsave(&phba->hbalock, iflags);
13797 	list_add_tail(&irspiocbq->cq_event.list,
13798 		      &phba->sli4_hba.sp_queue_event);
13799 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
13800 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13801 
13802 	return true;
13803 }
13804 
13805 /**
13806  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
13807  * @phba: Pointer to HBA context object.
13808  * @wcqe: Pointer to work-queue completion queue entry.
13809  *
13810  * This routine handles slow-path WQ entry consumed event by invoking the
13811  * proper WQ release routine to the slow-path WQ.
13812  **/
13813 static void
13814 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
13815 			     struct lpfc_wcqe_release *wcqe)
13816 {
13817 	/* sanity check on queue memory */
13818 	if (unlikely(!phba->sli4_hba.els_wq))
13819 		return;
13820 	/* Check for the slow-path ELS work queue */
13821 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
13822 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
13823 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
13824 	else
13825 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13826 				"2579 Slow-path wqe consume event carries "
13827 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
13828 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
13829 				phba->sli4_hba.els_wq->queue_id);
13830 }
13831 
13832 /**
13833  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
13834  * @phba: Pointer to HBA context object.
13835  * @cq: Pointer to a WQ completion queue.
13836  * @wcqe: Pointer to work-queue completion queue entry.
13837  *
13838  * This routine handles an XRI abort event.
13839  *
13840  * Return: true if work posted to worker thread, otherwise false.
13841  **/
13842 static bool
13843 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
13844 				   struct lpfc_queue *cq,
13845 				   struct sli4_wcqe_xri_aborted *wcqe)
13846 {
13847 	bool workposted = false;
13848 	struct lpfc_cq_event *cq_event;
13849 	unsigned long iflags;
13850 
13851 	switch (cq->subtype) {
13852 	case LPFC_IO:
13853 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
13854 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13855 			/* Notify aborted XRI for NVME work queue */
13856 			if (phba->nvmet_support)
13857 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
13858 		}
13859 		workposted = false;
13860 		break;
13861 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
13862 	case LPFC_ELS:
13863 		cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
13864 		if (!cq_event) {
13865 			workposted = false;
13866 			break;
13867 		}
13868 		cq_event->hdwq = cq->hdwq;
13869 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
13870 				  iflags);
13871 		list_add_tail(&cq_event->list,
13872 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
13873 		/* Set the els xri abort event flag */
13874 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
13875 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
13876 				       iflags);
13877 		workposted = true;
13878 		break;
13879 	default:
13880 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13881 				"0603 Invalid CQ subtype %d: "
13882 				"%08x %08x %08x %08x\n",
13883 				cq->subtype, wcqe->word0, wcqe->parameter,
13884 				wcqe->word2, wcqe->word3);
13885 		workposted = false;
13886 		break;
13887 	}
13888 	return workposted;
13889 }
13890 
13891 #define FC_RCTL_MDS_DIAGS	0xF4
13892 
13893 /**
13894  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
13895  * @phba: Pointer to HBA context object.
13896  * @rcqe: Pointer to receive-queue completion queue entry.
13897  *
13898  * This routine process a receive-queue completion queue entry.
13899  *
13900  * Return: true if work posted to worker thread, otherwise false.
13901  **/
13902 static bool
13903 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
13904 {
13905 	bool workposted = false;
13906 	struct fc_frame_header *fc_hdr;
13907 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
13908 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
13909 	struct lpfc_nvmet_tgtport *tgtp;
13910 	struct hbq_dmabuf *dma_buf;
13911 	uint32_t status, rq_id;
13912 	unsigned long iflags;
13913 
13914 	/* sanity check on queue memory */
13915 	if (unlikely(!hrq) || unlikely(!drq))
13916 		return workposted;
13917 
13918 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
13919 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
13920 	else
13921 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
13922 	if (rq_id != hrq->queue_id)
13923 		goto out;
13924 
13925 	status = bf_get(lpfc_rcqe_status, rcqe);
13926 	switch (status) {
13927 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
13928 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13929 				"2537 Receive Frame Truncated!!\n");
13930 		fallthrough;
13931 	case FC_STATUS_RQ_SUCCESS:
13932 		spin_lock_irqsave(&phba->hbalock, iflags);
13933 		lpfc_sli4_rq_release(hrq, drq);
13934 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
13935 		if (!dma_buf) {
13936 			hrq->RQ_no_buf_found++;
13937 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13938 			goto out;
13939 		}
13940 		hrq->RQ_rcv_buf++;
13941 		hrq->RQ_buf_posted--;
13942 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
13943 
13944 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
13945 
13946 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
13947 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
13948 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13949 			/* Handle MDS Loopback frames */
13950 			if  (!(phba->pport->load_flag & FC_UNLOADING))
13951 				lpfc_sli4_handle_mds_loopback(phba->pport,
13952 							      dma_buf);
13953 			else
13954 				lpfc_in_buf_free(phba, &dma_buf->dbuf);
13955 			break;
13956 		}
13957 
13958 		/* save off the frame for the work thread to process */
13959 		list_add_tail(&dma_buf->cq_event.list,
13960 			      &phba->sli4_hba.sp_queue_event);
13961 		/* Frame received */
13962 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
13963 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13964 		workposted = true;
13965 		break;
13966 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
13967 		if (phba->nvmet_support) {
13968 			tgtp = phba->targetport->private;
13969 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13970 					"6402 RQE Error x%x, posted %d err_cnt "
13971 					"%d: %x %x %x\n",
13972 					status, hrq->RQ_buf_posted,
13973 					hrq->RQ_no_posted_buf,
13974 					atomic_read(&tgtp->rcv_fcp_cmd_in),
13975 					atomic_read(&tgtp->rcv_fcp_cmd_out),
13976 					atomic_read(&tgtp->xmt_fcp_release));
13977 		}
13978 		fallthrough;
13979 
13980 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
13981 		hrq->RQ_no_posted_buf++;
13982 		/* Post more buffers if possible */
13983 		spin_lock_irqsave(&phba->hbalock, iflags);
13984 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
13985 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13986 		workposted = true;
13987 		break;
13988 	}
13989 out:
13990 	return workposted;
13991 }
13992 
13993 /**
13994  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
13995  * @phba: Pointer to HBA context object.
13996  * @cq: Pointer to the completion queue.
13997  * @cqe: Pointer to a completion queue entry.
13998  *
13999  * This routine process a slow-path work-queue or receive queue completion queue
14000  * entry.
14001  *
14002  * Return: true if work posted to worker thread, otherwise false.
14003  **/
14004 static bool
14005 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14006 			 struct lpfc_cqe *cqe)
14007 {
14008 	struct lpfc_cqe cqevt;
14009 	bool workposted = false;
14010 
14011 	/* Copy the work queue CQE and convert endian order if needed */
14012 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14013 
14014 	/* Check and process for different type of WCQE and dispatch */
14015 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
14016 	case CQE_CODE_COMPL_WQE:
14017 		/* Process the WQ/RQ complete event */
14018 		phba->last_completion_time = jiffies;
14019 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14020 				(struct lpfc_wcqe_complete *)&cqevt);
14021 		break;
14022 	case CQE_CODE_RELEASE_WQE:
14023 		/* Process the WQ release event */
14024 		lpfc_sli4_sp_handle_rel_wcqe(phba,
14025 				(struct lpfc_wcqe_release *)&cqevt);
14026 		break;
14027 	case CQE_CODE_XRI_ABORTED:
14028 		/* Process the WQ XRI abort event */
14029 		phba->last_completion_time = jiffies;
14030 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14031 				(struct sli4_wcqe_xri_aborted *)&cqevt);
14032 		break;
14033 	case CQE_CODE_RECEIVE:
14034 	case CQE_CODE_RECEIVE_V1:
14035 		/* Process the RQ event */
14036 		phba->last_completion_time = jiffies;
14037 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
14038 				(struct lpfc_rcqe *)&cqevt);
14039 		break;
14040 	default:
14041 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14042 				"0388 Not a valid WCQE code: x%x\n",
14043 				bf_get(lpfc_cqe_code, &cqevt));
14044 		break;
14045 	}
14046 	return workposted;
14047 }
14048 
14049 /**
14050  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14051  * @phba: Pointer to HBA context object.
14052  * @eqe: Pointer to fast-path event queue entry.
14053  * @speq: Pointer to slow-path event queue.
14054  *
14055  * This routine process a event queue entry from the slow-path event queue.
14056  * It will check the MajorCode and MinorCode to determine this is for a
14057  * completion event on a completion queue, if not, an error shall be logged
14058  * and just return. Otherwise, it will get to the corresponding completion
14059  * queue and process all the entries on that completion queue, rearm the
14060  * completion queue, and then return.
14061  *
14062  **/
14063 static void
14064 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14065 	struct lpfc_queue *speq)
14066 {
14067 	struct lpfc_queue *cq = NULL, *childq;
14068 	uint16_t cqid;
14069 	int ret = 0;
14070 
14071 	/* Get the reference to the corresponding CQ */
14072 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14073 
14074 	list_for_each_entry(childq, &speq->child_list, list) {
14075 		if (childq->queue_id == cqid) {
14076 			cq = childq;
14077 			break;
14078 		}
14079 	}
14080 	if (unlikely(!cq)) {
14081 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14082 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14083 					"0365 Slow-path CQ identifier "
14084 					"(%d) does not exist\n", cqid);
14085 		return;
14086 	}
14087 
14088 	/* Save EQ associated with this CQ */
14089 	cq->assoc_qp = speq;
14090 
14091 	if (is_kdump_kernel())
14092 		ret = queue_work(phba->wq, &cq->spwork);
14093 	else
14094 		ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14095 
14096 	if (!ret)
14097 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14098 				"0390 Cannot schedule queue work "
14099 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14100 				cqid, cq->queue_id, raw_smp_processor_id());
14101 }
14102 
14103 /**
14104  * __lpfc_sli4_process_cq - Process elements of a CQ
14105  * @phba: Pointer to HBA context object.
14106  * @cq: Pointer to CQ to be processed
14107  * @handler: Routine to process each cqe
14108  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14109  * @poll_mode: Polling mode we were called from
14110  *
14111  * This routine processes completion queue entries in a CQ. While a valid
14112  * queue element is found, the handler is called. During processing checks
14113  * are made for periodic doorbell writes to let the hardware know of
14114  * element consumption.
14115  *
14116  * If the max limit on cqes to process is hit, or there are no more valid
14117  * entries, the loop stops. If we processed a sufficient number of elements,
14118  * meaning there is sufficient load, rather than rearming and generating
14119  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14120  * indicates no rescheduling.
14121  *
14122  * Returns True if work scheduled, False otherwise.
14123  **/
14124 static bool
14125 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14126 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14127 			struct lpfc_cqe *), unsigned long *delay,
14128 			enum lpfc_poll_mode poll_mode)
14129 {
14130 	struct lpfc_cqe *cqe;
14131 	bool workposted = false;
14132 	int count = 0, consumed = 0;
14133 	bool arm = true;
14134 
14135 	/* default - no reschedule */
14136 	*delay = 0;
14137 
14138 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14139 		goto rearm_and_exit;
14140 
14141 	/* Process all the entries to the CQ */
14142 	cq->q_flag = 0;
14143 	cqe = lpfc_sli4_cq_get(cq);
14144 	while (cqe) {
14145 		workposted |= handler(phba, cq, cqe);
14146 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
14147 
14148 		consumed++;
14149 		if (!(++count % cq->max_proc_limit))
14150 			break;
14151 
14152 		if (!(count % cq->notify_interval)) {
14153 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14154 						LPFC_QUEUE_NOARM);
14155 			consumed = 0;
14156 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14157 		}
14158 
14159 		if (count == LPFC_NVMET_CQ_NOTIFY)
14160 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14161 
14162 		cqe = lpfc_sli4_cq_get(cq);
14163 	}
14164 	if (count >= phba->cfg_cq_poll_threshold) {
14165 		*delay = 1;
14166 		arm = false;
14167 	}
14168 
14169 	/* Note: complete the irq_poll softirq before rearming CQ */
14170 	if (poll_mode == LPFC_IRQ_POLL)
14171 		irq_poll_complete(&cq->iop);
14172 
14173 	/* Track the max number of CQEs processed in 1 EQ */
14174 	if (count > cq->CQ_max_cqe)
14175 		cq->CQ_max_cqe = count;
14176 
14177 	cq->assoc_qp->EQ_cqe_cnt += count;
14178 
14179 	/* Catch the no cq entry condition */
14180 	if (unlikely(count == 0))
14181 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14182 				"0369 No entry from completion queue "
14183 				"qid=%d\n", cq->queue_id);
14184 
14185 	xchg(&cq->queue_claimed, 0);
14186 
14187 rearm_and_exit:
14188 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14189 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14190 
14191 	return workposted;
14192 }
14193 
14194 /**
14195  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14196  * @cq: pointer to CQ to process
14197  *
14198  * This routine calls the cq processing routine with a handler specific
14199  * to the type of queue bound to it.
14200  *
14201  * The CQ routine returns two values: the first is the calling status,
14202  * which indicates whether work was queued to the  background discovery
14203  * thread. If true, the routine should wakeup the discovery thread;
14204  * the second is the delay parameter. If non-zero, rather than rearming
14205  * the CQ and yet another interrupt, the CQ handler should be queued so
14206  * that it is processed in a subsequent polling action. The value of
14207  * the delay indicates when to reschedule it.
14208  **/
14209 static void
14210 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14211 {
14212 	struct lpfc_hba *phba = cq->phba;
14213 	unsigned long delay;
14214 	bool workposted = false;
14215 	int ret = 0;
14216 
14217 	/* Process and rearm the CQ */
14218 	switch (cq->type) {
14219 	case LPFC_MCQ:
14220 		workposted |= __lpfc_sli4_process_cq(phba, cq,
14221 						lpfc_sli4_sp_handle_mcqe,
14222 						&delay, LPFC_QUEUE_WORK);
14223 		break;
14224 	case LPFC_WCQ:
14225 		if (cq->subtype == LPFC_IO)
14226 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14227 						lpfc_sli4_fp_handle_cqe,
14228 						&delay, LPFC_QUEUE_WORK);
14229 		else
14230 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14231 						lpfc_sli4_sp_handle_cqe,
14232 						&delay, LPFC_QUEUE_WORK);
14233 		break;
14234 	default:
14235 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14236 				"0370 Invalid completion queue type (%d)\n",
14237 				cq->type);
14238 		return;
14239 	}
14240 
14241 	if (delay) {
14242 		if (is_kdump_kernel())
14243 			ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
14244 						delay);
14245 		else
14246 			ret = queue_delayed_work_on(cq->chann, phba->wq,
14247 						&cq->sched_spwork, delay);
14248 		if (!ret)
14249 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14250 				"0394 Cannot schedule queue work "
14251 				"for cqid=%d on CPU %d\n",
14252 				cq->queue_id, cq->chann);
14253 	}
14254 
14255 	/* wake up worker thread if there are works to be done */
14256 	if (workposted)
14257 		lpfc_worker_wake_up(phba);
14258 }
14259 
14260 /**
14261  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
14262  *   interrupt
14263  * @work: pointer to work element
14264  *
14265  * translates from the work handler and calls the slow-path handler.
14266  **/
14267 static void
14268 lpfc_sli4_sp_process_cq(struct work_struct *work)
14269 {
14270 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
14271 
14272 	__lpfc_sli4_sp_process_cq(cq);
14273 }
14274 
14275 /**
14276  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
14277  * @work: pointer to work element
14278  *
14279  * translates from the work handler and calls the slow-path handler.
14280  **/
14281 static void
14282 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
14283 {
14284 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
14285 					struct lpfc_queue, sched_spwork);
14286 
14287 	__lpfc_sli4_sp_process_cq(cq);
14288 }
14289 
14290 /**
14291  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
14292  * @phba: Pointer to HBA context object.
14293  * @cq: Pointer to associated CQ
14294  * @wcqe: Pointer to work-queue completion queue entry.
14295  *
14296  * This routine process a fast-path work queue completion entry from fast-path
14297  * event queue for FCP command response completion.
14298  **/
14299 static void
14300 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14301 			     struct lpfc_wcqe_complete *wcqe)
14302 {
14303 	struct lpfc_sli_ring *pring = cq->pring;
14304 	struct lpfc_iocbq *cmdiocbq;
14305 	struct lpfc_iocbq irspiocbq;
14306 	unsigned long iflags;
14307 
14308 	/* Check for response status */
14309 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14310 		/* If resource errors reported from HBA, reduce queue
14311 		 * depth of the SCSI device.
14312 		 */
14313 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
14314 		     IOSTAT_LOCAL_REJECT)) &&
14315 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
14316 		     IOERR_NO_RESOURCES))
14317 			phba->lpfc_rampdown_queue_depth(phba);
14318 
14319 		/* Log the cmpl status */
14320 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14321 				"0373 FCP CQE cmpl: status=x%x: "
14322 				"CQE: %08x %08x %08x %08x\n",
14323 				bf_get(lpfc_wcqe_c_status, wcqe),
14324 				wcqe->word0, wcqe->total_data_placed,
14325 				wcqe->parameter, wcqe->word3);
14326 	}
14327 
14328 	/* Look up the FCP command IOCB and create pseudo response IOCB */
14329 	spin_lock_irqsave(&pring->ring_lock, iflags);
14330 	pring->stats.iocb_event++;
14331 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
14332 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14333 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14334 	if (unlikely(!cmdiocbq)) {
14335 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14336 				"0374 FCP complete with no corresponding "
14337 				"cmdiocb: iotag (%d)\n",
14338 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14339 		return;
14340 	}
14341 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
14342 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
14343 #endif
14344 	if (cmdiocbq->iocb_cmpl == NULL) {
14345 		if (cmdiocbq->wqe_cmpl) {
14346 			/* For FCP the flag is cleared in wqe_cmpl */
14347 			if (!(cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
14348 			    cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
14349 				spin_lock_irqsave(&phba->hbalock, iflags);
14350 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
14351 				spin_unlock_irqrestore(&phba->hbalock, iflags);
14352 			}
14353 
14354 			/* Pass the cmd_iocb and the wcqe to the upper layer */
14355 			(cmdiocbq->wqe_cmpl)(phba, cmdiocbq, wcqe);
14356 			return;
14357 		}
14358 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14359 				"0375 FCP cmdiocb not callback function "
14360 				"iotag: (%d)\n",
14361 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14362 		return;
14363 	}
14364 
14365 	/* Only SLI4 non-IO commands stil use IOCB */
14366 	/* Fake the irspiocb and copy necessary response information */
14367 	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
14368 
14369 	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
14370 		spin_lock_irqsave(&phba->hbalock, iflags);
14371 		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
14372 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14373 	}
14374 
14375 	/* Pass the cmd_iocb and the rsp state to the upper layer */
14376 	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
14377 }
14378 
14379 /**
14380  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
14381  * @phba: Pointer to HBA context object.
14382  * @cq: Pointer to completion queue.
14383  * @wcqe: Pointer to work-queue completion queue entry.
14384  *
14385  * This routine handles an fast-path WQ entry consumed event by invoking the
14386  * proper WQ release routine to the slow-path WQ.
14387  **/
14388 static void
14389 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14390 			     struct lpfc_wcqe_release *wcqe)
14391 {
14392 	struct lpfc_queue *childwq;
14393 	bool wqid_matched = false;
14394 	uint16_t hba_wqid;
14395 
14396 	/* Check for fast-path FCP work queue release */
14397 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
14398 	list_for_each_entry(childwq, &cq->child_list, list) {
14399 		if (childwq->queue_id == hba_wqid) {
14400 			lpfc_sli4_wq_release(childwq,
14401 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14402 			if (childwq->q_flag & HBA_NVMET_WQFULL)
14403 				lpfc_nvmet_wqfull_process(phba, childwq);
14404 			wqid_matched = true;
14405 			break;
14406 		}
14407 	}
14408 	/* Report warning log message if no match found */
14409 	if (wqid_matched != true)
14410 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14411 				"2580 Fast-path wqe consume event carries "
14412 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
14413 }
14414 
14415 /**
14416  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
14417  * @phba: Pointer to HBA context object.
14418  * @cq: Pointer to completion queue.
14419  * @rcqe: Pointer to receive-queue completion queue entry.
14420  *
14421  * This routine process a receive-queue completion queue entry.
14422  *
14423  * Return: true if work posted to worker thread, otherwise false.
14424  **/
14425 static bool
14426 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14427 			    struct lpfc_rcqe *rcqe)
14428 {
14429 	bool workposted = false;
14430 	struct lpfc_queue *hrq;
14431 	struct lpfc_queue *drq;
14432 	struct rqb_dmabuf *dma_buf;
14433 	struct fc_frame_header *fc_hdr;
14434 	struct lpfc_nvmet_tgtport *tgtp;
14435 	uint32_t status, rq_id;
14436 	unsigned long iflags;
14437 	uint32_t fctl, idx;
14438 
14439 	if ((phba->nvmet_support == 0) ||
14440 	    (phba->sli4_hba.nvmet_cqset == NULL))
14441 		return workposted;
14442 
14443 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
14444 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
14445 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
14446 
14447 	/* sanity check on queue memory */
14448 	if (unlikely(!hrq) || unlikely(!drq))
14449 		return workposted;
14450 
14451 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14452 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14453 	else
14454 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14455 
14456 	if ((phba->nvmet_support == 0) ||
14457 	    (rq_id != hrq->queue_id))
14458 		return workposted;
14459 
14460 	status = bf_get(lpfc_rcqe_status, rcqe);
14461 	switch (status) {
14462 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14463 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14464 				"6126 Receive Frame Truncated!!\n");
14465 		fallthrough;
14466 	case FC_STATUS_RQ_SUCCESS:
14467 		spin_lock_irqsave(&phba->hbalock, iflags);
14468 		lpfc_sli4_rq_release(hrq, drq);
14469 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
14470 		if (!dma_buf) {
14471 			hrq->RQ_no_buf_found++;
14472 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14473 			goto out;
14474 		}
14475 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14476 		hrq->RQ_rcv_buf++;
14477 		hrq->RQ_buf_posted--;
14478 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14479 
14480 		/* Just some basic sanity checks on FCP Command frame */
14481 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
14482 			fc_hdr->fh_f_ctl[1] << 8 |
14483 			fc_hdr->fh_f_ctl[2]);
14484 		if (((fctl &
14485 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
14486 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
14487 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
14488 			goto drop;
14489 
14490 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
14491 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
14492 			lpfc_nvmet_unsol_fcp_event(
14493 				phba, idx, dma_buf, cq->isr_timestamp,
14494 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
14495 			return false;
14496 		}
14497 drop:
14498 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
14499 		break;
14500 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14501 		if (phba->nvmet_support) {
14502 			tgtp = phba->targetport->private;
14503 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14504 					"6401 RQE Error x%x, posted %d err_cnt "
14505 					"%d: %x %x %x\n",
14506 					status, hrq->RQ_buf_posted,
14507 					hrq->RQ_no_posted_buf,
14508 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14509 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14510 					atomic_read(&tgtp->xmt_fcp_release));
14511 		}
14512 		fallthrough;
14513 
14514 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14515 		hrq->RQ_no_posted_buf++;
14516 		/* Post more buffers if possible */
14517 		break;
14518 	}
14519 out:
14520 	return workposted;
14521 }
14522 
14523 /**
14524  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
14525  * @phba: adapter with cq
14526  * @cq: Pointer to the completion queue.
14527  * @cqe: Pointer to fast-path completion queue entry.
14528  *
14529  * This routine process a fast-path work queue completion entry from fast-path
14530  * event queue for FCP command response completion.
14531  *
14532  * Return: true if work posted to worker thread, otherwise false.
14533  **/
14534 static bool
14535 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14536 			 struct lpfc_cqe *cqe)
14537 {
14538 	struct lpfc_wcqe_release wcqe;
14539 	bool workposted = false;
14540 
14541 	/* Copy the work queue CQE and convert endian order if needed */
14542 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
14543 
14544 	/* Check and process for different type of WCQE and dispatch */
14545 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
14546 	case CQE_CODE_COMPL_WQE:
14547 	case CQE_CODE_NVME_ERSP:
14548 		cq->CQ_wq++;
14549 		/* Process the WQ complete event */
14550 		phba->last_completion_time = jiffies;
14551 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
14552 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
14553 				(struct lpfc_wcqe_complete *)&wcqe);
14554 		break;
14555 	case CQE_CODE_RELEASE_WQE:
14556 		cq->CQ_release_wqe++;
14557 		/* Process the WQ release event */
14558 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
14559 				(struct lpfc_wcqe_release *)&wcqe);
14560 		break;
14561 	case CQE_CODE_XRI_ABORTED:
14562 		cq->CQ_xri_aborted++;
14563 		/* Process the WQ XRI abort event */
14564 		phba->last_completion_time = jiffies;
14565 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14566 				(struct sli4_wcqe_xri_aborted *)&wcqe);
14567 		break;
14568 	case CQE_CODE_RECEIVE_V1:
14569 	case CQE_CODE_RECEIVE:
14570 		phba->last_completion_time = jiffies;
14571 		if (cq->subtype == LPFC_NVMET) {
14572 			workposted = lpfc_sli4_nvmet_handle_rcqe(
14573 				phba, cq, (struct lpfc_rcqe *)&wcqe);
14574 		}
14575 		break;
14576 	default:
14577 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14578 				"0144 Not a valid CQE code: x%x\n",
14579 				bf_get(lpfc_wcqe_c_code, &wcqe));
14580 		break;
14581 	}
14582 	return workposted;
14583 }
14584 
14585 /**
14586  * lpfc_sli4_sched_cq_work - Schedules cq work
14587  * @phba: Pointer to HBA context object.
14588  * @cq: Pointer to CQ
14589  * @cqid: CQ ID
14590  *
14591  * This routine checks the poll mode of the CQ corresponding to
14592  * cq->chann, then either schedules a softirq or queue_work to complete
14593  * cq work.
14594  *
14595  * queue_work path is taken if in NVMET mode, or if poll_mode is in
14596  * LPFC_QUEUE_WORK mode.  Otherwise, softirq path is taken.
14597  *
14598  **/
14599 static void lpfc_sli4_sched_cq_work(struct lpfc_hba *phba,
14600 				    struct lpfc_queue *cq, uint16_t cqid)
14601 {
14602 	int ret = 0;
14603 
14604 	switch (cq->poll_mode) {
14605 	case LPFC_IRQ_POLL:
14606 		irq_poll_sched(&cq->iop);
14607 		break;
14608 	case LPFC_QUEUE_WORK:
14609 	default:
14610 		if (is_kdump_kernel())
14611 			ret = queue_work(phba->wq, &cq->irqwork);
14612 		else
14613 			ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
14614 		if (!ret)
14615 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14616 					"0383 Cannot schedule queue work "
14617 					"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14618 					cqid, cq->queue_id,
14619 					raw_smp_processor_id());
14620 	}
14621 }
14622 
14623 /**
14624  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
14625  * @phba: Pointer to HBA context object.
14626  * @eq: Pointer to the queue structure.
14627  * @eqe: Pointer to fast-path event queue entry.
14628  *
14629  * This routine process a event queue entry from the fast-path event queue.
14630  * It will check the MajorCode and MinorCode to determine this is for a
14631  * completion event on a completion queue, if not, an error shall be logged
14632  * and just return. Otherwise, it will get to the corresponding completion
14633  * queue and process all the entries on the completion queue, rearm the
14634  * completion queue, and then return.
14635  **/
14636 static void
14637 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
14638 			 struct lpfc_eqe *eqe)
14639 {
14640 	struct lpfc_queue *cq = NULL;
14641 	uint32_t qidx = eq->hdwq;
14642 	uint16_t cqid, id;
14643 
14644 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
14645 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14646 				"0366 Not a valid completion "
14647 				"event: majorcode=x%x, minorcode=x%x\n",
14648 				bf_get_le32(lpfc_eqe_major_code, eqe),
14649 				bf_get_le32(lpfc_eqe_minor_code, eqe));
14650 		return;
14651 	}
14652 
14653 	/* Get the reference to the corresponding CQ */
14654 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14655 
14656 	/* Use the fast lookup method first */
14657 	if (cqid <= phba->sli4_hba.cq_max) {
14658 		cq = phba->sli4_hba.cq_lookup[cqid];
14659 		if (cq)
14660 			goto  work_cq;
14661 	}
14662 
14663 	/* Next check for NVMET completion */
14664 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
14665 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
14666 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
14667 			/* Process NVMET unsol rcv */
14668 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
14669 			goto  process_cq;
14670 		}
14671 	}
14672 
14673 	if (phba->sli4_hba.nvmels_cq &&
14674 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
14675 		/* Process NVME unsol rcv */
14676 		cq = phba->sli4_hba.nvmels_cq;
14677 	}
14678 
14679 	/* Otherwise this is a Slow path event */
14680 	if (cq == NULL) {
14681 		lpfc_sli4_sp_handle_eqe(phba, eqe,
14682 					phba->sli4_hba.hdwq[qidx].hba_eq);
14683 		return;
14684 	}
14685 
14686 process_cq:
14687 	if (unlikely(cqid != cq->queue_id)) {
14688 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14689 				"0368 Miss-matched fast-path completion "
14690 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
14691 				cqid, cq->queue_id);
14692 		return;
14693 	}
14694 
14695 work_cq:
14696 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
14697 	if (phba->ktime_on)
14698 		cq->isr_timestamp = ktime_get_ns();
14699 	else
14700 		cq->isr_timestamp = 0;
14701 #endif
14702 	lpfc_sli4_sched_cq_work(phba, cq, cqid);
14703 }
14704 
14705 /**
14706  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
14707  * @cq: Pointer to CQ to be processed
14708  * @poll_mode: Enum lpfc_poll_state to determine poll mode
14709  *
14710  * This routine calls the cq processing routine with the handler for
14711  * fast path CQEs.
14712  *
14713  * The CQ routine returns two values: the first is the calling status,
14714  * which indicates whether work was queued to the  background discovery
14715  * thread. If true, the routine should wakeup the discovery thread;
14716  * the second is the delay parameter. If non-zero, rather than rearming
14717  * the CQ and yet another interrupt, the CQ handler should be queued so
14718  * that it is processed in a subsequent polling action. The value of
14719  * the delay indicates when to reschedule it.
14720  **/
14721 static void
14722 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq,
14723 			   enum lpfc_poll_mode poll_mode)
14724 {
14725 	struct lpfc_hba *phba = cq->phba;
14726 	unsigned long delay;
14727 	bool workposted = false;
14728 	int ret = 0;
14729 
14730 	/* process and rearm the CQ */
14731 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
14732 					     &delay, poll_mode);
14733 
14734 	if (delay) {
14735 		if (is_kdump_kernel())
14736 			ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
14737 						delay);
14738 		else
14739 			ret = queue_delayed_work_on(cq->chann, phba->wq,
14740 						&cq->sched_irqwork, delay);
14741 		if (!ret)
14742 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14743 					"0367 Cannot schedule queue work "
14744 					"for cqid=%d on CPU %d\n",
14745 					cq->queue_id, cq->chann);
14746 	}
14747 
14748 	/* wake up worker thread if there are works to be done */
14749 	if (workposted)
14750 		lpfc_worker_wake_up(phba);
14751 }
14752 
14753 /**
14754  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
14755  *   interrupt
14756  * @work: pointer to work element
14757  *
14758  * translates from the work handler and calls the fast-path handler.
14759  **/
14760 static void
14761 lpfc_sli4_hba_process_cq(struct work_struct *work)
14762 {
14763 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
14764 
14765 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
14766 }
14767 
14768 /**
14769  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
14770  * @work: pointer to work element
14771  *
14772  * translates from the work handler and calls the fast-path handler.
14773  **/
14774 static void
14775 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
14776 {
14777 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
14778 					struct lpfc_queue, sched_irqwork);
14779 
14780 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
14781 }
14782 
14783 /**
14784  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
14785  * @irq: Interrupt number.
14786  * @dev_id: The device context pointer.
14787  *
14788  * This function is directly called from the PCI layer as an interrupt
14789  * service routine when device with SLI-4 interface spec is enabled with
14790  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
14791  * ring event in the HBA. However, when the device is enabled with either
14792  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
14793  * device-level interrupt handler. When the PCI slot is in error recovery
14794  * or the HBA is undergoing initialization, the interrupt handler will not
14795  * process the interrupt. The SCSI FCP fast-path ring event are handled in
14796  * the intrrupt context. This function is called without any lock held.
14797  * It gets the hbalock to access and update SLI data structures. Note that,
14798  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
14799  * equal to that of FCP CQ index.
14800  *
14801  * The link attention and ELS ring attention events are handled
14802  * by the worker thread. The interrupt handler signals the worker thread
14803  * and returns for these events. This function is called without any lock
14804  * held. It gets the hbalock to access and update SLI data structures.
14805  *
14806  * This function returns IRQ_HANDLED when interrupt is handled else it
14807  * returns IRQ_NONE.
14808  **/
14809 irqreturn_t
14810 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
14811 {
14812 	struct lpfc_hba *phba;
14813 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
14814 	struct lpfc_queue *fpeq;
14815 	unsigned long iflag;
14816 	int ecount = 0;
14817 	int hba_eqidx;
14818 	struct lpfc_eq_intr_info *eqi;
14819 
14820 	/* Get the driver's phba structure from the dev_id */
14821 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
14822 	phba = hba_eq_hdl->phba;
14823 	hba_eqidx = hba_eq_hdl->idx;
14824 
14825 	if (unlikely(!phba))
14826 		return IRQ_NONE;
14827 	if (unlikely(!phba->sli4_hba.hdwq))
14828 		return IRQ_NONE;
14829 
14830 	/* Get to the EQ struct associated with this vector */
14831 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
14832 	if (unlikely(!fpeq))
14833 		return IRQ_NONE;
14834 
14835 	/* Check device state for handling interrupt */
14836 	if (unlikely(lpfc_intr_state_check(phba))) {
14837 		/* Check again for link_state with lock held */
14838 		spin_lock_irqsave(&phba->hbalock, iflag);
14839 		if (phba->link_state < LPFC_LINK_DOWN)
14840 			/* Flush, clear interrupt, and rearm the EQ */
14841 			lpfc_sli4_eqcq_flush(phba, fpeq);
14842 		spin_unlock_irqrestore(&phba->hbalock, iflag);
14843 		return IRQ_NONE;
14844 	}
14845 
14846 	eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
14847 	eqi->icnt++;
14848 
14849 	fpeq->last_cpu = raw_smp_processor_id();
14850 
14851 	if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
14852 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
14853 	    phba->cfg_auto_imax &&
14854 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
14855 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
14856 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
14857 
14858 	/* process and rearm the EQ */
14859 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
14860 
14861 	if (unlikely(ecount == 0)) {
14862 		fpeq->EQ_no_entry++;
14863 		if (phba->intr_type == MSIX)
14864 			/* MSI-X treated interrupt served as no EQ share INT */
14865 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14866 					"0358 MSI-X interrupt with no EQE\n");
14867 		else
14868 			/* Non MSI-X treated on interrupt as EQ share INT */
14869 			return IRQ_NONE;
14870 	}
14871 
14872 	return IRQ_HANDLED;
14873 } /* lpfc_sli4_hba_intr_handler */
14874 
14875 /**
14876  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
14877  * @irq: Interrupt number.
14878  * @dev_id: The device context pointer.
14879  *
14880  * This function is the device-level interrupt handler to device with SLI-4
14881  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
14882  * interrupt mode is enabled and there is an event in the HBA which requires
14883  * driver attention. This function invokes the slow-path interrupt attention
14884  * handling function and fast-path interrupt attention handling function in
14885  * turn to process the relevant HBA attention events. This function is called
14886  * without any lock held. It gets the hbalock to access and update SLI data
14887  * structures.
14888  *
14889  * This function returns IRQ_HANDLED when interrupt is handled, else it
14890  * returns IRQ_NONE.
14891  **/
14892 irqreturn_t
14893 lpfc_sli4_intr_handler(int irq, void *dev_id)
14894 {
14895 	struct lpfc_hba  *phba;
14896 	irqreturn_t hba_irq_rc;
14897 	bool hba_handled = false;
14898 	int qidx;
14899 
14900 	/* Get the driver's phba structure from the dev_id */
14901 	phba = (struct lpfc_hba *)dev_id;
14902 
14903 	if (unlikely(!phba))
14904 		return IRQ_NONE;
14905 
14906 	/*
14907 	 * Invoke fast-path host attention interrupt handling as appropriate.
14908 	 */
14909 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
14910 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
14911 					&phba->sli4_hba.hba_eq_hdl[qidx]);
14912 		if (hba_irq_rc == IRQ_HANDLED)
14913 			hba_handled |= true;
14914 	}
14915 
14916 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
14917 } /* lpfc_sli4_intr_handler */
14918 
14919 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
14920 {
14921 	struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
14922 	struct lpfc_queue *eq;
14923 	int i = 0;
14924 
14925 	rcu_read_lock();
14926 
14927 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
14928 		i += lpfc_sli4_poll_eq(eq, LPFC_POLL_SLOWPATH);
14929 	if (!list_empty(&phba->poll_list))
14930 		mod_timer(&phba->cpuhp_poll_timer,
14931 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
14932 
14933 	rcu_read_unlock();
14934 }
14935 
14936 inline int lpfc_sli4_poll_eq(struct lpfc_queue *eq, uint8_t path)
14937 {
14938 	struct lpfc_hba *phba = eq->phba;
14939 	int i = 0;
14940 
14941 	/*
14942 	 * Unlocking an irq is one of the entry point to check
14943 	 * for re-schedule, but we are good for io submission
14944 	 * path as midlayer does a get_cpu to glue us in. Flush
14945 	 * out the invalidate queue so we can see the updated
14946 	 * value for flag.
14947 	 */
14948 	smp_rmb();
14949 
14950 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
14951 		/* We will not likely get the completion for the caller
14952 		 * during this iteration but i guess that's fine.
14953 		 * Future io's coming on this eq should be able to
14954 		 * pick it up.  As for the case of single io's, they
14955 		 * will be handled through a sched from polling timer
14956 		 * function which is currently triggered every 1msec.
14957 		 */
14958 		i = lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM);
14959 
14960 	return i;
14961 }
14962 
14963 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
14964 {
14965 	struct lpfc_hba *phba = eq->phba;
14966 
14967 	/* kickstart slowpath processing if needed */
14968 	if (list_empty(&phba->poll_list))
14969 		mod_timer(&phba->cpuhp_poll_timer,
14970 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
14971 
14972 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
14973 	synchronize_rcu();
14974 }
14975 
14976 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
14977 {
14978 	struct lpfc_hba *phba = eq->phba;
14979 
14980 	/* Disable slowpath processing for this eq.  Kick start the eq
14981 	 * by RE-ARMING the eq's ASAP
14982 	 */
14983 	list_del_rcu(&eq->_poll_list);
14984 	synchronize_rcu();
14985 
14986 	if (list_empty(&phba->poll_list))
14987 		del_timer_sync(&phba->cpuhp_poll_timer);
14988 }
14989 
14990 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
14991 {
14992 	struct lpfc_queue *eq, *next;
14993 
14994 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
14995 		list_del(&eq->_poll_list);
14996 
14997 	INIT_LIST_HEAD(&phba->poll_list);
14998 	synchronize_rcu();
14999 }
15000 
15001 static inline void
15002 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
15003 {
15004 	if (mode == eq->mode)
15005 		return;
15006 	/*
15007 	 * currently this function is only called during a hotplug
15008 	 * event and the cpu on which this function is executing
15009 	 * is going offline.  By now the hotplug has instructed
15010 	 * the scheduler to remove this cpu from cpu active mask.
15011 	 * So we don't need to work about being put aside by the
15012 	 * scheduler for a high priority process.  Yes, the inte-
15013 	 * rrupts could come but they are known to retire ASAP.
15014 	 */
15015 
15016 	/* Disable polling in the fastpath */
15017 	WRITE_ONCE(eq->mode, mode);
15018 	/* flush out the store buffer */
15019 	smp_wmb();
15020 
15021 	/*
15022 	 * Add this eq to the polling list and start polling. For
15023 	 * a grace period both interrupt handler and poller will
15024 	 * try to process the eq _but_ that's fine.  We have a
15025 	 * synchronization mechanism in place (queue_claimed) to
15026 	 * deal with it.  This is just a draining phase for int-
15027 	 * errupt handler (not eq's) as we have guranteed through
15028 	 * barrier that all the CPUs have seen the new CQ_POLLED
15029 	 * state. which will effectively disable the REARMING of
15030 	 * the EQ.  The whole idea is eq's die off eventually as
15031 	 * we are not rearming EQ's anymore.
15032 	 */
15033 	mode ? lpfc_sli4_add_to_poll_list(eq) :
15034 	       lpfc_sli4_remove_from_poll_list(eq);
15035 }
15036 
15037 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15038 {
15039 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15040 }
15041 
15042 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15043 {
15044 	struct lpfc_hba *phba = eq->phba;
15045 
15046 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15047 
15048 	/* Kick start for the pending io's in h/w.
15049 	 * Once we switch back to interrupt processing on a eq
15050 	 * the io path completion will only arm eq's when it
15051 	 * receives a completion.  But since eq's are in disa-
15052 	 * rmed state it doesn't receive a completion.  This
15053 	 * creates a deadlock scenaro.
15054 	 */
15055 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15056 }
15057 
15058 /**
15059  * lpfc_sli4_queue_free - free a queue structure and associated memory
15060  * @queue: The queue structure to free.
15061  *
15062  * This function frees a queue structure and the DMAable memory used for
15063  * the host resident queue. This function must be called after destroying the
15064  * queue on the HBA.
15065  **/
15066 void
15067 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15068 {
15069 	struct lpfc_dmabuf *dmabuf;
15070 
15071 	if (!queue)
15072 		return;
15073 
15074 	if (!list_empty(&queue->wq_list))
15075 		list_del(&queue->wq_list);
15076 
15077 	while (!list_empty(&queue->page_list)) {
15078 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15079 				 list);
15080 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15081 				  dmabuf->virt, dmabuf->phys);
15082 		kfree(dmabuf);
15083 	}
15084 	if (queue->rqbp) {
15085 		lpfc_free_rq_buffer(queue->phba, queue);
15086 		kfree(queue->rqbp);
15087 	}
15088 
15089 	if (!list_empty(&queue->cpu_list))
15090 		list_del(&queue->cpu_list);
15091 
15092 	kfree(queue);
15093 	return;
15094 }
15095 
15096 /**
15097  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15098  * @phba: The HBA that this queue is being created on.
15099  * @page_size: The size of a queue page
15100  * @entry_size: The size of each queue entry for this queue.
15101  * @entry_count: The number of entries that this queue will handle.
15102  * @cpu: The cpu that will primarily utilize this queue.
15103  *
15104  * This function allocates a queue structure and the DMAable memory used for
15105  * the host resident queue. This function must be called before creating the
15106  * queue on the HBA.
15107  **/
15108 struct lpfc_queue *
15109 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15110 		      uint32_t entry_size, uint32_t entry_count, int cpu)
15111 {
15112 	struct lpfc_queue *queue;
15113 	struct lpfc_dmabuf *dmabuf;
15114 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15115 	uint16_t x, pgcnt;
15116 
15117 	if (!phba->sli4_hba.pc_sli4_params.supported)
15118 		hw_page_size = page_size;
15119 
15120 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15121 
15122 	/* If needed, Adjust page count to match the max the adapter supports */
15123 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15124 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15125 
15126 	queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
15127 			     GFP_KERNEL, cpu_to_node(cpu));
15128 	if (!queue)
15129 		return NULL;
15130 
15131 	INIT_LIST_HEAD(&queue->list);
15132 	INIT_LIST_HEAD(&queue->_poll_list);
15133 	INIT_LIST_HEAD(&queue->wq_list);
15134 	INIT_LIST_HEAD(&queue->wqfull_list);
15135 	INIT_LIST_HEAD(&queue->page_list);
15136 	INIT_LIST_HEAD(&queue->child_list);
15137 	INIT_LIST_HEAD(&queue->cpu_list);
15138 
15139 	/* Set queue parameters now.  If the system cannot provide memory
15140 	 * resources, the free routine needs to know what was allocated.
15141 	 */
15142 	queue->page_count = pgcnt;
15143 	queue->q_pgs = (void **)&queue[1];
15144 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
15145 	queue->entry_size = entry_size;
15146 	queue->entry_count = entry_count;
15147 	queue->page_size = hw_page_size;
15148 	queue->phba = phba;
15149 
15150 	for (x = 0; x < queue->page_count; x++) {
15151 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15152 				      dev_to_node(&phba->pcidev->dev));
15153 		if (!dmabuf)
15154 			goto out_fail;
15155 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15156 						  hw_page_size, &dmabuf->phys,
15157 						  GFP_KERNEL);
15158 		if (!dmabuf->virt) {
15159 			kfree(dmabuf);
15160 			goto out_fail;
15161 		}
15162 		dmabuf->buffer_tag = x;
15163 		list_add_tail(&dmabuf->list, &queue->page_list);
15164 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
15165 		queue->q_pgs[x] = dmabuf->virt;
15166 	}
15167 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15168 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15169 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15170 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15171 
15172 	/* notify_interval will be set during q creation */
15173 
15174 	return queue;
15175 out_fail:
15176 	lpfc_sli4_queue_free(queue);
15177 	return NULL;
15178 }
15179 
15180 /**
15181  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15182  * @phba: HBA structure that indicates port to create a queue on.
15183  * @pci_barset: PCI BAR set flag.
15184  *
15185  * This function shall perform iomap of the specified PCI BAR address to host
15186  * memory address if not already done so and return it. The returned host
15187  * memory address can be NULL.
15188  */
15189 static void __iomem *
15190 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15191 {
15192 	if (!phba->pcidev)
15193 		return NULL;
15194 
15195 	switch (pci_barset) {
15196 	case WQ_PCI_BAR_0_AND_1:
15197 		return phba->pci_bar0_memmap_p;
15198 	case WQ_PCI_BAR_2_AND_3:
15199 		return phba->pci_bar2_memmap_p;
15200 	case WQ_PCI_BAR_4_AND_5:
15201 		return phba->pci_bar4_memmap_p;
15202 	default:
15203 		break;
15204 	}
15205 	return NULL;
15206 }
15207 
15208 /**
15209  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
15210  * @phba: HBA structure that EQs are on.
15211  * @startq: The starting EQ index to modify
15212  * @numq: The number of EQs (consecutive indexes) to modify
15213  * @usdelay: amount of delay
15214  *
15215  * This function revises the EQ delay on 1 or more EQs. The EQ delay
15216  * is set either by writing to a register (if supported by the SLI Port)
15217  * or by mailbox command. The mailbox command allows several EQs to be
15218  * updated at once.
15219  *
15220  * The @phba struct is used to send a mailbox command to HBA. The @startq
15221  * is used to get the starting EQ index to change. The @numq value is
15222  * used to specify how many consecutive EQ indexes, starting at EQ index,
15223  * are to be changed. This function is asynchronous and will wait for any
15224  * mailbox commands to finish before returning.
15225  *
15226  * On success this function will return a zero. If unable to allocate
15227  * enough memory this function will return -ENOMEM. If a mailbox command
15228  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
15229  * have had their delay multipler changed.
15230  **/
15231 void
15232 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
15233 			 uint32_t numq, uint32_t usdelay)
15234 {
15235 	struct lpfc_mbx_modify_eq_delay *eq_delay;
15236 	LPFC_MBOXQ_t *mbox;
15237 	struct lpfc_queue *eq;
15238 	int cnt = 0, rc, length;
15239 	uint32_t shdr_status, shdr_add_status;
15240 	uint32_t dmult;
15241 	int qidx;
15242 	union lpfc_sli4_cfg_shdr *shdr;
15243 
15244 	if (startq >= phba->cfg_irq_chann)
15245 		return;
15246 
15247 	if (usdelay > 0xFFFF) {
15248 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
15249 				"6429 usdelay %d too large. Scaled down to "
15250 				"0xFFFF.\n", usdelay);
15251 		usdelay = 0xFFFF;
15252 	}
15253 
15254 	/* set values by EQ_DELAY register if supported */
15255 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
15256 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15257 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15258 			if (!eq)
15259 				continue;
15260 
15261 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
15262 
15263 			if (++cnt >= numq)
15264 				break;
15265 		}
15266 		return;
15267 	}
15268 
15269 	/* Otherwise, set values by mailbox cmd */
15270 
15271 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15272 	if (!mbox) {
15273 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15274 				"6428 Failed allocating mailbox cmd buffer."
15275 				" EQ delay was not set.\n");
15276 		return;
15277 	}
15278 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
15279 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15280 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15281 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
15282 			 length, LPFC_SLI4_MBX_EMBED);
15283 	eq_delay = &mbox->u.mqe.un.eq_delay;
15284 
15285 	/* Calculate delay multiper from maximum interrupt per second */
15286 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
15287 	if (dmult)
15288 		dmult--;
15289 	if (dmult > LPFC_DMULT_MAX)
15290 		dmult = LPFC_DMULT_MAX;
15291 
15292 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15293 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15294 		if (!eq)
15295 			continue;
15296 		eq->q_mode = usdelay;
15297 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
15298 		eq_delay->u.request.eq[cnt].phase = 0;
15299 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
15300 
15301 		if (++cnt >= numq)
15302 			break;
15303 	}
15304 	eq_delay->u.request.num_eq = cnt;
15305 
15306 	mbox->vport = phba->pport;
15307 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15308 	mbox->ctx_buf = NULL;
15309 	mbox->ctx_ndlp = NULL;
15310 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15311 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
15312 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15313 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15314 	if (shdr_status || shdr_add_status || rc) {
15315 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15316 				"2512 MODIFY_EQ_DELAY mailbox failed with "
15317 				"status x%x add_status x%x, mbx status x%x\n",
15318 				shdr_status, shdr_add_status, rc);
15319 	}
15320 	mempool_free(mbox, phba->mbox_mem_pool);
15321 	return;
15322 }
15323 
15324 /**
15325  * lpfc_eq_create - Create an Event Queue on the HBA
15326  * @phba: HBA structure that indicates port to create a queue on.
15327  * @eq: The queue structure to use to create the event queue.
15328  * @imax: The maximum interrupt per second limit.
15329  *
15330  * This function creates an event queue, as detailed in @eq, on a port,
15331  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
15332  *
15333  * The @phba struct is used to send mailbox command to HBA. The @eq struct
15334  * is used to get the entry count and entry size that are necessary to
15335  * determine the number of pages to allocate and use for this queue. This
15336  * function will send the EQ_CREATE mailbox command to the HBA to setup the
15337  * event queue. This function is asynchronous and will wait for the mailbox
15338  * command to finish before continuing.
15339  *
15340  * On success this function will return a zero. If unable to allocate enough
15341  * memory this function will return -ENOMEM. If the queue create mailbox command
15342  * fails this function will return -ENXIO.
15343  **/
15344 int
15345 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
15346 {
15347 	struct lpfc_mbx_eq_create *eq_create;
15348 	LPFC_MBOXQ_t *mbox;
15349 	int rc, length, status = 0;
15350 	struct lpfc_dmabuf *dmabuf;
15351 	uint32_t shdr_status, shdr_add_status;
15352 	union lpfc_sli4_cfg_shdr *shdr;
15353 	uint16_t dmult;
15354 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15355 
15356 	/* sanity check on queue memory */
15357 	if (!eq)
15358 		return -ENODEV;
15359 	if (!phba->sli4_hba.pc_sli4_params.supported)
15360 		hw_page_size = SLI4_PAGE_SIZE;
15361 
15362 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15363 	if (!mbox)
15364 		return -ENOMEM;
15365 	length = (sizeof(struct lpfc_mbx_eq_create) -
15366 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15367 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15368 			 LPFC_MBOX_OPCODE_EQ_CREATE,
15369 			 length, LPFC_SLI4_MBX_EMBED);
15370 	eq_create = &mbox->u.mqe.un.eq_create;
15371 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
15372 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
15373 	       eq->page_count);
15374 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
15375 	       LPFC_EQE_SIZE);
15376 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
15377 
15378 	/* Use version 2 of CREATE_EQ if eqav is set */
15379 	if (phba->sli4_hba.pc_sli4_params.eqav) {
15380 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
15381 		       LPFC_Q_CREATE_VERSION_2);
15382 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
15383 		       phba->sli4_hba.pc_sli4_params.eqav);
15384 	}
15385 
15386 	/* don't setup delay multiplier using EQ_CREATE */
15387 	dmult = 0;
15388 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
15389 	       dmult);
15390 	switch (eq->entry_count) {
15391 	default:
15392 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15393 				"0360 Unsupported EQ count. (%d)\n",
15394 				eq->entry_count);
15395 		if (eq->entry_count < 256) {
15396 			status = -EINVAL;
15397 			goto out;
15398 		}
15399 		fallthrough;	/* otherwise default to smallest count */
15400 	case 256:
15401 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15402 		       LPFC_EQ_CNT_256);
15403 		break;
15404 	case 512:
15405 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15406 		       LPFC_EQ_CNT_512);
15407 		break;
15408 	case 1024:
15409 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15410 		       LPFC_EQ_CNT_1024);
15411 		break;
15412 	case 2048:
15413 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15414 		       LPFC_EQ_CNT_2048);
15415 		break;
15416 	case 4096:
15417 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15418 		       LPFC_EQ_CNT_4096);
15419 		break;
15420 	}
15421 	list_for_each_entry(dmabuf, &eq->page_list, list) {
15422 		memset(dmabuf->virt, 0, hw_page_size);
15423 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15424 					putPaddrLow(dmabuf->phys);
15425 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15426 					putPaddrHigh(dmabuf->phys);
15427 	}
15428 	mbox->vport = phba->pport;
15429 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15430 	mbox->ctx_buf = NULL;
15431 	mbox->ctx_ndlp = NULL;
15432 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15433 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15434 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15435 	if (shdr_status || shdr_add_status || rc) {
15436 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15437 				"2500 EQ_CREATE mailbox failed with "
15438 				"status x%x add_status x%x, mbx status x%x\n",
15439 				shdr_status, shdr_add_status, rc);
15440 		status = -ENXIO;
15441 	}
15442 	eq->type = LPFC_EQ;
15443 	eq->subtype = LPFC_NONE;
15444 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
15445 	if (eq->queue_id == 0xFFFF)
15446 		status = -ENXIO;
15447 	eq->host_index = 0;
15448 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
15449 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
15450 out:
15451 	mempool_free(mbox, phba->mbox_mem_pool);
15452 	return status;
15453 }
15454 
15455 static int lpfc_cq_poll_hdler(struct irq_poll *iop, int budget)
15456 {
15457 	struct lpfc_queue *cq = container_of(iop, struct lpfc_queue, iop);
15458 
15459 	__lpfc_sli4_hba_process_cq(cq, LPFC_IRQ_POLL);
15460 
15461 	return 1;
15462 }
15463 
15464 /**
15465  * lpfc_cq_create - Create a Completion Queue on the HBA
15466  * @phba: HBA structure that indicates port to create a queue on.
15467  * @cq: The queue structure to use to create the completion queue.
15468  * @eq: The event queue to bind this completion queue to.
15469  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
15470  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
15471  *
15472  * This function creates a completion queue, as detailed in @wq, on a port,
15473  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
15474  *
15475  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15476  * is used to get the entry count and entry size that are necessary to
15477  * determine the number of pages to allocate and use for this queue. The @eq
15478  * is used to indicate which event queue to bind this completion queue to. This
15479  * function will send the CQ_CREATE mailbox command to the HBA to setup the
15480  * completion queue. This function is asynchronous and will wait for the mailbox
15481  * command to finish before continuing.
15482  *
15483  * On success this function will return a zero. If unable to allocate enough
15484  * memory this function will return -ENOMEM. If the queue create mailbox command
15485  * fails this function will return -ENXIO.
15486  **/
15487 int
15488 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
15489 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
15490 {
15491 	struct lpfc_mbx_cq_create *cq_create;
15492 	struct lpfc_dmabuf *dmabuf;
15493 	LPFC_MBOXQ_t *mbox;
15494 	int rc, length, status = 0;
15495 	uint32_t shdr_status, shdr_add_status;
15496 	union lpfc_sli4_cfg_shdr *shdr;
15497 
15498 	/* sanity check on queue memory */
15499 	if (!cq || !eq)
15500 		return -ENODEV;
15501 
15502 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15503 	if (!mbox)
15504 		return -ENOMEM;
15505 	length = (sizeof(struct lpfc_mbx_cq_create) -
15506 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15507 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15508 			 LPFC_MBOX_OPCODE_CQ_CREATE,
15509 			 length, LPFC_SLI4_MBX_EMBED);
15510 	cq_create = &mbox->u.mqe.un.cq_create;
15511 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
15512 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
15513 		    cq->page_count);
15514 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
15515 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
15516 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15517 	       phba->sli4_hba.pc_sli4_params.cqv);
15518 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
15519 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
15520 		       (cq->page_size / SLI4_PAGE_SIZE));
15521 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
15522 		       eq->queue_id);
15523 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
15524 		       phba->sli4_hba.pc_sli4_params.cqav);
15525 	} else {
15526 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
15527 		       eq->queue_id);
15528 	}
15529 	switch (cq->entry_count) {
15530 	case 2048:
15531 	case 4096:
15532 		if (phba->sli4_hba.pc_sli4_params.cqv ==
15533 		    LPFC_Q_CREATE_VERSION_2) {
15534 			cq_create->u.request.context.lpfc_cq_context_count =
15535 				cq->entry_count;
15536 			bf_set(lpfc_cq_context_count,
15537 			       &cq_create->u.request.context,
15538 			       LPFC_CQ_CNT_WORD7);
15539 			break;
15540 		}
15541 		fallthrough;
15542 	default:
15543 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15544 				"0361 Unsupported CQ count: "
15545 				"entry cnt %d sz %d pg cnt %d\n",
15546 				cq->entry_count, cq->entry_size,
15547 				cq->page_count);
15548 		if (cq->entry_count < 256) {
15549 			status = -EINVAL;
15550 			goto out;
15551 		}
15552 		fallthrough;	/* otherwise default to smallest count */
15553 	case 256:
15554 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15555 		       LPFC_CQ_CNT_256);
15556 		break;
15557 	case 512:
15558 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15559 		       LPFC_CQ_CNT_512);
15560 		break;
15561 	case 1024:
15562 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15563 		       LPFC_CQ_CNT_1024);
15564 		break;
15565 	}
15566 	list_for_each_entry(dmabuf, &cq->page_list, list) {
15567 		memset(dmabuf->virt, 0, cq->page_size);
15568 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15569 					putPaddrLow(dmabuf->phys);
15570 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15571 					putPaddrHigh(dmabuf->phys);
15572 	}
15573 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15574 
15575 	/* The IOCTL status is embedded in the mailbox subheader. */
15576 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15577 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15578 	if (shdr_status || shdr_add_status || rc) {
15579 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15580 				"2501 CQ_CREATE mailbox failed with "
15581 				"status x%x add_status x%x, mbx status x%x\n",
15582 				shdr_status, shdr_add_status, rc);
15583 		status = -ENXIO;
15584 		goto out;
15585 	}
15586 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15587 	if (cq->queue_id == 0xFFFF) {
15588 		status = -ENXIO;
15589 		goto out;
15590 	}
15591 	/* link the cq onto the parent eq child list */
15592 	list_add_tail(&cq->list, &eq->child_list);
15593 	/* Set up completion queue's type and subtype */
15594 	cq->type = type;
15595 	cq->subtype = subtype;
15596 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15597 	cq->assoc_qid = eq->queue_id;
15598 	cq->assoc_qp = eq;
15599 	cq->host_index = 0;
15600 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15601 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
15602 
15603 	if (cq->queue_id > phba->sli4_hba.cq_max)
15604 		phba->sli4_hba.cq_max = cq->queue_id;
15605 
15606 	irq_poll_init(&cq->iop, LPFC_IRQ_POLL_WEIGHT, lpfc_cq_poll_hdler);
15607 out:
15608 	mempool_free(mbox, phba->mbox_mem_pool);
15609 	return status;
15610 }
15611 
15612 /**
15613  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
15614  * @phba: HBA structure that indicates port to create a queue on.
15615  * @cqp: The queue structure array to use to create the completion queues.
15616  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
15617  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
15618  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
15619  *
15620  * This function creates a set of  completion queue, s to support MRQ
15621  * as detailed in @cqp, on a port,
15622  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
15623  *
15624  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15625  * is used to get the entry count and entry size that are necessary to
15626  * determine the number of pages to allocate and use for this queue. The @eq
15627  * is used to indicate which event queue to bind this completion queue to. This
15628  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
15629  * completion queue. This function is asynchronous and will wait for the mailbox
15630  * command to finish before continuing.
15631  *
15632  * On success this function will return a zero. If unable to allocate enough
15633  * memory this function will return -ENOMEM. If the queue create mailbox command
15634  * fails this function will return -ENXIO.
15635  **/
15636 int
15637 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
15638 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
15639 		   uint32_t subtype)
15640 {
15641 	struct lpfc_queue *cq;
15642 	struct lpfc_queue *eq;
15643 	struct lpfc_mbx_cq_create_set *cq_set;
15644 	struct lpfc_dmabuf *dmabuf;
15645 	LPFC_MBOXQ_t *mbox;
15646 	int rc, length, alloclen, status = 0;
15647 	int cnt, idx, numcq, page_idx = 0;
15648 	uint32_t shdr_status, shdr_add_status;
15649 	union lpfc_sli4_cfg_shdr *shdr;
15650 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15651 
15652 	/* sanity check on queue memory */
15653 	numcq = phba->cfg_nvmet_mrq;
15654 	if (!cqp || !hdwq || !numcq)
15655 		return -ENODEV;
15656 
15657 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15658 	if (!mbox)
15659 		return -ENOMEM;
15660 
15661 	length = sizeof(struct lpfc_mbx_cq_create_set);
15662 	length += ((numcq * cqp[0]->page_count) *
15663 		   sizeof(struct dma_address));
15664 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15665 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
15666 			LPFC_SLI4_MBX_NEMBED);
15667 	if (alloclen < length) {
15668 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15669 				"3098 Allocated DMA memory size (%d) is "
15670 				"less than the requested DMA memory size "
15671 				"(%d)\n", alloclen, length);
15672 		status = -ENOMEM;
15673 		goto out;
15674 	}
15675 	cq_set = mbox->sge_array->addr[0];
15676 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
15677 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
15678 
15679 	for (idx = 0; idx < numcq; idx++) {
15680 		cq = cqp[idx];
15681 		eq = hdwq[idx].hba_eq;
15682 		if (!cq || !eq) {
15683 			status = -ENOMEM;
15684 			goto out;
15685 		}
15686 		if (!phba->sli4_hba.pc_sli4_params.supported)
15687 			hw_page_size = cq->page_size;
15688 
15689 		switch (idx) {
15690 		case 0:
15691 			bf_set(lpfc_mbx_cq_create_set_page_size,
15692 			       &cq_set->u.request,
15693 			       (hw_page_size / SLI4_PAGE_SIZE));
15694 			bf_set(lpfc_mbx_cq_create_set_num_pages,
15695 			       &cq_set->u.request, cq->page_count);
15696 			bf_set(lpfc_mbx_cq_create_set_evt,
15697 			       &cq_set->u.request, 1);
15698 			bf_set(lpfc_mbx_cq_create_set_valid,
15699 			       &cq_set->u.request, 1);
15700 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
15701 			       &cq_set->u.request, 0);
15702 			bf_set(lpfc_mbx_cq_create_set_num_cq,
15703 			       &cq_set->u.request, numcq);
15704 			bf_set(lpfc_mbx_cq_create_set_autovalid,
15705 			       &cq_set->u.request,
15706 			       phba->sli4_hba.pc_sli4_params.cqav);
15707 			switch (cq->entry_count) {
15708 			case 2048:
15709 			case 4096:
15710 				if (phba->sli4_hba.pc_sli4_params.cqv ==
15711 				    LPFC_Q_CREATE_VERSION_2) {
15712 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15713 					       &cq_set->u.request,
15714 						cq->entry_count);
15715 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15716 					       &cq_set->u.request,
15717 					       LPFC_CQ_CNT_WORD7);
15718 					break;
15719 				}
15720 				fallthrough;
15721 			default:
15722 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15723 						"3118 Bad CQ count. (%d)\n",
15724 						cq->entry_count);
15725 				if (cq->entry_count < 256) {
15726 					status = -EINVAL;
15727 					goto out;
15728 				}
15729 				fallthrough;	/* otherwise default to smallest */
15730 			case 256:
15731 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15732 				       &cq_set->u.request, LPFC_CQ_CNT_256);
15733 				break;
15734 			case 512:
15735 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15736 				       &cq_set->u.request, LPFC_CQ_CNT_512);
15737 				break;
15738 			case 1024:
15739 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15740 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
15741 				break;
15742 			}
15743 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
15744 			       &cq_set->u.request, eq->queue_id);
15745 			break;
15746 		case 1:
15747 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
15748 			       &cq_set->u.request, eq->queue_id);
15749 			break;
15750 		case 2:
15751 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
15752 			       &cq_set->u.request, eq->queue_id);
15753 			break;
15754 		case 3:
15755 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
15756 			       &cq_set->u.request, eq->queue_id);
15757 			break;
15758 		case 4:
15759 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
15760 			       &cq_set->u.request, eq->queue_id);
15761 			break;
15762 		case 5:
15763 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
15764 			       &cq_set->u.request, eq->queue_id);
15765 			break;
15766 		case 6:
15767 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
15768 			       &cq_set->u.request, eq->queue_id);
15769 			break;
15770 		case 7:
15771 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
15772 			       &cq_set->u.request, eq->queue_id);
15773 			break;
15774 		case 8:
15775 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
15776 			       &cq_set->u.request, eq->queue_id);
15777 			break;
15778 		case 9:
15779 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
15780 			       &cq_set->u.request, eq->queue_id);
15781 			break;
15782 		case 10:
15783 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
15784 			       &cq_set->u.request, eq->queue_id);
15785 			break;
15786 		case 11:
15787 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
15788 			       &cq_set->u.request, eq->queue_id);
15789 			break;
15790 		case 12:
15791 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
15792 			       &cq_set->u.request, eq->queue_id);
15793 			break;
15794 		case 13:
15795 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
15796 			       &cq_set->u.request, eq->queue_id);
15797 			break;
15798 		case 14:
15799 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
15800 			       &cq_set->u.request, eq->queue_id);
15801 			break;
15802 		case 15:
15803 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
15804 			       &cq_set->u.request, eq->queue_id);
15805 			break;
15806 		}
15807 
15808 		/* link the cq onto the parent eq child list */
15809 		list_add_tail(&cq->list, &eq->child_list);
15810 		/* Set up completion queue's type and subtype */
15811 		cq->type = type;
15812 		cq->subtype = subtype;
15813 		cq->assoc_qid = eq->queue_id;
15814 		cq->assoc_qp = eq;
15815 		cq->host_index = 0;
15816 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15817 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
15818 					 cq->entry_count);
15819 		cq->chann = idx;
15820 
15821 		rc = 0;
15822 		list_for_each_entry(dmabuf, &cq->page_list, list) {
15823 			memset(dmabuf->virt, 0, hw_page_size);
15824 			cnt = page_idx + dmabuf->buffer_tag;
15825 			cq_set->u.request.page[cnt].addr_lo =
15826 					putPaddrLow(dmabuf->phys);
15827 			cq_set->u.request.page[cnt].addr_hi =
15828 					putPaddrHigh(dmabuf->phys);
15829 			rc++;
15830 		}
15831 		page_idx += rc;
15832 	}
15833 
15834 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15835 
15836 	/* The IOCTL status is embedded in the mailbox subheader. */
15837 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15838 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15839 	if (shdr_status || shdr_add_status || rc) {
15840 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15841 				"3119 CQ_CREATE_SET mailbox failed with "
15842 				"status x%x add_status x%x, mbx status x%x\n",
15843 				shdr_status, shdr_add_status, rc);
15844 		status = -ENXIO;
15845 		goto out;
15846 	}
15847 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
15848 	if (rc == 0xFFFF) {
15849 		status = -ENXIO;
15850 		goto out;
15851 	}
15852 
15853 	for (idx = 0; idx < numcq; idx++) {
15854 		cq = cqp[idx];
15855 		cq->queue_id = rc + idx;
15856 		if (cq->queue_id > phba->sli4_hba.cq_max)
15857 			phba->sli4_hba.cq_max = cq->queue_id;
15858 	}
15859 
15860 out:
15861 	lpfc_sli4_mbox_cmd_free(phba, mbox);
15862 	return status;
15863 }
15864 
15865 /**
15866  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
15867  * @phba: HBA structure that indicates port to create a queue on.
15868  * @mq: The queue structure to use to create the mailbox queue.
15869  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
15870  * @cq: The completion queue to associate with this cq.
15871  *
15872  * This function provides failback (fb) functionality when the
15873  * mq_create_ext fails on older FW generations.  It's purpose is identical
15874  * to mq_create_ext otherwise.
15875  *
15876  * This routine cannot fail as all attributes were previously accessed and
15877  * initialized in mq_create_ext.
15878  **/
15879 static void
15880 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
15881 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
15882 {
15883 	struct lpfc_mbx_mq_create *mq_create;
15884 	struct lpfc_dmabuf *dmabuf;
15885 	int length;
15886 
15887 	length = (sizeof(struct lpfc_mbx_mq_create) -
15888 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15889 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15890 			 LPFC_MBOX_OPCODE_MQ_CREATE,
15891 			 length, LPFC_SLI4_MBX_EMBED);
15892 	mq_create = &mbox->u.mqe.un.mq_create;
15893 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
15894 	       mq->page_count);
15895 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
15896 	       cq->queue_id);
15897 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
15898 	switch (mq->entry_count) {
15899 	case 16:
15900 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15901 		       LPFC_MQ_RING_SIZE_16);
15902 		break;
15903 	case 32:
15904 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15905 		       LPFC_MQ_RING_SIZE_32);
15906 		break;
15907 	case 64:
15908 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15909 		       LPFC_MQ_RING_SIZE_64);
15910 		break;
15911 	case 128:
15912 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15913 		       LPFC_MQ_RING_SIZE_128);
15914 		break;
15915 	}
15916 	list_for_each_entry(dmabuf, &mq->page_list, list) {
15917 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15918 			putPaddrLow(dmabuf->phys);
15919 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15920 			putPaddrHigh(dmabuf->phys);
15921 	}
15922 }
15923 
15924 /**
15925  * lpfc_mq_create - Create a mailbox Queue on the HBA
15926  * @phba: HBA structure that indicates port to create a queue on.
15927  * @mq: The queue structure to use to create the mailbox queue.
15928  * @cq: The completion queue to associate with this cq.
15929  * @subtype: The queue's subtype.
15930  *
15931  * This function creates a mailbox queue, as detailed in @mq, on a port,
15932  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
15933  *
15934  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15935  * is used to get the entry count and entry size that are necessary to
15936  * determine the number of pages to allocate and use for this queue. This
15937  * function will send the MQ_CREATE mailbox command to the HBA to setup the
15938  * mailbox queue. This function is asynchronous and will wait for the mailbox
15939  * command to finish before continuing.
15940  *
15941  * On success this function will return a zero. If unable to allocate enough
15942  * memory this function will return -ENOMEM. If the queue create mailbox command
15943  * fails this function will return -ENXIO.
15944  **/
15945 int32_t
15946 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
15947 	       struct lpfc_queue *cq, uint32_t subtype)
15948 {
15949 	struct lpfc_mbx_mq_create *mq_create;
15950 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
15951 	struct lpfc_dmabuf *dmabuf;
15952 	LPFC_MBOXQ_t *mbox;
15953 	int rc, length, status = 0;
15954 	uint32_t shdr_status, shdr_add_status;
15955 	union lpfc_sli4_cfg_shdr *shdr;
15956 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15957 
15958 	/* sanity check on queue memory */
15959 	if (!mq || !cq)
15960 		return -ENODEV;
15961 	if (!phba->sli4_hba.pc_sli4_params.supported)
15962 		hw_page_size = SLI4_PAGE_SIZE;
15963 
15964 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15965 	if (!mbox)
15966 		return -ENOMEM;
15967 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
15968 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15969 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15970 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
15971 			 length, LPFC_SLI4_MBX_EMBED);
15972 
15973 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
15974 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
15975 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
15976 	       &mq_create_ext->u.request, mq->page_count);
15977 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
15978 	       &mq_create_ext->u.request, 1);
15979 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
15980 	       &mq_create_ext->u.request, 1);
15981 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
15982 	       &mq_create_ext->u.request, 1);
15983 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
15984 	       &mq_create_ext->u.request, 1);
15985 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
15986 	       &mq_create_ext->u.request, 1);
15987 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
15988 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15989 	       phba->sli4_hba.pc_sli4_params.mqv);
15990 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
15991 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
15992 		       cq->queue_id);
15993 	else
15994 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
15995 		       cq->queue_id);
15996 	switch (mq->entry_count) {
15997 	default:
15998 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15999 				"0362 Unsupported MQ count. (%d)\n",
16000 				mq->entry_count);
16001 		if (mq->entry_count < 16) {
16002 			status = -EINVAL;
16003 			goto out;
16004 		}
16005 		fallthrough;	/* otherwise default to smallest count */
16006 	case 16:
16007 		bf_set(lpfc_mq_context_ring_size,
16008 		       &mq_create_ext->u.request.context,
16009 		       LPFC_MQ_RING_SIZE_16);
16010 		break;
16011 	case 32:
16012 		bf_set(lpfc_mq_context_ring_size,
16013 		       &mq_create_ext->u.request.context,
16014 		       LPFC_MQ_RING_SIZE_32);
16015 		break;
16016 	case 64:
16017 		bf_set(lpfc_mq_context_ring_size,
16018 		       &mq_create_ext->u.request.context,
16019 		       LPFC_MQ_RING_SIZE_64);
16020 		break;
16021 	case 128:
16022 		bf_set(lpfc_mq_context_ring_size,
16023 		       &mq_create_ext->u.request.context,
16024 		       LPFC_MQ_RING_SIZE_128);
16025 		break;
16026 	}
16027 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16028 		memset(dmabuf->virt, 0, hw_page_size);
16029 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16030 					putPaddrLow(dmabuf->phys);
16031 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16032 					putPaddrHigh(dmabuf->phys);
16033 	}
16034 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16035 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16036 			      &mq_create_ext->u.response);
16037 	if (rc != MBX_SUCCESS) {
16038 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16039 				"2795 MQ_CREATE_EXT failed with "
16040 				"status x%x. Failback to MQ_CREATE.\n",
16041 				rc);
16042 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16043 		mq_create = &mbox->u.mqe.un.mq_create;
16044 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16045 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16046 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16047 				      &mq_create->u.response);
16048 	}
16049 
16050 	/* The IOCTL status is embedded in the mailbox subheader. */
16051 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16052 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16053 	if (shdr_status || shdr_add_status || rc) {
16054 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16055 				"2502 MQ_CREATE mailbox failed with "
16056 				"status x%x add_status x%x, mbx status x%x\n",
16057 				shdr_status, shdr_add_status, rc);
16058 		status = -ENXIO;
16059 		goto out;
16060 	}
16061 	if (mq->queue_id == 0xFFFF) {
16062 		status = -ENXIO;
16063 		goto out;
16064 	}
16065 	mq->type = LPFC_MQ;
16066 	mq->assoc_qid = cq->queue_id;
16067 	mq->subtype = subtype;
16068 	mq->host_index = 0;
16069 	mq->hba_index = 0;
16070 
16071 	/* link the mq onto the parent cq child list */
16072 	list_add_tail(&mq->list, &cq->child_list);
16073 out:
16074 	mempool_free(mbox, phba->mbox_mem_pool);
16075 	return status;
16076 }
16077 
16078 /**
16079  * lpfc_wq_create - Create a Work Queue on the HBA
16080  * @phba: HBA structure that indicates port to create a queue on.
16081  * @wq: The queue structure to use to create the work queue.
16082  * @cq: The completion queue to bind this work queue to.
16083  * @subtype: The subtype of the work queue indicating its functionality.
16084  *
16085  * This function creates a work queue, as detailed in @wq, on a port, described
16086  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16087  *
16088  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16089  * is used to get the entry count and entry size that are necessary to
16090  * determine the number of pages to allocate and use for this queue. The @cq
16091  * is used to indicate which completion queue to bind this work queue to. This
16092  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16093  * work queue. This function is asynchronous and will wait for the mailbox
16094  * command to finish before continuing.
16095  *
16096  * On success this function will return a zero. If unable to allocate enough
16097  * memory this function will return -ENOMEM. If the queue create mailbox command
16098  * fails this function will return -ENXIO.
16099  **/
16100 int
16101 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16102 	       struct lpfc_queue *cq, uint32_t subtype)
16103 {
16104 	struct lpfc_mbx_wq_create *wq_create;
16105 	struct lpfc_dmabuf *dmabuf;
16106 	LPFC_MBOXQ_t *mbox;
16107 	int rc, length, status = 0;
16108 	uint32_t shdr_status, shdr_add_status;
16109 	union lpfc_sli4_cfg_shdr *shdr;
16110 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16111 	struct dma_address *page;
16112 	void __iomem *bar_memmap_p;
16113 	uint32_t db_offset;
16114 	uint16_t pci_barset;
16115 	uint8_t dpp_barset;
16116 	uint32_t dpp_offset;
16117 	uint8_t wq_create_version;
16118 #ifdef CONFIG_X86
16119 	unsigned long pg_addr;
16120 #endif
16121 
16122 	/* sanity check on queue memory */
16123 	if (!wq || !cq)
16124 		return -ENODEV;
16125 	if (!phba->sli4_hba.pc_sli4_params.supported)
16126 		hw_page_size = wq->page_size;
16127 
16128 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16129 	if (!mbox)
16130 		return -ENOMEM;
16131 	length = (sizeof(struct lpfc_mbx_wq_create) -
16132 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16133 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16134 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16135 			 length, LPFC_SLI4_MBX_EMBED);
16136 	wq_create = &mbox->u.mqe.un.wq_create;
16137 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16138 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16139 		    wq->page_count);
16140 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16141 		    cq->queue_id);
16142 
16143 	/* wqv is the earliest version supported, NOT the latest */
16144 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16145 	       phba->sli4_hba.pc_sli4_params.wqv);
16146 
16147 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16148 	    (wq->page_size > SLI4_PAGE_SIZE))
16149 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
16150 	else
16151 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
16152 
16153 	switch (wq_create_version) {
16154 	case LPFC_Q_CREATE_VERSION_1:
16155 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
16156 		       wq->entry_count);
16157 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16158 		       LPFC_Q_CREATE_VERSION_1);
16159 
16160 		switch (wq->entry_size) {
16161 		default:
16162 		case 64:
16163 			bf_set(lpfc_mbx_wq_create_wqe_size,
16164 			       &wq_create->u.request_1,
16165 			       LPFC_WQ_WQE_SIZE_64);
16166 			break;
16167 		case 128:
16168 			bf_set(lpfc_mbx_wq_create_wqe_size,
16169 			       &wq_create->u.request_1,
16170 			       LPFC_WQ_WQE_SIZE_128);
16171 			break;
16172 		}
16173 		/* Request DPP by default */
16174 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
16175 		bf_set(lpfc_mbx_wq_create_page_size,
16176 		       &wq_create->u.request_1,
16177 		       (wq->page_size / SLI4_PAGE_SIZE));
16178 		page = wq_create->u.request_1.page;
16179 		break;
16180 	default:
16181 		page = wq_create->u.request.page;
16182 		break;
16183 	}
16184 
16185 	list_for_each_entry(dmabuf, &wq->page_list, list) {
16186 		memset(dmabuf->virt, 0, hw_page_size);
16187 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
16188 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
16189 	}
16190 
16191 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16192 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
16193 
16194 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16195 	/* The IOCTL status is embedded in the mailbox subheader. */
16196 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16197 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16198 	if (shdr_status || shdr_add_status || rc) {
16199 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16200 				"2503 WQ_CREATE mailbox failed with "
16201 				"status x%x add_status x%x, mbx status x%x\n",
16202 				shdr_status, shdr_add_status, rc);
16203 		status = -ENXIO;
16204 		goto out;
16205 	}
16206 
16207 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
16208 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
16209 					&wq_create->u.response);
16210 	else
16211 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
16212 					&wq_create->u.response_1);
16213 
16214 	if (wq->queue_id == 0xFFFF) {
16215 		status = -ENXIO;
16216 		goto out;
16217 	}
16218 
16219 	wq->db_format = LPFC_DB_LIST_FORMAT;
16220 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
16221 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16222 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
16223 					       &wq_create->u.response);
16224 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
16225 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
16226 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16227 						"3265 WQ[%d] doorbell format "
16228 						"not supported: x%x\n",
16229 						wq->queue_id, wq->db_format);
16230 				status = -EINVAL;
16231 				goto out;
16232 			}
16233 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
16234 					    &wq_create->u.response);
16235 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16236 								   pci_barset);
16237 			if (!bar_memmap_p) {
16238 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16239 						"3263 WQ[%d] failed to memmap "
16240 						"pci barset:x%x\n",
16241 						wq->queue_id, pci_barset);
16242 				status = -ENOMEM;
16243 				goto out;
16244 			}
16245 			db_offset = wq_create->u.response.doorbell_offset;
16246 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
16247 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
16248 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16249 						"3252 WQ[%d] doorbell offset "
16250 						"not supported: x%x\n",
16251 						wq->queue_id, db_offset);
16252 				status = -EINVAL;
16253 				goto out;
16254 			}
16255 			wq->db_regaddr = bar_memmap_p + db_offset;
16256 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16257 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
16258 					"format:x%x\n", wq->queue_id,
16259 					pci_barset, db_offset, wq->db_format);
16260 		} else
16261 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
16262 	} else {
16263 		/* Check if DPP was honored by the firmware */
16264 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
16265 				    &wq_create->u.response_1);
16266 		if (wq->dpp_enable) {
16267 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
16268 					    &wq_create->u.response_1);
16269 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16270 								   pci_barset);
16271 			if (!bar_memmap_p) {
16272 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16273 						"3267 WQ[%d] failed to memmap "
16274 						"pci barset:x%x\n",
16275 						wq->queue_id, pci_barset);
16276 				status = -ENOMEM;
16277 				goto out;
16278 			}
16279 			db_offset = wq_create->u.response_1.doorbell_offset;
16280 			wq->db_regaddr = bar_memmap_p + db_offset;
16281 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
16282 					    &wq_create->u.response_1);
16283 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
16284 					    &wq_create->u.response_1);
16285 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16286 								   dpp_barset);
16287 			if (!bar_memmap_p) {
16288 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16289 						"3268 WQ[%d] failed to memmap "
16290 						"pci barset:x%x\n",
16291 						wq->queue_id, dpp_barset);
16292 				status = -ENOMEM;
16293 				goto out;
16294 			}
16295 			dpp_offset = wq_create->u.response_1.dpp_offset;
16296 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
16297 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16298 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
16299 					"dpp_id:x%x dpp_barset:x%x "
16300 					"dpp_offset:x%x\n",
16301 					wq->queue_id, pci_barset, db_offset,
16302 					wq->dpp_id, dpp_barset, dpp_offset);
16303 
16304 #ifdef CONFIG_X86
16305 			/* Enable combined writes for DPP aperture */
16306 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
16307 			rc = set_memory_wc(pg_addr, 1);
16308 			if (rc) {
16309 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16310 					"3272 Cannot setup Combined "
16311 					"Write on WQ[%d] - disable DPP\n",
16312 					wq->queue_id);
16313 				phba->cfg_enable_dpp = 0;
16314 			}
16315 #else
16316 			phba->cfg_enable_dpp = 0;
16317 #endif
16318 		} else
16319 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
16320 	}
16321 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
16322 	if (wq->pring == NULL) {
16323 		status = -ENOMEM;
16324 		goto out;
16325 	}
16326 	wq->type = LPFC_WQ;
16327 	wq->assoc_qid = cq->queue_id;
16328 	wq->subtype = subtype;
16329 	wq->host_index = 0;
16330 	wq->hba_index = 0;
16331 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
16332 
16333 	/* link the wq onto the parent cq child list */
16334 	list_add_tail(&wq->list, &cq->child_list);
16335 out:
16336 	mempool_free(mbox, phba->mbox_mem_pool);
16337 	return status;
16338 }
16339 
16340 /**
16341  * lpfc_rq_create - Create a Receive Queue on the HBA
16342  * @phba: HBA structure that indicates port to create a queue on.
16343  * @hrq: The queue structure to use to create the header receive queue.
16344  * @drq: The queue structure to use to create the data receive queue.
16345  * @cq: The completion queue to bind this work queue to.
16346  * @subtype: The subtype of the work queue indicating its functionality.
16347  *
16348  * This function creates a receive buffer queue pair , as detailed in @hrq and
16349  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
16350  * to the HBA.
16351  *
16352  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
16353  * struct is used to get the entry count that is necessary to determine the
16354  * number of pages to use for this queue. The @cq is used to indicate which
16355  * completion queue to bind received buffers that are posted to these queues to.
16356  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
16357  * receive queue pair. This function is asynchronous and will wait for the
16358  * mailbox command to finish before continuing.
16359  *
16360  * On success this function will return a zero. If unable to allocate enough
16361  * memory this function will return -ENOMEM. If the queue create mailbox command
16362  * fails this function will return -ENXIO.
16363  **/
16364 int
16365 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
16366 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
16367 {
16368 	struct lpfc_mbx_rq_create *rq_create;
16369 	struct lpfc_dmabuf *dmabuf;
16370 	LPFC_MBOXQ_t *mbox;
16371 	int rc, length, status = 0;
16372 	uint32_t shdr_status, shdr_add_status;
16373 	union lpfc_sli4_cfg_shdr *shdr;
16374 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16375 	void __iomem *bar_memmap_p;
16376 	uint32_t db_offset;
16377 	uint16_t pci_barset;
16378 
16379 	/* sanity check on queue memory */
16380 	if (!hrq || !drq || !cq)
16381 		return -ENODEV;
16382 	if (!phba->sli4_hba.pc_sli4_params.supported)
16383 		hw_page_size = SLI4_PAGE_SIZE;
16384 
16385 	if (hrq->entry_count != drq->entry_count)
16386 		return -EINVAL;
16387 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16388 	if (!mbox)
16389 		return -ENOMEM;
16390 	length = (sizeof(struct lpfc_mbx_rq_create) -
16391 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16392 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16393 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
16394 			 length, LPFC_SLI4_MBX_EMBED);
16395 	rq_create = &mbox->u.mqe.un.rq_create;
16396 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
16397 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16398 	       phba->sli4_hba.pc_sli4_params.rqv);
16399 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
16400 		bf_set(lpfc_rq_context_rqe_count_1,
16401 		       &rq_create->u.request.context,
16402 		       hrq->entry_count);
16403 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
16404 		bf_set(lpfc_rq_context_rqe_size,
16405 		       &rq_create->u.request.context,
16406 		       LPFC_RQE_SIZE_8);
16407 		bf_set(lpfc_rq_context_page_size,
16408 		       &rq_create->u.request.context,
16409 		       LPFC_RQ_PAGE_SIZE_4096);
16410 	} else {
16411 		switch (hrq->entry_count) {
16412 		default:
16413 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16414 					"2535 Unsupported RQ count. (%d)\n",
16415 					hrq->entry_count);
16416 			if (hrq->entry_count < 512) {
16417 				status = -EINVAL;
16418 				goto out;
16419 			}
16420 			fallthrough;	/* otherwise default to smallest count */
16421 		case 512:
16422 			bf_set(lpfc_rq_context_rqe_count,
16423 			       &rq_create->u.request.context,
16424 			       LPFC_RQ_RING_SIZE_512);
16425 			break;
16426 		case 1024:
16427 			bf_set(lpfc_rq_context_rqe_count,
16428 			       &rq_create->u.request.context,
16429 			       LPFC_RQ_RING_SIZE_1024);
16430 			break;
16431 		case 2048:
16432 			bf_set(lpfc_rq_context_rqe_count,
16433 			       &rq_create->u.request.context,
16434 			       LPFC_RQ_RING_SIZE_2048);
16435 			break;
16436 		case 4096:
16437 			bf_set(lpfc_rq_context_rqe_count,
16438 			       &rq_create->u.request.context,
16439 			       LPFC_RQ_RING_SIZE_4096);
16440 			break;
16441 		}
16442 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
16443 		       LPFC_HDR_BUF_SIZE);
16444 	}
16445 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16446 	       cq->queue_id);
16447 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16448 	       hrq->page_count);
16449 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
16450 		memset(dmabuf->virt, 0, hw_page_size);
16451 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16452 					putPaddrLow(dmabuf->phys);
16453 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16454 					putPaddrHigh(dmabuf->phys);
16455 	}
16456 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16457 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16458 
16459 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16460 	/* The IOCTL status is embedded in the mailbox subheader. */
16461 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16462 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16463 	if (shdr_status || shdr_add_status || rc) {
16464 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16465 				"2504 RQ_CREATE mailbox failed with "
16466 				"status x%x add_status x%x, mbx status x%x\n",
16467 				shdr_status, shdr_add_status, rc);
16468 		status = -ENXIO;
16469 		goto out;
16470 	}
16471 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16472 	if (hrq->queue_id == 0xFFFF) {
16473 		status = -ENXIO;
16474 		goto out;
16475 	}
16476 
16477 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16478 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
16479 					&rq_create->u.response);
16480 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
16481 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
16482 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16483 					"3262 RQ [%d] doorbell format not "
16484 					"supported: x%x\n", hrq->queue_id,
16485 					hrq->db_format);
16486 			status = -EINVAL;
16487 			goto out;
16488 		}
16489 
16490 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
16491 				    &rq_create->u.response);
16492 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
16493 		if (!bar_memmap_p) {
16494 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16495 					"3269 RQ[%d] failed to memmap pci "
16496 					"barset:x%x\n", hrq->queue_id,
16497 					pci_barset);
16498 			status = -ENOMEM;
16499 			goto out;
16500 		}
16501 
16502 		db_offset = rq_create->u.response.doorbell_offset;
16503 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
16504 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
16505 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16506 					"3270 RQ[%d] doorbell offset not "
16507 					"supported: x%x\n", hrq->queue_id,
16508 					db_offset);
16509 			status = -EINVAL;
16510 			goto out;
16511 		}
16512 		hrq->db_regaddr = bar_memmap_p + db_offset;
16513 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16514 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
16515 				"format:x%x\n", hrq->queue_id, pci_barset,
16516 				db_offset, hrq->db_format);
16517 	} else {
16518 		hrq->db_format = LPFC_DB_RING_FORMAT;
16519 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16520 	}
16521 	hrq->type = LPFC_HRQ;
16522 	hrq->assoc_qid = cq->queue_id;
16523 	hrq->subtype = subtype;
16524 	hrq->host_index = 0;
16525 	hrq->hba_index = 0;
16526 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16527 
16528 	/* now create the data queue */
16529 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16530 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
16531 			 length, LPFC_SLI4_MBX_EMBED);
16532 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16533 	       phba->sli4_hba.pc_sli4_params.rqv);
16534 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
16535 		bf_set(lpfc_rq_context_rqe_count_1,
16536 		       &rq_create->u.request.context, hrq->entry_count);
16537 		if (subtype == LPFC_NVMET)
16538 			rq_create->u.request.context.buffer_size =
16539 				LPFC_NVMET_DATA_BUF_SIZE;
16540 		else
16541 			rq_create->u.request.context.buffer_size =
16542 				LPFC_DATA_BUF_SIZE;
16543 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
16544 		       LPFC_RQE_SIZE_8);
16545 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
16546 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
16547 	} else {
16548 		switch (drq->entry_count) {
16549 		default:
16550 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16551 					"2536 Unsupported RQ count. (%d)\n",
16552 					drq->entry_count);
16553 			if (drq->entry_count < 512) {
16554 				status = -EINVAL;
16555 				goto out;
16556 			}
16557 			fallthrough;	/* otherwise default to smallest count */
16558 		case 512:
16559 			bf_set(lpfc_rq_context_rqe_count,
16560 			       &rq_create->u.request.context,
16561 			       LPFC_RQ_RING_SIZE_512);
16562 			break;
16563 		case 1024:
16564 			bf_set(lpfc_rq_context_rqe_count,
16565 			       &rq_create->u.request.context,
16566 			       LPFC_RQ_RING_SIZE_1024);
16567 			break;
16568 		case 2048:
16569 			bf_set(lpfc_rq_context_rqe_count,
16570 			       &rq_create->u.request.context,
16571 			       LPFC_RQ_RING_SIZE_2048);
16572 			break;
16573 		case 4096:
16574 			bf_set(lpfc_rq_context_rqe_count,
16575 			       &rq_create->u.request.context,
16576 			       LPFC_RQ_RING_SIZE_4096);
16577 			break;
16578 		}
16579 		if (subtype == LPFC_NVMET)
16580 			bf_set(lpfc_rq_context_buf_size,
16581 			       &rq_create->u.request.context,
16582 			       LPFC_NVMET_DATA_BUF_SIZE);
16583 		else
16584 			bf_set(lpfc_rq_context_buf_size,
16585 			       &rq_create->u.request.context,
16586 			       LPFC_DATA_BUF_SIZE);
16587 	}
16588 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16589 	       cq->queue_id);
16590 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16591 	       drq->page_count);
16592 	list_for_each_entry(dmabuf, &drq->page_list, list) {
16593 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16594 					putPaddrLow(dmabuf->phys);
16595 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16596 					putPaddrHigh(dmabuf->phys);
16597 	}
16598 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16599 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16600 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16601 	/* The IOCTL status is embedded in the mailbox subheader. */
16602 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
16603 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16604 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16605 	if (shdr_status || shdr_add_status || rc) {
16606 		status = -ENXIO;
16607 		goto out;
16608 	}
16609 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16610 	if (drq->queue_id == 0xFFFF) {
16611 		status = -ENXIO;
16612 		goto out;
16613 	}
16614 	drq->type = LPFC_DRQ;
16615 	drq->assoc_qid = cq->queue_id;
16616 	drq->subtype = subtype;
16617 	drq->host_index = 0;
16618 	drq->hba_index = 0;
16619 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16620 
16621 	/* link the header and data RQs onto the parent cq child list */
16622 	list_add_tail(&hrq->list, &cq->child_list);
16623 	list_add_tail(&drq->list, &cq->child_list);
16624 
16625 out:
16626 	mempool_free(mbox, phba->mbox_mem_pool);
16627 	return status;
16628 }
16629 
16630 /**
16631  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
16632  * @phba: HBA structure that indicates port to create a queue on.
16633  * @hrqp: The queue structure array to use to create the header receive queues.
16634  * @drqp: The queue structure array to use to create the data receive queues.
16635  * @cqp: The completion queue array to bind these receive queues to.
16636  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16637  *
16638  * This function creates a receive buffer queue pair , as detailed in @hrq and
16639  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
16640  * to the HBA.
16641  *
16642  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
16643  * struct is used to get the entry count that is necessary to determine the
16644  * number of pages to use for this queue. The @cq is used to indicate which
16645  * completion queue to bind received buffers that are posted to these queues to.
16646  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
16647  * receive queue pair. This function is asynchronous and will wait for the
16648  * mailbox command to finish before continuing.
16649  *
16650  * On success this function will return a zero. If unable to allocate enough
16651  * memory this function will return -ENOMEM. If the queue create mailbox command
16652  * fails this function will return -ENXIO.
16653  **/
16654 int
16655 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
16656 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
16657 		uint32_t subtype)
16658 {
16659 	struct lpfc_queue *hrq, *drq, *cq;
16660 	struct lpfc_mbx_rq_create_v2 *rq_create;
16661 	struct lpfc_dmabuf *dmabuf;
16662 	LPFC_MBOXQ_t *mbox;
16663 	int rc, length, alloclen, status = 0;
16664 	int cnt, idx, numrq, page_idx = 0;
16665 	uint32_t shdr_status, shdr_add_status;
16666 	union lpfc_sli4_cfg_shdr *shdr;
16667 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16668 
16669 	numrq = phba->cfg_nvmet_mrq;
16670 	/* sanity check on array memory */
16671 	if (!hrqp || !drqp || !cqp || !numrq)
16672 		return -ENODEV;
16673 	if (!phba->sli4_hba.pc_sli4_params.supported)
16674 		hw_page_size = SLI4_PAGE_SIZE;
16675 
16676 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16677 	if (!mbox)
16678 		return -ENOMEM;
16679 
16680 	length = sizeof(struct lpfc_mbx_rq_create_v2);
16681 	length += ((2 * numrq * hrqp[0]->page_count) *
16682 		   sizeof(struct dma_address));
16683 
16684 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16685 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
16686 				    LPFC_SLI4_MBX_NEMBED);
16687 	if (alloclen < length) {
16688 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16689 				"3099 Allocated DMA memory size (%d) is "
16690 				"less than the requested DMA memory size "
16691 				"(%d)\n", alloclen, length);
16692 		status = -ENOMEM;
16693 		goto out;
16694 	}
16695 
16696 
16697 
16698 	rq_create = mbox->sge_array->addr[0];
16699 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
16700 
16701 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
16702 	cnt = 0;
16703 
16704 	for (idx = 0; idx < numrq; idx++) {
16705 		hrq = hrqp[idx];
16706 		drq = drqp[idx];
16707 		cq  = cqp[idx];
16708 
16709 		/* sanity check on queue memory */
16710 		if (!hrq || !drq || !cq) {
16711 			status = -ENODEV;
16712 			goto out;
16713 		}
16714 
16715 		if (hrq->entry_count != drq->entry_count) {
16716 			status = -EINVAL;
16717 			goto out;
16718 		}
16719 
16720 		if (idx == 0) {
16721 			bf_set(lpfc_mbx_rq_create_num_pages,
16722 			       &rq_create->u.request,
16723 			       hrq->page_count);
16724 			bf_set(lpfc_mbx_rq_create_rq_cnt,
16725 			       &rq_create->u.request, (numrq * 2));
16726 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
16727 			       1);
16728 			bf_set(lpfc_rq_context_base_cq,
16729 			       &rq_create->u.request.context,
16730 			       cq->queue_id);
16731 			bf_set(lpfc_rq_context_data_size,
16732 			       &rq_create->u.request.context,
16733 			       LPFC_NVMET_DATA_BUF_SIZE);
16734 			bf_set(lpfc_rq_context_hdr_size,
16735 			       &rq_create->u.request.context,
16736 			       LPFC_HDR_BUF_SIZE);
16737 			bf_set(lpfc_rq_context_rqe_count_1,
16738 			       &rq_create->u.request.context,
16739 			       hrq->entry_count);
16740 			bf_set(lpfc_rq_context_rqe_size,
16741 			       &rq_create->u.request.context,
16742 			       LPFC_RQE_SIZE_8);
16743 			bf_set(lpfc_rq_context_page_size,
16744 			       &rq_create->u.request.context,
16745 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
16746 		}
16747 		rc = 0;
16748 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
16749 			memset(dmabuf->virt, 0, hw_page_size);
16750 			cnt = page_idx + dmabuf->buffer_tag;
16751 			rq_create->u.request.page[cnt].addr_lo =
16752 					putPaddrLow(dmabuf->phys);
16753 			rq_create->u.request.page[cnt].addr_hi =
16754 					putPaddrHigh(dmabuf->phys);
16755 			rc++;
16756 		}
16757 		page_idx += rc;
16758 
16759 		rc = 0;
16760 		list_for_each_entry(dmabuf, &drq->page_list, list) {
16761 			memset(dmabuf->virt, 0, hw_page_size);
16762 			cnt = page_idx + dmabuf->buffer_tag;
16763 			rq_create->u.request.page[cnt].addr_lo =
16764 					putPaddrLow(dmabuf->phys);
16765 			rq_create->u.request.page[cnt].addr_hi =
16766 					putPaddrHigh(dmabuf->phys);
16767 			rc++;
16768 		}
16769 		page_idx += rc;
16770 
16771 		hrq->db_format = LPFC_DB_RING_FORMAT;
16772 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16773 		hrq->type = LPFC_HRQ;
16774 		hrq->assoc_qid = cq->queue_id;
16775 		hrq->subtype = subtype;
16776 		hrq->host_index = 0;
16777 		hrq->hba_index = 0;
16778 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16779 
16780 		drq->db_format = LPFC_DB_RING_FORMAT;
16781 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16782 		drq->type = LPFC_DRQ;
16783 		drq->assoc_qid = cq->queue_id;
16784 		drq->subtype = subtype;
16785 		drq->host_index = 0;
16786 		drq->hba_index = 0;
16787 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16788 
16789 		list_add_tail(&hrq->list, &cq->child_list);
16790 		list_add_tail(&drq->list, &cq->child_list);
16791 	}
16792 
16793 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16794 	/* The IOCTL status is embedded in the mailbox subheader. */
16795 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16796 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16797 	if (shdr_status || shdr_add_status || rc) {
16798 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16799 				"3120 RQ_CREATE mailbox failed with "
16800 				"status x%x add_status x%x, mbx status x%x\n",
16801 				shdr_status, shdr_add_status, rc);
16802 		status = -ENXIO;
16803 		goto out;
16804 	}
16805 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16806 	if (rc == 0xFFFF) {
16807 		status = -ENXIO;
16808 		goto out;
16809 	}
16810 
16811 	/* Initialize all RQs with associated queue id */
16812 	for (idx = 0; idx < numrq; idx++) {
16813 		hrq = hrqp[idx];
16814 		hrq->queue_id = rc + (2 * idx);
16815 		drq = drqp[idx];
16816 		drq->queue_id = rc + (2 * idx) + 1;
16817 	}
16818 
16819 out:
16820 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16821 	return status;
16822 }
16823 
16824 /**
16825  * lpfc_eq_destroy - Destroy an event Queue on the HBA
16826  * @phba: HBA structure that indicates port to destroy a queue on.
16827  * @eq: The queue structure associated with the queue to destroy.
16828  *
16829  * This function destroys a queue, as detailed in @eq by sending an mailbox
16830  * command, specific to the type of queue, to the HBA.
16831  *
16832  * The @eq struct is used to get the queue ID of the queue to destroy.
16833  *
16834  * On success this function will return a zero. If the queue destroy mailbox
16835  * command fails this function will return -ENXIO.
16836  **/
16837 int
16838 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
16839 {
16840 	LPFC_MBOXQ_t *mbox;
16841 	int rc, length, status = 0;
16842 	uint32_t shdr_status, shdr_add_status;
16843 	union lpfc_sli4_cfg_shdr *shdr;
16844 
16845 	/* sanity check on queue memory */
16846 	if (!eq)
16847 		return -ENODEV;
16848 
16849 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
16850 	if (!mbox)
16851 		return -ENOMEM;
16852 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
16853 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16854 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16855 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
16856 			 length, LPFC_SLI4_MBX_EMBED);
16857 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
16858 	       eq->queue_id);
16859 	mbox->vport = eq->phba->pport;
16860 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16861 
16862 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
16863 	/* The IOCTL status is embedded in the mailbox subheader. */
16864 	shdr = (union lpfc_sli4_cfg_shdr *)
16865 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
16866 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16867 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16868 	if (shdr_status || shdr_add_status || rc) {
16869 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16870 				"2505 EQ_DESTROY mailbox failed with "
16871 				"status x%x add_status x%x, mbx status x%x\n",
16872 				shdr_status, shdr_add_status, rc);
16873 		status = -ENXIO;
16874 	}
16875 
16876 	/* Remove eq from any list */
16877 	list_del_init(&eq->list);
16878 	mempool_free(mbox, eq->phba->mbox_mem_pool);
16879 	return status;
16880 }
16881 
16882 /**
16883  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
16884  * @phba: HBA structure that indicates port to destroy a queue on.
16885  * @cq: The queue structure associated with the queue to destroy.
16886  *
16887  * This function destroys a queue, as detailed in @cq by sending an mailbox
16888  * command, specific to the type of queue, to the HBA.
16889  *
16890  * The @cq struct is used to get the queue ID of the queue to destroy.
16891  *
16892  * On success this function will return a zero. If the queue destroy mailbox
16893  * command fails this function will return -ENXIO.
16894  **/
16895 int
16896 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
16897 {
16898 	LPFC_MBOXQ_t *mbox;
16899 	int rc, length, status = 0;
16900 	uint32_t shdr_status, shdr_add_status;
16901 	union lpfc_sli4_cfg_shdr *shdr;
16902 
16903 	/* sanity check on queue memory */
16904 	if (!cq)
16905 		return -ENODEV;
16906 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
16907 	if (!mbox)
16908 		return -ENOMEM;
16909 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
16910 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16911 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16912 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
16913 			 length, LPFC_SLI4_MBX_EMBED);
16914 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
16915 	       cq->queue_id);
16916 	mbox->vport = cq->phba->pport;
16917 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16918 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
16919 	/* The IOCTL status is embedded in the mailbox subheader. */
16920 	shdr = (union lpfc_sli4_cfg_shdr *)
16921 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
16922 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16923 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16924 	if (shdr_status || shdr_add_status || rc) {
16925 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16926 				"2506 CQ_DESTROY mailbox failed with "
16927 				"status x%x add_status x%x, mbx status x%x\n",
16928 				shdr_status, shdr_add_status, rc);
16929 		status = -ENXIO;
16930 	}
16931 	/* Remove cq from any list */
16932 	list_del_init(&cq->list);
16933 	mempool_free(mbox, cq->phba->mbox_mem_pool);
16934 	return status;
16935 }
16936 
16937 /**
16938  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
16939  * @phba: HBA structure that indicates port to destroy a queue on.
16940  * @mq: The queue structure associated with the queue to destroy.
16941  *
16942  * This function destroys a queue, as detailed in @mq by sending an mailbox
16943  * command, specific to the type of queue, to the HBA.
16944  *
16945  * The @mq struct is used to get the queue ID of the queue to destroy.
16946  *
16947  * On success this function will return a zero. If the queue destroy mailbox
16948  * command fails this function will return -ENXIO.
16949  **/
16950 int
16951 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
16952 {
16953 	LPFC_MBOXQ_t *mbox;
16954 	int rc, length, status = 0;
16955 	uint32_t shdr_status, shdr_add_status;
16956 	union lpfc_sli4_cfg_shdr *shdr;
16957 
16958 	/* sanity check on queue memory */
16959 	if (!mq)
16960 		return -ENODEV;
16961 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
16962 	if (!mbox)
16963 		return -ENOMEM;
16964 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
16965 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16966 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16967 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
16968 			 length, LPFC_SLI4_MBX_EMBED);
16969 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
16970 	       mq->queue_id);
16971 	mbox->vport = mq->phba->pport;
16972 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16973 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
16974 	/* The IOCTL status is embedded in the mailbox subheader. */
16975 	shdr = (union lpfc_sli4_cfg_shdr *)
16976 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
16977 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16978 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16979 	if (shdr_status || shdr_add_status || rc) {
16980 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16981 				"2507 MQ_DESTROY mailbox failed with "
16982 				"status x%x add_status x%x, mbx status x%x\n",
16983 				shdr_status, shdr_add_status, rc);
16984 		status = -ENXIO;
16985 	}
16986 	/* Remove mq from any list */
16987 	list_del_init(&mq->list);
16988 	mempool_free(mbox, mq->phba->mbox_mem_pool);
16989 	return status;
16990 }
16991 
16992 /**
16993  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
16994  * @phba: HBA structure that indicates port to destroy a queue on.
16995  * @wq: The queue structure associated with the queue to destroy.
16996  *
16997  * This function destroys a queue, as detailed in @wq by sending an mailbox
16998  * command, specific to the type of queue, to the HBA.
16999  *
17000  * The @wq struct is used to get the queue ID of the queue to destroy.
17001  *
17002  * On success this function will return a zero. If the queue destroy mailbox
17003  * command fails this function will return -ENXIO.
17004  **/
17005 int
17006 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
17007 {
17008 	LPFC_MBOXQ_t *mbox;
17009 	int rc, length, status = 0;
17010 	uint32_t shdr_status, shdr_add_status;
17011 	union lpfc_sli4_cfg_shdr *shdr;
17012 
17013 	/* sanity check on queue memory */
17014 	if (!wq)
17015 		return -ENODEV;
17016 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17017 	if (!mbox)
17018 		return -ENOMEM;
17019 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
17020 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17021 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17022 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17023 			 length, LPFC_SLI4_MBX_EMBED);
17024 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17025 	       wq->queue_id);
17026 	mbox->vport = wq->phba->pport;
17027 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17028 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17029 	shdr = (union lpfc_sli4_cfg_shdr *)
17030 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17031 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17032 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17033 	if (shdr_status || shdr_add_status || rc) {
17034 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17035 				"2508 WQ_DESTROY mailbox failed with "
17036 				"status x%x add_status x%x, mbx status x%x\n",
17037 				shdr_status, shdr_add_status, rc);
17038 		status = -ENXIO;
17039 	}
17040 	/* Remove wq from any list */
17041 	list_del_init(&wq->list);
17042 	kfree(wq->pring);
17043 	wq->pring = NULL;
17044 	mempool_free(mbox, wq->phba->mbox_mem_pool);
17045 	return status;
17046 }
17047 
17048 /**
17049  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17050  * @phba: HBA structure that indicates port to destroy a queue on.
17051  * @hrq: The queue structure associated with the queue to destroy.
17052  * @drq: The queue structure associated with the queue to destroy.
17053  *
17054  * This function destroys a queue, as detailed in @rq by sending an mailbox
17055  * command, specific to the type of queue, to the HBA.
17056  *
17057  * The @rq struct is used to get the queue ID of the queue to destroy.
17058  *
17059  * On success this function will return a zero. If the queue destroy mailbox
17060  * command fails this function will return -ENXIO.
17061  **/
17062 int
17063 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17064 		struct lpfc_queue *drq)
17065 {
17066 	LPFC_MBOXQ_t *mbox;
17067 	int rc, length, status = 0;
17068 	uint32_t shdr_status, shdr_add_status;
17069 	union lpfc_sli4_cfg_shdr *shdr;
17070 
17071 	/* sanity check on queue memory */
17072 	if (!hrq || !drq)
17073 		return -ENODEV;
17074 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17075 	if (!mbox)
17076 		return -ENOMEM;
17077 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
17078 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17079 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17080 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17081 			 length, LPFC_SLI4_MBX_EMBED);
17082 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17083 	       hrq->queue_id);
17084 	mbox->vport = hrq->phba->pport;
17085 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17086 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17087 	/* The IOCTL status is embedded in the mailbox subheader. */
17088 	shdr = (union lpfc_sli4_cfg_shdr *)
17089 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17090 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17091 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17092 	if (shdr_status || shdr_add_status || rc) {
17093 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17094 				"2509 RQ_DESTROY mailbox failed with "
17095 				"status x%x add_status x%x, mbx status x%x\n",
17096 				shdr_status, shdr_add_status, rc);
17097 		mempool_free(mbox, hrq->phba->mbox_mem_pool);
17098 		return -ENXIO;
17099 	}
17100 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17101 	       drq->queue_id);
17102 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17103 	shdr = (union lpfc_sli4_cfg_shdr *)
17104 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17105 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17106 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17107 	if (shdr_status || shdr_add_status || rc) {
17108 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17109 				"2510 RQ_DESTROY mailbox failed with "
17110 				"status x%x add_status x%x, mbx status x%x\n",
17111 				shdr_status, shdr_add_status, rc);
17112 		status = -ENXIO;
17113 	}
17114 	list_del_init(&hrq->list);
17115 	list_del_init(&drq->list);
17116 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
17117 	return status;
17118 }
17119 
17120 /**
17121  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17122  * @phba: The virtual port for which this call being executed.
17123  * @pdma_phys_addr0: Physical address of the 1st SGL page.
17124  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
17125  * @xritag: the xritag that ties this io to the SGL pages.
17126  *
17127  * This routine will post the sgl pages for the IO that has the xritag
17128  * that is in the iocbq structure. The xritag is assigned during iocbq
17129  * creation and persists for as long as the driver is loaded.
17130  * if the caller has fewer than 256 scatter gather segments to map then
17131  * pdma_phys_addr1 should be 0.
17132  * If the caller needs to map more than 256 scatter gather segment then
17133  * pdma_phys_addr1 should be a valid physical address.
17134  * physical address for SGLs must be 64 byte aligned.
17135  * If you are going to map 2 SGL's then the first one must have 256 entries
17136  * the second sgl can have between 1 and 256 entries.
17137  *
17138  * Return codes:
17139  * 	0 - Success
17140  * 	-ENXIO, -ENOMEM - Failure
17141  **/
17142 int
17143 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
17144 		dma_addr_t pdma_phys_addr0,
17145 		dma_addr_t pdma_phys_addr1,
17146 		uint16_t xritag)
17147 {
17148 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
17149 	LPFC_MBOXQ_t *mbox;
17150 	int rc;
17151 	uint32_t shdr_status, shdr_add_status;
17152 	uint32_t mbox_tmo;
17153 	union lpfc_sli4_cfg_shdr *shdr;
17154 
17155 	if (xritag == NO_XRI) {
17156 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17157 				"0364 Invalid param:\n");
17158 		return -EINVAL;
17159 	}
17160 
17161 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17162 	if (!mbox)
17163 		return -ENOMEM;
17164 
17165 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17166 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17167 			sizeof(struct lpfc_mbx_post_sgl_pages) -
17168 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17169 
17170 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
17171 				&mbox->u.mqe.un.post_sgl_pages;
17172 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
17173 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
17174 
17175 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
17176 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
17177 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
17178 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
17179 
17180 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
17181 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
17182 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
17183 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
17184 	if (!phba->sli4_hba.intr_enable)
17185 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17186 	else {
17187 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17188 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17189 	}
17190 	/* The IOCTL status is embedded in the mailbox subheader. */
17191 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
17192 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17193 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17194 	if (!phba->sli4_hba.intr_enable)
17195 		mempool_free(mbox, phba->mbox_mem_pool);
17196 	else if (rc != MBX_TIMEOUT)
17197 		mempool_free(mbox, phba->mbox_mem_pool);
17198 	if (shdr_status || shdr_add_status || rc) {
17199 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17200 				"2511 POST_SGL mailbox failed with "
17201 				"status x%x add_status x%x, mbx status x%x\n",
17202 				shdr_status, shdr_add_status, rc);
17203 	}
17204 	return 0;
17205 }
17206 
17207 /**
17208  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
17209  * @phba: pointer to lpfc hba data structure.
17210  *
17211  * This routine is invoked to post rpi header templates to the
17212  * HBA consistent with the SLI-4 interface spec.  This routine
17213  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
17214  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
17215  *
17216  * Returns
17217  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
17218  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
17219  **/
17220 static uint16_t
17221 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
17222 {
17223 	unsigned long xri;
17224 
17225 	/*
17226 	 * Fetch the next logical xri.  Because this index is logical,
17227 	 * the driver starts at 0 each time.
17228 	 */
17229 	spin_lock_irq(&phba->hbalock);
17230 	xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
17231 				 phba->sli4_hba.max_cfg_param.max_xri, 0);
17232 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
17233 		spin_unlock_irq(&phba->hbalock);
17234 		return NO_XRI;
17235 	} else {
17236 		set_bit(xri, phba->sli4_hba.xri_bmask);
17237 		phba->sli4_hba.max_cfg_param.xri_used++;
17238 	}
17239 	spin_unlock_irq(&phba->hbalock);
17240 	return xri;
17241 }
17242 
17243 /**
17244  * __lpfc_sli4_free_xri - Release an xri for reuse.
17245  * @phba: pointer to lpfc hba data structure.
17246  * @xri: xri to release.
17247  *
17248  * This routine is invoked to release an xri to the pool of
17249  * available rpis maintained by the driver.
17250  **/
17251 static void
17252 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
17253 {
17254 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
17255 		phba->sli4_hba.max_cfg_param.xri_used--;
17256 	}
17257 }
17258 
17259 /**
17260  * lpfc_sli4_free_xri - Release an xri for reuse.
17261  * @phba: pointer to lpfc hba data structure.
17262  * @xri: xri to release.
17263  *
17264  * This routine is invoked to release an xri to the pool of
17265  * available rpis maintained by the driver.
17266  **/
17267 void
17268 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
17269 {
17270 	spin_lock_irq(&phba->hbalock);
17271 	__lpfc_sli4_free_xri(phba, xri);
17272 	spin_unlock_irq(&phba->hbalock);
17273 }
17274 
17275 /**
17276  * lpfc_sli4_next_xritag - Get an xritag for the io
17277  * @phba: Pointer to HBA context object.
17278  *
17279  * This function gets an xritag for the iocb. If there is no unused xritag
17280  * it will return 0xffff.
17281  * The function returns the allocated xritag if successful, else returns zero.
17282  * Zero is not a valid xritag.
17283  * The caller is not required to hold any lock.
17284  **/
17285 uint16_t
17286 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
17287 {
17288 	uint16_t xri_index;
17289 
17290 	xri_index = lpfc_sli4_alloc_xri(phba);
17291 	if (xri_index == NO_XRI)
17292 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
17293 				"2004 Failed to allocate XRI.last XRITAG is %d"
17294 				" Max XRI is %d, Used XRI is %d\n",
17295 				xri_index,
17296 				phba->sli4_hba.max_cfg_param.max_xri,
17297 				phba->sli4_hba.max_cfg_param.xri_used);
17298 	return xri_index;
17299 }
17300 
17301 /**
17302  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
17303  * @phba: pointer to lpfc hba data structure.
17304  * @post_sgl_list: pointer to els sgl entry list.
17305  * @post_cnt: number of els sgl entries on the list.
17306  *
17307  * This routine is invoked to post a block of driver's sgl pages to the
17308  * HBA using non-embedded mailbox command. No Lock is held. This routine
17309  * is only called when the driver is loading and after all IO has been
17310  * stopped.
17311  **/
17312 static int
17313 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
17314 			    struct list_head *post_sgl_list,
17315 			    int post_cnt)
17316 {
17317 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
17318 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
17319 	struct sgl_page_pairs *sgl_pg_pairs;
17320 	void *viraddr;
17321 	LPFC_MBOXQ_t *mbox;
17322 	uint32_t reqlen, alloclen, pg_pairs;
17323 	uint32_t mbox_tmo;
17324 	uint16_t xritag_start = 0;
17325 	int rc = 0;
17326 	uint32_t shdr_status, shdr_add_status;
17327 	union lpfc_sli4_cfg_shdr *shdr;
17328 
17329 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
17330 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
17331 	if (reqlen > SLI4_PAGE_SIZE) {
17332 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17333 				"2559 Block sgl registration required DMA "
17334 				"size (%d) great than a page\n", reqlen);
17335 		return -ENOMEM;
17336 	}
17337 
17338 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17339 	if (!mbox)
17340 		return -ENOMEM;
17341 
17342 	/* Allocate DMA memory and set up the non-embedded mailbox command */
17343 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17344 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
17345 			 LPFC_SLI4_MBX_NEMBED);
17346 
17347 	if (alloclen < reqlen) {
17348 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17349 				"0285 Allocated DMA memory size (%d) is "
17350 				"less than the requested DMA memory "
17351 				"size (%d)\n", alloclen, reqlen);
17352 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17353 		return -ENOMEM;
17354 	}
17355 	/* Set up the SGL pages in the non-embedded DMA pages */
17356 	viraddr = mbox->sge_array->addr[0];
17357 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
17358 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
17359 
17360 	pg_pairs = 0;
17361 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
17362 		/* Set up the sge entry */
17363 		sgl_pg_pairs->sgl_pg0_addr_lo =
17364 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
17365 		sgl_pg_pairs->sgl_pg0_addr_hi =
17366 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
17367 		sgl_pg_pairs->sgl_pg1_addr_lo =
17368 				cpu_to_le32(putPaddrLow(0));
17369 		sgl_pg_pairs->sgl_pg1_addr_hi =
17370 				cpu_to_le32(putPaddrHigh(0));
17371 
17372 		/* Keep the first xritag on the list */
17373 		if (pg_pairs == 0)
17374 			xritag_start = sglq_entry->sli4_xritag;
17375 		sgl_pg_pairs++;
17376 		pg_pairs++;
17377 	}
17378 
17379 	/* Complete initialization and perform endian conversion. */
17380 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
17381 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
17382 	sgl->word0 = cpu_to_le32(sgl->word0);
17383 
17384 	if (!phba->sli4_hba.intr_enable)
17385 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17386 	else {
17387 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17388 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17389 	}
17390 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
17391 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17392 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17393 	if (!phba->sli4_hba.intr_enable)
17394 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17395 	else if (rc != MBX_TIMEOUT)
17396 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17397 	if (shdr_status || shdr_add_status || rc) {
17398 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17399 				"2513 POST_SGL_BLOCK mailbox command failed "
17400 				"status x%x add_status x%x mbx status x%x\n",
17401 				shdr_status, shdr_add_status, rc);
17402 		rc = -ENXIO;
17403 	}
17404 	return rc;
17405 }
17406 
17407 /**
17408  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
17409  * @phba: pointer to lpfc hba data structure.
17410  * @nblist: pointer to nvme buffer list.
17411  * @count: number of scsi buffers on the list.
17412  *
17413  * This routine is invoked to post a block of @count scsi sgl pages from a
17414  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
17415  * No Lock is held.
17416  *
17417  **/
17418 static int
17419 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
17420 			    int count)
17421 {
17422 	struct lpfc_io_buf *lpfc_ncmd;
17423 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
17424 	struct sgl_page_pairs *sgl_pg_pairs;
17425 	void *viraddr;
17426 	LPFC_MBOXQ_t *mbox;
17427 	uint32_t reqlen, alloclen, pg_pairs;
17428 	uint32_t mbox_tmo;
17429 	uint16_t xritag_start = 0;
17430 	int rc = 0;
17431 	uint32_t shdr_status, shdr_add_status;
17432 	dma_addr_t pdma_phys_bpl1;
17433 	union lpfc_sli4_cfg_shdr *shdr;
17434 
17435 	/* Calculate the requested length of the dma memory */
17436 	reqlen = count * sizeof(struct sgl_page_pairs) +
17437 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
17438 	if (reqlen > SLI4_PAGE_SIZE) {
17439 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
17440 				"6118 Block sgl registration required DMA "
17441 				"size (%d) great than a page\n", reqlen);
17442 		return -ENOMEM;
17443 	}
17444 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17445 	if (!mbox) {
17446 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17447 				"6119 Failed to allocate mbox cmd memory\n");
17448 		return -ENOMEM;
17449 	}
17450 
17451 	/* Allocate DMA memory and set up the non-embedded mailbox command */
17452 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17453 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17454 				    reqlen, LPFC_SLI4_MBX_NEMBED);
17455 
17456 	if (alloclen < reqlen) {
17457 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17458 				"6120 Allocated DMA memory size (%d) is "
17459 				"less than the requested DMA memory "
17460 				"size (%d)\n", alloclen, reqlen);
17461 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17462 		return -ENOMEM;
17463 	}
17464 
17465 	/* Get the first SGE entry from the non-embedded DMA memory */
17466 	viraddr = mbox->sge_array->addr[0];
17467 
17468 	/* Set up the SGL pages in the non-embedded DMA pages */
17469 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
17470 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
17471 
17472 	pg_pairs = 0;
17473 	list_for_each_entry(lpfc_ncmd, nblist, list) {
17474 		/* Set up the sge entry */
17475 		sgl_pg_pairs->sgl_pg0_addr_lo =
17476 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
17477 		sgl_pg_pairs->sgl_pg0_addr_hi =
17478 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
17479 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
17480 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
17481 						SGL_PAGE_SIZE;
17482 		else
17483 			pdma_phys_bpl1 = 0;
17484 		sgl_pg_pairs->sgl_pg1_addr_lo =
17485 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
17486 		sgl_pg_pairs->sgl_pg1_addr_hi =
17487 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
17488 		/* Keep the first xritag on the list */
17489 		if (pg_pairs == 0)
17490 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
17491 		sgl_pg_pairs++;
17492 		pg_pairs++;
17493 	}
17494 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
17495 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
17496 	/* Perform endian conversion if necessary */
17497 	sgl->word0 = cpu_to_le32(sgl->word0);
17498 
17499 	if (!phba->sli4_hba.intr_enable) {
17500 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17501 	} else {
17502 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17503 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17504 	}
17505 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
17506 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17507 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17508 	if (!phba->sli4_hba.intr_enable)
17509 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17510 	else if (rc != MBX_TIMEOUT)
17511 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17512 	if (shdr_status || shdr_add_status || rc) {
17513 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17514 				"6125 POST_SGL_BLOCK mailbox command failed "
17515 				"status x%x add_status x%x mbx status x%x\n",
17516 				shdr_status, shdr_add_status, rc);
17517 		rc = -ENXIO;
17518 	}
17519 	return rc;
17520 }
17521 
17522 /**
17523  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
17524  * @phba: pointer to lpfc hba data structure.
17525  * @post_nblist: pointer to the nvme buffer list.
17526  * @sb_count: number of nvme buffers.
17527  *
17528  * This routine walks a list of nvme buffers that was passed in. It attempts
17529  * to construct blocks of nvme buffer sgls which contains contiguous xris and
17530  * uses the non-embedded SGL block post mailbox commands to post to the port.
17531  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
17532  * embedded SGL post mailbox command for posting. The @post_nblist passed in
17533  * must be local list, thus no lock is needed when manipulate the list.
17534  *
17535  * Returns: 0 = failure, non-zero number of successfully posted buffers.
17536  **/
17537 int
17538 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
17539 			   struct list_head *post_nblist, int sb_count)
17540 {
17541 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
17542 	int status, sgl_size;
17543 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
17544 	dma_addr_t pdma_phys_sgl1;
17545 	int last_xritag = NO_XRI;
17546 	int cur_xritag;
17547 	LIST_HEAD(prep_nblist);
17548 	LIST_HEAD(blck_nblist);
17549 	LIST_HEAD(nvme_nblist);
17550 
17551 	/* sanity check */
17552 	if (sb_count <= 0)
17553 		return -EINVAL;
17554 
17555 	sgl_size = phba->cfg_sg_dma_buf_size;
17556 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
17557 		list_del_init(&lpfc_ncmd->list);
17558 		block_cnt++;
17559 		if ((last_xritag != NO_XRI) &&
17560 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
17561 			/* a hole in xri block, form a sgl posting block */
17562 			list_splice_init(&prep_nblist, &blck_nblist);
17563 			post_cnt = block_cnt - 1;
17564 			/* prepare list for next posting block */
17565 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17566 			block_cnt = 1;
17567 		} else {
17568 			/* prepare list for next posting block */
17569 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17570 			/* enough sgls for non-embed sgl mbox command */
17571 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
17572 				list_splice_init(&prep_nblist, &blck_nblist);
17573 				post_cnt = block_cnt;
17574 				block_cnt = 0;
17575 			}
17576 		}
17577 		num_posting++;
17578 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17579 
17580 		/* end of repost sgl list condition for NVME buffers */
17581 		if (num_posting == sb_count) {
17582 			if (post_cnt == 0) {
17583 				/* last sgl posting block */
17584 				list_splice_init(&prep_nblist, &blck_nblist);
17585 				post_cnt = block_cnt;
17586 			} else if (block_cnt == 1) {
17587 				/* last single sgl with non-contiguous xri */
17588 				if (sgl_size > SGL_PAGE_SIZE)
17589 					pdma_phys_sgl1 =
17590 						lpfc_ncmd->dma_phys_sgl +
17591 						SGL_PAGE_SIZE;
17592 				else
17593 					pdma_phys_sgl1 = 0;
17594 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17595 				status = lpfc_sli4_post_sgl(
17596 						phba, lpfc_ncmd->dma_phys_sgl,
17597 						pdma_phys_sgl1, cur_xritag);
17598 				if (status) {
17599 					/* Post error.  Buffer unavailable. */
17600 					lpfc_ncmd->flags |=
17601 						LPFC_SBUF_NOT_POSTED;
17602 				} else {
17603 					/* Post success. Bffer available. */
17604 					lpfc_ncmd->flags &=
17605 						~LPFC_SBUF_NOT_POSTED;
17606 					lpfc_ncmd->status = IOSTAT_SUCCESS;
17607 					num_posted++;
17608 				}
17609 				/* success, put on NVME buffer sgl list */
17610 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17611 			}
17612 		}
17613 
17614 		/* continue until a nembed page worth of sgls */
17615 		if (post_cnt == 0)
17616 			continue;
17617 
17618 		/* post block of NVME buffer list sgls */
17619 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
17620 						     post_cnt);
17621 
17622 		/* don't reset xirtag due to hole in xri block */
17623 		if (block_cnt == 0)
17624 			last_xritag = NO_XRI;
17625 
17626 		/* reset NVME buffer post count for next round of posting */
17627 		post_cnt = 0;
17628 
17629 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
17630 		while (!list_empty(&blck_nblist)) {
17631 			list_remove_head(&blck_nblist, lpfc_ncmd,
17632 					 struct lpfc_io_buf, list);
17633 			if (status) {
17634 				/* Post error.  Mark buffer unavailable. */
17635 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
17636 			} else {
17637 				/* Post success, Mark buffer available. */
17638 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
17639 				lpfc_ncmd->status = IOSTAT_SUCCESS;
17640 				num_posted++;
17641 			}
17642 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17643 		}
17644 	}
17645 	/* Push NVME buffers with sgl posted to the available list */
17646 	lpfc_io_buf_replenish(phba, &nvme_nblist);
17647 
17648 	return num_posted;
17649 }
17650 
17651 /**
17652  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
17653  * @phba: pointer to lpfc_hba struct that the frame was received on
17654  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17655  *
17656  * This function checks the fields in the @fc_hdr to see if the FC frame is a
17657  * valid type of frame that the LPFC driver will handle. This function will
17658  * return a zero if the frame is a valid frame or a non zero value when the
17659  * frame does not pass the check.
17660  **/
17661 static int
17662 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
17663 {
17664 	/*  make rctl_names static to save stack space */
17665 	struct fc_vft_header *fc_vft_hdr;
17666 	uint32_t *header = (uint32_t *) fc_hdr;
17667 
17668 #define FC_RCTL_MDS_DIAGS	0xF4
17669 
17670 	switch (fc_hdr->fh_r_ctl) {
17671 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
17672 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
17673 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
17674 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
17675 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
17676 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
17677 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
17678 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
17679 	case FC_RCTL_ELS_REQ:	/* extended link services request */
17680 	case FC_RCTL_ELS_REP:	/* extended link services reply */
17681 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
17682 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
17683 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
17684 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
17685 	case FC_RCTL_BA_RMC: 	/* remove connection */
17686 	case FC_RCTL_BA_ACC:	/* basic accept */
17687 	case FC_RCTL_BA_RJT:	/* basic reject */
17688 	case FC_RCTL_BA_PRMT:
17689 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
17690 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
17691 	case FC_RCTL_P_RJT:	/* port reject */
17692 	case FC_RCTL_F_RJT:	/* fabric reject */
17693 	case FC_RCTL_P_BSY:	/* port busy */
17694 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
17695 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
17696 	case FC_RCTL_LCR:	/* link credit reset */
17697 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
17698 	case FC_RCTL_END:	/* end */
17699 		break;
17700 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
17701 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17702 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
17703 		return lpfc_fc_frame_check(phba, fc_hdr);
17704 	default:
17705 		goto drop;
17706 	}
17707 
17708 	switch (fc_hdr->fh_type) {
17709 	case FC_TYPE_BLS:
17710 	case FC_TYPE_ELS:
17711 	case FC_TYPE_FCP:
17712 	case FC_TYPE_CT:
17713 	case FC_TYPE_NVME:
17714 		break;
17715 	case FC_TYPE_IP:
17716 	case FC_TYPE_ILS:
17717 	default:
17718 		goto drop;
17719 	}
17720 
17721 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
17722 			"2538 Received frame rctl:x%x, type:x%x, "
17723 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
17724 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
17725 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
17726 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
17727 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
17728 			be32_to_cpu(header[6]));
17729 	return 0;
17730 drop:
17731 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
17732 			"2539 Dropped frame rctl:x%x type:x%x\n",
17733 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17734 	return 1;
17735 }
17736 
17737 /**
17738  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
17739  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17740  *
17741  * This function processes the FC header to retrieve the VFI from the VF
17742  * header, if one exists. This function will return the VFI if one exists
17743  * or 0 if no VSAN Header exists.
17744  **/
17745 static uint32_t
17746 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
17747 {
17748 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17749 
17750 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
17751 		return 0;
17752 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
17753 }
17754 
17755 /**
17756  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
17757  * @phba: Pointer to the HBA structure to search for the vport on
17758  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17759  * @fcfi: The FC Fabric ID that the frame came from
17760  * @did: Destination ID to match against
17761  *
17762  * This function searches the @phba for a vport that matches the content of the
17763  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
17764  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
17765  * returns the matching vport pointer or NULL if unable to match frame to a
17766  * vport.
17767  **/
17768 static struct lpfc_vport *
17769 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
17770 		       uint16_t fcfi, uint32_t did)
17771 {
17772 	struct lpfc_vport **vports;
17773 	struct lpfc_vport *vport = NULL;
17774 	int i;
17775 
17776 	if (did == Fabric_DID)
17777 		return phba->pport;
17778 	if ((phba->pport->fc_flag & FC_PT2PT) &&
17779 		!(phba->link_state == LPFC_HBA_READY))
17780 		return phba->pport;
17781 
17782 	vports = lpfc_create_vport_work_array(phba);
17783 	if (vports != NULL) {
17784 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
17785 			if (phba->fcf.fcfi == fcfi &&
17786 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
17787 			    vports[i]->fc_myDID == did) {
17788 				vport = vports[i];
17789 				break;
17790 			}
17791 		}
17792 	}
17793 	lpfc_destroy_vport_work_array(phba, vports);
17794 	return vport;
17795 }
17796 
17797 /**
17798  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
17799  * @vport: The vport to work on.
17800  *
17801  * This function updates the receive sequence time stamp for this vport. The
17802  * receive sequence time stamp indicates the time that the last frame of the
17803  * the sequence that has been idle for the longest amount of time was received.
17804  * the driver uses this time stamp to indicate if any received sequences have
17805  * timed out.
17806  **/
17807 static void
17808 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
17809 {
17810 	struct lpfc_dmabuf *h_buf;
17811 	struct hbq_dmabuf *dmabuf = NULL;
17812 
17813 	/* get the oldest sequence on the rcv list */
17814 	h_buf = list_get_first(&vport->rcv_buffer_list,
17815 			       struct lpfc_dmabuf, list);
17816 	if (!h_buf)
17817 		return;
17818 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17819 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
17820 }
17821 
17822 /**
17823  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
17824  * @vport: The vport that the received sequences were sent to.
17825  *
17826  * This function cleans up all outstanding received sequences. This is called
17827  * by the driver when a link event or user action invalidates all the received
17828  * sequences.
17829  **/
17830 void
17831 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
17832 {
17833 	struct lpfc_dmabuf *h_buf, *hnext;
17834 	struct lpfc_dmabuf *d_buf, *dnext;
17835 	struct hbq_dmabuf *dmabuf = NULL;
17836 
17837 	/* start with the oldest sequence on the rcv list */
17838 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17839 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17840 		list_del_init(&dmabuf->hbuf.list);
17841 		list_for_each_entry_safe(d_buf, dnext,
17842 					 &dmabuf->dbuf.list, list) {
17843 			list_del_init(&d_buf->list);
17844 			lpfc_in_buf_free(vport->phba, d_buf);
17845 		}
17846 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17847 	}
17848 }
17849 
17850 /**
17851  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
17852  * @vport: The vport that the received sequences were sent to.
17853  *
17854  * This function determines whether any received sequences have timed out by
17855  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
17856  * indicates that there is at least one timed out sequence this routine will
17857  * go through the received sequences one at a time from most inactive to most
17858  * active to determine which ones need to be cleaned up. Once it has determined
17859  * that a sequence needs to be cleaned up it will simply free up the resources
17860  * without sending an abort.
17861  **/
17862 void
17863 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
17864 {
17865 	struct lpfc_dmabuf *h_buf, *hnext;
17866 	struct lpfc_dmabuf *d_buf, *dnext;
17867 	struct hbq_dmabuf *dmabuf = NULL;
17868 	unsigned long timeout;
17869 	int abort_count = 0;
17870 
17871 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17872 		   vport->rcv_buffer_time_stamp);
17873 	if (list_empty(&vport->rcv_buffer_list) ||
17874 	    time_before(jiffies, timeout))
17875 		return;
17876 	/* start with the oldest sequence on the rcv list */
17877 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17878 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17879 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17880 			   dmabuf->time_stamp);
17881 		if (time_before(jiffies, timeout))
17882 			break;
17883 		abort_count++;
17884 		list_del_init(&dmabuf->hbuf.list);
17885 		list_for_each_entry_safe(d_buf, dnext,
17886 					 &dmabuf->dbuf.list, list) {
17887 			list_del_init(&d_buf->list);
17888 			lpfc_in_buf_free(vport->phba, d_buf);
17889 		}
17890 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17891 	}
17892 	if (abort_count)
17893 		lpfc_update_rcv_time_stamp(vport);
17894 }
17895 
17896 /**
17897  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
17898  * @vport: pointer to a vitural port
17899  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
17900  *
17901  * This function searches through the existing incomplete sequences that have
17902  * been sent to this @vport. If the frame matches one of the incomplete
17903  * sequences then the dbuf in the @dmabuf is added to the list of frames that
17904  * make up that sequence. If no sequence is found that matches this frame then
17905  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
17906  * This function returns a pointer to the first dmabuf in the sequence list that
17907  * the frame was linked to.
17908  **/
17909 static struct hbq_dmabuf *
17910 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
17911 {
17912 	struct fc_frame_header *new_hdr;
17913 	struct fc_frame_header *temp_hdr;
17914 	struct lpfc_dmabuf *d_buf;
17915 	struct lpfc_dmabuf *h_buf;
17916 	struct hbq_dmabuf *seq_dmabuf = NULL;
17917 	struct hbq_dmabuf *temp_dmabuf = NULL;
17918 	uint8_t	found = 0;
17919 
17920 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
17921 	dmabuf->time_stamp = jiffies;
17922 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17923 
17924 	/* Use the hdr_buf to find the sequence that this frame belongs to */
17925 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
17926 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
17927 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
17928 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
17929 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
17930 			continue;
17931 		/* found a pending sequence that matches this frame */
17932 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17933 		break;
17934 	}
17935 	if (!seq_dmabuf) {
17936 		/*
17937 		 * This indicates first frame received for this sequence.
17938 		 * Queue the buffer on the vport's rcv_buffer_list.
17939 		 */
17940 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17941 		lpfc_update_rcv_time_stamp(vport);
17942 		return dmabuf;
17943 	}
17944 	temp_hdr = seq_dmabuf->hbuf.virt;
17945 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
17946 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17947 		list_del_init(&seq_dmabuf->hbuf.list);
17948 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17949 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17950 		lpfc_update_rcv_time_stamp(vport);
17951 		return dmabuf;
17952 	}
17953 	/* move this sequence to the tail to indicate a young sequence */
17954 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
17955 	seq_dmabuf->time_stamp = jiffies;
17956 	lpfc_update_rcv_time_stamp(vport);
17957 	if (list_empty(&seq_dmabuf->dbuf.list)) {
17958 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17959 		return seq_dmabuf;
17960 	}
17961 	/* find the correct place in the sequence to insert this frame */
17962 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
17963 	while (!found) {
17964 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17965 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
17966 		/*
17967 		 * If the frame's sequence count is greater than the frame on
17968 		 * the list then insert the frame right after this frame
17969 		 */
17970 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
17971 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17972 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
17973 			found = 1;
17974 			break;
17975 		}
17976 
17977 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
17978 			break;
17979 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
17980 	}
17981 
17982 	if (found)
17983 		return seq_dmabuf;
17984 	return NULL;
17985 }
17986 
17987 /**
17988  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
17989  * @vport: pointer to a vitural port
17990  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17991  *
17992  * This function tries to abort from the partially assembed sequence, described
17993  * by the information from basic abbort @dmabuf. It checks to see whether such
17994  * partially assembled sequence held by the driver. If so, it shall free up all
17995  * the frames from the partially assembled sequence.
17996  *
17997  * Return
17998  * true  -- if there is matching partially assembled sequence present and all
17999  *          the frames freed with the sequence;
18000  * false -- if there is no matching partially assembled sequence present so
18001  *          nothing got aborted in the lower layer driver
18002  **/
18003 static bool
18004 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
18005 			    struct hbq_dmabuf *dmabuf)
18006 {
18007 	struct fc_frame_header *new_hdr;
18008 	struct fc_frame_header *temp_hdr;
18009 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
18010 	struct hbq_dmabuf *seq_dmabuf = NULL;
18011 
18012 	/* Use the hdr_buf to find the sequence that matches this frame */
18013 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18014 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
18015 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18016 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18017 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18018 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18019 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18020 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18021 			continue;
18022 		/* found a pending sequence that matches this frame */
18023 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18024 		break;
18025 	}
18026 
18027 	/* Free up all the frames from the partially assembled sequence */
18028 	if (seq_dmabuf) {
18029 		list_for_each_entry_safe(d_buf, n_buf,
18030 					 &seq_dmabuf->dbuf.list, list) {
18031 			list_del_init(&d_buf->list);
18032 			lpfc_in_buf_free(vport->phba, d_buf);
18033 		}
18034 		return true;
18035 	}
18036 	return false;
18037 }
18038 
18039 /**
18040  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18041  * @vport: pointer to a vitural port
18042  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18043  *
18044  * This function tries to abort from the assembed sequence from upper level
18045  * protocol, described by the information from basic abbort @dmabuf. It
18046  * checks to see whether such pending context exists at upper level protocol.
18047  * If so, it shall clean up the pending context.
18048  *
18049  * Return
18050  * true  -- if there is matching pending context of the sequence cleaned
18051  *          at ulp;
18052  * false -- if there is no matching pending context of the sequence present
18053  *          at ulp.
18054  **/
18055 static bool
18056 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18057 {
18058 	struct lpfc_hba *phba = vport->phba;
18059 	int handled;
18060 
18061 	/* Accepting abort at ulp with SLI4 only */
18062 	if (phba->sli_rev < LPFC_SLI_REV4)
18063 		return false;
18064 
18065 	/* Register all caring upper level protocols to attend abort */
18066 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18067 	if (handled)
18068 		return true;
18069 
18070 	return false;
18071 }
18072 
18073 /**
18074  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18075  * @phba: Pointer to HBA context object.
18076  * @cmd_iocbq: pointer to the command iocbq structure.
18077  * @rsp_iocbq: pointer to the response iocbq structure.
18078  *
18079  * This function handles the sequence abort response iocb command complete
18080  * event. It properly releases the memory allocated to the sequence abort
18081  * accept iocb.
18082  **/
18083 static void
18084 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18085 			     struct lpfc_iocbq *cmd_iocbq,
18086 			     struct lpfc_iocbq *rsp_iocbq)
18087 {
18088 	struct lpfc_nodelist *ndlp;
18089 
18090 	if (cmd_iocbq) {
18091 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
18092 		lpfc_nlp_put(ndlp);
18093 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
18094 	}
18095 
18096 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
18097 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18098 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18099 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
18100 			rsp_iocbq->iocb.ulpStatus,
18101 			rsp_iocbq->iocb.un.ulpWord[4]);
18102 }
18103 
18104 /**
18105  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
18106  * @phba: Pointer to HBA context object.
18107  * @xri: xri id in transaction.
18108  *
18109  * This function validates the xri maps to the known range of XRIs allocated an
18110  * used by the driver.
18111  **/
18112 uint16_t
18113 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
18114 		      uint16_t xri)
18115 {
18116 	uint16_t i;
18117 
18118 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
18119 		if (xri == phba->sli4_hba.xri_ids[i])
18120 			return i;
18121 	}
18122 	return NO_XRI;
18123 }
18124 
18125 /**
18126  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
18127  * @vport: pointer to a virtual port.
18128  * @fc_hdr: pointer to a FC frame header.
18129  * @aborted: was the partially assembled receive sequence successfully aborted
18130  *
18131  * This function sends a basic response to a previous unsol sequence abort
18132  * event after aborting the sequence handling.
18133  **/
18134 void
18135 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
18136 			struct fc_frame_header *fc_hdr, bool aborted)
18137 {
18138 	struct lpfc_hba *phba = vport->phba;
18139 	struct lpfc_iocbq *ctiocb = NULL;
18140 	struct lpfc_nodelist *ndlp;
18141 	uint16_t oxid, rxid, xri, lxri;
18142 	uint32_t sid, fctl;
18143 	IOCB_t *icmd;
18144 	int rc;
18145 
18146 	if (!lpfc_is_link_up(phba))
18147 		return;
18148 
18149 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18150 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
18151 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
18152 
18153 	ndlp = lpfc_findnode_did(vport, sid);
18154 	if (!ndlp) {
18155 		ndlp = lpfc_nlp_init(vport, sid);
18156 		if (!ndlp) {
18157 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
18158 					 "1268 Failed to allocate ndlp for "
18159 					 "oxid:x%x SID:x%x\n", oxid, sid);
18160 			return;
18161 		}
18162 		/* Put ndlp onto pport node list */
18163 		lpfc_enqueue_node(vport, ndlp);
18164 	}
18165 
18166 	/* Allocate buffer for rsp iocb */
18167 	ctiocb = lpfc_sli_get_iocbq(phba);
18168 	if (!ctiocb)
18169 		return;
18170 
18171 	/* Extract the F_CTL field from FC_HDR */
18172 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
18173 
18174 	icmd = &ctiocb->iocb;
18175 	icmd->un.xseq64.bdl.bdeSize = 0;
18176 	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
18177 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
18178 	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
18179 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
18180 
18181 	/* Fill in the rest of iocb fields */
18182 	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
18183 	icmd->ulpBdeCount = 0;
18184 	icmd->ulpLe = 1;
18185 	icmd->ulpClass = CLASS3;
18186 	icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
18187 	ctiocb->context1 = lpfc_nlp_get(ndlp);
18188 	if (!ctiocb->context1) {
18189 		lpfc_sli_release_iocbq(phba, ctiocb);
18190 		return;
18191 	}
18192 
18193 	ctiocb->vport = phba->pport;
18194 	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
18195 	ctiocb->sli4_lxritag = NO_XRI;
18196 	ctiocb->sli4_xritag = NO_XRI;
18197 
18198 	if (fctl & FC_FC_EX_CTX)
18199 		/* Exchange responder sent the abort so we
18200 		 * own the oxid.
18201 		 */
18202 		xri = oxid;
18203 	else
18204 		xri = rxid;
18205 	lxri = lpfc_sli4_xri_inrange(phba, xri);
18206 	if (lxri != NO_XRI)
18207 		lpfc_set_rrq_active(phba, ndlp, lxri,
18208 			(xri == oxid) ? rxid : oxid, 0);
18209 	/* For BA_ABTS from exchange responder, if the logical xri with
18210 	 * the oxid maps to the FCP XRI range, the port no longer has
18211 	 * that exchange context, send a BLS_RJT. Override the IOCB for
18212 	 * a BA_RJT.
18213 	 */
18214 	if ((fctl & FC_FC_EX_CTX) &&
18215 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
18216 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
18217 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
18218 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
18219 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
18220 	}
18221 
18222 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
18223 	 * the driver no longer has that exchange, send a BLS_RJT. Override
18224 	 * the IOCB for a BA_RJT.
18225 	 */
18226 	if (aborted == false) {
18227 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
18228 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
18229 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
18230 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
18231 	}
18232 
18233 	if (fctl & FC_FC_EX_CTX) {
18234 		/* ABTS sent by responder to CT exchange, construction
18235 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
18236 		 * field and RX_ID from ABTS for RX_ID field.
18237 		 */
18238 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
18239 	} else {
18240 		/* ABTS sent by initiator to CT exchange, construction
18241 		 * of BA_ACC will need to allocate a new XRI as for the
18242 		 * XRI_TAG field.
18243 		 */
18244 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
18245 	}
18246 	bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
18247 	bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
18248 
18249 	/* Xmit CT abts response on exchange <xid> */
18250 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
18251 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
18252 			 icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
18253 
18254 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
18255 	if (rc == IOCB_ERROR) {
18256 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
18257 				 "2925 Failed to issue CT ABTS RSP x%x on "
18258 				 "xri x%x, Data x%x\n",
18259 				 icmd->un.xseq64.w5.hcsw.Rctl, oxid,
18260 				 phba->link_state);
18261 		lpfc_nlp_put(ndlp);
18262 		ctiocb->context1 = NULL;
18263 		lpfc_sli_release_iocbq(phba, ctiocb);
18264 	}
18265 }
18266 
18267 /**
18268  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
18269  * @vport: Pointer to the vport on which this sequence was received
18270  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18271  *
18272  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
18273  * receive sequence is only partially assembed by the driver, it shall abort
18274  * the partially assembled frames for the sequence. Otherwise, if the
18275  * unsolicited receive sequence has been completely assembled and passed to
18276  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
18277  * unsolicited sequence has been aborted. After that, it will issue a basic
18278  * accept to accept the abort.
18279  **/
18280 static void
18281 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
18282 			     struct hbq_dmabuf *dmabuf)
18283 {
18284 	struct lpfc_hba *phba = vport->phba;
18285 	struct fc_frame_header fc_hdr;
18286 	uint32_t fctl;
18287 	bool aborted;
18288 
18289 	/* Make a copy of fc_hdr before the dmabuf being released */
18290 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
18291 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
18292 
18293 	if (fctl & FC_FC_EX_CTX) {
18294 		/* ABTS by responder to exchange, no cleanup needed */
18295 		aborted = true;
18296 	} else {
18297 		/* ABTS by initiator to exchange, need to do cleanup */
18298 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
18299 		if (aborted == false)
18300 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
18301 	}
18302 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18303 
18304 	if (phba->nvmet_support) {
18305 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
18306 		return;
18307 	}
18308 
18309 	/* Respond with BA_ACC or BA_RJT accordingly */
18310 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
18311 }
18312 
18313 /**
18314  * lpfc_seq_complete - Indicates if a sequence is complete
18315  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18316  *
18317  * This function checks the sequence, starting with the frame described by
18318  * @dmabuf, to see if all the frames associated with this sequence are present.
18319  * the frames associated with this sequence are linked to the @dmabuf using the
18320  * dbuf list. This function looks for two major things. 1) That the first frame
18321  * has a sequence count of zero. 2) There is a frame with last frame of sequence
18322  * set. 3) That there are no holes in the sequence count. The function will
18323  * return 1 when the sequence is complete, otherwise it will return 0.
18324  **/
18325 static int
18326 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
18327 {
18328 	struct fc_frame_header *hdr;
18329 	struct lpfc_dmabuf *d_buf;
18330 	struct hbq_dmabuf *seq_dmabuf;
18331 	uint32_t fctl;
18332 	int seq_count = 0;
18333 
18334 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18335 	/* make sure first fame of sequence has a sequence count of zero */
18336 	if (hdr->fh_seq_cnt != seq_count)
18337 		return 0;
18338 	fctl = (hdr->fh_f_ctl[0] << 16 |
18339 		hdr->fh_f_ctl[1] << 8 |
18340 		hdr->fh_f_ctl[2]);
18341 	/* If last frame of sequence we can return success. */
18342 	if (fctl & FC_FC_END_SEQ)
18343 		return 1;
18344 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
18345 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18346 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18347 		/* If there is a hole in the sequence count then fail. */
18348 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
18349 			return 0;
18350 		fctl = (hdr->fh_f_ctl[0] << 16 |
18351 			hdr->fh_f_ctl[1] << 8 |
18352 			hdr->fh_f_ctl[2]);
18353 		/* If last frame of sequence we can return success. */
18354 		if (fctl & FC_FC_END_SEQ)
18355 			return 1;
18356 	}
18357 	return 0;
18358 }
18359 
18360 /**
18361  * lpfc_prep_seq - Prep sequence for ULP processing
18362  * @vport: Pointer to the vport on which this sequence was received
18363  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
18364  *
18365  * This function takes a sequence, described by a list of frames, and creates
18366  * a list of iocbq structures to describe the sequence. This iocbq list will be
18367  * used to issue to the generic unsolicited sequence handler. This routine
18368  * returns a pointer to the first iocbq in the list. If the function is unable
18369  * to allocate an iocbq then it throw out the received frames that were not
18370  * able to be described and return a pointer to the first iocbq. If unable to
18371  * allocate any iocbqs (including the first) this function will return NULL.
18372  **/
18373 static struct lpfc_iocbq *
18374 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
18375 {
18376 	struct hbq_dmabuf *hbq_buf;
18377 	struct lpfc_dmabuf *d_buf, *n_buf;
18378 	struct lpfc_iocbq *first_iocbq, *iocbq;
18379 	struct fc_frame_header *fc_hdr;
18380 	uint32_t sid;
18381 	uint32_t len, tot_len;
18382 	struct ulp_bde64 *pbde;
18383 
18384 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18385 	/* remove from receive buffer list */
18386 	list_del_init(&seq_dmabuf->hbuf.list);
18387 	lpfc_update_rcv_time_stamp(vport);
18388 	/* get the Remote Port's SID */
18389 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18390 	tot_len = 0;
18391 	/* Get an iocbq struct to fill in. */
18392 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
18393 	if (first_iocbq) {
18394 		/* Initialize the first IOCB. */
18395 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
18396 		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
18397 		first_iocbq->vport = vport;
18398 
18399 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
18400 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
18401 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
18402 			first_iocbq->iocb.un.rcvels.parmRo =
18403 				sli4_did_from_fc_hdr(fc_hdr);
18404 			first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
18405 		} else
18406 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
18407 		first_iocbq->iocb.ulpContext = NO_XRI;
18408 		first_iocbq->iocb.unsli3.rcvsli3.ox_id =
18409 			be16_to_cpu(fc_hdr->fh_ox_id);
18410 		/* iocbq is prepped for internal consumption.  Physical vpi. */
18411 		first_iocbq->iocb.unsli3.rcvsli3.vpi =
18412 			vport->phba->vpi_ids[vport->vpi];
18413 		/* put the first buffer into the first IOCBq */
18414 		tot_len = bf_get(lpfc_rcqe_length,
18415 				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
18416 
18417 		first_iocbq->context2 = &seq_dmabuf->dbuf;
18418 		first_iocbq->context3 = NULL;
18419 		first_iocbq->iocb.ulpBdeCount = 1;
18420 		if (tot_len > LPFC_DATA_BUF_SIZE)
18421 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
18422 							LPFC_DATA_BUF_SIZE;
18423 		else
18424 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
18425 
18426 		first_iocbq->iocb.un.rcvels.remoteID = sid;
18427 
18428 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
18429 	}
18430 	iocbq = first_iocbq;
18431 	/*
18432 	 * Each IOCBq can have two Buffers assigned, so go through the list
18433 	 * of buffers for this sequence and save two buffers in each IOCBq
18434 	 */
18435 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
18436 		if (!iocbq) {
18437 			lpfc_in_buf_free(vport->phba, d_buf);
18438 			continue;
18439 		}
18440 		if (!iocbq->context3) {
18441 			iocbq->context3 = d_buf;
18442 			iocbq->iocb.ulpBdeCount++;
18443 			/* We need to get the size out of the right CQE */
18444 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18445 			len = bf_get(lpfc_rcqe_length,
18446 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
18447 			pbde = (struct ulp_bde64 *)
18448 					&iocbq->iocb.unsli3.sli3Words[4];
18449 			if (len > LPFC_DATA_BUF_SIZE)
18450 				pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
18451 			else
18452 				pbde->tus.f.bdeSize = len;
18453 
18454 			iocbq->iocb.unsli3.rcvsli3.acc_len += len;
18455 			tot_len += len;
18456 		} else {
18457 			iocbq = lpfc_sli_get_iocbq(vport->phba);
18458 			if (!iocbq) {
18459 				if (first_iocbq) {
18460 					first_iocbq->iocb.ulpStatus =
18461 							IOSTAT_FCP_RSP_ERROR;
18462 					first_iocbq->iocb.un.ulpWord[4] =
18463 							IOERR_NO_RESOURCES;
18464 				}
18465 				lpfc_in_buf_free(vport->phba, d_buf);
18466 				continue;
18467 			}
18468 			/* We need to get the size out of the right CQE */
18469 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18470 			len = bf_get(lpfc_rcqe_length,
18471 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
18472 			iocbq->context2 = d_buf;
18473 			iocbq->context3 = NULL;
18474 			iocbq->iocb.ulpBdeCount = 1;
18475 			if (len > LPFC_DATA_BUF_SIZE)
18476 				iocbq->iocb.un.cont64[0].tus.f.bdeSize =
18477 							LPFC_DATA_BUF_SIZE;
18478 			else
18479 				iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
18480 
18481 			tot_len += len;
18482 			iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
18483 
18484 			iocbq->iocb.un.rcvels.remoteID = sid;
18485 			list_add_tail(&iocbq->list, &first_iocbq->list);
18486 		}
18487 	}
18488 	/* Free the sequence's header buffer */
18489 	if (!first_iocbq)
18490 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
18491 
18492 	return first_iocbq;
18493 }
18494 
18495 static void
18496 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
18497 			  struct hbq_dmabuf *seq_dmabuf)
18498 {
18499 	struct fc_frame_header *fc_hdr;
18500 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
18501 	struct lpfc_hba *phba = vport->phba;
18502 
18503 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18504 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
18505 	if (!iocbq) {
18506 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18507 				"2707 Ring %d handler: Failed to allocate "
18508 				"iocb Rctl x%x Type x%x received\n",
18509 				LPFC_ELS_RING,
18510 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18511 		return;
18512 	}
18513 	if (!lpfc_complete_unsol_iocb(phba,
18514 				      phba->sli4_hba.els_wq->pring,
18515 				      iocbq, fc_hdr->fh_r_ctl,
18516 				      fc_hdr->fh_type))
18517 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18518 				"2540 Ring %d handler: unexpected Rctl "
18519 				"x%x Type x%x received\n",
18520 				LPFC_ELS_RING,
18521 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18522 
18523 	/* Free iocb created in lpfc_prep_seq */
18524 	list_for_each_entry_safe(curr_iocb, next_iocb,
18525 		&iocbq->list, list) {
18526 		list_del_init(&curr_iocb->list);
18527 		lpfc_sli_release_iocbq(phba, curr_iocb);
18528 	}
18529 	lpfc_sli_release_iocbq(phba, iocbq);
18530 }
18531 
18532 static void
18533 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
18534 			    struct lpfc_iocbq *rspiocb)
18535 {
18536 	struct lpfc_dmabuf *pcmd = cmdiocb->context2;
18537 
18538 	if (pcmd && pcmd->virt)
18539 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18540 	kfree(pcmd);
18541 	lpfc_sli_release_iocbq(phba, cmdiocb);
18542 	lpfc_drain_txq(phba);
18543 }
18544 
18545 static void
18546 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
18547 			      struct hbq_dmabuf *dmabuf)
18548 {
18549 	struct fc_frame_header *fc_hdr;
18550 	struct lpfc_hba *phba = vport->phba;
18551 	struct lpfc_iocbq *iocbq = NULL;
18552 	union  lpfc_wqe *wqe;
18553 	struct lpfc_dmabuf *pcmd = NULL;
18554 	uint32_t frame_len;
18555 	int rc;
18556 	unsigned long iflags;
18557 
18558 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18559 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
18560 
18561 	/* Send the received frame back */
18562 	iocbq = lpfc_sli_get_iocbq(phba);
18563 	if (!iocbq) {
18564 		/* Queue cq event and wakeup worker thread to process it */
18565 		spin_lock_irqsave(&phba->hbalock, iflags);
18566 		list_add_tail(&dmabuf->cq_event.list,
18567 			      &phba->sli4_hba.sp_queue_event);
18568 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
18569 		spin_unlock_irqrestore(&phba->hbalock, iflags);
18570 		lpfc_worker_wake_up(phba);
18571 		return;
18572 	}
18573 
18574 	/* Allocate buffer for command payload */
18575 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
18576 	if (pcmd)
18577 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
18578 					    &pcmd->phys);
18579 	if (!pcmd || !pcmd->virt)
18580 		goto exit;
18581 
18582 	INIT_LIST_HEAD(&pcmd->list);
18583 
18584 	/* copyin the payload */
18585 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
18586 
18587 	/* fill in BDE's for command */
18588 	iocbq->iocb.un.xseq64.bdl.addrHigh = putPaddrHigh(pcmd->phys);
18589 	iocbq->iocb.un.xseq64.bdl.addrLow = putPaddrLow(pcmd->phys);
18590 	iocbq->iocb.un.xseq64.bdl.bdeFlags = BUFF_TYPE_BDE_64;
18591 	iocbq->iocb.un.xseq64.bdl.bdeSize = frame_len;
18592 
18593 	iocbq->context2 = pcmd;
18594 	iocbq->vport = vport;
18595 	iocbq->iocb_flag &= ~LPFC_FIP_ELS_ID_MASK;
18596 	iocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
18597 
18598 	/*
18599 	 * Setup rest of the iocb as though it were a WQE
18600 	 * Build the SEND_FRAME WQE
18601 	 */
18602 	wqe = (union lpfc_wqe *)&iocbq->iocb;
18603 
18604 	wqe->send_frame.frame_len = frame_len;
18605 	wqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((uint32_t *)fc_hdr));
18606 	wqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((uint32_t *)fc_hdr + 1));
18607 	wqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((uint32_t *)fc_hdr + 2));
18608 	wqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((uint32_t *)fc_hdr + 3));
18609 	wqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((uint32_t *)fc_hdr + 4));
18610 	wqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((uint32_t *)fc_hdr + 5));
18611 
18612 	iocbq->iocb.ulpCommand = CMD_SEND_FRAME;
18613 	iocbq->iocb.ulpLe = 1;
18614 	iocbq->iocb_cmpl = lpfc_sli4_mds_loopback_cmpl;
18615 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
18616 	if (rc == IOCB_ERROR)
18617 		goto exit;
18618 
18619 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18620 	return;
18621 
18622 exit:
18623 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18624 			"2023 Unable to process MDS loopback frame\n");
18625 	if (pcmd && pcmd->virt)
18626 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18627 	kfree(pcmd);
18628 	if (iocbq)
18629 		lpfc_sli_release_iocbq(phba, iocbq);
18630 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18631 }
18632 
18633 /**
18634  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
18635  * @phba: Pointer to HBA context object.
18636  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
18637  *
18638  * This function is called with no lock held. This function processes all
18639  * the received buffers and gives it to upper layers when a received buffer
18640  * indicates that it is the final frame in the sequence. The interrupt
18641  * service routine processes received buffers at interrupt contexts.
18642  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
18643  * appropriate receive function when the final frame in a sequence is received.
18644  **/
18645 void
18646 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
18647 				 struct hbq_dmabuf *dmabuf)
18648 {
18649 	struct hbq_dmabuf *seq_dmabuf;
18650 	struct fc_frame_header *fc_hdr;
18651 	struct lpfc_vport *vport;
18652 	uint32_t fcfi;
18653 	uint32_t did;
18654 
18655 	/* Process each received buffer */
18656 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18657 
18658 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
18659 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
18660 		vport = phba->pport;
18661 		/* Handle MDS Loopback frames */
18662 		if  (!(phba->pport->load_flag & FC_UNLOADING))
18663 			lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18664 		else
18665 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
18666 		return;
18667 	}
18668 
18669 	/* check to see if this a valid type of frame */
18670 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
18671 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18672 		return;
18673 	}
18674 
18675 	if ((bf_get(lpfc_cqe_code,
18676 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
18677 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
18678 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
18679 	else
18680 		fcfi = bf_get(lpfc_rcqe_fcf_id,
18681 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
18682 
18683 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
18684 		vport = phba->pport;
18685 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
18686 				"2023 MDS Loopback %d bytes\n",
18687 				bf_get(lpfc_rcqe_length,
18688 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
18689 		/* Handle MDS Loopback frames */
18690 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18691 		return;
18692 	}
18693 
18694 	/* d_id this frame is directed to */
18695 	did = sli4_did_from_fc_hdr(fc_hdr);
18696 
18697 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
18698 	if (!vport) {
18699 		/* throw out the frame */
18700 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18701 		return;
18702 	}
18703 
18704 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
18705 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
18706 		(did != Fabric_DID)) {
18707 		/*
18708 		 * Throw out the frame if we are not pt2pt.
18709 		 * The pt2pt protocol allows for discovery frames
18710 		 * to be received without a registered VPI.
18711 		 */
18712 		if (!(vport->fc_flag & FC_PT2PT) ||
18713 			(phba->link_state == LPFC_HBA_READY)) {
18714 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
18715 			return;
18716 		}
18717 	}
18718 
18719 	/* Handle the basic abort sequence (BA_ABTS) event */
18720 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
18721 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
18722 		return;
18723 	}
18724 
18725 	/* Link this frame */
18726 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
18727 	if (!seq_dmabuf) {
18728 		/* unable to add frame to vport - throw it out */
18729 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18730 		return;
18731 	}
18732 	/* If not last frame in sequence continue processing frames. */
18733 	if (!lpfc_seq_complete(seq_dmabuf))
18734 		return;
18735 
18736 	/* Send the complete sequence to the upper layer protocol */
18737 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
18738 }
18739 
18740 /**
18741  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
18742  * @phba: pointer to lpfc hba data structure.
18743  *
18744  * This routine is invoked to post rpi header templates to the
18745  * HBA consistent with the SLI-4 interface spec.  This routine
18746  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18747  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18748  *
18749  * This routine does not require any locks.  It's usage is expected
18750  * to be driver load or reset recovery when the driver is
18751  * sequential.
18752  *
18753  * Return codes
18754  * 	0 - successful
18755  *      -EIO - The mailbox failed to complete successfully.
18756  * 	When this error occurs, the driver is not guaranteed
18757  *	to have any rpi regions posted to the device and
18758  *	must either attempt to repost the regions or take a
18759  *	fatal error.
18760  **/
18761 int
18762 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
18763 {
18764 	struct lpfc_rpi_hdr *rpi_page;
18765 	uint32_t rc = 0;
18766 	uint16_t lrpi = 0;
18767 
18768 	/* SLI4 ports that support extents do not require RPI headers. */
18769 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18770 		goto exit;
18771 	if (phba->sli4_hba.extents_in_use)
18772 		return -EIO;
18773 
18774 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
18775 		/*
18776 		 * Assign the rpi headers a physical rpi only if the driver
18777 		 * has not initialized those resources.  A port reset only
18778 		 * needs the headers posted.
18779 		 */
18780 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
18781 		    LPFC_RPI_RSRC_RDY)
18782 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18783 
18784 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
18785 		if (rc != MBX_SUCCESS) {
18786 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18787 					"2008 Error %d posting all rpi "
18788 					"headers\n", rc);
18789 			rc = -EIO;
18790 			break;
18791 		}
18792 	}
18793 
18794  exit:
18795 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
18796 	       LPFC_RPI_RSRC_RDY);
18797 	return rc;
18798 }
18799 
18800 /**
18801  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
18802  * @phba: pointer to lpfc hba data structure.
18803  * @rpi_page:  pointer to the rpi memory region.
18804  *
18805  * This routine is invoked to post a single rpi header to the
18806  * HBA consistent with the SLI-4 interface spec.  This memory region
18807  * maps up to 64 rpi context regions.
18808  *
18809  * Return codes
18810  * 	0 - successful
18811  * 	-ENOMEM - No available memory
18812  *      -EIO - The mailbox failed to complete successfully.
18813  **/
18814 int
18815 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
18816 {
18817 	LPFC_MBOXQ_t *mboxq;
18818 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
18819 	uint32_t rc = 0;
18820 	uint32_t shdr_status, shdr_add_status;
18821 	union lpfc_sli4_cfg_shdr *shdr;
18822 
18823 	/* SLI4 ports that support extents do not require RPI headers. */
18824 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18825 		return rc;
18826 	if (phba->sli4_hba.extents_in_use)
18827 		return -EIO;
18828 
18829 	/* The port is notified of the header region via a mailbox command. */
18830 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18831 	if (!mboxq) {
18832 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18833 				"2001 Unable to allocate memory for issuing "
18834 				"SLI_CONFIG_SPECIAL mailbox command\n");
18835 		return -ENOMEM;
18836 	}
18837 
18838 	/* Post all rpi memory regions to the port. */
18839 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
18840 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
18841 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
18842 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
18843 			 sizeof(struct lpfc_sli4_cfg_mhdr),
18844 			 LPFC_SLI4_MBX_EMBED);
18845 
18846 
18847 	/* Post the physical rpi to the port for this rpi header. */
18848 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
18849 	       rpi_page->start_rpi);
18850 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
18851 	       hdr_tmpl, rpi_page->page_count);
18852 
18853 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
18854 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
18855 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
18856 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
18857 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18858 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18859 	mempool_free(mboxq, phba->mbox_mem_pool);
18860 	if (shdr_status || shdr_add_status || rc) {
18861 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18862 				"2514 POST_RPI_HDR mailbox failed with "
18863 				"status x%x add_status x%x, mbx status x%x\n",
18864 				shdr_status, shdr_add_status, rc);
18865 		rc = -ENXIO;
18866 	} else {
18867 		/*
18868 		 * The next_rpi stores the next logical module-64 rpi value used
18869 		 * to post physical rpis in subsequent rpi postings.
18870 		 */
18871 		spin_lock_irq(&phba->hbalock);
18872 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
18873 		spin_unlock_irq(&phba->hbalock);
18874 	}
18875 	return rc;
18876 }
18877 
18878 /**
18879  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
18880  * @phba: pointer to lpfc hba data structure.
18881  *
18882  * This routine is invoked to post rpi header templates to the
18883  * HBA consistent with the SLI-4 interface spec.  This routine
18884  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18885  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18886  *
18887  * Returns
18888  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
18889  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
18890  **/
18891 int
18892 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
18893 {
18894 	unsigned long rpi;
18895 	uint16_t max_rpi, rpi_limit;
18896 	uint16_t rpi_remaining, lrpi = 0;
18897 	struct lpfc_rpi_hdr *rpi_hdr;
18898 	unsigned long iflag;
18899 
18900 	/*
18901 	 * Fetch the next logical rpi.  Because this index is logical,
18902 	 * the  driver starts at 0 each time.
18903 	 */
18904 	spin_lock_irqsave(&phba->hbalock, iflag);
18905 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
18906 	rpi_limit = phba->sli4_hba.next_rpi;
18907 
18908 	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
18909 	if (rpi >= rpi_limit)
18910 		rpi = LPFC_RPI_ALLOC_ERROR;
18911 	else {
18912 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
18913 		phba->sli4_hba.max_cfg_param.rpi_used++;
18914 		phba->sli4_hba.rpi_count++;
18915 	}
18916 	lpfc_printf_log(phba, KERN_INFO,
18917 			LOG_NODE | LOG_DISCOVERY,
18918 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
18919 			(int) rpi, max_rpi, rpi_limit);
18920 
18921 	/*
18922 	 * Don't try to allocate more rpi header regions if the device limit
18923 	 * has been exhausted.
18924 	 */
18925 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
18926 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
18927 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18928 		return rpi;
18929 	}
18930 
18931 	/*
18932 	 * RPI header postings are not required for SLI4 ports capable of
18933 	 * extents.
18934 	 */
18935 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
18936 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18937 		return rpi;
18938 	}
18939 
18940 	/*
18941 	 * If the driver is running low on rpi resources, allocate another
18942 	 * page now.  Note that the next_rpi value is used because
18943 	 * it represents how many are actually in use whereas max_rpi notes
18944 	 * how many are supported max by the device.
18945 	 */
18946 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
18947 	spin_unlock_irqrestore(&phba->hbalock, iflag);
18948 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
18949 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
18950 		if (!rpi_hdr) {
18951 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18952 					"2002 Error Could not grow rpi "
18953 					"count\n");
18954 		} else {
18955 			lrpi = rpi_hdr->start_rpi;
18956 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18957 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
18958 		}
18959 	}
18960 
18961 	return rpi;
18962 }
18963 
18964 /**
18965  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
18966  * @phba: pointer to lpfc hba data structure.
18967  * @rpi: rpi to free
18968  *
18969  * This routine is invoked to release an rpi to the pool of
18970  * available rpis maintained by the driver.
18971  **/
18972 static void
18973 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
18974 {
18975 	/*
18976 	 * if the rpi value indicates a prior unreg has already
18977 	 * been done, skip the unreg.
18978 	 */
18979 	if (rpi == LPFC_RPI_ALLOC_ERROR)
18980 		return;
18981 
18982 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
18983 		phba->sli4_hba.rpi_count--;
18984 		phba->sli4_hba.max_cfg_param.rpi_used--;
18985 	} else {
18986 		lpfc_printf_log(phba, KERN_INFO,
18987 				LOG_NODE | LOG_DISCOVERY,
18988 				"2016 rpi %x not inuse\n",
18989 				rpi);
18990 	}
18991 }
18992 
18993 /**
18994  * lpfc_sli4_free_rpi - Release an rpi for reuse.
18995  * @phba: pointer to lpfc hba data structure.
18996  * @rpi: rpi to free
18997  *
18998  * This routine is invoked to release an rpi to the pool of
18999  * available rpis maintained by the driver.
19000  **/
19001 void
19002 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19003 {
19004 	spin_lock_irq(&phba->hbalock);
19005 	__lpfc_sli4_free_rpi(phba, rpi);
19006 	spin_unlock_irq(&phba->hbalock);
19007 }
19008 
19009 /**
19010  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19011  * @phba: pointer to lpfc hba data structure.
19012  *
19013  * This routine is invoked to remove the memory region that
19014  * provided rpi via a bitmask.
19015  **/
19016 void
19017 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19018 {
19019 	kfree(phba->sli4_hba.rpi_bmask);
19020 	kfree(phba->sli4_hba.rpi_ids);
19021 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19022 }
19023 
19024 /**
19025  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
19026  * @ndlp: pointer to lpfc nodelist data structure.
19027  * @cmpl: completion call-back.
19028  * @arg: data to load as MBox 'caller buffer information'
19029  *
19030  * This routine is invoked to remove the memory region that
19031  * provided rpi via a bitmask.
19032  **/
19033 int
19034 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19035 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
19036 {
19037 	LPFC_MBOXQ_t *mboxq;
19038 	struct lpfc_hba *phba = ndlp->phba;
19039 	int rc;
19040 
19041 	/* The port is notified of the header region via a mailbox command. */
19042 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19043 	if (!mboxq)
19044 		return -ENOMEM;
19045 
19046 	/* If cmpl assigned, then this nlp_get pairs with
19047 	 * lpfc_mbx_cmpl_resume_rpi.
19048 	 *
19049 	 * Else cmpl is NULL, then this nlp_get pairs with
19050 	 * lpfc_sli_def_mbox_cmpl.
19051 	 */
19052 	if (!lpfc_nlp_get(ndlp)) {
19053 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19054 				"2122 %s: Failed to get nlp ref\n",
19055 				__func__);
19056 		mempool_free(mboxq, phba->mbox_mem_pool);
19057 		return -EIO;
19058 	}
19059 
19060 	/* Post all rpi memory regions to the port. */
19061 	lpfc_resume_rpi(mboxq, ndlp);
19062 	if (cmpl) {
19063 		mboxq->mbox_cmpl = cmpl;
19064 		mboxq->ctx_buf = arg;
19065 	} else
19066 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19067 	mboxq->ctx_ndlp = ndlp;
19068 	mboxq->vport = ndlp->vport;
19069 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19070 	if (rc == MBX_NOT_FINISHED) {
19071 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19072 				"2010 Resume RPI Mailbox failed "
19073 				"status %d, mbxStatus x%x\n", rc,
19074 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19075 		lpfc_nlp_put(ndlp);
19076 		mempool_free(mboxq, phba->mbox_mem_pool);
19077 		return -EIO;
19078 	}
19079 	return 0;
19080 }
19081 
19082 /**
19083  * lpfc_sli4_init_vpi - Initialize a vpi with the port
19084  * @vport: Pointer to the vport for which the vpi is being initialized
19085  *
19086  * This routine is invoked to activate a vpi with the port.
19087  *
19088  * Returns:
19089  *    0 success
19090  *    -Evalue otherwise
19091  **/
19092 int
19093 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
19094 {
19095 	LPFC_MBOXQ_t *mboxq;
19096 	int rc = 0;
19097 	int retval = MBX_SUCCESS;
19098 	uint32_t mbox_tmo;
19099 	struct lpfc_hba *phba = vport->phba;
19100 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19101 	if (!mboxq)
19102 		return -ENOMEM;
19103 	lpfc_init_vpi(phba, mboxq, vport->vpi);
19104 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
19105 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
19106 	if (rc != MBX_SUCCESS) {
19107 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19108 				"2022 INIT VPI Mailbox failed "
19109 				"status %d, mbxStatus x%x\n", rc,
19110 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19111 		retval = -EIO;
19112 	}
19113 	if (rc != MBX_TIMEOUT)
19114 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
19115 
19116 	return retval;
19117 }
19118 
19119 /**
19120  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
19121  * @phba: pointer to lpfc hba data structure.
19122  * @mboxq: Pointer to mailbox object.
19123  *
19124  * This routine is invoked to manually add a single FCF record. The caller
19125  * must pass a completely initialized FCF_Record.  This routine takes
19126  * care of the nonembedded mailbox operations.
19127  **/
19128 static void
19129 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
19130 {
19131 	void *virt_addr;
19132 	union lpfc_sli4_cfg_shdr *shdr;
19133 	uint32_t shdr_status, shdr_add_status;
19134 
19135 	virt_addr = mboxq->sge_array->addr[0];
19136 	/* The IOCTL status is embedded in the mailbox subheader. */
19137 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
19138 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19139 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19140 
19141 	if ((shdr_status || shdr_add_status) &&
19142 		(shdr_status != STATUS_FCF_IN_USE))
19143 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19144 			"2558 ADD_FCF_RECORD mailbox failed with "
19145 			"status x%x add_status x%x\n",
19146 			shdr_status, shdr_add_status);
19147 
19148 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
19149 }
19150 
19151 /**
19152  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
19153  * @phba: pointer to lpfc hba data structure.
19154  * @fcf_record:  pointer to the initialized fcf record to add.
19155  *
19156  * This routine is invoked to manually add a single FCF record. The caller
19157  * must pass a completely initialized FCF_Record.  This routine takes
19158  * care of the nonembedded mailbox operations.
19159  **/
19160 int
19161 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
19162 {
19163 	int rc = 0;
19164 	LPFC_MBOXQ_t *mboxq;
19165 	uint8_t *bytep;
19166 	void *virt_addr;
19167 	struct lpfc_mbx_sge sge;
19168 	uint32_t alloc_len, req_len;
19169 	uint32_t fcfindex;
19170 
19171 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19172 	if (!mboxq) {
19173 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19174 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
19175 		return -ENOMEM;
19176 	}
19177 
19178 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
19179 		  sizeof(uint32_t);
19180 
19181 	/* Allocate DMA memory and set up the non-embedded mailbox command */
19182 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19183 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
19184 				     req_len, LPFC_SLI4_MBX_NEMBED);
19185 	if (alloc_len < req_len) {
19186 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19187 			"2523 Allocated DMA memory size (x%x) is "
19188 			"less than the requested DMA memory "
19189 			"size (x%x)\n", alloc_len, req_len);
19190 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19191 		return -ENOMEM;
19192 	}
19193 
19194 	/*
19195 	 * Get the first SGE entry from the non-embedded DMA memory.  This
19196 	 * routine only uses a single SGE.
19197 	 */
19198 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
19199 	virt_addr = mboxq->sge_array->addr[0];
19200 	/*
19201 	 * Configure the FCF record for FCFI 0.  This is the driver's
19202 	 * hardcoded default and gets used in nonFIP mode.
19203 	 */
19204 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
19205 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
19206 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
19207 
19208 	/*
19209 	 * Copy the fcf_index and the FCF Record Data. The data starts after
19210 	 * the FCoE header plus word10. The data copy needs to be endian
19211 	 * correct.
19212 	 */
19213 	bytep += sizeof(uint32_t);
19214 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
19215 	mboxq->vport = phba->pport;
19216 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
19217 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19218 	if (rc == MBX_NOT_FINISHED) {
19219 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19220 			"2515 ADD_FCF_RECORD mailbox failed with "
19221 			"status 0x%x\n", rc);
19222 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19223 		rc = -EIO;
19224 	} else
19225 		rc = 0;
19226 
19227 	return rc;
19228 }
19229 
19230 /**
19231  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
19232  * @phba: pointer to lpfc hba data structure.
19233  * @fcf_record:  pointer to the fcf record to write the default data.
19234  * @fcf_index: FCF table entry index.
19235  *
19236  * This routine is invoked to build the driver's default FCF record.  The
19237  * values used are hardcoded.  This routine handles memory initialization.
19238  *
19239  **/
19240 void
19241 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
19242 				struct fcf_record *fcf_record,
19243 				uint16_t fcf_index)
19244 {
19245 	memset(fcf_record, 0, sizeof(struct fcf_record));
19246 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
19247 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
19248 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
19249 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
19250 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
19251 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
19252 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
19253 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
19254 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
19255 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
19256 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
19257 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
19258 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
19259 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
19260 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
19261 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
19262 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
19263 	/* Set the VLAN bit map */
19264 	if (phba->valid_vlan) {
19265 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
19266 			= 1 << (phba->vlan_id % 8);
19267 	}
19268 }
19269 
19270 /**
19271  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
19272  * @phba: pointer to lpfc hba data structure.
19273  * @fcf_index: FCF table entry offset.
19274  *
19275  * This routine is invoked to scan the entire FCF table by reading FCF
19276  * record and processing it one at a time starting from the @fcf_index
19277  * for initial FCF discovery or fast FCF failover rediscovery.
19278  *
19279  * Return 0 if the mailbox command is submitted successfully, none 0
19280  * otherwise.
19281  **/
19282 int
19283 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19284 {
19285 	int rc = 0, error;
19286 	LPFC_MBOXQ_t *mboxq;
19287 
19288 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
19289 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
19290 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19291 	if (!mboxq) {
19292 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19293 				"2000 Failed to allocate mbox for "
19294 				"READ_FCF cmd\n");
19295 		error = -ENOMEM;
19296 		goto fail_fcf_scan;
19297 	}
19298 	/* Construct the read FCF record mailbox command */
19299 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19300 	if (rc) {
19301 		error = -EINVAL;
19302 		goto fail_fcf_scan;
19303 	}
19304 	/* Issue the mailbox command asynchronously */
19305 	mboxq->vport = phba->pport;
19306 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
19307 
19308 	spin_lock_irq(&phba->hbalock);
19309 	phba->hba_flag |= FCF_TS_INPROG;
19310 	spin_unlock_irq(&phba->hbalock);
19311 
19312 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19313 	if (rc == MBX_NOT_FINISHED)
19314 		error = -EIO;
19315 	else {
19316 		/* Reset eligible FCF count for new scan */
19317 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
19318 			phba->fcf.eligible_fcf_cnt = 0;
19319 		error = 0;
19320 	}
19321 fail_fcf_scan:
19322 	if (error) {
19323 		if (mboxq)
19324 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
19325 		/* FCF scan failed, clear FCF_TS_INPROG flag */
19326 		spin_lock_irq(&phba->hbalock);
19327 		phba->hba_flag &= ~FCF_TS_INPROG;
19328 		spin_unlock_irq(&phba->hbalock);
19329 	}
19330 	return error;
19331 }
19332 
19333 /**
19334  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
19335  * @phba: pointer to lpfc hba data structure.
19336  * @fcf_index: FCF table entry offset.
19337  *
19338  * This routine is invoked to read an FCF record indicated by @fcf_index
19339  * and to use it for FLOGI roundrobin FCF failover.
19340  *
19341  * Return 0 if the mailbox command is submitted successfully, none 0
19342  * otherwise.
19343  **/
19344 int
19345 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19346 {
19347 	int rc = 0, error;
19348 	LPFC_MBOXQ_t *mboxq;
19349 
19350 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19351 	if (!mboxq) {
19352 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
19353 				"2763 Failed to allocate mbox for "
19354 				"READ_FCF cmd\n");
19355 		error = -ENOMEM;
19356 		goto fail_fcf_read;
19357 	}
19358 	/* Construct the read FCF record mailbox command */
19359 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19360 	if (rc) {
19361 		error = -EINVAL;
19362 		goto fail_fcf_read;
19363 	}
19364 	/* Issue the mailbox command asynchronously */
19365 	mboxq->vport = phba->pport;
19366 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
19367 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19368 	if (rc == MBX_NOT_FINISHED)
19369 		error = -EIO;
19370 	else
19371 		error = 0;
19372 
19373 fail_fcf_read:
19374 	if (error && mboxq)
19375 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19376 	return error;
19377 }
19378 
19379 /**
19380  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
19381  * @phba: pointer to lpfc hba data structure.
19382  * @fcf_index: FCF table entry offset.
19383  *
19384  * This routine is invoked to read an FCF record indicated by @fcf_index to
19385  * determine whether it's eligible for FLOGI roundrobin failover list.
19386  *
19387  * Return 0 if the mailbox command is submitted successfully, none 0
19388  * otherwise.
19389  **/
19390 int
19391 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19392 {
19393 	int rc = 0, error;
19394 	LPFC_MBOXQ_t *mboxq;
19395 
19396 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19397 	if (!mboxq) {
19398 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
19399 				"2758 Failed to allocate mbox for "
19400 				"READ_FCF cmd\n");
19401 				error = -ENOMEM;
19402 				goto fail_fcf_read;
19403 	}
19404 	/* Construct the read FCF record mailbox command */
19405 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19406 	if (rc) {
19407 		error = -EINVAL;
19408 		goto fail_fcf_read;
19409 	}
19410 	/* Issue the mailbox command asynchronously */
19411 	mboxq->vport = phba->pport;
19412 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
19413 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19414 	if (rc == MBX_NOT_FINISHED)
19415 		error = -EIO;
19416 	else
19417 		error = 0;
19418 
19419 fail_fcf_read:
19420 	if (error && mboxq)
19421 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19422 	return error;
19423 }
19424 
19425 /**
19426  * lpfc_check_next_fcf_pri_level
19427  * @phba: pointer to the lpfc_hba struct for this port.
19428  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
19429  * routine when the rr_bmask is empty. The FCF indecies are put into the
19430  * rr_bmask based on their priority level. Starting from the highest priority
19431  * to the lowest. The most likely FCF candidate will be in the highest
19432  * priority group. When this routine is called it searches the fcf_pri list for
19433  * next lowest priority group and repopulates the rr_bmask with only those
19434  * fcf_indexes.
19435  * returns:
19436  * 1=success 0=failure
19437  **/
19438 static int
19439 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
19440 {
19441 	uint16_t next_fcf_pri;
19442 	uint16_t last_index;
19443 	struct lpfc_fcf_pri *fcf_pri;
19444 	int rc;
19445 	int ret = 0;
19446 
19447 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
19448 			LPFC_SLI4_FCF_TBL_INDX_MAX);
19449 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19450 			"3060 Last IDX %d\n", last_index);
19451 
19452 	/* Verify the priority list has 2 or more entries */
19453 	spin_lock_irq(&phba->hbalock);
19454 	if (list_empty(&phba->fcf.fcf_pri_list) ||
19455 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
19456 		spin_unlock_irq(&phba->hbalock);
19457 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19458 			"3061 Last IDX %d\n", last_index);
19459 		return 0; /* Empty rr list */
19460 	}
19461 	spin_unlock_irq(&phba->hbalock);
19462 
19463 	next_fcf_pri = 0;
19464 	/*
19465 	 * Clear the rr_bmask and set all of the bits that are at this
19466 	 * priority.
19467 	 */
19468 	memset(phba->fcf.fcf_rr_bmask, 0,
19469 			sizeof(*phba->fcf.fcf_rr_bmask));
19470 	spin_lock_irq(&phba->hbalock);
19471 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
19472 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
19473 			continue;
19474 		/*
19475 		 * the 1st priority that has not FLOGI failed
19476 		 * will be the highest.
19477 		 */
19478 		if (!next_fcf_pri)
19479 			next_fcf_pri = fcf_pri->fcf_rec.priority;
19480 		spin_unlock_irq(&phba->hbalock);
19481 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
19482 			rc = lpfc_sli4_fcf_rr_index_set(phba,
19483 						fcf_pri->fcf_rec.fcf_index);
19484 			if (rc)
19485 				return 0;
19486 		}
19487 		spin_lock_irq(&phba->hbalock);
19488 	}
19489 	/*
19490 	 * if next_fcf_pri was not set above and the list is not empty then
19491 	 * we have failed flogis on all of them. So reset flogi failed
19492 	 * and start at the beginning.
19493 	 */
19494 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
19495 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
19496 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
19497 			/*
19498 			 * the 1st priority that has not FLOGI failed
19499 			 * will be the highest.
19500 			 */
19501 			if (!next_fcf_pri)
19502 				next_fcf_pri = fcf_pri->fcf_rec.priority;
19503 			spin_unlock_irq(&phba->hbalock);
19504 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
19505 				rc = lpfc_sli4_fcf_rr_index_set(phba,
19506 						fcf_pri->fcf_rec.fcf_index);
19507 				if (rc)
19508 					return 0;
19509 			}
19510 			spin_lock_irq(&phba->hbalock);
19511 		}
19512 	} else
19513 		ret = 1;
19514 	spin_unlock_irq(&phba->hbalock);
19515 
19516 	return ret;
19517 }
19518 /**
19519  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
19520  * @phba: pointer to lpfc hba data structure.
19521  *
19522  * This routine is to get the next eligible FCF record index in a round
19523  * robin fashion. If the next eligible FCF record index equals to the
19524  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
19525  * shall be returned, otherwise, the next eligible FCF record's index
19526  * shall be returned.
19527  **/
19528 uint16_t
19529 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
19530 {
19531 	uint16_t next_fcf_index;
19532 
19533 initial_priority:
19534 	/* Search start from next bit of currently registered FCF index */
19535 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
19536 
19537 next_priority:
19538 	/* Determine the next fcf index to check */
19539 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
19540 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
19541 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
19542 				       next_fcf_index);
19543 
19544 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
19545 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19546 		/*
19547 		 * If we have wrapped then we need to clear the bits that
19548 		 * have been tested so that we can detect when we should
19549 		 * change the priority level.
19550 		 */
19551 		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
19552 					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
19553 	}
19554 
19555 
19556 	/* Check roundrobin failover list empty condition */
19557 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
19558 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
19559 		/*
19560 		 * If next fcf index is not found check if there are lower
19561 		 * Priority level fcf's in the fcf_priority list.
19562 		 * Set up the rr_bmask with all of the avaiable fcf bits
19563 		 * at that level and continue the selection process.
19564 		 */
19565 		if (lpfc_check_next_fcf_pri_level(phba))
19566 			goto initial_priority;
19567 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
19568 				"2844 No roundrobin failover FCF available\n");
19569 
19570 		return LPFC_FCOE_FCF_NEXT_NONE;
19571 	}
19572 
19573 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
19574 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
19575 		LPFC_FCF_FLOGI_FAILED) {
19576 		if (list_is_singular(&phba->fcf.fcf_pri_list))
19577 			return LPFC_FCOE_FCF_NEXT_NONE;
19578 
19579 		goto next_priority;
19580 	}
19581 
19582 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19583 			"2845 Get next roundrobin failover FCF (x%x)\n",
19584 			next_fcf_index);
19585 
19586 	return next_fcf_index;
19587 }
19588 
19589 /**
19590  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
19591  * @phba: pointer to lpfc hba data structure.
19592  * @fcf_index: index into the FCF table to 'set'
19593  *
19594  * This routine sets the FCF record index in to the eligible bmask for
19595  * roundrobin failover search. It checks to make sure that the index
19596  * does not go beyond the range of the driver allocated bmask dimension
19597  * before setting the bit.
19598  *
19599  * Returns 0 if the index bit successfully set, otherwise, it returns
19600  * -EINVAL.
19601  **/
19602 int
19603 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
19604 {
19605 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19606 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19607 				"2610 FCF (x%x) reached driver's book "
19608 				"keeping dimension:x%x\n",
19609 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19610 		return -EINVAL;
19611 	}
19612 	/* Set the eligible FCF record index bmask */
19613 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19614 
19615 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19616 			"2790 Set FCF (x%x) to roundrobin FCF failover "
19617 			"bmask\n", fcf_index);
19618 
19619 	return 0;
19620 }
19621 
19622 /**
19623  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
19624  * @phba: pointer to lpfc hba data structure.
19625  * @fcf_index: index into the FCF table to 'clear'
19626  *
19627  * This routine clears the FCF record index from the eligible bmask for
19628  * roundrobin failover search. It checks to make sure that the index
19629  * does not go beyond the range of the driver allocated bmask dimension
19630  * before clearing the bit.
19631  **/
19632 void
19633 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
19634 {
19635 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
19636 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19637 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19638 				"2762 FCF (x%x) reached driver's book "
19639 				"keeping dimension:x%x\n",
19640 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19641 		return;
19642 	}
19643 	/* Clear the eligible FCF record index bmask */
19644 	spin_lock_irq(&phba->hbalock);
19645 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
19646 				 list) {
19647 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
19648 			list_del_init(&fcf_pri->list);
19649 			break;
19650 		}
19651 	}
19652 	spin_unlock_irq(&phba->hbalock);
19653 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19654 
19655 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19656 			"2791 Clear FCF (x%x) from roundrobin failover "
19657 			"bmask\n", fcf_index);
19658 }
19659 
19660 /**
19661  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
19662  * @phba: pointer to lpfc hba data structure.
19663  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
19664  *
19665  * This routine is the completion routine for the rediscover FCF table mailbox
19666  * command. If the mailbox command returned failure, it will try to stop the
19667  * FCF rediscover wait timer.
19668  **/
19669 static void
19670 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
19671 {
19672 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19673 	uint32_t shdr_status, shdr_add_status;
19674 
19675 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19676 
19677 	shdr_status = bf_get(lpfc_mbox_hdr_status,
19678 			     &redisc_fcf->header.cfg_shdr.response);
19679 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
19680 			     &redisc_fcf->header.cfg_shdr.response);
19681 	if (shdr_status || shdr_add_status) {
19682 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19683 				"2746 Requesting for FCF rediscovery failed "
19684 				"status x%x add_status x%x\n",
19685 				shdr_status, shdr_add_status);
19686 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
19687 			spin_lock_irq(&phba->hbalock);
19688 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
19689 			spin_unlock_irq(&phba->hbalock);
19690 			/*
19691 			 * CVL event triggered FCF rediscover request failed,
19692 			 * last resort to re-try current registered FCF entry.
19693 			 */
19694 			lpfc_retry_pport_discovery(phba);
19695 		} else {
19696 			spin_lock_irq(&phba->hbalock);
19697 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
19698 			spin_unlock_irq(&phba->hbalock);
19699 			/*
19700 			 * DEAD FCF event triggered FCF rediscover request
19701 			 * failed, last resort to fail over as a link down
19702 			 * to FCF registration.
19703 			 */
19704 			lpfc_sli4_fcf_dead_failthrough(phba);
19705 		}
19706 	} else {
19707 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19708 				"2775 Start FCF rediscover quiescent timer\n");
19709 		/*
19710 		 * Start FCF rediscovery wait timer for pending FCF
19711 		 * before rescan FCF record table.
19712 		 */
19713 		lpfc_fcf_redisc_wait_start_timer(phba);
19714 	}
19715 
19716 	mempool_free(mbox, phba->mbox_mem_pool);
19717 }
19718 
19719 /**
19720  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
19721  * @phba: pointer to lpfc hba data structure.
19722  *
19723  * This routine is invoked to request for rediscovery of the entire FCF table
19724  * by the port.
19725  **/
19726 int
19727 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
19728 {
19729 	LPFC_MBOXQ_t *mbox;
19730 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19731 	int rc, length;
19732 
19733 	/* Cancel retry delay timers to all vports before FCF rediscover */
19734 	lpfc_cancel_all_vport_retry_delay_timer(phba);
19735 
19736 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19737 	if (!mbox) {
19738 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19739 				"2745 Failed to allocate mbox for "
19740 				"requesting FCF rediscover.\n");
19741 		return -ENOMEM;
19742 	}
19743 
19744 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
19745 		  sizeof(struct lpfc_sli4_cfg_mhdr));
19746 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
19747 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
19748 			 length, LPFC_SLI4_MBX_EMBED);
19749 
19750 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19751 	/* Set count to 0 for invalidating the entire FCF database */
19752 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
19753 
19754 	/* Issue the mailbox command asynchronously */
19755 	mbox->vport = phba->pport;
19756 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
19757 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
19758 
19759 	if (rc == MBX_NOT_FINISHED) {
19760 		mempool_free(mbox, phba->mbox_mem_pool);
19761 		return -EIO;
19762 	}
19763 	return 0;
19764 }
19765 
19766 /**
19767  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
19768  * @phba: pointer to lpfc hba data structure.
19769  *
19770  * This function is the failover routine as a last resort to the FCF DEAD
19771  * event when driver failed to perform fast FCF failover.
19772  **/
19773 void
19774 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
19775 {
19776 	uint32_t link_state;
19777 
19778 	/*
19779 	 * Last resort as FCF DEAD event failover will treat this as
19780 	 * a link down, but save the link state because we don't want
19781 	 * it to be changed to Link Down unless it is already down.
19782 	 */
19783 	link_state = phba->link_state;
19784 	lpfc_linkdown(phba);
19785 	phba->link_state = link_state;
19786 
19787 	/* Unregister FCF if no devices connected to it */
19788 	lpfc_unregister_unused_fcf(phba);
19789 }
19790 
19791 /**
19792  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
19793  * @phba: pointer to lpfc hba data structure.
19794  * @rgn23_data: pointer to configure region 23 data.
19795  *
19796  * This function gets SLI3 port configure region 23 data through memory dump
19797  * mailbox command. When it successfully retrieves data, the size of the data
19798  * will be returned, otherwise, 0 will be returned.
19799  **/
19800 static uint32_t
19801 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19802 {
19803 	LPFC_MBOXQ_t *pmb = NULL;
19804 	MAILBOX_t *mb;
19805 	uint32_t offset = 0;
19806 	int rc;
19807 
19808 	if (!rgn23_data)
19809 		return 0;
19810 
19811 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19812 	if (!pmb) {
19813 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19814 				"2600 failed to allocate mailbox memory\n");
19815 		return 0;
19816 	}
19817 	mb = &pmb->u.mb;
19818 
19819 	do {
19820 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
19821 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
19822 
19823 		if (rc != MBX_SUCCESS) {
19824 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19825 					"2601 failed to read config "
19826 					"region 23, rc 0x%x Status 0x%x\n",
19827 					rc, mb->mbxStatus);
19828 			mb->un.varDmp.word_cnt = 0;
19829 		}
19830 		/*
19831 		 * dump mem may return a zero when finished or we got a
19832 		 * mailbox error, either way we are done.
19833 		 */
19834 		if (mb->un.varDmp.word_cnt == 0)
19835 			break;
19836 
19837 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
19838 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
19839 
19840 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
19841 				       rgn23_data + offset,
19842 				       mb->un.varDmp.word_cnt);
19843 		offset += mb->un.varDmp.word_cnt;
19844 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
19845 
19846 	mempool_free(pmb, phba->mbox_mem_pool);
19847 	return offset;
19848 }
19849 
19850 /**
19851  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
19852  * @phba: pointer to lpfc hba data structure.
19853  * @rgn23_data: pointer to configure region 23 data.
19854  *
19855  * This function gets SLI4 port configure region 23 data through memory dump
19856  * mailbox command. When it successfully retrieves data, the size of the data
19857  * will be returned, otherwise, 0 will be returned.
19858  **/
19859 static uint32_t
19860 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19861 {
19862 	LPFC_MBOXQ_t *mboxq = NULL;
19863 	struct lpfc_dmabuf *mp = NULL;
19864 	struct lpfc_mqe *mqe;
19865 	uint32_t data_length = 0;
19866 	int rc;
19867 
19868 	if (!rgn23_data)
19869 		return 0;
19870 
19871 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19872 	if (!mboxq) {
19873 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19874 				"3105 failed to allocate mailbox memory\n");
19875 		return 0;
19876 	}
19877 
19878 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
19879 		goto out;
19880 	mqe = &mboxq->u.mqe;
19881 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
19882 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19883 	if (rc)
19884 		goto out;
19885 	data_length = mqe->un.mb_words[5];
19886 	if (data_length == 0)
19887 		goto out;
19888 	if (data_length > DMP_RGN23_SIZE) {
19889 		data_length = 0;
19890 		goto out;
19891 	}
19892 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
19893 out:
19894 	mempool_free(mboxq, phba->mbox_mem_pool);
19895 	if (mp) {
19896 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
19897 		kfree(mp);
19898 	}
19899 	return data_length;
19900 }
19901 
19902 /**
19903  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
19904  * @phba: pointer to lpfc hba data structure.
19905  *
19906  * This function read region 23 and parse TLV for port status to
19907  * decide if the user disaled the port. If the TLV indicates the
19908  * port is disabled, the hba_flag is set accordingly.
19909  **/
19910 void
19911 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
19912 {
19913 	uint8_t *rgn23_data = NULL;
19914 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
19915 	uint32_t offset = 0;
19916 
19917 	/* Get adapter Region 23 data */
19918 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
19919 	if (!rgn23_data)
19920 		goto out;
19921 
19922 	if (phba->sli_rev < LPFC_SLI_REV4)
19923 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
19924 	else {
19925 		if_type = bf_get(lpfc_sli_intf_if_type,
19926 				 &phba->sli4_hba.sli_intf);
19927 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
19928 			goto out;
19929 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
19930 	}
19931 
19932 	if (!data_size)
19933 		goto out;
19934 
19935 	/* Check the region signature first */
19936 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
19937 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19938 			"2619 Config region 23 has bad signature\n");
19939 			goto out;
19940 	}
19941 	offset += 4;
19942 
19943 	/* Check the data structure version */
19944 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
19945 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19946 			"2620 Config region 23 has bad version\n");
19947 		goto out;
19948 	}
19949 	offset += 4;
19950 
19951 	/* Parse TLV entries in the region */
19952 	while (offset < data_size) {
19953 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
19954 			break;
19955 		/*
19956 		 * If the TLV is not driver specific TLV or driver id is
19957 		 * not linux driver id, skip the record.
19958 		 */
19959 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
19960 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
19961 		    (rgn23_data[offset + 3] != 0)) {
19962 			offset += rgn23_data[offset + 1] * 4 + 4;
19963 			continue;
19964 		}
19965 
19966 		/* Driver found a driver specific TLV in the config region */
19967 		sub_tlv_len = rgn23_data[offset + 1] * 4;
19968 		offset += 4;
19969 		tlv_offset = 0;
19970 
19971 		/*
19972 		 * Search for configured port state sub-TLV.
19973 		 */
19974 		while ((offset < data_size) &&
19975 			(tlv_offset < sub_tlv_len)) {
19976 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
19977 				offset += 4;
19978 				tlv_offset += 4;
19979 				break;
19980 			}
19981 			if (rgn23_data[offset] != PORT_STE_TYPE) {
19982 				offset += rgn23_data[offset + 1] * 4 + 4;
19983 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
19984 				continue;
19985 			}
19986 
19987 			/* This HBA contains PORT_STE configured */
19988 			if (!rgn23_data[offset + 2])
19989 				phba->hba_flag |= LINK_DISABLED;
19990 
19991 			goto out;
19992 		}
19993 	}
19994 
19995 out:
19996 	kfree(rgn23_data);
19997 	return;
19998 }
19999 
20000 /**
20001  * lpfc_wr_object - write an object to the firmware
20002  * @phba: HBA structure that indicates port to create a queue on.
20003  * @dmabuf_list: list of dmabufs to write to the port.
20004  * @size: the total byte value of the objects to write to the port.
20005  * @offset: the current offset to be used to start the transfer.
20006  *
20007  * This routine will create a wr_object mailbox command to send to the port.
20008  * the mailbox command will be constructed using the dma buffers described in
20009  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
20010  * BDEs that the imbedded mailbox can support. The @offset variable will be
20011  * used to indicate the starting offset of the transfer and will also return
20012  * the offset after the write object mailbox has completed. @size is used to
20013  * determine the end of the object and whether the eof bit should be set.
20014  *
20015  * Return 0 is successful and offset will contain the the new offset to use
20016  * for the next write.
20017  * Return negative value for error cases.
20018  **/
20019 int
20020 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
20021 	       uint32_t size, uint32_t *offset)
20022 {
20023 	struct lpfc_mbx_wr_object *wr_object;
20024 	LPFC_MBOXQ_t *mbox;
20025 	int rc = 0, i = 0;
20026 	uint32_t shdr_status, shdr_add_status, shdr_change_status, shdr_csf;
20027 	uint32_t mbox_tmo;
20028 	struct lpfc_dmabuf *dmabuf;
20029 	uint32_t written = 0;
20030 	bool check_change_status = false;
20031 
20032 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20033 	if (!mbox)
20034 		return -ENOMEM;
20035 
20036 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
20037 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
20038 			sizeof(struct lpfc_mbx_wr_object) -
20039 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
20040 
20041 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
20042 	wr_object->u.request.write_offset = *offset;
20043 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
20044 	wr_object->u.request.object_name[0] =
20045 		cpu_to_le32(wr_object->u.request.object_name[0]);
20046 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
20047 	list_for_each_entry(dmabuf, dmabuf_list, list) {
20048 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
20049 			break;
20050 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
20051 		wr_object->u.request.bde[i].addrHigh =
20052 			putPaddrHigh(dmabuf->phys);
20053 		if (written + SLI4_PAGE_SIZE >= size) {
20054 			wr_object->u.request.bde[i].tus.f.bdeSize =
20055 				(size - written);
20056 			written += (size - written);
20057 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
20058 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
20059 			check_change_status = true;
20060 		} else {
20061 			wr_object->u.request.bde[i].tus.f.bdeSize =
20062 				SLI4_PAGE_SIZE;
20063 			written += SLI4_PAGE_SIZE;
20064 		}
20065 		i++;
20066 	}
20067 	wr_object->u.request.bde_count = i;
20068 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
20069 	if (!phba->sli4_hba.intr_enable)
20070 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
20071 	else {
20072 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
20073 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
20074 	}
20075 	/* The IOCTL status is embedded in the mailbox subheader. */
20076 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20077 			     &wr_object->header.cfg_shdr.response);
20078 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20079 				 &wr_object->header.cfg_shdr.response);
20080 	if (check_change_status) {
20081 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
20082 					    &wr_object->u.response);
20083 
20084 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20085 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20086 			shdr_csf = bf_get(lpfc_wr_object_csf,
20087 					  &wr_object->u.response);
20088 			if (shdr_csf)
20089 				shdr_change_status =
20090 						   LPFC_CHANGE_STATUS_PCI_RESET;
20091 		}
20092 
20093 		switch (shdr_change_status) {
20094 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20095 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20096 					"3198 Firmware write complete: System "
20097 					"reboot required to instantiate\n");
20098 			break;
20099 		case (LPFC_CHANGE_STATUS_FW_RESET):
20100 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20101 					"3199 Firmware write complete: Firmware"
20102 					" reset required to instantiate\n");
20103 			break;
20104 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20105 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20106 					"3200 Firmware write complete: Port "
20107 					"Migration or PCI Reset required to "
20108 					"instantiate\n");
20109 			break;
20110 		case (LPFC_CHANGE_STATUS_PCI_RESET):
20111 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20112 					"3201 Firmware write complete: PCI "
20113 					"Reset required to instantiate\n");
20114 			break;
20115 		default:
20116 			break;
20117 		}
20118 	}
20119 	if (!phba->sli4_hba.intr_enable)
20120 		mempool_free(mbox, phba->mbox_mem_pool);
20121 	else if (rc != MBX_TIMEOUT)
20122 		mempool_free(mbox, phba->mbox_mem_pool);
20123 	if (shdr_status || shdr_add_status || rc) {
20124 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20125 				"3025 Write Object mailbox failed with "
20126 				"status x%x add_status x%x, mbx status x%x\n",
20127 				shdr_status, shdr_add_status, rc);
20128 		rc = -ENXIO;
20129 		*offset = shdr_add_status;
20130 	} else
20131 		*offset += wr_object->u.response.actual_write_length;
20132 	return rc;
20133 }
20134 
20135 /**
20136  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
20137  * @vport: pointer to vport data structure.
20138  *
20139  * This function iterate through the mailboxq and clean up all REG_LOGIN
20140  * and REG_VPI mailbox commands associated with the vport. This function
20141  * is called when driver want to restart discovery of the vport due to
20142  * a Clear Virtual Link event.
20143  **/
20144 void
20145 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
20146 {
20147 	struct lpfc_hba *phba = vport->phba;
20148 	LPFC_MBOXQ_t *mb, *nextmb;
20149 	struct lpfc_dmabuf *mp;
20150 	struct lpfc_nodelist *ndlp;
20151 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
20152 	LIST_HEAD(mbox_cmd_list);
20153 	uint8_t restart_loop;
20154 
20155 	/* Clean up internally queued mailbox commands with the vport */
20156 	spin_lock_irq(&phba->hbalock);
20157 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
20158 		if (mb->vport != vport)
20159 			continue;
20160 
20161 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
20162 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
20163 			continue;
20164 
20165 		list_del(&mb->list);
20166 		list_add_tail(&mb->list, &mbox_cmd_list);
20167 	}
20168 	/* Clean up active mailbox command with the vport */
20169 	mb = phba->sli.mbox_active;
20170 	if (mb && (mb->vport == vport)) {
20171 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
20172 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
20173 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
20174 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20175 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20176 			/* Put reference count for delayed processing */
20177 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
20178 			/* Unregister the RPI when mailbox complete */
20179 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
20180 		}
20181 	}
20182 	/* Cleanup any mailbox completions which are not yet processed */
20183 	do {
20184 		restart_loop = 0;
20185 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
20186 			/*
20187 			 * If this mailox is already processed or it is
20188 			 * for another vport ignore it.
20189 			 */
20190 			if ((mb->vport != vport) ||
20191 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
20192 				continue;
20193 
20194 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
20195 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
20196 				continue;
20197 
20198 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
20199 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20200 				ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20201 				/* Unregister the RPI when mailbox complete */
20202 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
20203 				restart_loop = 1;
20204 				spin_unlock_irq(&phba->hbalock);
20205 				spin_lock(&ndlp->lock);
20206 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20207 				spin_unlock(&ndlp->lock);
20208 				spin_lock_irq(&phba->hbalock);
20209 				break;
20210 			}
20211 		}
20212 	} while (restart_loop);
20213 
20214 	spin_unlock_irq(&phba->hbalock);
20215 
20216 	/* Release the cleaned-up mailbox commands */
20217 	while (!list_empty(&mbox_cmd_list)) {
20218 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
20219 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20220 			mp = (struct lpfc_dmabuf *)(mb->ctx_buf);
20221 			if (mp) {
20222 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
20223 				kfree(mp);
20224 			}
20225 			mb->ctx_buf = NULL;
20226 			ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20227 			mb->ctx_ndlp = NULL;
20228 			if (ndlp) {
20229 				spin_lock(&ndlp->lock);
20230 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20231 				spin_unlock(&ndlp->lock);
20232 				lpfc_nlp_put(ndlp);
20233 			}
20234 		}
20235 		mempool_free(mb, phba->mbox_mem_pool);
20236 	}
20237 
20238 	/* Release the ndlp with the cleaned-up active mailbox command */
20239 	if (act_mbx_ndlp) {
20240 		spin_lock(&act_mbx_ndlp->lock);
20241 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20242 		spin_unlock(&act_mbx_ndlp->lock);
20243 		lpfc_nlp_put(act_mbx_ndlp);
20244 	}
20245 }
20246 
20247 /**
20248  * lpfc_drain_txq - Drain the txq
20249  * @phba: Pointer to HBA context object.
20250  *
20251  * This function attempt to submit IOCBs on the txq
20252  * to the adapter.  For SLI4 adapters, the txq contains
20253  * ELS IOCBs that have been deferred because the there
20254  * are no SGLs.  This congestion can occur with large
20255  * vport counts during node discovery.
20256  **/
20257 
20258 uint32_t
20259 lpfc_drain_txq(struct lpfc_hba *phba)
20260 {
20261 	LIST_HEAD(completions);
20262 	struct lpfc_sli_ring *pring;
20263 	struct lpfc_iocbq *piocbq = NULL;
20264 	unsigned long iflags = 0;
20265 	char *fail_msg = NULL;
20266 	struct lpfc_sglq *sglq;
20267 	union lpfc_wqe128 wqe;
20268 	uint32_t txq_cnt = 0;
20269 	struct lpfc_queue *wq;
20270 
20271 	if (phba->link_flag & LS_MDS_LOOPBACK) {
20272 		/* MDS WQE are posted only to first WQ*/
20273 		wq = phba->sli4_hba.hdwq[0].io_wq;
20274 		if (unlikely(!wq))
20275 			return 0;
20276 		pring = wq->pring;
20277 	} else {
20278 		wq = phba->sli4_hba.els_wq;
20279 		if (unlikely(!wq))
20280 			return 0;
20281 		pring = lpfc_phba_elsring(phba);
20282 	}
20283 
20284 	if (unlikely(!pring) || list_empty(&pring->txq))
20285 		return 0;
20286 
20287 	spin_lock_irqsave(&pring->ring_lock, iflags);
20288 	list_for_each_entry(piocbq, &pring->txq, list) {
20289 		txq_cnt++;
20290 	}
20291 
20292 	if (txq_cnt > pring->txq_max)
20293 		pring->txq_max = txq_cnt;
20294 
20295 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
20296 
20297 	while (!list_empty(&pring->txq)) {
20298 		spin_lock_irqsave(&pring->ring_lock, iflags);
20299 
20300 		piocbq = lpfc_sli_ringtx_get(phba, pring);
20301 		if (!piocbq) {
20302 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20303 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20304 				"2823 txq empty and txq_cnt is %d\n ",
20305 				txq_cnt);
20306 			break;
20307 		}
20308 		sglq = __lpfc_sli_get_els_sglq(phba, piocbq);
20309 		if (!sglq) {
20310 			__lpfc_sli_ringtx_put(phba, pring, piocbq);
20311 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20312 			break;
20313 		}
20314 		txq_cnt--;
20315 
20316 		/* The xri and iocb resources secured,
20317 		 * attempt to issue request
20318 		 */
20319 		piocbq->sli4_lxritag = sglq->sli4_lxritag;
20320 		piocbq->sli4_xritag = sglq->sli4_xritag;
20321 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
20322 			fail_msg = "to convert bpl to sgl";
20323 		else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
20324 			fail_msg = "to convert iocb to wqe";
20325 		else if (lpfc_sli4_wq_put(wq, &wqe))
20326 			fail_msg = " - Wq is full";
20327 		else
20328 			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
20329 
20330 		if (fail_msg) {
20331 			/* Failed means we can't issue and need to cancel */
20332 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20333 					"2822 IOCB failed %s iotag 0x%x "
20334 					"xri 0x%x\n",
20335 					fail_msg,
20336 					piocbq->iotag, piocbq->sli4_xritag);
20337 			list_add_tail(&piocbq->list, &completions);
20338 		}
20339 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20340 	}
20341 
20342 	/* Cancel all the IOCBs that cannot be issued */
20343 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
20344 				IOERR_SLI_ABORTED);
20345 
20346 	return txq_cnt;
20347 }
20348 
20349 /**
20350  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
20351  * @phba: Pointer to HBA context object.
20352  * @pwqeq: Pointer to command WQE.
20353  * @sglq: Pointer to the scatter gather queue object.
20354  *
20355  * This routine converts the bpl or bde that is in the WQE
20356  * to a sgl list for the sli4 hardware. The physical address
20357  * of the bpl/bde is converted back to a virtual address.
20358  * If the WQE contains a BPL then the list of BDE's is
20359  * converted to sli4_sge's. If the WQE contains a single
20360  * BDE then it is converted to a single sli_sge.
20361  * The WQE is still in cpu endianness so the contents of
20362  * the bpl can be used without byte swapping.
20363  *
20364  * Returns valid XRI = Success, NO_XRI = Failure.
20365  */
20366 static uint16_t
20367 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
20368 		 struct lpfc_sglq *sglq)
20369 {
20370 	uint16_t xritag = NO_XRI;
20371 	struct ulp_bde64 *bpl = NULL;
20372 	struct ulp_bde64 bde;
20373 	struct sli4_sge *sgl  = NULL;
20374 	struct lpfc_dmabuf *dmabuf;
20375 	union lpfc_wqe128 *wqe;
20376 	int numBdes = 0;
20377 	int i = 0;
20378 	uint32_t offset = 0; /* accumulated offset in the sg request list */
20379 	int inbound = 0; /* number of sg reply entries inbound from firmware */
20380 	uint32_t cmd;
20381 
20382 	if (!pwqeq || !sglq)
20383 		return xritag;
20384 
20385 	sgl  = (struct sli4_sge *)sglq->sgl;
20386 	wqe = &pwqeq->wqe;
20387 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
20388 
20389 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
20390 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
20391 		return sglq->sli4_xritag;
20392 	numBdes = pwqeq->rsvd2;
20393 	if (numBdes) {
20394 		/* The addrHigh and addrLow fields within the WQE
20395 		 * have not been byteswapped yet so there is no
20396 		 * need to swap them back.
20397 		 */
20398 		if (pwqeq->context3)
20399 			dmabuf = (struct lpfc_dmabuf *)pwqeq->context3;
20400 		else
20401 			return xritag;
20402 
20403 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
20404 		if (!bpl)
20405 			return xritag;
20406 
20407 		for (i = 0; i < numBdes; i++) {
20408 			/* Should already be byte swapped. */
20409 			sgl->addr_hi = bpl->addrHigh;
20410 			sgl->addr_lo = bpl->addrLow;
20411 
20412 			sgl->word2 = le32_to_cpu(sgl->word2);
20413 			if ((i+1) == numBdes)
20414 				bf_set(lpfc_sli4_sge_last, sgl, 1);
20415 			else
20416 				bf_set(lpfc_sli4_sge_last, sgl, 0);
20417 			/* swap the size field back to the cpu so we
20418 			 * can assign it to the sgl.
20419 			 */
20420 			bde.tus.w = le32_to_cpu(bpl->tus.w);
20421 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
20422 			/* The offsets in the sgl need to be accumulated
20423 			 * separately for the request and reply lists.
20424 			 * The request is always first, the reply follows.
20425 			 */
20426 			switch (cmd) {
20427 			case CMD_GEN_REQUEST64_WQE:
20428 				/* add up the reply sg entries */
20429 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
20430 					inbound++;
20431 				/* first inbound? reset the offset */
20432 				if (inbound == 1)
20433 					offset = 0;
20434 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
20435 				bf_set(lpfc_sli4_sge_type, sgl,
20436 					LPFC_SGE_TYPE_DATA);
20437 				offset += bde.tus.f.bdeSize;
20438 				break;
20439 			case CMD_FCP_TRSP64_WQE:
20440 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
20441 				bf_set(lpfc_sli4_sge_type, sgl,
20442 					LPFC_SGE_TYPE_DATA);
20443 				break;
20444 			case CMD_FCP_TSEND64_WQE:
20445 			case CMD_FCP_TRECEIVE64_WQE:
20446 				bf_set(lpfc_sli4_sge_type, sgl,
20447 					bpl->tus.f.bdeFlags);
20448 				if (i < 3)
20449 					offset = 0;
20450 				else
20451 					offset += bde.tus.f.bdeSize;
20452 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
20453 				break;
20454 			}
20455 			sgl->word2 = cpu_to_le32(sgl->word2);
20456 			bpl++;
20457 			sgl++;
20458 		}
20459 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
20460 		/* The addrHigh and addrLow fields of the BDE have not
20461 		 * been byteswapped yet so they need to be swapped
20462 		 * before putting them in the sgl.
20463 		 */
20464 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
20465 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
20466 		sgl->word2 = le32_to_cpu(sgl->word2);
20467 		bf_set(lpfc_sli4_sge_last, sgl, 1);
20468 		sgl->word2 = cpu_to_le32(sgl->word2);
20469 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
20470 	}
20471 	return sglq->sli4_xritag;
20472 }
20473 
20474 /**
20475  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
20476  * @phba: Pointer to HBA context object.
20477  * @qp: Pointer to HDW queue.
20478  * @pwqe: Pointer to command WQE.
20479  **/
20480 int
20481 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
20482 		    struct lpfc_iocbq *pwqe)
20483 {
20484 	union lpfc_wqe128 *wqe = &pwqe->wqe;
20485 	struct lpfc_async_xchg_ctx *ctxp;
20486 	struct lpfc_queue *wq;
20487 	struct lpfc_sglq *sglq;
20488 	struct lpfc_sli_ring *pring;
20489 	unsigned long iflags;
20490 	uint32_t ret = 0;
20491 
20492 	/* NVME_LS and NVME_LS ABTS requests. */
20493 	if (pwqe->iocb_flag & LPFC_IO_NVME_LS) {
20494 		pring =  phba->sli4_hba.nvmels_wq->pring;
20495 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20496 					  qp, wq_access);
20497 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
20498 		if (!sglq) {
20499 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20500 			return WQE_BUSY;
20501 		}
20502 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
20503 		pwqe->sli4_xritag = sglq->sli4_xritag;
20504 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
20505 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20506 			return WQE_ERROR;
20507 		}
20508 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
20509 		       pwqe->sli4_xritag);
20510 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
20511 		if (ret) {
20512 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20513 			return ret;
20514 		}
20515 
20516 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20517 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20518 
20519 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20520 		return 0;
20521 	}
20522 
20523 	/* NVME_FCREQ and NVME_ABTS requests */
20524 	if (pwqe->iocb_flag & LPFC_IO_NVME ||
20525 	    pwqe->iocb_flag & LPFC_IO_FCP) {
20526 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
20527 		wq = qp->io_wq;
20528 		pring = wq->pring;
20529 
20530 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
20531 
20532 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20533 					  qp, wq_access);
20534 		ret = lpfc_sli4_wq_put(wq, wqe);
20535 		if (ret) {
20536 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20537 			return ret;
20538 		}
20539 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20540 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20541 
20542 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20543 		return 0;
20544 	}
20545 
20546 	/* NVMET requests */
20547 	if (pwqe->iocb_flag & LPFC_IO_NVMET) {
20548 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
20549 		wq = qp->io_wq;
20550 		pring = wq->pring;
20551 
20552 		ctxp = pwqe->context2;
20553 		sglq = ctxp->ctxbuf->sglq;
20554 		if (pwqe->sli4_xritag ==  NO_XRI) {
20555 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
20556 			pwqe->sli4_xritag = sglq->sli4_xritag;
20557 		}
20558 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
20559 		       pwqe->sli4_xritag);
20560 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
20561 
20562 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20563 					  qp, wq_access);
20564 		ret = lpfc_sli4_wq_put(wq, wqe);
20565 		if (ret) {
20566 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20567 			return ret;
20568 		}
20569 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20570 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20571 
20572 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20573 		return 0;
20574 	}
20575 	return WQE_ERROR;
20576 }
20577 
20578 /**
20579  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
20580  * @phba: Pointer to HBA context object.
20581  * @cmdiocb: Pointer to driver command iocb object.
20582  * @cmpl: completion function.
20583  *
20584  * Fill the appropriate fields for the abort WQE and call
20585  * internal routine lpfc_sli4_issue_wqe to send the WQE
20586  * This function is called with hbalock held and no ring_lock held.
20587  *
20588  * RETURNS 0 - SUCCESS
20589  **/
20590 
20591 int
20592 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
20593 			    void *cmpl)
20594 {
20595 	struct lpfc_vport *vport = cmdiocb->vport;
20596 	struct lpfc_iocbq *abtsiocb = NULL;
20597 	union lpfc_wqe128 *abtswqe;
20598 	struct lpfc_io_buf *lpfc_cmd;
20599 	int retval = IOCB_ERROR;
20600 	u16 xritag = cmdiocb->sli4_xritag;
20601 
20602 	/*
20603 	 * The scsi command can not be in txq and it is in flight because the
20604 	 * pCmd is still pointing at the SCSI command we have to abort. There
20605 	 * is no need to search the txcmplq. Just send an abort to the FW.
20606 	 */
20607 
20608 	abtsiocb = __lpfc_sli_get_iocbq(phba);
20609 	if (!abtsiocb)
20610 		return WQE_NORESOURCE;
20611 
20612 	/* Indicate the IO is being aborted by the driver. */
20613 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
20614 
20615 	abtswqe = &abtsiocb->wqe;
20616 	memset(abtswqe, 0, sizeof(*abtswqe));
20617 
20618 	if (lpfc_is_link_up(phba))
20619 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
20620 	else
20621 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 0);
20622 	bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
20623 	abtswqe->abort_cmd.rsrvd5 = 0;
20624 	abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
20625 	bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
20626 	bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
20627 	bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
20628 	bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
20629 	bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
20630 	bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
20631 
20632 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
20633 	abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
20634 	abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
20635 	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
20636 		abtsiocb->iocb_flag |= LPFC_IO_FCP;
20637 	if (cmdiocb->iocb_flag & LPFC_IO_NVME)
20638 		abtsiocb->iocb_flag |= LPFC_IO_NVME;
20639 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
20640 		abtsiocb->iocb_flag |= LPFC_IO_FOF;
20641 	abtsiocb->vport = vport;
20642 	abtsiocb->wqe_cmpl = cmpl;
20643 
20644 	lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
20645 	retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
20646 
20647 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
20648 			 "0359 Abort xri x%x, original iotag x%x, "
20649 			 "abort cmd iotag x%x retval x%x\n",
20650 			 xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
20651 
20652 	if (retval) {
20653 		cmdiocb->iocb_flag &= ~LPFC_DRIVER_ABORTED;
20654 		__lpfc_sli_release_iocbq(phba, abtsiocb);
20655 	}
20656 
20657 	return retval;
20658 }
20659 
20660 #ifdef LPFC_MXP_STAT
20661 /**
20662  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
20663  * @phba: pointer to lpfc hba data structure.
20664  * @hwqid: belong to which HWQ.
20665  *
20666  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
20667  * 15 seconds after a test case is running.
20668  *
20669  * The user should call lpfc_debugfs_multixripools_write before running a test
20670  * case to clear stat_snapshot_taken. Then the user starts a test case. During
20671  * test case is running, stat_snapshot_taken is incremented by 1 every time when
20672  * this routine is called from heartbeat timer. When stat_snapshot_taken is
20673  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
20674  **/
20675 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
20676 {
20677 	struct lpfc_sli4_hdw_queue *qp;
20678 	struct lpfc_multixri_pool *multixri_pool;
20679 	struct lpfc_pvt_pool *pvt_pool;
20680 	struct lpfc_pbl_pool *pbl_pool;
20681 	u32 txcmplq_cnt;
20682 
20683 	qp = &phba->sli4_hba.hdwq[hwqid];
20684 	multixri_pool = qp->p_multixri_pool;
20685 	if (!multixri_pool)
20686 		return;
20687 
20688 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
20689 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
20690 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
20691 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20692 
20693 		multixri_pool->stat_pbl_count = pbl_pool->count;
20694 		multixri_pool->stat_pvt_count = pvt_pool->count;
20695 		multixri_pool->stat_busy_count = txcmplq_cnt;
20696 	}
20697 
20698 	multixri_pool->stat_snapshot_taken++;
20699 }
20700 #endif
20701 
20702 /**
20703  * lpfc_adjust_pvt_pool_count - Adjust private pool count
20704  * @phba: pointer to lpfc hba data structure.
20705  * @hwqid: belong to which HWQ.
20706  *
20707  * This routine moves some XRIs from private to public pool when private pool
20708  * is not busy.
20709  **/
20710 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
20711 {
20712 	struct lpfc_multixri_pool *multixri_pool;
20713 	u32 io_req_count;
20714 	u32 prev_io_req_count;
20715 
20716 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
20717 	if (!multixri_pool)
20718 		return;
20719 	io_req_count = multixri_pool->io_req_count;
20720 	prev_io_req_count = multixri_pool->prev_io_req_count;
20721 
20722 	if (prev_io_req_count != io_req_count) {
20723 		/* Private pool is busy */
20724 		multixri_pool->prev_io_req_count = io_req_count;
20725 	} else {
20726 		/* Private pool is not busy.
20727 		 * Move XRIs from private to public pool.
20728 		 */
20729 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
20730 	}
20731 }
20732 
20733 /**
20734  * lpfc_adjust_high_watermark - Adjust high watermark
20735  * @phba: pointer to lpfc hba data structure.
20736  * @hwqid: belong to which HWQ.
20737  *
20738  * This routine sets high watermark as number of outstanding XRIs,
20739  * but make sure the new value is between xri_limit/2 and xri_limit.
20740  **/
20741 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
20742 {
20743 	u32 new_watermark;
20744 	u32 watermark_max;
20745 	u32 watermark_min;
20746 	u32 xri_limit;
20747 	u32 txcmplq_cnt;
20748 	u32 abts_io_bufs;
20749 	struct lpfc_multixri_pool *multixri_pool;
20750 	struct lpfc_sli4_hdw_queue *qp;
20751 
20752 	qp = &phba->sli4_hba.hdwq[hwqid];
20753 	multixri_pool = qp->p_multixri_pool;
20754 	if (!multixri_pool)
20755 		return;
20756 	xri_limit = multixri_pool->xri_limit;
20757 
20758 	watermark_max = xri_limit;
20759 	watermark_min = xri_limit / 2;
20760 
20761 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20762 	abts_io_bufs = qp->abts_scsi_io_bufs;
20763 	abts_io_bufs += qp->abts_nvme_io_bufs;
20764 
20765 	new_watermark = txcmplq_cnt + abts_io_bufs;
20766 	new_watermark = min(watermark_max, new_watermark);
20767 	new_watermark = max(watermark_min, new_watermark);
20768 	multixri_pool->pvt_pool.high_watermark = new_watermark;
20769 
20770 #ifdef LPFC_MXP_STAT
20771 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
20772 					  new_watermark);
20773 #endif
20774 }
20775 
20776 /**
20777  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
20778  * @phba: pointer to lpfc hba data structure.
20779  * @hwqid: belong to which HWQ.
20780  *
20781  * This routine is called from hearbeat timer when pvt_pool is idle.
20782  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
20783  * The first step moves (all - low_watermark) amount of XRIs.
20784  * The second step moves the rest of XRIs.
20785  **/
20786 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
20787 {
20788 	struct lpfc_pbl_pool *pbl_pool;
20789 	struct lpfc_pvt_pool *pvt_pool;
20790 	struct lpfc_sli4_hdw_queue *qp;
20791 	struct lpfc_io_buf *lpfc_ncmd;
20792 	struct lpfc_io_buf *lpfc_ncmd_next;
20793 	unsigned long iflag;
20794 	struct list_head tmp_list;
20795 	u32 tmp_count;
20796 
20797 	qp = &phba->sli4_hba.hdwq[hwqid];
20798 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
20799 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
20800 	tmp_count = 0;
20801 
20802 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
20803 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
20804 
20805 	if (pvt_pool->count > pvt_pool->low_watermark) {
20806 		/* Step 1: move (all - low_watermark) from pvt_pool
20807 		 * to pbl_pool
20808 		 */
20809 
20810 		/* Move low watermark of bufs from pvt_pool to tmp_list */
20811 		INIT_LIST_HEAD(&tmp_list);
20812 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20813 					 &pvt_pool->list, list) {
20814 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
20815 			tmp_count++;
20816 			if (tmp_count >= pvt_pool->low_watermark)
20817 				break;
20818 		}
20819 
20820 		/* Move all bufs from pvt_pool to pbl_pool */
20821 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
20822 
20823 		/* Move all bufs from tmp_list to pvt_pool */
20824 		list_splice(&tmp_list, &pvt_pool->list);
20825 
20826 		pbl_pool->count += (pvt_pool->count - tmp_count);
20827 		pvt_pool->count = tmp_count;
20828 	} else {
20829 		/* Step 2: move the rest from pvt_pool to pbl_pool */
20830 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
20831 		pbl_pool->count += pvt_pool->count;
20832 		pvt_pool->count = 0;
20833 	}
20834 
20835 	spin_unlock(&pvt_pool->lock);
20836 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20837 }
20838 
20839 /**
20840  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
20841  * @phba: pointer to lpfc hba data structure
20842  * @qp: pointer to HDW queue
20843  * @pbl_pool: specified public free XRI pool
20844  * @pvt_pool: specified private free XRI pool
20845  * @count: number of XRIs to move
20846  *
20847  * This routine tries to move some free common bufs from the specified pbl_pool
20848  * to the specified pvt_pool. It might move less than count XRIs if there's not
20849  * enough in public pool.
20850  *
20851  * Return:
20852  *   true - if XRIs are successfully moved from the specified pbl_pool to the
20853  *          specified pvt_pool
20854  *   false - if the specified pbl_pool is empty or locked by someone else
20855  **/
20856 static bool
20857 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
20858 			  struct lpfc_pbl_pool *pbl_pool,
20859 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
20860 {
20861 	struct lpfc_io_buf *lpfc_ncmd;
20862 	struct lpfc_io_buf *lpfc_ncmd_next;
20863 	unsigned long iflag;
20864 	int ret;
20865 
20866 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
20867 	if (ret) {
20868 		if (pbl_pool->count) {
20869 			/* Move a batch of XRIs from public to private pool */
20870 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
20871 			list_for_each_entry_safe(lpfc_ncmd,
20872 						 lpfc_ncmd_next,
20873 						 &pbl_pool->list,
20874 						 list) {
20875 				list_move_tail(&lpfc_ncmd->list,
20876 					       &pvt_pool->list);
20877 				pvt_pool->count++;
20878 				pbl_pool->count--;
20879 				count--;
20880 				if (count == 0)
20881 					break;
20882 			}
20883 
20884 			spin_unlock(&pvt_pool->lock);
20885 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20886 			return true;
20887 		}
20888 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20889 	}
20890 
20891 	return false;
20892 }
20893 
20894 /**
20895  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
20896  * @phba: pointer to lpfc hba data structure.
20897  * @hwqid: belong to which HWQ.
20898  * @count: number of XRIs to move
20899  *
20900  * This routine tries to find some free common bufs in one of public pools with
20901  * Round Robin method. The search always starts from local hwqid, then the next
20902  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
20903  * a batch of free common bufs are moved to private pool on hwqid.
20904  * It might move less than count XRIs if there's not enough in public pool.
20905  **/
20906 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
20907 {
20908 	struct lpfc_multixri_pool *multixri_pool;
20909 	struct lpfc_multixri_pool *next_multixri_pool;
20910 	struct lpfc_pvt_pool *pvt_pool;
20911 	struct lpfc_pbl_pool *pbl_pool;
20912 	struct lpfc_sli4_hdw_queue *qp;
20913 	u32 next_hwqid;
20914 	u32 hwq_count;
20915 	int ret;
20916 
20917 	qp = &phba->sli4_hba.hdwq[hwqid];
20918 	multixri_pool = qp->p_multixri_pool;
20919 	pvt_pool = &multixri_pool->pvt_pool;
20920 	pbl_pool = &multixri_pool->pbl_pool;
20921 
20922 	/* Check if local pbl_pool is available */
20923 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
20924 	if (ret) {
20925 #ifdef LPFC_MXP_STAT
20926 		multixri_pool->local_pbl_hit_count++;
20927 #endif
20928 		return;
20929 	}
20930 
20931 	hwq_count = phba->cfg_hdw_queue;
20932 
20933 	/* Get the next hwqid which was found last time */
20934 	next_hwqid = multixri_pool->rrb_next_hwqid;
20935 
20936 	do {
20937 		/* Go to next hwq */
20938 		next_hwqid = (next_hwqid + 1) % hwq_count;
20939 
20940 		next_multixri_pool =
20941 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
20942 		pbl_pool = &next_multixri_pool->pbl_pool;
20943 
20944 		/* Check if the public free xri pool is available */
20945 		ret = _lpfc_move_xri_pbl_to_pvt(
20946 			phba, qp, pbl_pool, pvt_pool, count);
20947 
20948 		/* Exit while-loop if success or all hwqid are checked */
20949 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
20950 
20951 	/* Starting point for the next time */
20952 	multixri_pool->rrb_next_hwqid = next_hwqid;
20953 
20954 	if (!ret) {
20955 		/* stats: all public pools are empty*/
20956 		multixri_pool->pbl_empty_count++;
20957 	}
20958 
20959 #ifdef LPFC_MXP_STAT
20960 	if (ret) {
20961 		if (next_hwqid == hwqid)
20962 			multixri_pool->local_pbl_hit_count++;
20963 		else
20964 			multixri_pool->other_pbl_hit_count++;
20965 	}
20966 #endif
20967 }
20968 
20969 /**
20970  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
20971  * @phba: pointer to lpfc hba data structure.
20972  * @hwqid: belong to which HWQ.
20973  *
20974  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
20975  * low watermark.
20976  **/
20977 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
20978 {
20979 	struct lpfc_multixri_pool *multixri_pool;
20980 	struct lpfc_pvt_pool *pvt_pool;
20981 
20982 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
20983 	pvt_pool = &multixri_pool->pvt_pool;
20984 
20985 	if (pvt_pool->count < pvt_pool->low_watermark)
20986 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
20987 }
20988 
20989 /**
20990  * lpfc_release_io_buf - Return one IO buf back to free pool
20991  * @phba: pointer to lpfc hba data structure.
20992  * @lpfc_ncmd: IO buf to be returned.
20993  * @qp: belong to which HWQ.
20994  *
20995  * This routine returns one IO buf back to free pool. If this is an urgent IO,
20996  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
20997  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
20998  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
20999  * lpfc_io_buf_list_put.
21000  **/
21001 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
21002 			 struct lpfc_sli4_hdw_queue *qp)
21003 {
21004 	unsigned long iflag;
21005 	struct lpfc_pbl_pool *pbl_pool;
21006 	struct lpfc_pvt_pool *pvt_pool;
21007 	struct lpfc_epd_pool *epd_pool;
21008 	u32 txcmplq_cnt;
21009 	u32 xri_owned;
21010 	u32 xri_limit;
21011 	u32 abts_io_bufs;
21012 
21013 	/* MUST zero fields if buffer is reused by another protocol */
21014 	lpfc_ncmd->nvmeCmd = NULL;
21015 	lpfc_ncmd->cur_iocbq.wqe_cmpl = NULL;
21016 	lpfc_ncmd->cur_iocbq.iocb_cmpl = NULL;
21017 
21018 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
21019 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
21020 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
21021 
21022 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
21023 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
21024 
21025 	if (phba->cfg_xri_rebalancing) {
21026 		if (lpfc_ncmd->expedite) {
21027 			/* Return to expedite pool */
21028 			epd_pool = &phba->epd_pool;
21029 			spin_lock_irqsave(&epd_pool->lock, iflag);
21030 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21031 			epd_pool->count++;
21032 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
21033 			return;
21034 		}
21035 
21036 		/* Avoid invalid access if an IO sneaks in and is being rejected
21037 		 * just _after_ xri pools are destroyed in lpfc_offline.
21038 		 * Nothing much can be done at this point.
21039 		 */
21040 		if (!qp->p_multixri_pool)
21041 			return;
21042 
21043 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21044 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21045 
21046 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21047 		abts_io_bufs = qp->abts_scsi_io_bufs;
21048 		abts_io_bufs += qp->abts_nvme_io_bufs;
21049 
21050 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21051 		xri_limit = qp->p_multixri_pool->xri_limit;
21052 
21053 #ifdef LPFC_MXP_STAT
21054 		if (xri_owned <= xri_limit)
21055 			qp->p_multixri_pool->below_limit_count++;
21056 		else
21057 			qp->p_multixri_pool->above_limit_count++;
21058 #endif
21059 
21060 		/* XRI goes to either public or private free xri pool
21061 		 *     based on watermark and xri_limit
21062 		 */
21063 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
21064 		    (xri_owned < xri_limit &&
21065 		     pvt_pool->count < pvt_pool->high_watermark)) {
21066 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
21067 						  qp, free_pvt_pool);
21068 			list_add_tail(&lpfc_ncmd->list,
21069 				      &pvt_pool->list);
21070 			pvt_pool->count++;
21071 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21072 		} else {
21073 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
21074 						  qp, free_pub_pool);
21075 			list_add_tail(&lpfc_ncmd->list,
21076 				      &pbl_pool->list);
21077 			pbl_pool->count++;
21078 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21079 		}
21080 	} else {
21081 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
21082 					  qp, free_xri);
21083 		list_add_tail(&lpfc_ncmd->list,
21084 			      &qp->lpfc_io_buf_list_put);
21085 		qp->put_io_bufs++;
21086 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
21087 				       iflag);
21088 	}
21089 }
21090 
21091 /**
21092  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
21093  * @phba: pointer to lpfc hba data structure.
21094  * @qp: pointer to HDW queue
21095  * @pvt_pool: pointer to private pool data structure.
21096  * @ndlp: pointer to lpfc nodelist data structure.
21097  *
21098  * This routine tries to get one free IO buf from private pool.
21099  *
21100  * Return:
21101  *   pointer to one free IO buf - if private pool is not empty
21102  *   NULL - if private pool is empty
21103  **/
21104 static struct lpfc_io_buf *
21105 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
21106 				  struct lpfc_sli4_hdw_queue *qp,
21107 				  struct lpfc_pvt_pool *pvt_pool,
21108 				  struct lpfc_nodelist *ndlp)
21109 {
21110 	struct lpfc_io_buf *lpfc_ncmd;
21111 	struct lpfc_io_buf *lpfc_ncmd_next;
21112 	unsigned long iflag;
21113 
21114 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
21115 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21116 				 &pvt_pool->list, list) {
21117 		if (lpfc_test_rrq_active(
21118 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
21119 			continue;
21120 		list_del(&lpfc_ncmd->list);
21121 		pvt_pool->count--;
21122 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21123 		return lpfc_ncmd;
21124 	}
21125 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21126 
21127 	return NULL;
21128 }
21129 
21130 /**
21131  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
21132  * @phba: pointer to lpfc hba data structure.
21133  *
21134  * This routine tries to get one free IO buf from expedite pool.
21135  *
21136  * Return:
21137  *   pointer to one free IO buf - if expedite pool is not empty
21138  *   NULL - if expedite pool is empty
21139  **/
21140 static struct lpfc_io_buf *
21141 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
21142 {
21143 	struct lpfc_io_buf *lpfc_ncmd;
21144 	struct lpfc_io_buf *lpfc_ncmd_next;
21145 	unsigned long iflag;
21146 	struct lpfc_epd_pool *epd_pool;
21147 
21148 	epd_pool = &phba->epd_pool;
21149 	lpfc_ncmd = NULL;
21150 
21151 	spin_lock_irqsave(&epd_pool->lock, iflag);
21152 	if (epd_pool->count > 0) {
21153 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21154 					 &epd_pool->list, list) {
21155 			list_del(&lpfc_ncmd->list);
21156 			epd_pool->count--;
21157 			break;
21158 		}
21159 	}
21160 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
21161 
21162 	return lpfc_ncmd;
21163 }
21164 
21165 /**
21166  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
21167  * @phba: pointer to lpfc hba data structure.
21168  * @ndlp: pointer to lpfc nodelist data structure.
21169  * @hwqid: belong to which HWQ
21170  * @expedite: 1 means this request is urgent.
21171  *
21172  * This routine will do the following actions and then return a pointer to
21173  * one free IO buf.
21174  *
21175  * 1. If private free xri count is empty, move some XRIs from public to
21176  *    private pool.
21177  * 2. Get one XRI from private free xri pool.
21178  * 3. If we fail to get one from pvt_pool and this is an expedite request,
21179  *    get one free xri from expedite pool.
21180  *
21181  * Note: ndlp is only used on SCSI side for RRQ testing.
21182  *       The caller should pass NULL for ndlp on NVME side.
21183  *
21184  * Return:
21185  *   pointer to one free IO buf - if private pool is not empty
21186  *   NULL - if private pool is empty
21187  **/
21188 static struct lpfc_io_buf *
21189 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
21190 				    struct lpfc_nodelist *ndlp,
21191 				    int hwqid, int expedite)
21192 {
21193 	struct lpfc_sli4_hdw_queue *qp;
21194 	struct lpfc_multixri_pool *multixri_pool;
21195 	struct lpfc_pvt_pool *pvt_pool;
21196 	struct lpfc_io_buf *lpfc_ncmd;
21197 
21198 	qp = &phba->sli4_hba.hdwq[hwqid];
21199 	lpfc_ncmd = NULL;
21200 	multixri_pool = qp->p_multixri_pool;
21201 	pvt_pool = &multixri_pool->pvt_pool;
21202 	multixri_pool->io_req_count++;
21203 
21204 	/* If pvt_pool is empty, move some XRIs from public to private pool */
21205 	if (pvt_pool->count == 0)
21206 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21207 
21208 	/* Get one XRI from private free xri pool */
21209 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
21210 
21211 	if (lpfc_ncmd) {
21212 		lpfc_ncmd->hdwq = qp;
21213 		lpfc_ncmd->hdwq_no = hwqid;
21214 	} else if (expedite) {
21215 		/* If we fail to get one from pvt_pool and this is an expedite
21216 		 * request, get one free xri from expedite pool.
21217 		 */
21218 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
21219 	}
21220 
21221 	return lpfc_ncmd;
21222 }
21223 
21224 static inline struct lpfc_io_buf *
21225 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
21226 {
21227 	struct lpfc_sli4_hdw_queue *qp;
21228 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
21229 
21230 	qp = &phba->sli4_hba.hdwq[idx];
21231 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
21232 				 &qp->lpfc_io_buf_list_get, list) {
21233 		if (lpfc_test_rrq_active(phba, ndlp,
21234 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
21235 			continue;
21236 
21237 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
21238 			continue;
21239 
21240 		list_del_init(&lpfc_cmd->list);
21241 		qp->get_io_bufs--;
21242 		lpfc_cmd->hdwq = qp;
21243 		lpfc_cmd->hdwq_no = idx;
21244 		return lpfc_cmd;
21245 	}
21246 	return NULL;
21247 }
21248 
21249 /**
21250  * lpfc_get_io_buf - Get one IO buffer from free pool
21251  * @phba: The HBA for which this call is being executed.
21252  * @ndlp: pointer to lpfc nodelist data structure.
21253  * @hwqid: belong to which HWQ
21254  * @expedite: 1 means this request is urgent.
21255  *
21256  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
21257  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
21258  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
21259  *
21260  * Note: ndlp is only used on SCSI side for RRQ testing.
21261  *       The caller should pass NULL for ndlp on NVME side.
21262  *
21263  * Return codes:
21264  *   NULL - Error
21265  *   Pointer to lpfc_io_buf - Success
21266  **/
21267 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
21268 				    struct lpfc_nodelist *ndlp,
21269 				    u32 hwqid, int expedite)
21270 {
21271 	struct lpfc_sli4_hdw_queue *qp;
21272 	unsigned long iflag;
21273 	struct lpfc_io_buf *lpfc_cmd;
21274 
21275 	qp = &phba->sli4_hba.hdwq[hwqid];
21276 	lpfc_cmd = NULL;
21277 
21278 	if (phba->cfg_xri_rebalancing)
21279 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
21280 			phba, ndlp, hwqid, expedite);
21281 	else {
21282 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
21283 					  qp, alloc_xri_get);
21284 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
21285 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
21286 		if (!lpfc_cmd) {
21287 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
21288 					  qp, alloc_xri_put);
21289 			list_splice(&qp->lpfc_io_buf_list_put,
21290 				    &qp->lpfc_io_buf_list_get);
21291 			qp->get_io_bufs += qp->put_io_bufs;
21292 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
21293 			qp->put_io_bufs = 0;
21294 			spin_unlock(&qp->io_buf_list_put_lock);
21295 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
21296 			    expedite)
21297 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
21298 		}
21299 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
21300 	}
21301 
21302 	return lpfc_cmd;
21303 }
21304 
21305 /**
21306  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
21307  * @phba: The HBA for which this call is being executed.
21308  * @lpfc_buf: IO buf structure to append the SGL chunk
21309  *
21310  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
21311  * and will allocate an SGL chunk if the pool is empty.
21312  *
21313  * Return codes:
21314  *   NULL - Error
21315  *   Pointer to sli4_hybrid_sgl - Success
21316  **/
21317 struct sli4_hybrid_sgl *
21318 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
21319 {
21320 	struct sli4_hybrid_sgl *list_entry = NULL;
21321 	struct sli4_hybrid_sgl *tmp = NULL;
21322 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
21323 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21324 	struct list_head *buf_list = &hdwq->sgl_list;
21325 	unsigned long iflags;
21326 
21327 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21328 
21329 	if (likely(!list_empty(buf_list))) {
21330 		/* break off 1 chunk from the sgl_list */
21331 		list_for_each_entry_safe(list_entry, tmp,
21332 					 buf_list, list_node) {
21333 			list_move_tail(&list_entry->list_node,
21334 				       &lpfc_buf->dma_sgl_xtra_list);
21335 			break;
21336 		}
21337 	} else {
21338 		/* allocate more */
21339 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21340 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
21341 				   cpu_to_node(hdwq->io_wq->chann));
21342 		if (!tmp) {
21343 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21344 					"8353 error kmalloc memory for HDWQ "
21345 					"%d %s\n",
21346 					lpfc_buf->hdwq_no, __func__);
21347 			return NULL;
21348 		}
21349 
21350 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
21351 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
21352 		if (!tmp->dma_sgl) {
21353 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21354 					"8354 error pool_alloc memory for HDWQ "
21355 					"%d %s\n",
21356 					lpfc_buf->hdwq_no, __func__);
21357 			kfree(tmp);
21358 			return NULL;
21359 		}
21360 
21361 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21362 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
21363 	}
21364 
21365 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
21366 					struct sli4_hybrid_sgl,
21367 					list_node);
21368 
21369 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21370 
21371 	return allocated_sgl;
21372 }
21373 
21374 /**
21375  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
21376  * @phba: The HBA for which this call is being executed.
21377  * @lpfc_buf: IO buf structure with the SGL chunk
21378  *
21379  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
21380  *
21381  * Return codes:
21382  *   0 - Success
21383  *   -EINVAL - Error
21384  **/
21385 int
21386 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
21387 {
21388 	int rc = 0;
21389 	struct sli4_hybrid_sgl *list_entry = NULL;
21390 	struct sli4_hybrid_sgl *tmp = NULL;
21391 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21392 	struct list_head *buf_list = &hdwq->sgl_list;
21393 	unsigned long iflags;
21394 
21395 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21396 
21397 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
21398 		list_for_each_entry_safe(list_entry, tmp,
21399 					 &lpfc_buf->dma_sgl_xtra_list,
21400 					 list_node) {
21401 			list_move_tail(&list_entry->list_node,
21402 				       buf_list);
21403 		}
21404 	} else {
21405 		rc = -EINVAL;
21406 	}
21407 
21408 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21409 	return rc;
21410 }
21411 
21412 /**
21413  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
21414  * @phba: phba object
21415  * @hdwq: hdwq to cleanup sgl buff resources on
21416  *
21417  * This routine frees all SGL chunks of hdwq SGL chunk pool.
21418  *
21419  * Return codes:
21420  *   None
21421  **/
21422 void
21423 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
21424 		       struct lpfc_sli4_hdw_queue *hdwq)
21425 {
21426 	struct list_head *buf_list = &hdwq->sgl_list;
21427 	struct sli4_hybrid_sgl *list_entry = NULL;
21428 	struct sli4_hybrid_sgl *tmp = NULL;
21429 	unsigned long iflags;
21430 
21431 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21432 
21433 	/* Free sgl pool */
21434 	list_for_each_entry_safe(list_entry, tmp,
21435 				 buf_list, list_node) {
21436 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
21437 			      list_entry->dma_sgl,
21438 			      list_entry->dma_phys_sgl);
21439 		list_del(&list_entry->list_node);
21440 		kfree(list_entry);
21441 	}
21442 
21443 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21444 }
21445 
21446 /**
21447  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
21448  * @phba: The HBA for which this call is being executed.
21449  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
21450  *
21451  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
21452  * and will allocate an CMD/RSP buffer if the pool is empty.
21453  *
21454  * Return codes:
21455  *   NULL - Error
21456  *   Pointer to fcp_cmd_rsp_buf - Success
21457  **/
21458 struct fcp_cmd_rsp_buf *
21459 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
21460 			      struct lpfc_io_buf *lpfc_buf)
21461 {
21462 	struct fcp_cmd_rsp_buf *list_entry = NULL;
21463 	struct fcp_cmd_rsp_buf *tmp = NULL;
21464 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
21465 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21466 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
21467 	unsigned long iflags;
21468 
21469 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21470 
21471 	if (likely(!list_empty(buf_list))) {
21472 		/* break off 1 chunk from the list */
21473 		list_for_each_entry_safe(list_entry, tmp,
21474 					 buf_list,
21475 					 list_node) {
21476 			list_move_tail(&list_entry->list_node,
21477 				       &lpfc_buf->dma_cmd_rsp_list);
21478 			break;
21479 		}
21480 	} else {
21481 		/* allocate more */
21482 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21483 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
21484 				   cpu_to_node(hdwq->io_wq->chann));
21485 		if (!tmp) {
21486 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21487 					"8355 error kmalloc memory for HDWQ "
21488 					"%d %s\n",
21489 					lpfc_buf->hdwq_no, __func__);
21490 			return NULL;
21491 		}
21492 
21493 		tmp->fcp_cmnd = dma_pool_alloc(phba->lpfc_cmd_rsp_buf_pool,
21494 						GFP_ATOMIC,
21495 						&tmp->fcp_cmd_rsp_dma_handle);
21496 
21497 		if (!tmp->fcp_cmnd) {
21498 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21499 					"8356 error pool_alloc memory for HDWQ "
21500 					"%d %s\n",
21501 					lpfc_buf->hdwq_no, __func__);
21502 			kfree(tmp);
21503 			return NULL;
21504 		}
21505 
21506 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
21507 				sizeof(struct fcp_cmnd));
21508 
21509 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21510 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
21511 	}
21512 
21513 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
21514 					struct fcp_cmd_rsp_buf,
21515 					list_node);
21516 
21517 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21518 
21519 	return allocated_buf;
21520 }
21521 
21522 /**
21523  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
21524  * @phba: The HBA for which this call is being executed.
21525  * @lpfc_buf: IO buf structure with the CMD/RSP buf
21526  *
21527  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
21528  *
21529  * Return codes:
21530  *   0 - Success
21531  *   -EINVAL - Error
21532  **/
21533 int
21534 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
21535 			      struct lpfc_io_buf *lpfc_buf)
21536 {
21537 	int rc = 0;
21538 	struct fcp_cmd_rsp_buf *list_entry = NULL;
21539 	struct fcp_cmd_rsp_buf *tmp = NULL;
21540 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21541 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
21542 	unsigned long iflags;
21543 
21544 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21545 
21546 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
21547 		list_for_each_entry_safe(list_entry, tmp,
21548 					 &lpfc_buf->dma_cmd_rsp_list,
21549 					 list_node) {
21550 			list_move_tail(&list_entry->list_node,
21551 				       buf_list);
21552 		}
21553 	} else {
21554 		rc = -EINVAL;
21555 	}
21556 
21557 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21558 	return rc;
21559 }
21560 
21561 /**
21562  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
21563  * @phba: phba object
21564  * @hdwq: hdwq to cleanup cmd rsp buff resources on
21565  *
21566  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
21567  *
21568  * Return codes:
21569  *   None
21570  **/
21571 void
21572 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
21573 			       struct lpfc_sli4_hdw_queue *hdwq)
21574 {
21575 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
21576 	struct fcp_cmd_rsp_buf *list_entry = NULL;
21577 	struct fcp_cmd_rsp_buf *tmp = NULL;
21578 	unsigned long iflags;
21579 
21580 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21581 
21582 	/* Free cmd_rsp buf pool */
21583 	list_for_each_entry_safe(list_entry, tmp,
21584 				 buf_list,
21585 				 list_node) {
21586 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
21587 			      list_entry->fcp_cmnd,
21588 			      list_entry->fcp_cmd_rsp_dma_handle);
21589 		list_del(&list_entry->list_node);
21590 		kfree(list_entry);
21591 	}
21592 
21593 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21594 }
21595