xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision 28dce2c4)
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 	/* Check security permission status on INIT_LINK mailbox command */
2683 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2684 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2685 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2686 				"2860 SLI authentication is required "
2687 				"for INIT_LINK but has not done yet\n");
2688 
2689 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2690 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2691 	else
2692 		mempool_free(pmb, phba->mbox_mem_pool);
2693 }
2694  /**
2695  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2696  * @phba: Pointer to HBA context object.
2697  * @pmb: Pointer to mailbox object.
2698  *
2699  * This function is the unreg rpi mailbox completion handler. It
2700  * frees the memory resources associated with the completed mailbox
2701  * command. An additional reference is put on the ndlp to prevent
2702  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2703  * the unreg mailbox command completes, this routine puts the
2704  * reference back.
2705  *
2706  **/
2707 void
2708 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2709 {
2710 	struct lpfc_vport  *vport = pmb->vport;
2711 	struct lpfc_nodelist *ndlp;
2712 
2713 	ndlp = pmb->ctx_ndlp;
2714 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2715 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2716 		    (bf_get(lpfc_sli_intf_if_type,
2717 		     &phba->sli4_hba.sli_intf) >=
2718 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2719 			if (ndlp) {
2720 				lpfc_printf_vlog(
2721 					 vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2722 					 "0010 UNREG_LOGIN vpi:%x "
2723 					 "rpi:%x DID:%x defer x%x flg x%x "
2724 					 "x%px\n",
2725 					 vport->vpi, ndlp->nlp_rpi,
2726 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
2727 					 ndlp->nlp_flag,
2728 					 ndlp);
2729 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2730 
2731 				/* Check to see if there are any deferred
2732 				 * events to process
2733 				 */
2734 				if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2735 				    (ndlp->nlp_defer_did !=
2736 				    NLP_EVT_NOTHING_PENDING)) {
2737 					lpfc_printf_vlog(
2738 						vport, KERN_INFO, LOG_DISCOVERY,
2739 						"4111 UNREG cmpl deferred "
2740 						"clr x%x on "
2741 						"NPort x%x Data: x%x x%px\n",
2742 						ndlp->nlp_rpi, ndlp->nlp_DID,
2743 						ndlp->nlp_defer_did, ndlp);
2744 					ndlp->nlp_flag &= ~NLP_UNREG_INP;
2745 					ndlp->nlp_defer_did =
2746 						NLP_EVT_NOTHING_PENDING;
2747 					lpfc_issue_els_plogi(
2748 						vport, ndlp->nlp_DID, 0);
2749 				} else {
2750 					__lpfc_sli_rpi_release(vport, ndlp);
2751 				}
2752 
2753 				lpfc_nlp_put(ndlp);
2754 			}
2755 		}
2756 	}
2757 
2758 	mempool_free(pmb, phba->mbox_mem_pool);
2759 }
2760 
2761 /**
2762  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
2763  * @phba: Pointer to HBA context object.
2764  *
2765  * This function is called with no lock held. This function processes all
2766  * the completed mailbox commands and gives it to upper layers. The interrupt
2767  * service routine processes mailbox completion interrupt and adds completed
2768  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
2769  * Worker thread call lpfc_sli_handle_mb_event, which will return the
2770  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
2771  * function returns the mailbox commands to the upper layer by calling the
2772  * completion handler function of each mailbox.
2773  **/
2774 int
2775 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
2776 {
2777 	MAILBOX_t *pmbox;
2778 	LPFC_MBOXQ_t *pmb;
2779 	int rc;
2780 	LIST_HEAD(cmplq);
2781 
2782 	phba->sli.slistat.mbox_event++;
2783 
2784 	/* Get all completed mailboxe buffers into the cmplq */
2785 	spin_lock_irq(&phba->hbalock);
2786 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
2787 	spin_unlock_irq(&phba->hbalock);
2788 
2789 	/* Get a Mailbox buffer to setup mailbox commands for callback */
2790 	do {
2791 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
2792 		if (pmb == NULL)
2793 			break;
2794 
2795 		pmbox = &pmb->u.mb;
2796 
2797 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
2798 			if (pmb->vport) {
2799 				lpfc_debugfs_disc_trc(pmb->vport,
2800 					LPFC_DISC_TRC_MBOX_VPORT,
2801 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
2802 					(uint32_t)pmbox->mbxCommand,
2803 					pmbox->un.varWords[0],
2804 					pmbox->un.varWords[1]);
2805 			}
2806 			else {
2807 				lpfc_debugfs_disc_trc(phba->pport,
2808 					LPFC_DISC_TRC_MBOX,
2809 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
2810 					(uint32_t)pmbox->mbxCommand,
2811 					pmbox->un.varWords[0],
2812 					pmbox->un.varWords[1]);
2813 			}
2814 		}
2815 
2816 		/*
2817 		 * It is a fatal error if unknown mbox command completion.
2818 		 */
2819 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
2820 		    MBX_SHUTDOWN) {
2821 			/* Unknown mailbox command compl */
2822 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2823 					"(%d):0323 Unknown Mailbox command "
2824 					"x%x (x%x/x%x) Cmpl\n",
2825 					pmb->vport ? pmb->vport->vpi :
2826 					LPFC_VPORT_UNKNOWN,
2827 					pmbox->mbxCommand,
2828 					lpfc_sli_config_mbox_subsys_get(phba,
2829 									pmb),
2830 					lpfc_sli_config_mbox_opcode_get(phba,
2831 									pmb));
2832 			phba->link_state = LPFC_HBA_ERROR;
2833 			phba->work_hs = HS_FFER3;
2834 			lpfc_handle_eratt(phba);
2835 			continue;
2836 		}
2837 
2838 		if (pmbox->mbxStatus) {
2839 			phba->sli.slistat.mbox_stat_err++;
2840 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
2841 				/* Mbox cmd cmpl error - RETRYing */
2842 				lpfc_printf_log(phba, KERN_INFO,
2843 					LOG_MBOX | LOG_SLI,
2844 					"(%d):0305 Mbox cmd cmpl "
2845 					"error - RETRYing Data: x%x "
2846 					"(x%x/x%x) x%x x%x x%x\n",
2847 					pmb->vport ? pmb->vport->vpi :
2848 					LPFC_VPORT_UNKNOWN,
2849 					pmbox->mbxCommand,
2850 					lpfc_sli_config_mbox_subsys_get(phba,
2851 									pmb),
2852 					lpfc_sli_config_mbox_opcode_get(phba,
2853 									pmb),
2854 					pmbox->mbxStatus,
2855 					pmbox->un.varWords[0],
2856 					pmb->vport ? pmb->vport->port_state :
2857 					LPFC_VPORT_UNKNOWN);
2858 				pmbox->mbxStatus = 0;
2859 				pmbox->mbxOwner = OWN_HOST;
2860 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2861 				if (rc != MBX_NOT_FINISHED)
2862 					continue;
2863 			}
2864 		}
2865 
2866 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
2867 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
2868 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
2869 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
2870 				"x%x x%x x%x\n",
2871 				pmb->vport ? pmb->vport->vpi : 0,
2872 				pmbox->mbxCommand,
2873 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
2874 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
2875 				pmb->mbox_cmpl,
2876 				*((uint32_t *) pmbox),
2877 				pmbox->un.varWords[0],
2878 				pmbox->un.varWords[1],
2879 				pmbox->un.varWords[2],
2880 				pmbox->un.varWords[3],
2881 				pmbox->un.varWords[4],
2882 				pmbox->un.varWords[5],
2883 				pmbox->un.varWords[6],
2884 				pmbox->un.varWords[7],
2885 				pmbox->un.varWords[8],
2886 				pmbox->un.varWords[9],
2887 				pmbox->un.varWords[10]);
2888 
2889 		if (pmb->mbox_cmpl)
2890 			pmb->mbox_cmpl(phba,pmb);
2891 	} while (1);
2892 	return 0;
2893 }
2894 
2895 /**
2896  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
2897  * @phba: Pointer to HBA context object.
2898  * @pring: Pointer to driver SLI ring object.
2899  * @tag: buffer tag.
2900  *
2901  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
2902  * is set in the tag the buffer is posted for a particular exchange,
2903  * the function will return the buffer without replacing the buffer.
2904  * If the buffer is for unsolicited ELS or CT traffic, this function
2905  * returns the buffer and also posts another buffer to the firmware.
2906  **/
2907 static struct lpfc_dmabuf *
2908 lpfc_sli_get_buff(struct lpfc_hba *phba,
2909 		  struct lpfc_sli_ring *pring,
2910 		  uint32_t tag)
2911 {
2912 	struct hbq_dmabuf *hbq_entry;
2913 
2914 	if (tag & QUE_BUFTAG_BIT)
2915 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
2916 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
2917 	if (!hbq_entry)
2918 		return NULL;
2919 	return &hbq_entry->dbuf;
2920 }
2921 
2922 /**
2923  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
2924  *                              containing a NVME LS request.
2925  * @phba: pointer to lpfc hba data structure.
2926  * @piocb: pointer to the iocbq struct representing the sequence starting
2927  *        frame.
2928  *
2929  * This routine initially validates the NVME LS, validates there is a login
2930  * with the port that sent the LS, and then calls the appropriate nvme host
2931  * or target LS request handler.
2932  **/
2933 static void
2934 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
2935 {
2936 	struct lpfc_nodelist *ndlp;
2937 	struct lpfc_dmabuf *d_buf;
2938 	struct hbq_dmabuf *nvmebuf;
2939 	struct fc_frame_header *fc_hdr;
2940 	struct lpfc_async_xchg_ctx *axchg = NULL;
2941 	char *failwhy = NULL;
2942 	uint32_t oxid, sid, did, fctl, size;
2943 	int ret = 1;
2944 
2945 	d_buf = piocb->context2;
2946 
2947 	nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2948 	fc_hdr = nvmebuf->hbuf.virt;
2949 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
2950 	sid = sli4_sid_from_fc_hdr(fc_hdr);
2951 	did = sli4_did_from_fc_hdr(fc_hdr);
2952 	fctl = (fc_hdr->fh_f_ctl[0] << 16 |
2953 		fc_hdr->fh_f_ctl[1] << 8 |
2954 		fc_hdr->fh_f_ctl[2]);
2955 	size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
2956 
2957 	lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
2958 			 oxid, size, sid);
2959 
2960 	if (phba->pport->load_flag & FC_UNLOADING) {
2961 		failwhy = "Driver Unloading";
2962 	} else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
2963 		failwhy = "NVME FC4 Disabled";
2964 	} else if (!phba->nvmet_support && !phba->pport->localport) {
2965 		failwhy = "No Localport";
2966 	} else if (phba->nvmet_support && !phba->targetport) {
2967 		failwhy = "No Targetport";
2968 	} else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
2969 		failwhy = "Bad NVME LS R_CTL";
2970 	} else if (unlikely((fctl & 0x00FF0000) !=
2971 			(FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
2972 		failwhy = "Bad NVME LS F_CTL";
2973 	} else {
2974 		axchg = kzalloc(sizeof(*axchg), GFP_ATOMIC);
2975 		if (!axchg)
2976 			failwhy = "No CTX memory";
2977 	}
2978 
2979 	if (unlikely(failwhy)) {
2980 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2981 				"6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
2982 				sid, oxid, failwhy);
2983 		goto out_fail;
2984 	}
2985 
2986 	/* validate the source of the LS is logged in */
2987 	ndlp = lpfc_findnode_did(phba->pport, sid);
2988 	if (!ndlp ||
2989 	    ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
2990 	     (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
2991 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
2992 				"6216 NVME Unsol rcv: No ndlp: "
2993 				"NPort_ID x%x oxid x%x\n",
2994 				sid, oxid);
2995 		goto out_fail;
2996 	}
2997 
2998 	axchg->phba = phba;
2999 	axchg->ndlp = ndlp;
3000 	axchg->size = size;
3001 	axchg->oxid = oxid;
3002 	axchg->sid = sid;
3003 	axchg->wqeq = NULL;
3004 	axchg->state = LPFC_NVME_STE_LS_RCV;
3005 	axchg->entry_cnt = 1;
3006 	axchg->rqb_buffer = (void *)nvmebuf;
3007 	axchg->hdwq = &phba->sli4_hba.hdwq[0];
3008 	axchg->payload = nvmebuf->dbuf.virt;
3009 	INIT_LIST_HEAD(&axchg->list);
3010 
3011 	if (phba->nvmet_support) {
3012 		ret = lpfc_nvmet_handle_lsreq(phba, axchg);
3013 		spin_lock_irq(&ndlp->lock);
3014 		if (!ret && !(ndlp->fc4_xpt_flags & NLP_XPT_HAS_HH)) {
3015 			ndlp->fc4_xpt_flags |= NLP_XPT_HAS_HH;
3016 			spin_unlock_irq(&ndlp->lock);
3017 
3018 			/* This reference is a single occurrence to hold the
3019 			 * node valid until the nvmet transport calls
3020 			 * host_release.
3021 			 */
3022 			if (!lpfc_nlp_get(ndlp))
3023 				goto out_fail;
3024 
3025 			lpfc_printf_log(phba, KERN_ERR, LOG_NODE,
3026 					"6206 NVMET unsol ls_req ndlp x%px "
3027 					"DID x%x xflags x%x refcnt %d\n",
3028 					ndlp, ndlp->nlp_DID,
3029 					ndlp->fc4_xpt_flags,
3030 					kref_read(&ndlp->kref));
3031 		} else {
3032 			spin_unlock_irq(&ndlp->lock);
3033 		}
3034 	} else {
3035 		ret = lpfc_nvme_handle_lsreq(phba, axchg);
3036 	}
3037 
3038 	/* if zero, LS was successfully handled. If non-zero, LS not handled */
3039 	if (!ret)
3040 		return;
3041 
3042 out_fail:
3043 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3044 			"6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
3045 			"NVMe%s handler failed %d\n",
3046 			did, sid, oxid,
3047 			(phba->nvmet_support) ? "T" : "I", ret);
3048 
3049 	/* recycle receive buffer */
3050 	lpfc_in_buf_free(phba, &nvmebuf->dbuf);
3051 
3052 	/* If start of new exchange, abort it */
3053 	if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
3054 		ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
3055 
3056 	if (ret)
3057 		kfree(axchg);
3058 }
3059 
3060 /**
3061  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
3062  * @phba: Pointer to HBA context object.
3063  * @pring: Pointer to driver SLI ring object.
3064  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
3065  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
3066  * @fch_type: the type for the first frame of the sequence.
3067  *
3068  * This function is called with no lock held. This function uses the r_ctl and
3069  * type of the received sequence to find the correct callback function to call
3070  * to process the sequence.
3071  **/
3072 static int
3073 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3074 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
3075 			 uint32_t fch_type)
3076 {
3077 	int i;
3078 
3079 	switch (fch_type) {
3080 	case FC_TYPE_NVME:
3081 		lpfc_nvme_unsol_ls_handler(phba, saveq);
3082 		return 1;
3083 	default:
3084 		break;
3085 	}
3086 
3087 	/* unSolicited Responses */
3088 	if (pring->prt[0].profile) {
3089 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
3090 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
3091 									saveq);
3092 		return 1;
3093 	}
3094 	/* We must search, based on rctl / type
3095 	   for the right routine */
3096 	for (i = 0; i < pring->num_mask; i++) {
3097 		if ((pring->prt[i].rctl == fch_r_ctl) &&
3098 		    (pring->prt[i].type == fch_type)) {
3099 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
3100 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
3101 						(phba, pring, saveq);
3102 			return 1;
3103 		}
3104 	}
3105 	return 0;
3106 }
3107 
3108 /**
3109  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
3110  * @phba: Pointer to HBA context object.
3111  * @pring: Pointer to driver SLI ring object.
3112  * @saveq: Pointer to the unsolicited iocb.
3113  *
3114  * This function is called with no lock held by the ring event handler
3115  * when there is an unsolicited iocb posted to the response ring by the
3116  * firmware. This function gets the buffer associated with the iocbs
3117  * and calls the event handler for the ring. This function handles both
3118  * qring buffers and hbq buffers.
3119  * When the function returns 1 the caller can free the iocb object otherwise
3120  * upper layer functions will free the iocb objects.
3121  **/
3122 static int
3123 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3124 			    struct lpfc_iocbq *saveq)
3125 {
3126 	IOCB_t           * irsp;
3127 	WORD5            * w5p;
3128 	uint32_t           Rctl, Type;
3129 	struct lpfc_iocbq *iocbq;
3130 	struct lpfc_dmabuf *dmzbuf;
3131 
3132 	irsp = &(saveq->iocb);
3133 
3134 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
3135 		if (pring->lpfc_sli_rcv_async_status)
3136 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
3137 		else
3138 			lpfc_printf_log(phba,
3139 					KERN_WARNING,
3140 					LOG_SLI,
3141 					"0316 Ring %d handler: unexpected "
3142 					"ASYNC_STATUS iocb received evt_code "
3143 					"0x%x\n",
3144 					pring->ringno,
3145 					irsp->un.asyncstat.evt_code);
3146 		return 1;
3147 	}
3148 
3149 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3150 		(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3151 		if (irsp->ulpBdeCount > 0) {
3152 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3153 					irsp->un.ulpWord[3]);
3154 			lpfc_in_buf_free(phba, dmzbuf);
3155 		}
3156 
3157 		if (irsp->ulpBdeCount > 1) {
3158 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3159 					irsp->unsli3.sli3Words[3]);
3160 			lpfc_in_buf_free(phba, dmzbuf);
3161 		}
3162 
3163 		if (irsp->ulpBdeCount > 2) {
3164 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3165 				irsp->unsli3.sli3Words[7]);
3166 			lpfc_in_buf_free(phba, dmzbuf);
3167 		}
3168 
3169 		return 1;
3170 	}
3171 
3172 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3173 		if (irsp->ulpBdeCount != 0) {
3174 			saveq->context2 = lpfc_sli_get_buff(phba, pring,
3175 						irsp->un.ulpWord[3]);
3176 			if (!saveq->context2)
3177 				lpfc_printf_log(phba,
3178 					KERN_ERR,
3179 					LOG_SLI,
3180 					"0341 Ring %d Cannot find buffer for "
3181 					"an unsolicited iocb. tag 0x%x\n",
3182 					pring->ringno,
3183 					irsp->un.ulpWord[3]);
3184 		}
3185 		if (irsp->ulpBdeCount == 2) {
3186 			saveq->context3 = lpfc_sli_get_buff(phba, pring,
3187 						irsp->unsli3.sli3Words[7]);
3188 			if (!saveq->context3)
3189 				lpfc_printf_log(phba,
3190 					KERN_ERR,
3191 					LOG_SLI,
3192 					"0342 Ring %d Cannot find buffer for an"
3193 					" unsolicited iocb. tag 0x%x\n",
3194 					pring->ringno,
3195 					irsp->unsli3.sli3Words[7]);
3196 		}
3197 		list_for_each_entry(iocbq, &saveq->list, list) {
3198 			irsp = &(iocbq->iocb);
3199 			if (irsp->ulpBdeCount != 0) {
3200 				iocbq->context2 = lpfc_sli_get_buff(phba, pring,
3201 							irsp->un.ulpWord[3]);
3202 				if (!iocbq->context2)
3203 					lpfc_printf_log(phba,
3204 						KERN_ERR,
3205 						LOG_SLI,
3206 						"0343 Ring %d Cannot find "
3207 						"buffer for an unsolicited iocb"
3208 						". tag 0x%x\n", pring->ringno,
3209 						irsp->un.ulpWord[3]);
3210 			}
3211 			if (irsp->ulpBdeCount == 2) {
3212 				iocbq->context3 = lpfc_sli_get_buff(phba, pring,
3213 						irsp->unsli3.sli3Words[7]);
3214 				if (!iocbq->context3)
3215 					lpfc_printf_log(phba,
3216 						KERN_ERR,
3217 						LOG_SLI,
3218 						"0344 Ring %d Cannot find "
3219 						"buffer for an unsolicited "
3220 						"iocb. tag 0x%x\n",
3221 						pring->ringno,
3222 						irsp->unsli3.sli3Words[7]);
3223 			}
3224 		}
3225 	}
3226 	if (irsp->ulpBdeCount != 0 &&
3227 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3228 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3229 		int found = 0;
3230 
3231 		/* search continue save q for same XRI */
3232 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3233 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3234 				saveq->iocb.unsli3.rcvsli3.ox_id) {
3235 				list_add_tail(&saveq->list, &iocbq->list);
3236 				found = 1;
3237 				break;
3238 			}
3239 		}
3240 		if (!found)
3241 			list_add_tail(&saveq->clist,
3242 				      &pring->iocb_continue_saveq);
3243 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3244 			list_del_init(&iocbq->clist);
3245 			saveq = iocbq;
3246 			irsp = &(saveq->iocb);
3247 		} else
3248 			return 0;
3249 	}
3250 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3251 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3252 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3253 		Rctl = FC_RCTL_ELS_REQ;
3254 		Type = FC_TYPE_ELS;
3255 	} else {
3256 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3257 		Rctl = w5p->hcsw.Rctl;
3258 		Type = w5p->hcsw.Type;
3259 
3260 		/* Firmware Workaround */
3261 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3262 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3263 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3264 			Rctl = FC_RCTL_ELS_REQ;
3265 			Type = FC_TYPE_ELS;
3266 			w5p->hcsw.Rctl = Rctl;
3267 			w5p->hcsw.Type = Type;
3268 		}
3269 	}
3270 
3271 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3272 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3273 				"0313 Ring %d handler: unexpected Rctl x%x "
3274 				"Type x%x received\n",
3275 				pring->ringno, Rctl, Type);
3276 
3277 	return 1;
3278 }
3279 
3280 /**
3281  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3282  * @phba: Pointer to HBA context object.
3283  * @pring: Pointer to driver SLI ring object.
3284  * @prspiocb: Pointer to response iocb object.
3285  *
3286  * This function looks up the iocb_lookup table to get the command iocb
3287  * corresponding to the given response iocb using the iotag of the
3288  * response iocb. The driver calls this function with the hbalock held
3289  * for SLI3 ports or the ring lock held for SLI4 ports.
3290  * This function returns the command iocb object if it finds the command
3291  * iocb else returns NULL.
3292  **/
3293 static struct lpfc_iocbq *
3294 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3295 		      struct lpfc_sli_ring *pring,
3296 		      struct lpfc_iocbq *prspiocb)
3297 {
3298 	struct lpfc_iocbq *cmd_iocb = NULL;
3299 	uint16_t iotag;
3300 	spinlock_t *temp_lock = NULL;
3301 	unsigned long iflag = 0;
3302 
3303 	if (phba->sli_rev == LPFC_SLI_REV4)
3304 		temp_lock = &pring->ring_lock;
3305 	else
3306 		temp_lock = &phba->hbalock;
3307 
3308 	spin_lock_irqsave(temp_lock, iflag);
3309 	iotag = prspiocb->iocb.ulpIoTag;
3310 
3311 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3312 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3313 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3314 			/* remove from txcmpl queue list */
3315 			list_del_init(&cmd_iocb->list);
3316 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3317 			pring->txcmplq_cnt--;
3318 			spin_unlock_irqrestore(temp_lock, iflag);
3319 			return cmd_iocb;
3320 		}
3321 	}
3322 
3323 	spin_unlock_irqrestore(temp_lock, iflag);
3324 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3325 			"0317 iotag x%x is out of "
3326 			"range: max iotag x%x wd0 x%x\n",
3327 			iotag, phba->sli.last_iotag,
3328 			*(((uint32_t *) &prspiocb->iocb) + 7));
3329 	return NULL;
3330 }
3331 
3332 /**
3333  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3334  * @phba: Pointer to HBA context object.
3335  * @pring: Pointer to driver SLI ring object.
3336  * @iotag: IOCB tag.
3337  *
3338  * This function looks up the iocb_lookup table to get the command iocb
3339  * corresponding to the given iotag. The driver calls this function with
3340  * the ring lock held because this function is an SLI4 port only helper.
3341  * This function returns the command iocb object if it finds the command
3342  * iocb else returns NULL.
3343  **/
3344 static struct lpfc_iocbq *
3345 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3346 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3347 {
3348 	struct lpfc_iocbq *cmd_iocb = NULL;
3349 	spinlock_t *temp_lock = NULL;
3350 	unsigned long iflag = 0;
3351 
3352 	if (phba->sli_rev == LPFC_SLI_REV4)
3353 		temp_lock = &pring->ring_lock;
3354 	else
3355 		temp_lock = &phba->hbalock;
3356 
3357 	spin_lock_irqsave(temp_lock, iflag);
3358 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3359 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3360 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3361 			/* remove from txcmpl queue list */
3362 			list_del_init(&cmd_iocb->list);
3363 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3364 			pring->txcmplq_cnt--;
3365 			spin_unlock_irqrestore(temp_lock, iflag);
3366 			return cmd_iocb;
3367 		}
3368 	}
3369 
3370 	spin_unlock_irqrestore(temp_lock, iflag);
3371 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3372 			"0372 iotag x%x lookup error: max iotag (x%x) "
3373 			"iocb_flag x%x\n",
3374 			iotag, phba->sli.last_iotag,
3375 			cmd_iocb ? cmd_iocb->iocb_flag : 0xffff);
3376 	return NULL;
3377 }
3378 
3379 /**
3380  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3381  * @phba: Pointer to HBA context object.
3382  * @pring: Pointer to driver SLI ring object.
3383  * @saveq: Pointer to the response iocb to be processed.
3384  *
3385  * This function is called by the ring event handler for non-fcp
3386  * rings when there is a new response iocb in the response ring.
3387  * The caller is not required to hold any locks. This function
3388  * gets the command iocb associated with the response iocb and
3389  * calls the completion handler for the command iocb. If there
3390  * is no completion handler, the function will free the resources
3391  * associated with command iocb. If the response iocb is for
3392  * an already aborted command iocb, the status of the completion
3393  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3394  * This function always returns 1.
3395  **/
3396 static int
3397 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3398 			  struct lpfc_iocbq *saveq)
3399 {
3400 	struct lpfc_iocbq *cmdiocbp;
3401 	int rc = 1;
3402 	unsigned long iflag;
3403 
3404 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3405 	if (cmdiocbp) {
3406 		if (cmdiocbp->iocb_cmpl) {
3407 			/*
3408 			 * If an ELS command failed send an event to mgmt
3409 			 * application.
3410 			 */
3411 			if (saveq->iocb.ulpStatus &&
3412 			     (pring->ringno == LPFC_ELS_RING) &&
3413 			     (cmdiocbp->iocb.ulpCommand ==
3414 				CMD_ELS_REQUEST64_CR))
3415 				lpfc_send_els_failure_event(phba,
3416 					cmdiocbp, saveq);
3417 
3418 			/*
3419 			 * Post all ELS completions to the worker thread.
3420 			 * All other are passed to the completion callback.
3421 			 */
3422 			if (pring->ringno == LPFC_ELS_RING) {
3423 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3424 				    (cmdiocbp->iocb_flag &
3425 							LPFC_DRIVER_ABORTED)) {
3426 					spin_lock_irqsave(&phba->hbalock,
3427 							  iflag);
3428 					cmdiocbp->iocb_flag &=
3429 						~LPFC_DRIVER_ABORTED;
3430 					spin_unlock_irqrestore(&phba->hbalock,
3431 							       iflag);
3432 					saveq->iocb.ulpStatus =
3433 						IOSTAT_LOCAL_REJECT;
3434 					saveq->iocb.un.ulpWord[4] =
3435 						IOERR_SLI_ABORTED;
3436 
3437 					/* Firmware could still be in progress
3438 					 * of DMAing payload, so don't free data
3439 					 * buffer till after a hbeat.
3440 					 */
3441 					spin_lock_irqsave(&phba->hbalock,
3442 							  iflag);
3443 					saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
3444 					spin_unlock_irqrestore(&phba->hbalock,
3445 							       iflag);
3446 				}
3447 				if (phba->sli_rev == LPFC_SLI_REV4) {
3448 					if (saveq->iocb_flag &
3449 					    LPFC_EXCHANGE_BUSY) {
3450 						/* Set cmdiocb flag for the
3451 						 * exchange busy so sgl (xri)
3452 						 * will not be released until
3453 						 * the abort xri is received
3454 						 * from hba.
3455 						 */
3456 						spin_lock_irqsave(
3457 							&phba->hbalock, iflag);
3458 						cmdiocbp->iocb_flag |=
3459 							LPFC_EXCHANGE_BUSY;
3460 						spin_unlock_irqrestore(
3461 							&phba->hbalock, iflag);
3462 					}
3463 					if (cmdiocbp->iocb_flag &
3464 					    LPFC_DRIVER_ABORTED) {
3465 						/*
3466 						 * Clear LPFC_DRIVER_ABORTED
3467 						 * bit in case it was driver
3468 						 * initiated abort.
3469 						 */
3470 						spin_lock_irqsave(
3471 							&phba->hbalock, iflag);
3472 						cmdiocbp->iocb_flag &=
3473 							~LPFC_DRIVER_ABORTED;
3474 						spin_unlock_irqrestore(
3475 							&phba->hbalock, iflag);
3476 						cmdiocbp->iocb.ulpStatus =
3477 							IOSTAT_LOCAL_REJECT;
3478 						cmdiocbp->iocb.un.ulpWord[4] =
3479 							IOERR_ABORT_REQUESTED;
3480 						/*
3481 						 * For SLI4, irsiocb contains
3482 						 * NO_XRI in sli_xritag, it
3483 						 * shall not affect releasing
3484 						 * sgl (xri) process.
3485 						 */
3486 						saveq->iocb.ulpStatus =
3487 							IOSTAT_LOCAL_REJECT;
3488 						saveq->iocb.un.ulpWord[4] =
3489 							IOERR_SLI_ABORTED;
3490 						spin_lock_irqsave(
3491 							&phba->hbalock, iflag);
3492 						saveq->iocb_flag |=
3493 							LPFC_DELAY_MEM_FREE;
3494 						spin_unlock_irqrestore(
3495 							&phba->hbalock, iflag);
3496 					}
3497 				}
3498 			}
3499 			(cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
3500 		} else
3501 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3502 	} else {
3503 		/*
3504 		 * Unknown initiating command based on the response iotag.
3505 		 * This could be the case on the ELS ring because of
3506 		 * lpfc_els_abort().
3507 		 */
3508 		if (pring->ringno != LPFC_ELS_RING) {
3509 			/*
3510 			 * Ring <ringno> handler: unexpected completion IoTag
3511 			 * <IoTag>
3512 			 */
3513 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3514 					 "0322 Ring %d handler: "
3515 					 "unexpected completion IoTag x%x "
3516 					 "Data: x%x x%x x%x x%x\n",
3517 					 pring->ringno,
3518 					 saveq->iocb.ulpIoTag,
3519 					 saveq->iocb.ulpStatus,
3520 					 saveq->iocb.un.ulpWord[4],
3521 					 saveq->iocb.ulpCommand,
3522 					 saveq->iocb.ulpContext);
3523 		}
3524 	}
3525 
3526 	return rc;
3527 }
3528 
3529 /**
3530  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3531  * @phba: Pointer to HBA context object.
3532  * @pring: Pointer to driver SLI ring object.
3533  *
3534  * This function is called from the iocb ring event handlers when
3535  * put pointer is ahead of the get pointer for a ring. This function signal
3536  * an error attention condition to the worker thread and the worker
3537  * thread will transition the HBA to offline state.
3538  **/
3539 static void
3540 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3541 {
3542 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3543 	/*
3544 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3545 	 * rsp ring <portRspMax>
3546 	 */
3547 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3548 			"0312 Ring %d handler: portRspPut %d "
3549 			"is bigger than rsp ring %d\n",
3550 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3551 			pring->sli.sli3.numRiocb);
3552 
3553 	phba->link_state = LPFC_HBA_ERROR;
3554 
3555 	/*
3556 	 * All error attention handlers are posted to
3557 	 * worker thread
3558 	 */
3559 	phba->work_ha |= HA_ERATT;
3560 	phba->work_hs = HS_FFER3;
3561 
3562 	lpfc_worker_wake_up(phba);
3563 
3564 	return;
3565 }
3566 
3567 /**
3568  * lpfc_poll_eratt - Error attention polling timer timeout handler
3569  * @t: Context to fetch pointer to address of HBA context object from.
3570  *
3571  * This function is invoked by the Error Attention polling timer when the
3572  * timer times out. It will check the SLI Error Attention register for
3573  * possible attention events. If so, it will post an Error Attention event
3574  * and wake up worker thread to process it. Otherwise, it will set up the
3575  * Error Attention polling timer for the next poll.
3576  **/
3577 void lpfc_poll_eratt(struct timer_list *t)
3578 {
3579 	struct lpfc_hba *phba;
3580 	uint32_t eratt = 0;
3581 	uint64_t sli_intr, cnt;
3582 
3583 	phba = from_timer(phba, t, eratt_poll);
3584 
3585 	/* Here we will also keep track of interrupts per sec of the hba */
3586 	sli_intr = phba->sli.slistat.sli_intr;
3587 
3588 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3589 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3590 			sli_intr);
3591 	else
3592 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3593 
3594 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3595 	do_div(cnt, phba->eratt_poll_interval);
3596 	phba->sli.slistat.sli_ips = cnt;
3597 
3598 	phba->sli.slistat.sli_prev_intr = sli_intr;
3599 
3600 	/* Check chip HA register for error event */
3601 	eratt = lpfc_sli_check_eratt(phba);
3602 
3603 	if (eratt)
3604 		/* Tell the worker thread there is work to do */
3605 		lpfc_worker_wake_up(phba);
3606 	else
3607 		/* Restart the timer for next eratt poll */
3608 		mod_timer(&phba->eratt_poll,
3609 			  jiffies +
3610 			  msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3611 	return;
3612 }
3613 
3614 
3615 /**
3616  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3617  * @phba: Pointer to HBA context object.
3618  * @pring: Pointer to driver SLI ring object.
3619  * @mask: Host attention register mask for this ring.
3620  *
3621  * This function is called from the interrupt context when there is a ring
3622  * event for the fcp ring. The caller does not hold any lock.
3623  * The function processes each response iocb in the response ring until it
3624  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3625  * LE bit set. The function will call the completion handler of the command iocb
3626  * if the response iocb indicates a completion for a command iocb or it is
3627  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3628  * function if this is an unsolicited iocb.
3629  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3630  * to check it explicitly.
3631  */
3632 int
3633 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3634 				struct lpfc_sli_ring *pring, uint32_t mask)
3635 {
3636 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3637 	IOCB_t *irsp = NULL;
3638 	IOCB_t *entry = NULL;
3639 	struct lpfc_iocbq *cmdiocbq = NULL;
3640 	struct lpfc_iocbq rspiocbq;
3641 	uint32_t status;
3642 	uint32_t portRspPut, portRspMax;
3643 	int rc = 1;
3644 	lpfc_iocb_type type;
3645 	unsigned long iflag;
3646 	uint32_t rsp_cmpl = 0;
3647 
3648 	spin_lock_irqsave(&phba->hbalock, iflag);
3649 	pring->stats.iocb_event++;
3650 
3651 	/*
3652 	 * The next available response entry should never exceed the maximum
3653 	 * entries.  If it does, treat it as an adapter hardware error.
3654 	 */
3655 	portRspMax = pring->sli.sli3.numRiocb;
3656 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3657 	if (unlikely(portRspPut >= portRspMax)) {
3658 		lpfc_sli_rsp_pointers_error(phba, pring);
3659 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3660 		return 1;
3661 	}
3662 	if (phba->fcp_ring_in_use) {
3663 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3664 		return 1;
3665 	} else
3666 		phba->fcp_ring_in_use = 1;
3667 
3668 	rmb();
3669 	while (pring->sli.sli3.rspidx != portRspPut) {
3670 		/*
3671 		 * Fetch an entry off the ring and copy it into a local data
3672 		 * structure.  The copy involves a byte-swap since the
3673 		 * network byte order and pci byte orders are different.
3674 		 */
3675 		entry = lpfc_resp_iocb(phba, pring);
3676 		phba->last_completion_time = jiffies;
3677 
3678 		if (++pring->sli.sli3.rspidx >= portRspMax)
3679 			pring->sli.sli3.rspidx = 0;
3680 
3681 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3682 				      (uint32_t *) &rspiocbq.iocb,
3683 				      phba->iocb_rsp_size);
3684 		INIT_LIST_HEAD(&(rspiocbq.list));
3685 		irsp = &rspiocbq.iocb;
3686 
3687 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3688 		pring->stats.iocb_rsp++;
3689 		rsp_cmpl++;
3690 
3691 		if (unlikely(irsp->ulpStatus)) {
3692 			/*
3693 			 * If resource errors reported from HBA, reduce
3694 			 * queuedepths of the SCSI device.
3695 			 */
3696 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3697 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3698 			     IOERR_NO_RESOURCES)) {
3699 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3700 				phba->lpfc_rampdown_queue_depth(phba);
3701 				spin_lock_irqsave(&phba->hbalock, iflag);
3702 			}
3703 
3704 			/* Rsp ring <ringno> error: IOCB */
3705 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3706 					"0336 Rsp Ring %d error: IOCB Data: "
3707 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
3708 					pring->ringno,
3709 					irsp->un.ulpWord[0],
3710 					irsp->un.ulpWord[1],
3711 					irsp->un.ulpWord[2],
3712 					irsp->un.ulpWord[3],
3713 					irsp->un.ulpWord[4],
3714 					irsp->un.ulpWord[5],
3715 					*(uint32_t *)&irsp->un1,
3716 					*((uint32_t *)&irsp->un1 + 1));
3717 		}
3718 
3719 		switch (type) {
3720 		case LPFC_ABORT_IOCB:
3721 		case LPFC_SOL_IOCB:
3722 			/*
3723 			 * Idle exchange closed via ABTS from port.  No iocb
3724 			 * resources need to be recovered.
3725 			 */
3726 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3727 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3728 						"0333 IOCB cmd 0x%x"
3729 						" processed. Skipping"
3730 						" completion\n",
3731 						irsp->ulpCommand);
3732 				break;
3733 			}
3734 
3735 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3736 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3737 							 &rspiocbq);
3738 			spin_lock_irqsave(&phba->hbalock, iflag);
3739 			if (unlikely(!cmdiocbq))
3740 				break;
3741 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3742 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3743 			if (cmdiocbq->iocb_cmpl) {
3744 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3745 				(cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
3746 						      &rspiocbq);
3747 				spin_lock_irqsave(&phba->hbalock, iflag);
3748 			}
3749 			break;
3750 		case LPFC_UNSOL_IOCB:
3751 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3752 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
3753 			spin_lock_irqsave(&phba->hbalock, iflag);
3754 			break;
3755 		default:
3756 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3757 				char adaptermsg[LPFC_MAX_ADPTMSG];
3758 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3759 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
3760 				       MAX_MSG_DATA);
3761 				dev_warn(&((phba->pcidev)->dev),
3762 					 "lpfc%d: %s\n",
3763 					 phba->brd_no, adaptermsg);
3764 			} else {
3765 				/* Unknown IOCB command */
3766 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3767 						"0334 Unknown IOCB command "
3768 						"Data: x%x, x%x x%x x%x x%x\n",
3769 						type, irsp->ulpCommand,
3770 						irsp->ulpStatus,
3771 						irsp->ulpIoTag,
3772 						irsp->ulpContext);
3773 			}
3774 			break;
3775 		}
3776 
3777 		/*
3778 		 * The response IOCB has been processed.  Update the ring
3779 		 * pointer in SLIM.  If the port response put pointer has not
3780 		 * been updated, sync the pgp->rspPutInx and fetch the new port
3781 		 * response put pointer.
3782 		 */
3783 		writel(pring->sli.sli3.rspidx,
3784 			&phba->host_gp[pring->ringno].rspGetInx);
3785 
3786 		if (pring->sli.sli3.rspidx == portRspPut)
3787 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3788 	}
3789 
3790 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
3791 		pring->stats.iocb_rsp_full++;
3792 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3793 		writel(status, phba->CAregaddr);
3794 		readl(phba->CAregaddr);
3795 	}
3796 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3797 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3798 		pring->stats.iocb_cmd_empty++;
3799 
3800 		/* Force update of the local copy of cmdGetInx */
3801 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3802 		lpfc_sli_resume_iocb(phba, pring);
3803 
3804 		if ((pring->lpfc_sli_cmd_available))
3805 			(pring->lpfc_sli_cmd_available) (phba, pring);
3806 
3807 	}
3808 
3809 	phba->fcp_ring_in_use = 0;
3810 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3811 	return rc;
3812 }
3813 
3814 /**
3815  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
3816  * @phba: Pointer to HBA context object.
3817  * @pring: Pointer to driver SLI ring object.
3818  * @rspiocbp: Pointer to driver response IOCB object.
3819  *
3820  * This function is called from the worker thread when there is a slow-path
3821  * response IOCB to process. This function chains all the response iocbs until
3822  * seeing the iocb with the LE bit set. The function will call
3823  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
3824  * completion of a command iocb. The function will call the
3825  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
3826  * The function frees the resources or calls the completion handler if this
3827  * iocb is an abort completion. The function returns NULL when the response
3828  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
3829  * this function shall chain the iocb on to the iocb_continueq and return the
3830  * response iocb passed in.
3831  **/
3832 static struct lpfc_iocbq *
3833 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3834 			struct lpfc_iocbq *rspiocbp)
3835 {
3836 	struct lpfc_iocbq *saveq;
3837 	struct lpfc_iocbq *cmdiocbp;
3838 	struct lpfc_iocbq *next_iocb;
3839 	IOCB_t *irsp = NULL;
3840 	uint32_t free_saveq;
3841 	uint8_t iocb_cmd_type;
3842 	lpfc_iocb_type type;
3843 	unsigned long iflag;
3844 	int rc;
3845 
3846 	spin_lock_irqsave(&phba->hbalock, iflag);
3847 	/* First add the response iocb to the countinueq list */
3848 	list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
3849 	pring->iocb_continueq_cnt++;
3850 
3851 	/* Now, determine whether the list is completed for processing */
3852 	irsp = &rspiocbp->iocb;
3853 	if (irsp->ulpLe) {
3854 		/*
3855 		 * By default, the driver expects to free all resources
3856 		 * associated with this iocb completion.
3857 		 */
3858 		free_saveq = 1;
3859 		saveq = list_get_first(&pring->iocb_continueq,
3860 				       struct lpfc_iocbq, list);
3861 		irsp = &(saveq->iocb);
3862 		list_del_init(&pring->iocb_continueq);
3863 		pring->iocb_continueq_cnt = 0;
3864 
3865 		pring->stats.iocb_rsp++;
3866 
3867 		/*
3868 		 * If resource errors reported from HBA, reduce
3869 		 * queuedepths of the SCSI device.
3870 		 */
3871 		if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3872 		    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3873 		     IOERR_NO_RESOURCES)) {
3874 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3875 			phba->lpfc_rampdown_queue_depth(phba);
3876 			spin_lock_irqsave(&phba->hbalock, iflag);
3877 		}
3878 
3879 		if (irsp->ulpStatus) {
3880 			/* Rsp ring <ringno> error: IOCB */
3881 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3882 					"0328 Rsp Ring %d error: "
3883 					"IOCB Data: "
3884 					"x%x x%x x%x x%x "
3885 					"x%x x%x x%x x%x "
3886 					"x%x x%x x%x x%x "
3887 					"x%x x%x x%x x%x\n",
3888 					pring->ringno,
3889 					irsp->un.ulpWord[0],
3890 					irsp->un.ulpWord[1],
3891 					irsp->un.ulpWord[2],
3892 					irsp->un.ulpWord[3],
3893 					irsp->un.ulpWord[4],
3894 					irsp->un.ulpWord[5],
3895 					*(((uint32_t *) irsp) + 6),
3896 					*(((uint32_t *) irsp) + 7),
3897 					*(((uint32_t *) irsp) + 8),
3898 					*(((uint32_t *) irsp) + 9),
3899 					*(((uint32_t *) irsp) + 10),
3900 					*(((uint32_t *) irsp) + 11),
3901 					*(((uint32_t *) irsp) + 12),
3902 					*(((uint32_t *) irsp) + 13),
3903 					*(((uint32_t *) irsp) + 14),
3904 					*(((uint32_t *) irsp) + 15));
3905 		}
3906 
3907 		/*
3908 		 * Fetch the IOCB command type and call the correct completion
3909 		 * routine. Solicited and Unsolicited IOCBs on the ELS ring
3910 		 * get freed back to the lpfc_iocb_list by the discovery
3911 		 * kernel thread.
3912 		 */
3913 		iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
3914 		type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
3915 		switch (type) {
3916 		case LPFC_SOL_IOCB:
3917 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3918 			rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
3919 			spin_lock_irqsave(&phba->hbalock, iflag);
3920 			break;
3921 
3922 		case LPFC_UNSOL_IOCB:
3923 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3924 			rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
3925 			spin_lock_irqsave(&phba->hbalock, iflag);
3926 			if (!rc)
3927 				free_saveq = 0;
3928 			break;
3929 
3930 		case LPFC_ABORT_IOCB:
3931 			cmdiocbp = NULL;
3932 			if (irsp->ulpCommand != CMD_XRI_ABORTED_CX) {
3933 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3934 				cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
3935 								 saveq);
3936 				spin_lock_irqsave(&phba->hbalock, iflag);
3937 			}
3938 			if (cmdiocbp) {
3939 				/* Call the specified completion routine */
3940 				if (cmdiocbp->iocb_cmpl) {
3941 					spin_unlock_irqrestore(&phba->hbalock,
3942 							       iflag);
3943 					(cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
3944 							      saveq);
3945 					spin_lock_irqsave(&phba->hbalock,
3946 							  iflag);
3947 				} else
3948 					__lpfc_sli_release_iocbq(phba,
3949 								 cmdiocbp);
3950 			}
3951 			break;
3952 
3953 		case LPFC_UNKNOWN_IOCB:
3954 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3955 				char adaptermsg[LPFC_MAX_ADPTMSG];
3956 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3957 				memcpy(&adaptermsg[0], (uint8_t *)irsp,
3958 				       MAX_MSG_DATA);
3959 				dev_warn(&((phba->pcidev)->dev),
3960 					 "lpfc%d: %s\n",
3961 					 phba->brd_no, adaptermsg);
3962 			} else {
3963 				/* Unknown IOCB command */
3964 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3965 						"0335 Unknown IOCB "
3966 						"command Data: x%x "
3967 						"x%x x%x x%x\n",
3968 						irsp->ulpCommand,
3969 						irsp->ulpStatus,
3970 						irsp->ulpIoTag,
3971 						irsp->ulpContext);
3972 			}
3973 			break;
3974 		}
3975 
3976 		if (free_saveq) {
3977 			list_for_each_entry_safe(rspiocbp, next_iocb,
3978 						 &saveq->list, list) {
3979 				list_del_init(&rspiocbp->list);
3980 				__lpfc_sli_release_iocbq(phba, rspiocbp);
3981 			}
3982 			__lpfc_sli_release_iocbq(phba, saveq);
3983 		}
3984 		rspiocbp = NULL;
3985 	}
3986 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3987 	return rspiocbp;
3988 }
3989 
3990 /**
3991  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
3992  * @phba: Pointer to HBA context object.
3993  * @pring: Pointer to driver SLI ring object.
3994  * @mask: Host attention register mask for this ring.
3995  *
3996  * This routine wraps the actual slow_ring event process routine from the
3997  * API jump table function pointer from the lpfc_hba struct.
3998  **/
3999 void
4000 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
4001 				struct lpfc_sli_ring *pring, uint32_t mask)
4002 {
4003 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
4004 }
4005 
4006 /**
4007  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
4008  * @phba: Pointer to HBA context object.
4009  * @pring: Pointer to driver SLI ring object.
4010  * @mask: Host attention register mask for this ring.
4011  *
4012  * This function is called from the worker thread when there is a ring event
4013  * for non-fcp rings. The caller does not hold any lock. The function will
4014  * remove each response iocb in the response ring and calls the handle
4015  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4016  **/
4017 static void
4018 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
4019 				   struct lpfc_sli_ring *pring, uint32_t mask)
4020 {
4021 	struct lpfc_pgp *pgp;
4022 	IOCB_t *entry;
4023 	IOCB_t *irsp = NULL;
4024 	struct lpfc_iocbq *rspiocbp = NULL;
4025 	uint32_t portRspPut, portRspMax;
4026 	unsigned long iflag;
4027 	uint32_t status;
4028 
4029 	pgp = &phba->port_gp[pring->ringno];
4030 	spin_lock_irqsave(&phba->hbalock, iflag);
4031 	pring->stats.iocb_event++;
4032 
4033 	/*
4034 	 * The next available response entry should never exceed the maximum
4035 	 * entries.  If it does, treat it as an adapter hardware error.
4036 	 */
4037 	portRspMax = pring->sli.sli3.numRiocb;
4038 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4039 	if (portRspPut >= portRspMax) {
4040 		/*
4041 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
4042 		 * rsp ring <portRspMax>
4043 		 */
4044 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4045 				"0303 Ring %d handler: portRspPut %d "
4046 				"is bigger than rsp ring %d\n",
4047 				pring->ringno, portRspPut, portRspMax);
4048 
4049 		phba->link_state = LPFC_HBA_ERROR;
4050 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4051 
4052 		phba->work_hs = HS_FFER3;
4053 		lpfc_handle_eratt(phba);
4054 
4055 		return;
4056 	}
4057 
4058 	rmb();
4059 	while (pring->sli.sli3.rspidx != portRspPut) {
4060 		/*
4061 		 * Build a completion list and call the appropriate handler.
4062 		 * The process is to get the next available response iocb, get
4063 		 * a free iocb from the list, copy the response data into the
4064 		 * free iocb, insert to the continuation list, and update the
4065 		 * next response index to slim.  This process makes response
4066 		 * iocb's in the ring available to DMA as fast as possible but
4067 		 * pays a penalty for a copy operation.  Since the iocb is
4068 		 * only 32 bytes, this penalty is considered small relative to
4069 		 * the PCI reads for register values and a slim write.  When
4070 		 * the ulpLe field is set, the entire Command has been
4071 		 * received.
4072 		 */
4073 		entry = lpfc_resp_iocb(phba, pring);
4074 
4075 		phba->last_completion_time = jiffies;
4076 		rspiocbp = __lpfc_sli_get_iocbq(phba);
4077 		if (rspiocbp == NULL) {
4078 			printk(KERN_ERR "%s: out of buffers! Failing "
4079 			       "completion.\n", __func__);
4080 			break;
4081 		}
4082 
4083 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
4084 				      phba->iocb_rsp_size);
4085 		irsp = &rspiocbp->iocb;
4086 
4087 		if (++pring->sli.sli3.rspidx >= portRspMax)
4088 			pring->sli.sli3.rspidx = 0;
4089 
4090 		if (pring->ringno == LPFC_ELS_RING) {
4091 			lpfc_debugfs_slow_ring_trc(phba,
4092 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
4093 				*(((uint32_t *) irsp) + 4),
4094 				*(((uint32_t *) irsp) + 6),
4095 				*(((uint32_t *) irsp) + 7));
4096 		}
4097 
4098 		writel(pring->sli.sli3.rspidx,
4099 			&phba->host_gp[pring->ringno].rspGetInx);
4100 
4101 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4102 		/* Handle the response IOCB */
4103 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
4104 		spin_lock_irqsave(&phba->hbalock, iflag);
4105 
4106 		/*
4107 		 * If the port response put pointer has not been updated, sync
4108 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
4109 		 * response put pointer.
4110 		 */
4111 		if (pring->sli.sli3.rspidx == portRspPut) {
4112 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4113 		}
4114 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
4115 
4116 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
4117 		/* At least one response entry has been freed */
4118 		pring->stats.iocb_rsp_full++;
4119 		/* SET RxRE_RSP in Chip Att register */
4120 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4121 		writel(status, phba->CAregaddr);
4122 		readl(phba->CAregaddr); /* flush */
4123 	}
4124 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4125 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4126 		pring->stats.iocb_cmd_empty++;
4127 
4128 		/* Force update of the local copy of cmdGetInx */
4129 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4130 		lpfc_sli_resume_iocb(phba, pring);
4131 
4132 		if ((pring->lpfc_sli_cmd_available))
4133 			(pring->lpfc_sli_cmd_available) (phba, pring);
4134 
4135 	}
4136 
4137 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4138 	return;
4139 }
4140 
4141 /**
4142  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
4143  * @phba: Pointer to HBA context object.
4144  * @pring: Pointer to driver SLI ring object.
4145  * @mask: Host attention register mask for this ring.
4146  *
4147  * This function is called from the worker thread when there is a pending
4148  * ELS response iocb on the driver internal slow-path response iocb worker
4149  * queue. The caller does not hold any lock. The function will remove each
4150  * response iocb from the response worker queue and calls the handle
4151  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4152  **/
4153 static void
4154 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4155 				   struct lpfc_sli_ring *pring, uint32_t mask)
4156 {
4157 	struct lpfc_iocbq *irspiocbq;
4158 	struct hbq_dmabuf *dmabuf;
4159 	struct lpfc_cq_event *cq_event;
4160 	unsigned long iflag;
4161 	int count = 0;
4162 
4163 	spin_lock_irqsave(&phba->hbalock, iflag);
4164 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
4165 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4166 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4167 		/* Get the response iocb from the head of work queue */
4168 		spin_lock_irqsave(&phba->hbalock, iflag);
4169 		list_remove_head(&phba->sli4_hba.sp_queue_event,
4170 				 cq_event, struct lpfc_cq_event, list);
4171 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4172 
4173 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4174 		case CQE_CODE_COMPL_WQE:
4175 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4176 						 cq_event);
4177 			/* Translate ELS WCQE to response IOCBQ */
4178 			irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
4179 								   irspiocbq);
4180 			if (irspiocbq)
4181 				lpfc_sli_sp_handle_rspiocb(phba, pring,
4182 							   irspiocbq);
4183 			count++;
4184 			break;
4185 		case CQE_CODE_RECEIVE:
4186 		case CQE_CODE_RECEIVE_V1:
4187 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
4188 					      cq_event);
4189 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
4190 			count++;
4191 			break;
4192 		default:
4193 			break;
4194 		}
4195 
4196 		/* Limit the number of events to 64 to avoid soft lockups */
4197 		if (count == 64)
4198 			break;
4199 	}
4200 }
4201 
4202 /**
4203  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4204  * @phba: Pointer to HBA context object.
4205  * @pring: Pointer to driver SLI ring object.
4206  *
4207  * This function aborts all iocbs in the given ring and frees all the iocb
4208  * objects in txq. This function issues an abort iocb for all the iocb commands
4209  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4210  * the return of this function. The caller is not required to hold any locks.
4211  **/
4212 void
4213 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4214 {
4215 	LIST_HEAD(completions);
4216 	struct lpfc_iocbq *iocb, *next_iocb;
4217 
4218 	if (pring->ringno == LPFC_ELS_RING) {
4219 		lpfc_fabric_abort_hba(phba);
4220 	}
4221 
4222 	/* Error everything on txq and txcmplq
4223 	 * First do the txq.
4224 	 */
4225 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4226 		spin_lock_irq(&pring->ring_lock);
4227 		list_splice_init(&pring->txq, &completions);
4228 		pring->txq_cnt = 0;
4229 		spin_unlock_irq(&pring->ring_lock);
4230 
4231 		spin_lock_irq(&phba->hbalock);
4232 		/* Next issue ABTS for everything on the txcmplq */
4233 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4234 			lpfc_sli_issue_abort_iotag(phba, pring, iocb, NULL);
4235 		spin_unlock_irq(&phba->hbalock);
4236 	} else {
4237 		spin_lock_irq(&phba->hbalock);
4238 		list_splice_init(&pring->txq, &completions);
4239 		pring->txq_cnt = 0;
4240 
4241 		/* Next issue ABTS for everything on the txcmplq */
4242 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4243 			lpfc_sli_issue_abort_iotag(phba, pring, iocb, NULL);
4244 		spin_unlock_irq(&phba->hbalock);
4245 	}
4246 	/* Make sure HBA is alive */
4247 	lpfc_issue_hb_tmo(phba);
4248 
4249 	/* Cancel all the IOCBs from the completions list */
4250 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
4251 			      IOERR_SLI_ABORTED);
4252 }
4253 
4254 /**
4255  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4256  * @phba: Pointer to HBA context object.
4257  *
4258  * This function aborts all iocbs in FCP rings and frees all the iocb
4259  * objects in txq. This function issues an abort iocb for all the iocb commands
4260  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4261  * the return of this function. The caller is not required to hold any locks.
4262  **/
4263 void
4264 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4265 {
4266 	struct lpfc_sli *psli = &phba->sli;
4267 	struct lpfc_sli_ring  *pring;
4268 	uint32_t i;
4269 
4270 	/* Look on all the FCP Rings for the iotag */
4271 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4272 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4273 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4274 			lpfc_sli_abort_iocb_ring(phba, pring);
4275 		}
4276 	} else {
4277 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4278 		lpfc_sli_abort_iocb_ring(phba, pring);
4279 	}
4280 }
4281 
4282 /**
4283  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4284  * @phba: Pointer to HBA context object.
4285  *
4286  * This function flushes all iocbs in the IO ring and frees all the iocb
4287  * objects in txq and txcmplq. This function will not issue abort iocbs
4288  * for all the iocb commands in txcmplq, they will just be returned with
4289  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4290  * slot has been permanently disabled.
4291  **/
4292 void
4293 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4294 {
4295 	LIST_HEAD(txq);
4296 	LIST_HEAD(txcmplq);
4297 	struct lpfc_sli *psli = &phba->sli;
4298 	struct lpfc_sli_ring  *pring;
4299 	uint32_t i;
4300 	struct lpfc_iocbq *piocb, *next_iocb;
4301 
4302 	spin_lock_irq(&phba->hbalock);
4303 	if (phba->hba_flag & HBA_IOQ_FLUSH ||
4304 	    !phba->sli4_hba.hdwq) {
4305 		spin_unlock_irq(&phba->hbalock);
4306 		return;
4307 	}
4308 	/* Indicate the I/O queues are flushed */
4309 	phba->hba_flag |= HBA_IOQ_FLUSH;
4310 	spin_unlock_irq(&phba->hbalock);
4311 
4312 	/* Look on all the FCP Rings for the iotag */
4313 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4314 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4315 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4316 
4317 			spin_lock_irq(&pring->ring_lock);
4318 			/* Retrieve everything on txq */
4319 			list_splice_init(&pring->txq, &txq);
4320 			list_for_each_entry_safe(piocb, next_iocb,
4321 						 &pring->txcmplq, list)
4322 				piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4323 			/* Retrieve everything on the txcmplq */
4324 			list_splice_init(&pring->txcmplq, &txcmplq);
4325 			pring->txq_cnt = 0;
4326 			pring->txcmplq_cnt = 0;
4327 			spin_unlock_irq(&pring->ring_lock);
4328 
4329 			/* Flush the txq */
4330 			lpfc_sli_cancel_iocbs(phba, &txq,
4331 					      IOSTAT_LOCAL_REJECT,
4332 					      IOERR_SLI_DOWN);
4333 			/* Flush the txcmpq */
4334 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4335 					      IOSTAT_LOCAL_REJECT,
4336 					      IOERR_SLI_DOWN);
4337 		}
4338 	} else {
4339 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4340 
4341 		spin_lock_irq(&phba->hbalock);
4342 		/* Retrieve everything on txq */
4343 		list_splice_init(&pring->txq, &txq);
4344 		list_for_each_entry_safe(piocb, next_iocb,
4345 					 &pring->txcmplq, list)
4346 			piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4347 		/* Retrieve everything on the txcmplq */
4348 		list_splice_init(&pring->txcmplq, &txcmplq);
4349 		pring->txq_cnt = 0;
4350 		pring->txcmplq_cnt = 0;
4351 		spin_unlock_irq(&phba->hbalock);
4352 
4353 		/* Flush the txq */
4354 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4355 				      IOERR_SLI_DOWN);
4356 		/* Flush the txcmpq */
4357 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4358 				      IOERR_SLI_DOWN);
4359 	}
4360 }
4361 
4362 /**
4363  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4364  * @phba: Pointer to HBA context object.
4365  * @mask: Bit mask to be checked.
4366  *
4367  * This function reads the host status register and compares
4368  * with the provided bit mask to check if HBA completed
4369  * the restart. This function will wait in a loop for the
4370  * HBA to complete restart. If the HBA does not restart within
4371  * 15 iterations, the function will reset the HBA again. The
4372  * function returns 1 when HBA fail to restart otherwise returns
4373  * zero.
4374  **/
4375 static int
4376 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4377 {
4378 	uint32_t status;
4379 	int i = 0;
4380 	int retval = 0;
4381 
4382 	/* Read the HBA Host Status Register */
4383 	if (lpfc_readl(phba->HSregaddr, &status))
4384 		return 1;
4385 
4386 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4387 
4388 	/*
4389 	 * Check status register every 100ms for 5 retries, then every
4390 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4391 	 * every 2.5 sec for 4.
4392 	 * Break our of the loop if errors occurred during init.
4393 	 */
4394 	while (((status & mask) != mask) &&
4395 	       !(status & HS_FFERM) &&
4396 	       i++ < 20) {
4397 
4398 		if (i <= 5)
4399 			msleep(10);
4400 		else if (i <= 10)
4401 			msleep(500);
4402 		else
4403 			msleep(2500);
4404 
4405 		if (i == 15) {
4406 				/* Do post */
4407 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4408 			lpfc_sli_brdrestart(phba);
4409 		}
4410 		/* Read the HBA Host Status Register */
4411 		if (lpfc_readl(phba->HSregaddr, &status)) {
4412 			retval = 1;
4413 			break;
4414 		}
4415 	}
4416 
4417 	/* Check to see if any errors occurred during init */
4418 	if ((status & HS_FFERM) || (i >= 20)) {
4419 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4420 				"2751 Adapter failed to restart, "
4421 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4422 				status,
4423 				readl(phba->MBslimaddr + 0xa8),
4424 				readl(phba->MBslimaddr + 0xac));
4425 		phba->link_state = LPFC_HBA_ERROR;
4426 		retval = 1;
4427 	}
4428 
4429 	return retval;
4430 }
4431 
4432 /**
4433  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4434  * @phba: Pointer to HBA context object.
4435  * @mask: Bit mask to be checked.
4436  *
4437  * This function checks the host status register to check if HBA is
4438  * ready. This function will wait in a loop for the HBA to be ready
4439  * If the HBA is not ready , the function will will reset the HBA PCI
4440  * function again. The function returns 1 when HBA fail to be ready
4441  * otherwise returns zero.
4442  **/
4443 static int
4444 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4445 {
4446 	uint32_t status;
4447 	int retval = 0;
4448 
4449 	/* Read the HBA Host Status Register */
4450 	status = lpfc_sli4_post_status_check(phba);
4451 
4452 	if (status) {
4453 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4454 		lpfc_sli_brdrestart(phba);
4455 		status = lpfc_sli4_post_status_check(phba);
4456 	}
4457 
4458 	/* Check to see if any errors occurred during init */
4459 	if (status) {
4460 		phba->link_state = LPFC_HBA_ERROR;
4461 		retval = 1;
4462 	} else
4463 		phba->sli4_hba.intr_enable = 0;
4464 
4465 	return retval;
4466 }
4467 
4468 /**
4469  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4470  * @phba: Pointer to HBA context object.
4471  * @mask: Bit mask to be checked.
4472  *
4473  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4474  * from the API jump table function pointer from the lpfc_hba struct.
4475  **/
4476 int
4477 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4478 {
4479 	return phba->lpfc_sli_brdready(phba, mask);
4480 }
4481 
4482 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4483 
4484 /**
4485  * lpfc_reset_barrier - Make HBA ready for HBA reset
4486  * @phba: Pointer to HBA context object.
4487  *
4488  * This function is called before resetting an HBA. This function is called
4489  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4490  **/
4491 void lpfc_reset_barrier(struct lpfc_hba *phba)
4492 {
4493 	uint32_t __iomem *resp_buf;
4494 	uint32_t __iomem *mbox_buf;
4495 	volatile uint32_t mbox;
4496 	uint32_t hc_copy, ha_copy, resp_data;
4497 	int  i;
4498 	uint8_t hdrtype;
4499 
4500 	lockdep_assert_held(&phba->hbalock);
4501 
4502 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4503 	if (hdrtype != 0x80 ||
4504 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4505 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4506 		return;
4507 
4508 	/*
4509 	 * Tell the other part of the chip to suspend temporarily all
4510 	 * its DMA activity.
4511 	 */
4512 	resp_buf = phba->MBslimaddr;
4513 
4514 	/* Disable the error attention */
4515 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4516 		return;
4517 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4518 	readl(phba->HCregaddr); /* flush */
4519 	phba->link_flag |= LS_IGNORE_ERATT;
4520 
4521 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4522 		return;
4523 	if (ha_copy & HA_ERATT) {
4524 		/* Clear Chip error bit */
4525 		writel(HA_ERATT, phba->HAregaddr);
4526 		phba->pport->stopped = 1;
4527 	}
4528 
4529 	mbox = 0;
4530 	((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
4531 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
4532 
4533 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4534 	mbox_buf = phba->MBslimaddr;
4535 	writel(mbox, mbox_buf);
4536 
4537 	for (i = 0; i < 50; i++) {
4538 		if (lpfc_readl((resp_buf + 1), &resp_data))
4539 			return;
4540 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4541 			mdelay(1);
4542 		else
4543 			break;
4544 	}
4545 	resp_data = 0;
4546 	if (lpfc_readl((resp_buf + 1), &resp_data))
4547 		return;
4548 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4549 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4550 		    phba->pport->stopped)
4551 			goto restore_hc;
4552 		else
4553 			goto clear_errat;
4554 	}
4555 
4556 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
4557 	resp_data = 0;
4558 	for (i = 0; i < 500; i++) {
4559 		if (lpfc_readl(resp_buf, &resp_data))
4560 			return;
4561 		if (resp_data != mbox)
4562 			mdelay(1);
4563 		else
4564 			break;
4565 	}
4566 
4567 clear_errat:
4568 
4569 	while (++i < 500) {
4570 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4571 			return;
4572 		if (!(ha_copy & HA_ERATT))
4573 			mdelay(1);
4574 		else
4575 			break;
4576 	}
4577 
4578 	if (readl(phba->HAregaddr) & HA_ERATT) {
4579 		writel(HA_ERATT, phba->HAregaddr);
4580 		phba->pport->stopped = 1;
4581 	}
4582 
4583 restore_hc:
4584 	phba->link_flag &= ~LS_IGNORE_ERATT;
4585 	writel(hc_copy, phba->HCregaddr);
4586 	readl(phba->HCregaddr); /* flush */
4587 }
4588 
4589 /**
4590  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4591  * @phba: Pointer to HBA context object.
4592  *
4593  * This function issues a kill_board mailbox command and waits for
4594  * the error attention interrupt. This function is called for stopping
4595  * the firmware processing. The caller is not required to hold any
4596  * locks. This function calls lpfc_hba_down_post function to free
4597  * any pending commands after the kill. The function will return 1 when it
4598  * fails to kill the board else will return 0.
4599  **/
4600 int
4601 lpfc_sli_brdkill(struct lpfc_hba *phba)
4602 {
4603 	struct lpfc_sli *psli;
4604 	LPFC_MBOXQ_t *pmb;
4605 	uint32_t status;
4606 	uint32_t ha_copy;
4607 	int retval;
4608 	int i = 0;
4609 
4610 	psli = &phba->sli;
4611 
4612 	/* Kill HBA */
4613 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4614 			"0329 Kill HBA Data: x%x x%x\n",
4615 			phba->pport->port_state, psli->sli_flag);
4616 
4617 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4618 	if (!pmb)
4619 		return 1;
4620 
4621 	/* Disable the error attention */
4622 	spin_lock_irq(&phba->hbalock);
4623 	if (lpfc_readl(phba->HCregaddr, &status)) {
4624 		spin_unlock_irq(&phba->hbalock);
4625 		mempool_free(pmb, phba->mbox_mem_pool);
4626 		return 1;
4627 	}
4628 	status &= ~HC_ERINT_ENA;
4629 	writel(status, phba->HCregaddr);
4630 	readl(phba->HCregaddr); /* flush */
4631 	phba->link_flag |= LS_IGNORE_ERATT;
4632 	spin_unlock_irq(&phba->hbalock);
4633 
4634 	lpfc_kill_board(phba, pmb);
4635 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4636 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4637 
4638 	if (retval != MBX_SUCCESS) {
4639 		if (retval != MBX_BUSY)
4640 			mempool_free(pmb, phba->mbox_mem_pool);
4641 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4642 				"2752 KILL_BOARD command failed retval %d\n",
4643 				retval);
4644 		spin_lock_irq(&phba->hbalock);
4645 		phba->link_flag &= ~LS_IGNORE_ERATT;
4646 		spin_unlock_irq(&phba->hbalock);
4647 		return 1;
4648 	}
4649 
4650 	spin_lock_irq(&phba->hbalock);
4651 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
4652 	spin_unlock_irq(&phba->hbalock);
4653 
4654 	mempool_free(pmb, phba->mbox_mem_pool);
4655 
4656 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
4657 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
4658 	 * 3 seconds we still set HBA_ERROR state because the status of the
4659 	 * board is now undefined.
4660 	 */
4661 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4662 		return 1;
4663 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
4664 		mdelay(100);
4665 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4666 			return 1;
4667 	}
4668 
4669 	del_timer_sync(&psli->mbox_tmo);
4670 	if (ha_copy & HA_ERATT) {
4671 		writel(HA_ERATT, phba->HAregaddr);
4672 		phba->pport->stopped = 1;
4673 	}
4674 	spin_lock_irq(&phba->hbalock);
4675 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4676 	psli->mbox_active = NULL;
4677 	phba->link_flag &= ~LS_IGNORE_ERATT;
4678 	spin_unlock_irq(&phba->hbalock);
4679 
4680 	lpfc_hba_down_post(phba);
4681 	phba->link_state = LPFC_HBA_ERROR;
4682 
4683 	return ha_copy & HA_ERATT ? 0 : 1;
4684 }
4685 
4686 /**
4687  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
4688  * @phba: Pointer to HBA context object.
4689  *
4690  * This function resets the HBA by writing HC_INITFF to the control
4691  * register. After the HBA resets, this function resets all the iocb ring
4692  * indices. This function disables PCI layer parity checking during
4693  * the reset.
4694  * This function returns 0 always.
4695  * The caller is not required to hold any locks.
4696  **/
4697 int
4698 lpfc_sli_brdreset(struct lpfc_hba *phba)
4699 {
4700 	struct lpfc_sli *psli;
4701 	struct lpfc_sli_ring *pring;
4702 	uint16_t cfg_value;
4703 	int i;
4704 
4705 	psli = &phba->sli;
4706 
4707 	/* Reset HBA */
4708 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4709 			"0325 Reset HBA Data: x%x x%x\n",
4710 			(phba->pport) ? phba->pport->port_state : 0,
4711 			psli->sli_flag);
4712 
4713 	/* perform board reset */
4714 	phba->fc_eventTag = 0;
4715 	phba->link_events = 0;
4716 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4717 	if (phba->pport) {
4718 		phba->pport->fc_myDID = 0;
4719 		phba->pport->fc_prevDID = 0;
4720 	}
4721 
4722 	/* Turn off parity checking and serr during the physical reset */
4723 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
4724 		return -EIO;
4725 
4726 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
4727 			      (cfg_value &
4728 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4729 
4730 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4731 
4732 	/* Now toggle INITFF bit in the Host Control Register */
4733 	writel(HC_INITFF, phba->HCregaddr);
4734 	mdelay(1);
4735 	readl(phba->HCregaddr); /* flush */
4736 	writel(0, phba->HCregaddr);
4737 	readl(phba->HCregaddr); /* flush */
4738 
4739 	/* Restore PCI cmd register */
4740 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4741 
4742 	/* Initialize relevant SLI info */
4743 	for (i = 0; i < psli->num_rings; i++) {
4744 		pring = &psli->sli3_ring[i];
4745 		pring->flag = 0;
4746 		pring->sli.sli3.rspidx = 0;
4747 		pring->sli.sli3.next_cmdidx  = 0;
4748 		pring->sli.sli3.local_getidx = 0;
4749 		pring->sli.sli3.cmdidx = 0;
4750 		pring->missbufcnt = 0;
4751 	}
4752 
4753 	phba->link_state = LPFC_WARM_START;
4754 	return 0;
4755 }
4756 
4757 /**
4758  * lpfc_sli4_brdreset - Reset a sli-4 HBA
4759  * @phba: Pointer to HBA context object.
4760  *
4761  * This function resets a SLI4 HBA. This function disables PCI layer parity
4762  * checking during resets the device. The caller is not required to hold
4763  * any locks.
4764  *
4765  * This function returns 0 on success else returns negative error code.
4766  **/
4767 int
4768 lpfc_sli4_brdreset(struct lpfc_hba *phba)
4769 {
4770 	struct lpfc_sli *psli = &phba->sli;
4771 	uint16_t cfg_value;
4772 	int rc = 0;
4773 
4774 	/* Reset HBA */
4775 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4776 			"0295 Reset HBA Data: x%x x%x x%x\n",
4777 			phba->pport->port_state, psli->sli_flag,
4778 			phba->hba_flag);
4779 
4780 	/* perform board reset */
4781 	phba->fc_eventTag = 0;
4782 	phba->link_events = 0;
4783 	phba->pport->fc_myDID = 0;
4784 	phba->pport->fc_prevDID = 0;
4785 
4786 	spin_lock_irq(&phba->hbalock);
4787 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
4788 	phba->fcf.fcf_flag = 0;
4789 	spin_unlock_irq(&phba->hbalock);
4790 
4791 	/* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
4792 	if (phba->hba_flag & HBA_FW_DUMP_OP) {
4793 		phba->hba_flag &= ~HBA_FW_DUMP_OP;
4794 		return rc;
4795 	}
4796 
4797 	/* Now physically reset the device */
4798 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4799 			"0389 Performing PCI function reset!\n");
4800 
4801 	/* Turn off parity checking and serr during the physical reset */
4802 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
4803 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4804 				"3205 PCI read Config failed\n");
4805 		return -EIO;
4806 	}
4807 
4808 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
4809 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4810 
4811 	/* Perform FCoE PCI function reset before freeing queue memory */
4812 	rc = lpfc_pci_function_reset(phba);
4813 
4814 	/* Restore PCI cmd register */
4815 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4816 
4817 	return rc;
4818 }
4819 
4820 /**
4821  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
4822  * @phba: Pointer to HBA context object.
4823  *
4824  * This function is called in the SLI initialization code path to
4825  * restart the HBA. The caller is not required to hold any lock.
4826  * This function writes MBX_RESTART mailbox command to the SLIM and
4827  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
4828  * function to free any pending commands. The function enables
4829  * POST only during the first initialization. The function returns zero.
4830  * The function does not guarantee completion of MBX_RESTART mailbox
4831  * command before the return of this function.
4832  **/
4833 static int
4834 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
4835 {
4836 	MAILBOX_t *mb;
4837 	struct lpfc_sli *psli;
4838 	volatile uint32_t word0;
4839 	void __iomem *to_slim;
4840 	uint32_t hba_aer_enabled;
4841 
4842 	spin_lock_irq(&phba->hbalock);
4843 
4844 	/* Take PCIe device Advanced Error Reporting (AER) state */
4845 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4846 
4847 	psli = &phba->sli;
4848 
4849 	/* Restart HBA */
4850 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4851 			"0337 Restart HBA Data: x%x x%x\n",
4852 			(phba->pport) ? phba->pport->port_state : 0,
4853 			psli->sli_flag);
4854 
4855 	word0 = 0;
4856 	mb = (MAILBOX_t *) &word0;
4857 	mb->mbxCommand = MBX_RESTART;
4858 	mb->mbxHc = 1;
4859 
4860 	lpfc_reset_barrier(phba);
4861 
4862 	to_slim = phba->MBslimaddr;
4863 	writel(*(uint32_t *) mb, to_slim);
4864 	readl(to_slim); /* flush */
4865 
4866 	/* Only skip post after fc_ffinit is completed */
4867 	if (phba->pport && phba->pport->port_state)
4868 		word0 = 1;	/* This is really setting up word1 */
4869 	else
4870 		word0 = 0;	/* This is really setting up word1 */
4871 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
4872 	writel(*(uint32_t *) mb, to_slim);
4873 	readl(to_slim); /* flush */
4874 
4875 	lpfc_sli_brdreset(phba);
4876 	if (phba->pport)
4877 		phba->pport->stopped = 0;
4878 	phba->link_state = LPFC_INIT_START;
4879 	phba->hba_flag = 0;
4880 	spin_unlock_irq(&phba->hbalock);
4881 
4882 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4883 	psli->stats_start = ktime_get_seconds();
4884 
4885 	/* Give the INITFF and Post time to settle. */
4886 	mdelay(100);
4887 
4888 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4889 	if (hba_aer_enabled)
4890 		pci_disable_pcie_error_reporting(phba->pcidev);
4891 
4892 	lpfc_hba_down_post(phba);
4893 
4894 	return 0;
4895 }
4896 
4897 /**
4898  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
4899  * @phba: Pointer to HBA context object.
4900  *
4901  * This function is called in the SLI initialization code path to restart
4902  * a SLI4 HBA. The caller is not required to hold any lock.
4903  * At the end of the function, it calls lpfc_hba_down_post function to
4904  * free any pending commands.
4905  **/
4906 static int
4907 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
4908 {
4909 	struct lpfc_sli *psli = &phba->sli;
4910 	uint32_t hba_aer_enabled;
4911 	int rc;
4912 
4913 	/* Restart HBA */
4914 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4915 			"0296 Restart HBA Data: x%x x%x\n",
4916 			phba->pport->port_state, psli->sli_flag);
4917 
4918 	/* Take PCIe device Advanced Error Reporting (AER) state */
4919 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4920 
4921 	rc = lpfc_sli4_brdreset(phba);
4922 	if (rc) {
4923 		phba->link_state = LPFC_HBA_ERROR;
4924 		goto hba_down_queue;
4925 	}
4926 
4927 	spin_lock_irq(&phba->hbalock);
4928 	phba->pport->stopped = 0;
4929 	phba->link_state = LPFC_INIT_START;
4930 	phba->hba_flag = 0;
4931 	spin_unlock_irq(&phba->hbalock);
4932 
4933 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4934 	psli->stats_start = ktime_get_seconds();
4935 
4936 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4937 	if (hba_aer_enabled)
4938 		pci_disable_pcie_error_reporting(phba->pcidev);
4939 
4940 hba_down_queue:
4941 	lpfc_hba_down_post(phba);
4942 	lpfc_sli4_queue_destroy(phba);
4943 
4944 	return rc;
4945 }
4946 
4947 /**
4948  * lpfc_sli_brdrestart - Wrapper func for restarting hba
4949  * @phba: Pointer to HBA context object.
4950  *
4951  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
4952  * API jump table function pointer from the lpfc_hba struct.
4953 **/
4954 int
4955 lpfc_sli_brdrestart(struct lpfc_hba *phba)
4956 {
4957 	return phba->lpfc_sli_brdrestart(phba);
4958 }
4959 
4960 /**
4961  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
4962  * @phba: Pointer to HBA context object.
4963  *
4964  * This function is called after a HBA restart to wait for successful
4965  * restart of the HBA. Successful restart of the HBA is indicated by
4966  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
4967  * iteration, the function will restart the HBA again. The function returns
4968  * zero if HBA successfully restarted else returns negative error code.
4969  **/
4970 int
4971 lpfc_sli_chipset_init(struct lpfc_hba *phba)
4972 {
4973 	uint32_t status, i = 0;
4974 
4975 	/* Read the HBA Host Status Register */
4976 	if (lpfc_readl(phba->HSregaddr, &status))
4977 		return -EIO;
4978 
4979 	/* Check status register to see what current state is */
4980 	i = 0;
4981 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
4982 
4983 		/* Check every 10ms for 10 retries, then every 100ms for 90
4984 		 * retries, then every 1 sec for 50 retires for a total of
4985 		 * ~60 seconds before reset the board again and check every
4986 		 * 1 sec for 50 retries. The up to 60 seconds before the
4987 		 * board ready is required by the Falcon FIPS zeroization
4988 		 * complete, and any reset the board in between shall cause
4989 		 * restart of zeroization, further delay the board ready.
4990 		 */
4991 		if (i++ >= 200) {
4992 			/* Adapter failed to init, timeout, status reg
4993 			   <status> */
4994 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4995 					"0436 Adapter failed to init, "
4996 					"timeout, status reg x%x, "
4997 					"FW Data: A8 x%x AC x%x\n", status,
4998 					readl(phba->MBslimaddr + 0xa8),
4999 					readl(phba->MBslimaddr + 0xac));
5000 			phba->link_state = LPFC_HBA_ERROR;
5001 			return -ETIMEDOUT;
5002 		}
5003 
5004 		/* Check to see if any errors occurred during init */
5005 		if (status & HS_FFERM) {
5006 			/* ERROR: During chipset initialization */
5007 			/* Adapter failed to init, chipset, status reg
5008 			   <status> */
5009 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5010 					"0437 Adapter failed to init, "
5011 					"chipset, status reg x%x, "
5012 					"FW Data: A8 x%x AC x%x\n", status,
5013 					readl(phba->MBslimaddr + 0xa8),
5014 					readl(phba->MBslimaddr + 0xac));
5015 			phba->link_state = LPFC_HBA_ERROR;
5016 			return -EIO;
5017 		}
5018 
5019 		if (i <= 10)
5020 			msleep(10);
5021 		else if (i <= 100)
5022 			msleep(100);
5023 		else
5024 			msleep(1000);
5025 
5026 		if (i == 150) {
5027 			/* Do post */
5028 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5029 			lpfc_sli_brdrestart(phba);
5030 		}
5031 		/* Read the HBA Host Status Register */
5032 		if (lpfc_readl(phba->HSregaddr, &status))
5033 			return -EIO;
5034 	}
5035 
5036 	/* Check to see if any errors occurred during init */
5037 	if (status & HS_FFERM) {
5038 		/* ERROR: During chipset initialization */
5039 		/* Adapter failed to init, chipset, status reg <status> */
5040 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5041 				"0438 Adapter failed to init, chipset, "
5042 				"status reg x%x, "
5043 				"FW Data: A8 x%x AC x%x\n", status,
5044 				readl(phba->MBslimaddr + 0xa8),
5045 				readl(phba->MBslimaddr + 0xac));
5046 		phba->link_state = LPFC_HBA_ERROR;
5047 		return -EIO;
5048 	}
5049 
5050 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5051 
5052 	/* Clear all interrupt enable conditions */
5053 	writel(0, phba->HCregaddr);
5054 	readl(phba->HCregaddr); /* flush */
5055 
5056 	/* setup host attn register */
5057 	writel(0xffffffff, phba->HAregaddr);
5058 	readl(phba->HAregaddr); /* flush */
5059 	return 0;
5060 }
5061 
5062 /**
5063  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5064  *
5065  * This function calculates and returns the number of HBQs required to be
5066  * configured.
5067  **/
5068 int
5069 lpfc_sli_hbq_count(void)
5070 {
5071 	return ARRAY_SIZE(lpfc_hbq_defs);
5072 }
5073 
5074 /**
5075  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5076  *
5077  * This function adds the number of hbq entries in every HBQ to get
5078  * the total number of hbq entries required for the HBA and returns
5079  * the total count.
5080  **/
5081 static int
5082 lpfc_sli_hbq_entry_count(void)
5083 {
5084 	int  hbq_count = lpfc_sli_hbq_count();
5085 	int  count = 0;
5086 	int  i;
5087 
5088 	for (i = 0; i < hbq_count; ++i)
5089 		count += lpfc_hbq_defs[i]->entry_count;
5090 	return count;
5091 }
5092 
5093 /**
5094  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5095  *
5096  * This function calculates amount of memory required for all hbq entries
5097  * to be configured and returns the total memory required.
5098  **/
5099 int
5100 lpfc_sli_hbq_size(void)
5101 {
5102 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5103 }
5104 
5105 /**
5106  * lpfc_sli_hbq_setup - configure and initialize HBQs
5107  * @phba: Pointer to HBA context object.
5108  *
5109  * This function is called during the SLI initialization to configure
5110  * all the HBQs and post buffers to the HBQ. The caller is not
5111  * required to hold any locks. This function will return zero if successful
5112  * else it will return negative error code.
5113  **/
5114 static int
5115 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5116 {
5117 	int  hbq_count = lpfc_sli_hbq_count();
5118 	LPFC_MBOXQ_t *pmb;
5119 	MAILBOX_t *pmbox;
5120 	uint32_t hbqno;
5121 	uint32_t hbq_entry_index;
5122 
5123 				/* Get a Mailbox buffer to setup mailbox
5124 				 * commands for HBA initialization
5125 				 */
5126 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5127 
5128 	if (!pmb)
5129 		return -ENOMEM;
5130 
5131 	pmbox = &pmb->u.mb;
5132 
5133 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
5134 	phba->link_state = LPFC_INIT_MBX_CMDS;
5135 	phba->hbq_in_use = 1;
5136 
5137 	hbq_entry_index = 0;
5138 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5139 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
5140 		phba->hbqs[hbqno].hbqPutIdx      = 0;
5141 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5142 		phba->hbqs[hbqno].entry_count =
5143 			lpfc_hbq_defs[hbqno]->entry_count;
5144 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5145 			hbq_entry_index, pmb);
5146 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
5147 
5148 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5149 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5150 			   mbxStatus <status>, ring <num> */
5151 
5152 			lpfc_printf_log(phba, KERN_ERR,
5153 					LOG_SLI | LOG_VPORT,
5154 					"1805 Adapter failed to init. "
5155 					"Data: x%x x%x x%x\n",
5156 					pmbox->mbxCommand,
5157 					pmbox->mbxStatus, hbqno);
5158 
5159 			phba->link_state = LPFC_HBA_ERROR;
5160 			mempool_free(pmb, phba->mbox_mem_pool);
5161 			return -ENXIO;
5162 		}
5163 	}
5164 	phba->hbq_count = hbq_count;
5165 
5166 	mempool_free(pmb, phba->mbox_mem_pool);
5167 
5168 	/* Initially populate or replenish the HBQs */
5169 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5170 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5171 	return 0;
5172 }
5173 
5174 /**
5175  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5176  * @phba: Pointer to HBA context object.
5177  *
5178  * This function is called during the SLI initialization to configure
5179  * all the HBQs and post buffers to the HBQ. The caller is not
5180  * required to hold any locks. This function will return zero if successful
5181  * else it will return negative error code.
5182  **/
5183 static int
5184 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5185 {
5186 	phba->hbq_in_use = 1;
5187 	/**
5188 	 * Specific case when the MDS diagnostics is enabled and supported.
5189 	 * The receive buffer count is truncated to manage the incoming
5190 	 * traffic.
5191 	 **/
5192 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5193 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5194 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5195 	else
5196 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5197 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5198 	phba->hbq_count = 1;
5199 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5200 	/* Initially populate or replenish the HBQs */
5201 	return 0;
5202 }
5203 
5204 /**
5205  * lpfc_sli_config_port - Issue config port mailbox command
5206  * @phba: Pointer to HBA context object.
5207  * @sli_mode: sli mode - 2/3
5208  *
5209  * This function is called by the sli initialization code path
5210  * to issue config_port mailbox command. This function restarts the
5211  * HBA firmware and issues a config_port mailbox command to configure
5212  * the SLI interface in the sli mode specified by sli_mode
5213  * variable. The caller is not required to hold any locks.
5214  * The function returns 0 if successful, else returns negative error
5215  * code.
5216  **/
5217 int
5218 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5219 {
5220 	LPFC_MBOXQ_t *pmb;
5221 	uint32_t resetcount = 0, rc = 0, done = 0;
5222 
5223 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5224 	if (!pmb) {
5225 		phba->link_state = LPFC_HBA_ERROR;
5226 		return -ENOMEM;
5227 	}
5228 
5229 	phba->sli_rev = sli_mode;
5230 	while (resetcount < 2 && !done) {
5231 		spin_lock_irq(&phba->hbalock);
5232 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5233 		spin_unlock_irq(&phba->hbalock);
5234 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5235 		lpfc_sli_brdrestart(phba);
5236 		rc = lpfc_sli_chipset_init(phba);
5237 		if (rc)
5238 			break;
5239 
5240 		spin_lock_irq(&phba->hbalock);
5241 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5242 		spin_unlock_irq(&phba->hbalock);
5243 		resetcount++;
5244 
5245 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5246 		 * value of 0 means the call was successful.  Any other
5247 		 * nonzero value is a failure, but if ERESTART is returned,
5248 		 * the driver may reset the HBA and try again.
5249 		 */
5250 		rc = lpfc_config_port_prep(phba);
5251 		if (rc == -ERESTART) {
5252 			phba->link_state = LPFC_LINK_UNKNOWN;
5253 			continue;
5254 		} else if (rc)
5255 			break;
5256 
5257 		phba->link_state = LPFC_INIT_MBX_CMDS;
5258 		lpfc_config_port(phba, pmb);
5259 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5260 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5261 					LPFC_SLI3_HBQ_ENABLED |
5262 					LPFC_SLI3_CRP_ENABLED |
5263 					LPFC_SLI3_DSS_ENABLED);
5264 		if (rc != MBX_SUCCESS) {
5265 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5266 				"0442 Adapter failed to init, mbxCmd x%x "
5267 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5268 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5269 			spin_lock_irq(&phba->hbalock);
5270 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5271 			spin_unlock_irq(&phba->hbalock);
5272 			rc = -ENXIO;
5273 		} else {
5274 			/* Allow asynchronous mailbox command to go through */
5275 			spin_lock_irq(&phba->hbalock);
5276 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5277 			spin_unlock_irq(&phba->hbalock);
5278 			done = 1;
5279 
5280 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5281 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5282 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5283 					"3110 Port did not grant ASABT\n");
5284 		}
5285 	}
5286 	if (!done) {
5287 		rc = -EINVAL;
5288 		goto do_prep_failed;
5289 	}
5290 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5291 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5292 			rc = -ENXIO;
5293 			goto do_prep_failed;
5294 		}
5295 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5296 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5297 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5298 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5299 				phba->max_vpi : phba->max_vports;
5300 
5301 		} else
5302 			phba->max_vpi = 0;
5303 		if (pmb->u.mb.un.varCfgPort.gerbm)
5304 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5305 		if (pmb->u.mb.un.varCfgPort.gcrp)
5306 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5307 
5308 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5309 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5310 
5311 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5312 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5313 				phba->cfg_enable_bg = 0;
5314 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5315 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5316 						"0443 Adapter did not grant "
5317 						"BlockGuard\n");
5318 			}
5319 		}
5320 	} else {
5321 		phba->hbq_get = NULL;
5322 		phba->port_gp = phba->mbox->us.s2.port;
5323 		phba->max_vpi = 0;
5324 	}
5325 do_prep_failed:
5326 	mempool_free(pmb, phba->mbox_mem_pool);
5327 	return rc;
5328 }
5329 
5330 
5331 /**
5332  * lpfc_sli_hba_setup - SLI initialization function
5333  * @phba: Pointer to HBA context object.
5334  *
5335  * This function is the main SLI initialization function. This function
5336  * is called by the HBA initialization code, HBA reset code and HBA
5337  * error attention handler code. Caller is not required to hold any
5338  * locks. This function issues config_port mailbox command to configure
5339  * the SLI, setup iocb rings and HBQ rings. In the end the function
5340  * calls the config_port_post function to issue init_link mailbox
5341  * command and to start the discovery. The function will return zero
5342  * if successful, else it will return negative error code.
5343  **/
5344 int
5345 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5346 {
5347 	uint32_t rc;
5348 	int  i;
5349 	int longs;
5350 
5351 	/* Enable ISR already does config_port because of config_msi mbx */
5352 	if (phba->hba_flag & HBA_NEEDS_CFG_PORT) {
5353 		rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5354 		if (rc)
5355 			return -EIO;
5356 		phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
5357 	}
5358 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5359 
5360 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
5361 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
5362 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
5363 		if (!rc) {
5364 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5365 					"2709 This device supports "
5366 					"Advanced Error Reporting (AER)\n");
5367 			spin_lock_irq(&phba->hbalock);
5368 			phba->hba_flag |= HBA_AER_ENABLED;
5369 			spin_unlock_irq(&phba->hbalock);
5370 		} else {
5371 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5372 					"2708 This device does not support "
5373 					"Advanced Error Reporting (AER): %d\n",
5374 					rc);
5375 			phba->cfg_aer_support = 0;
5376 		}
5377 	}
5378 
5379 	if (phba->sli_rev == 3) {
5380 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5381 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5382 	} else {
5383 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5384 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5385 		phba->sli3_options = 0;
5386 	}
5387 
5388 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5389 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5390 			phba->sli_rev, phba->max_vpi);
5391 	rc = lpfc_sli_ring_map(phba);
5392 
5393 	if (rc)
5394 		goto lpfc_sli_hba_setup_error;
5395 
5396 	/* Initialize VPIs. */
5397 	if (phba->sli_rev == LPFC_SLI_REV3) {
5398 		/*
5399 		 * The VPI bitmask and physical ID array are allocated
5400 		 * and initialized once only - at driver load.  A port
5401 		 * reset doesn't need to reinitialize this memory.
5402 		 */
5403 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5404 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5405 			phba->vpi_bmask = kcalloc(longs,
5406 						  sizeof(unsigned long),
5407 						  GFP_KERNEL);
5408 			if (!phba->vpi_bmask) {
5409 				rc = -ENOMEM;
5410 				goto lpfc_sli_hba_setup_error;
5411 			}
5412 
5413 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5414 						sizeof(uint16_t),
5415 						GFP_KERNEL);
5416 			if (!phba->vpi_ids) {
5417 				kfree(phba->vpi_bmask);
5418 				rc = -ENOMEM;
5419 				goto lpfc_sli_hba_setup_error;
5420 			}
5421 			for (i = 0; i < phba->max_vpi; i++)
5422 				phba->vpi_ids[i] = i;
5423 		}
5424 	}
5425 
5426 	/* Init HBQs */
5427 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5428 		rc = lpfc_sli_hbq_setup(phba);
5429 		if (rc)
5430 			goto lpfc_sli_hba_setup_error;
5431 	}
5432 	spin_lock_irq(&phba->hbalock);
5433 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5434 	spin_unlock_irq(&phba->hbalock);
5435 
5436 	rc = lpfc_config_port_post(phba);
5437 	if (rc)
5438 		goto lpfc_sli_hba_setup_error;
5439 
5440 	return rc;
5441 
5442 lpfc_sli_hba_setup_error:
5443 	phba->link_state = LPFC_HBA_ERROR;
5444 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5445 			"0445 Firmware initialization failed\n");
5446 	return rc;
5447 }
5448 
5449 /**
5450  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5451  * @phba: Pointer to HBA context object.
5452  *
5453  * This function issue a dump mailbox command to read config region
5454  * 23 and parse the records in the region and populate driver
5455  * data structure.
5456  **/
5457 static int
5458 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5459 {
5460 	LPFC_MBOXQ_t *mboxq;
5461 	struct lpfc_dmabuf *mp;
5462 	struct lpfc_mqe *mqe;
5463 	uint32_t data_length;
5464 	int rc;
5465 
5466 	/* Program the default value of vlan_id and fc_map */
5467 	phba->valid_vlan = 0;
5468 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5469 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5470 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5471 
5472 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5473 	if (!mboxq)
5474 		return -ENOMEM;
5475 
5476 	mqe = &mboxq->u.mqe;
5477 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5478 		rc = -ENOMEM;
5479 		goto out_free_mboxq;
5480 	}
5481 
5482 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5483 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5484 
5485 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5486 			"(%d):2571 Mailbox cmd x%x Status x%x "
5487 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5488 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5489 			"CQ: x%x x%x x%x x%x\n",
5490 			mboxq->vport ? mboxq->vport->vpi : 0,
5491 			bf_get(lpfc_mqe_command, mqe),
5492 			bf_get(lpfc_mqe_status, mqe),
5493 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5494 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5495 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5496 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5497 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5498 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5499 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5500 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5501 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5502 			mboxq->mcqe.word0,
5503 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5504 			mboxq->mcqe.trailer);
5505 
5506 	if (rc) {
5507 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5508 		kfree(mp);
5509 		rc = -EIO;
5510 		goto out_free_mboxq;
5511 	}
5512 	data_length = mqe->un.mb_words[5];
5513 	if (data_length > DMP_RGN23_SIZE) {
5514 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5515 		kfree(mp);
5516 		rc = -EIO;
5517 		goto out_free_mboxq;
5518 	}
5519 
5520 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5521 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
5522 	kfree(mp);
5523 	rc = 0;
5524 
5525 out_free_mboxq:
5526 	mempool_free(mboxq, phba->mbox_mem_pool);
5527 	return rc;
5528 }
5529 
5530 /**
5531  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5532  * @phba: pointer to lpfc hba data structure.
5533  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5534  * @vpd: pointer to the memory to hold resulting port vpd data.
5535  * @vpd_size: On input, the number of bytes allocated to @vpd.
5536  *	      On output, the number of data bytes in @vpd.
5537  *
5538  * This routine executes a READ_REV SLI4 mailbox command.  In
5539  * addition, this routine gets the port vpd data.
5540  *
5541  * Return codes
5542  * 	0 - successful
5543  * 	-ENOMEM - could not allocated memory.
5544  **/
5545 static int
5546 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5547 		    uint8_t *vpd, uint32_t *vpd_size)
5548 {
5549 	int rc = 0;
5550 	uint32_t dma_size;
5551 	struct lpfc_dmabuf *dmabuf;
5552 	struct lpfc_mqe *mqe;
5553 
5554 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5555 	if (!dmabuf)
5556 		return -ENOMEM;
5557 
5558 	/*
5559 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5560 	 * mailbox command.
5561 	 */
5562 	dma_size = *vpd_size;
5563 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5564 					  &dmabuf->phys, GFP_KERNEL);
5565 	if (!dmabuf->virt) {
5566 		kfree(dmabuf);
5567 		return -ENOMEM;
5568 	}
5569 
5570 	/*
5571 	 * The SLI4 implementation of READ_REV conflicts at word1,
5572 	 * bits 31:16 and SLI4 adds vpd functionality not present
5573 	 * in SLI3.  This code corrects the conflicts.
5574 	 */
5575 	lpfc_read_rev(phba, mboxq);
5576 	mqe = &mboxq->u.mqe;
5577 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5578 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5579 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5580 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5581 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5582 
5583 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5584 	if (rc) {
5585 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5586 				  dmabuf->virt, dmabuf->phys);
5587 		kfree(dmabuf);
5588 		return -EIO;
5589 	}
5590 
5591 	/*
5592 	 * The available vpd length cannot be bigger than the
5593 	 * DMA buffer passed to the port.  Catch the less than
5594 	 * case and update the caller's size.
5595 	 */
5596 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5597 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5598 
5599 	memcpy(vpd, dmabuf->virt, *vpd_size);
5600 
5601 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5602 			  dmabuf->virt, dmabuf->phys);
5603 	kfree(dmabuf);
5604 	return 0;
5605 }
5606 
5607 /**
5608  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5609  * @phba: pointer to lpfc hba data structure.
5610  *
5611  * This routine retrieves SLI4 device physical port name this PCI function
5612  * is attached to.
5613  *
5614  * Return codes
5615  *      0 - successful
5616  *      otherwise - failed to retrieve controller attributes
5617  **/
5618 static int
5619 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5620 {
5621 	LPFC_MBOXQ_t *mboxq;
5622 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5623 	struct lpfc_controller_attribute *cntl_attr;
5624 	void *virtaddr = NULL;
5625 	uint32_t alloclen, reqlen;
5626 	uint32_t shdr_status, shdr_add_status;
5627 	union lpfc_sli4_cfg_shdr *shdr;
5628 	int rc;
5629 
5630 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5631 	if (!mboxq)
5632 		return -ENOMEM;
5633 
5634 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5635 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5636 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5637 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5638 			LPFC_SLI4_MBX_NEMBED);
5639 
5640 	if (alloclen < reqlen) {
5641 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5642 				"3084 Allocated DMA memory size (%d) is "
5643 				"less than the requested DMA memory size "
5644 				"(%d)\n", alloclen, reqlen);
5645 		rc = -ENOMEM;
5646 		goto out_free_mboxq;
5647 	}
5648 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5649 	virtaddr = mboxq->sge_array->addr[0];
5650 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5651 	shdr = &mbx_cntl_attr->cfg_shdr;
5652 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5653 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5654 	if (shdr_status || shdr_add_status || rc) {
5655 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5656 				"3085 Mailbox x%x (x%x/x%x) failed, "
5657 				"rc:x%x, status:x%x, add_status:x%x\n",
5658 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5659 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5660 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5661 				rc, shdr_status, shdr_add_status);
5662 		rc = -ENXIO;
5663 		goto out_free_mboxq;
5664 	}
5665 
5666 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5667 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5668 	phba->sli4_hba.lnk_info.lnk_tp =
5669 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5670 	phba->sli4_hba.lnk_info.lnk_no =
5671 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5672 
5673 	memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
5674 	strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
5675 		sizeof(phba->BIOSVersion));
5676 
5677 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5678 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s\n",
5679 			phba->sli4_hba.lnk_info.lnk_tp,
5680 			phba->sli4_hba.lnk_info.lnk_no,
5681 			phba->BIOSVersion);
5682 out_free_mboxq:
5683 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5684 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
5685 	else
5686 		mempool_free(mboxq, phba->mbox_mem_pool);
5687 	return rc;
5688 }
5689 
5690 /**
5691  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
5692  * @phba: pointer to lpfc hba data structure.
5693  *
5694  * This routine retrieves SLI4 device physical port name this PCI function
5695  * is attached to.
5696  *
5697  * Return codes
5698  *      0 - successful
5699  *      otherwise - failed to retrieve physical port name
5700  **/
5701 static int
5702 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
5703 {
5704 	LPFC_MBOXQ_t *mboxq;
5705 	struct lpfc_mbx_get_port_name *get_port_name;
5706 	uint32_t shdr_status, shdr_add_status;
5707 	union lpfc_sli4_cfg_shdr *shdr;
5708 	char cport_name = 0;
5709 	int rc;
5710 
5711 	/* We assume nothing at this point */
5712 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5713 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
5714 
5715 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5716 	if (!mboxq)
5717 		return -ENOMEM;
5718 	/* obtain link type and link number via READ_CONFIG */
5719 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5720 	lpfc_sli4_read_config(phba);
5721 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
5722 		goto retrieve_ppname;
5723 
5724 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
5725 	rc = lpfc_sli4_get_ctl_attr(phba);
5726 	if (rc)
5727 		goto out_free_mboxq;
5728 
5729 retrieve_ppname:
5730 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5731 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
5732 		sizeof(struct lpfc_mbx_get_port_name) -
5733 		sizeof(struct lpfc_sli4_cfg_mhdr),
5734 		LPFC_SLI4_MBX_EMBED);
5735 	get_port_name = &mboxq->u.mqe.un.get_port_name;
5736 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5737 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
5738 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
5739 		phba->sli4_hba.lnk_info.lnk_tp);
5740 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5741 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5742 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5743 	if (shdr_status || shdr_add_status || rc) {
5744 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5745 				"3087 Mailbox x%x (x%x/x%x) failed: "
5746 				"rc:x%x, status:x%x, add_status:x%x\n",
5747 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5748 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5749 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5750 				rc, shdr_status, shdr_add_status);
5751 		rc = -ENXIO;
5752 		goto out_free_mboxq;
5753 	}
5754 	switch (phba->sli4_hba.lnk_info.lnk_no) {
5755 	case LPFC_LINK_NUMBER_0:
5756 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
5757 				&get_port_name->u.response);
5758 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5759 		break;
5760 	case LPFC_LINK_NUMBER_1:
5761 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
5762 				&get_port_name->u.response);
5763 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5764 		break;
5765 	case LPFC_LINK_NUMBER_2:
5766 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
5767 				&get_port_name->u.response);
5768 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5769 		break;
5770 	case LPFC_LINK_NUMBER_3:
5771 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
5772 				&get_port_name->u.response);
5773 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5774 		break;
5775 	default:
5776 		break;
5777 	}
5778 
5779 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
5780 		phba->Port[0] = cport_name;
5781 		phba->Port[1] = '\0';
5782 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5783 				"3091 SLI get port name: %s\n", phba->Port);
5784 	}
5785 
5786 out_free_mboxq:
5787 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5788 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
5789 	else
5790 		mempool_free(mboxq, phba->mbox_mem_pool);
5791 	return rc;
5792 }
5793 
5794 /**
5795  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
5796  * @phba: pointer to lpfc hba data structure.
5797  *
5798  * This routine is called to explicitly arm the SLI4 device's completion and
5799  * event queues
5800  **/
5801 static void
5802 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
5803 {
5804 	int qidx;
5805 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
5806 	struct lpfc_sli4_hdw_queue *qp;
5807 	struct lpfc_queue *eq;
5808 
5809 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
5810 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
5811 	if (sli4_hba->nvmels_cq)
5812 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
5813 					   LPFC_QUEUE_REARM);
5814 
5815 	if (sli4_hba->hdwq) {
5816 		/* Loop thru all Hardware Queues */
5817 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
5818 			qp = &sli4_hba->hdwq[qidx];
5819 			/* ARM the corresponding CQ */
5820 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
5821 						LPFC_QUEUE_REARM);
5822 		}
5823 
5824 		/* Loop thru all IRQ vectors */
5825 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
5826 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
5827 			/* ARM the corresponding EQ */
5828 			sli4_hba->sli4_write_eq_db(phba, eq,
5829 						   0, LPFC_QUEUE_REARM);
5830 		}
5831 	}
5832 
5833 	if (phba->nvmet_support) {
5834 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
5835 			sli4_hba->sli4_write_cq_db(phba,
5836 				sli4_hba->nvmet_cqset[qidx], 0,
5837 				LPFC_QUEUE_REARM);
5838 		}
5839 	}
5840 }
5841 
5842 /**
5843  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
5844  * @phba: Pointer to HBA context object.
5845  * @type: The resource extent type.
5846  * @extnt_count: buffer to hold port available extent count.
5847  * @extnt_size: buffer to hold element count per extent.
5848  *
5849  * This function calls the port and retrievs the number of available
5850  * extents and their size for a particular extent type.
5851  *
5852  * Returns: 0 if successful.  Nonzero otherwise.
5853  **/
5854 int
5855 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
5856 			       uint16_t *extnt_count, uint16_t *extnt_size)
5857 {
5858 	int rc = 0;
5859 	uint32_t length;
5860 	uint32_t mbox_tmo;
5861 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
5862 	LPFC_MBOXQ_t *mbox;
5863 
5864 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5865 	if (!mbox)
5866 		return -ENOMEM;
5867 
5868 	/* Find out how many extents are available for this resource type */
5869 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
5870 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5871 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5872 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
5873 			 length, LPFC_SLI4_MBX_EMBED);
5874 
5875 	/* Send an extents count of 0 - the GET doesn't use it. */
5876 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5877 					LPFC_SLI4_MBX_EMBED);
5878 	if (unlikely(rc)) {
5879 		rc = -EIO;
5880 		goto err_exit;
5881 	}
5882 
5883 	if (!phba->sli4_hba.intr_enable)
5884 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5885 	else {
5886 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5887 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5888 	}
5889 	if (unlikely(rc)) {
5890 		rc = -EIO;
5891 		goto err_exit;
5892 	}
5893 
5894 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
5895 	if (bf_get(lpfc_mbox_hdr_status,
5896 		   &rsrc_info->header.cfg_shdr.response)) {
5897 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5898 				"2930 Failed to get resource extents "
5899 				"Status 0x%x Add'l Status 0x%x\n",
5900 				bf_get(lpfc_mbox_hdr_status,
5901 				       &rsrc_info->header.cfg_shdr.response),
5902 				bf_get(lpfc_mbox_hdr_add_status,
5903 				       &rsrc_info->header.cfg_shdr.response));
5904 		rc = -EIO;
5905 		goto err_exit;
5906 	}
5907 
5908 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
5909 			      &rsrc_info->u.rsp);
5910 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
5911 			     &rsrc_info->u.rsp);
5912 
5913 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5914 			"3162 Retrieved extents type-%d from port: count:%d, "
5915 			"size:%d\n", type, *extnt_count, *extnt_size);
5916 
5917 err_exit:
5918 	mempool_free(mbox, phba->mbox_mem_pool);
5919 	return rc;
5920 }
5921 
5922 /**
5923  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
5924  * @phba: Pointer to HBA context object.
5925  * @type: The extent type to check.
5926  *
5927  * This function reads the current available extents from the port and checks
5928  * if the extent count or extent size has changed since the last access.
5929  * Callers use this routine post port reset to understand if there is a
5930  * extent reprovisioning requirement.
5931  *
5932  * Returns:
5933  *   -Error: error indicates problem.
5934  *   1: Extent count or size has changed.
5935  *   0: No changes.
5936  **/
5937 static int
5938 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
5939 {
5940 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
5941 	uint16_t size_diff, rsrc_ext_size;
5942 	int rc = 0;
5943 	struct lpfc_rsrc_blks *rsrc_entry;
5944 	struct list_head *rsrc_blk_list = NULL;
5945 
5946 	size_diff = 0;
5947 	curr_ext_cnt = 0;
5948 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5949 					    &rsrc_ext_cnt,
5950 					    &rsrc_ext_size);
5951 	if (unlikely(rc))
5952 		return -EIO;
5953 
5954 	switch (type) {
5955 	case LPFC_RSC_TYPE_FCOE_RPI:
5956 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5957 		break;
5958 	case LPFC_RSC_TYPE_FCOE_VPI:
5959 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
5960 		break;
5961 	case LPFC_RSC_TYPE_FCOE_XRI:
5962 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5963 		break;
5964 	case LPFC_RSC_TYPE_FCOE_VFI:
5965 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5966 		break;
5967 	default:
5968 		break;
5969 	}
5970 
5971 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
5972 		curr_ext_cnt++;
5973 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
5974 			size_diff++;
5975 	}
5976 
5977 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
5978 		rc = 1;
5979 
5980 	return rc;
5981 }
5982 
5983 /**
5984  * lpfc_sli4_cfg_post_extnts -
5985  * @phba: Pointer to HBA context object.
5986  * @extnt_cnt: number of available extents.
5987  * @type: the extent type (rpi, xri, vfi, vpi).
5988  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
5989  * @mbox: pointer to the caller's allocated mailbox structure.
5990  *
5991  * This function executes the extents allocation request.  It also
5992  * takes care of the amount of memory needed to allocate or get the
5993  * allocated extents. It is the caller's responsibility to evaluate
5994  * the response.
5995  *
5996  * Returns:
5997  *   -Error:  Error value describes the condition found.
5998  *   0: if successful
5999  **/
6000 static int
6001 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6002 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6003 {
6004 	int rc = 0;
6005 	uint32_t req_len;
6006 	uint32_t emb_len;
6007 	uint32_t alloc_len, mbox_tmo;
6008 
6009 	/* Calculate the total requested length of the dma memory */
6010 	req_len = extnt_cnt * sizeof(uint16_t);
6011 
6012 	/*
6013 	 * Calculate the size of an embedded mailbox.  The uint32_t
6014 	 * accounts for extents-specific word.
6015 	 */
6016 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6017 		sizeof(uint32_t);
6018 
6019 	/*
6020 	 * Presume the allocation and response will fit into an embedded
6021 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6022 	 */
6023 	*emb = LPFC_SLI4_MBX_EMBED;
6024 	if (req_len > emb_len) {
6025 		req_len = extnt_cnt * sizeof(uint16_t) +
6026 			sizeof(union lpfc_sli4_cfg_shdr) +
6027 			sizeof(uint32_t);
6028 		*emb = LPFC_SLI4_MBX_NEMBED;
6029 	}
6030 
6031 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6032 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6033 				     req_len, *emb);
6034 	if (alloc_len < req_len) {
6035 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6036 			"2982 Allocated DMA memory size (x%x) is "
6037 			"less than the requested DMA memory "
6038 			"size (x%x)\n", alloc_len, req_len);
6039 		return -ENOMEM;
6040 	}
6041 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6042 	if (unlikely(rc))
6043 		return -EIO;
6044 
6045 	if (!phba->sli4_hba.intr_enable)
6046 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6047 	else {
6048 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6049 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6050 	}
6051 
6052 	if (unlikely(rc))
6053 		rc = -EIO;
6054 	return rc;
6055 }
6056 
6057 /**
6058  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6059  * @phba: Pointer to HBA context object.
6060  * @type:  The resource extent type to allocate.
6061  *
6062  * This function allocates the number of elements for the specified
6063  * resource type.
6064  **/
6065 static int
6066 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6067 {
6068 	bool emb = false;
6069 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6070 	uint16_t rsrc_id, rsrc_start, j, k;
6071 	uint16_t *ids;
6072 	int i, rc;
6073 	unsigned long longs;
6074 	unsigned long *bmask;
6075 	struct lpfc_rsrc_blks *rsrc_blks;
6076 	LPFC_MBOXQ_t *mbox;
6077 	uint32_t length;
6078 	struct lpfc_id_range *id_array = NULL;
6079 	void *virtaddr = NULL;
6080 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6081 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6082 	struct list_head *ext_blk_list;
6083 
6084 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6085 					    &rsrc_cnt,
6086 					    &rsrc_size);
6087 	if (unlikely(rc))
6088 		return -EIO;
6089 
6090 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6091 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6092 			"3009 No available Resource Extents "
6093 			"for resource type 0x%x: Count: 0x%x, "
6094 			"Size 0x%x\n", type, rsrc_cnt,
6095 			rsrc_size);
6096 		return -ENOMEM;
6097 	}
6098 
6099 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6100 			"2903 Post resource extents type-0x%x: "
6101 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6102 
6103 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6104 	if (!mbox)
6105 		return -ENOMEM;
6106 
6107 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6108 	if (unlikely(rc)) {
6109 		rc = -EIO;
6110 		goto err_exit;
6111 	}
6112 
6113 	/*
6114 	 * Figure out where the response is located.  Then get local pointers
6115 	 * to the response data.  The port does not guarantee to respond to
6116 	 * all extents counts request so update the local variable with the
6117 	 * allocated count from the port.
6118 	 */
6119 	if (emb == LPFC_SLI4_MBX_EMBED) {
6120 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6121 		id_array = &rsrc_ext->u.rsp.id[0];
6122 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6123 	} else {
6124 		virtaddr = mbox->sge_array->addr[0];
6125 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6126 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6127 		id_array = &n_rsrc->id;
6128 	}
6129 
6130 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6131 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6132 
6133 	/*
6134 	 * Based on the resource size and count, correct the base and max
6135 	 * resource values.
6136 	 */
6137 	length = sizeof(struct lpfc_rsrc_blks);
6138 	switch (type) {
6139 	case LPFC_RSC_TYPE_FCOE_RPI:
6140 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6141 						   sizeof(unsigned long),
6142 						   GFP_KERNEL);
6143 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6144 			rc = -ENOMEM;
6145 			goto err_exit;
6146 		}
6147 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6148 						 sizeof(uint16_t),
6149 						 GFP_KERNEL);
6150 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6151 			kfree(phba->sli4_hba.rpi_bmask);
6152 			rc = -ENOMEM;
6153 			goto err_exit;
6154 		}
6155 
6156 		/*
6157 		 * The next_rpi was initialized with the maximum available
6158 		 * count but the port may allocate a smaller number.  Catch
6159 		 * that case and update the next_rpi.
6160 		 */
6161 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6162 
6163 		/* Initialize local ptrs for common extent processing later. */
6164 		bmask = phba->sli4_hba.rpi_bmask;
6165 		ids = phba->sli4_hba.rpi_ids;
6166 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6167 		break;
6168 	case LPFC_RSC_TYPE_FCOE_VPI:
6169 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6170 					  GFP_KERNEL);
6171 		if (unlikely(!phba->vpi_bmask)) {
6172 			rc = -ENOMEM;
6173 			goto err_exit;
6174 		}
6175 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6176 					 GFP_KERNEL);
6177 		if (unlikely(!phba->vpi_ids)) {
6178 			kfree(phba->vpi_bmask);
6179 			rc = -ENOMEM;
6180 			goto err_exit;
6181 		}
6182 
6183 		/* Initialize local ptrs for common extent processing later. */
6184 		bmask = phba->vpi_bmask;
6185 		ids = phba->vpi_ids;
6186 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6187 		break;
6188 	case LPFC_RSC_TYPE_FCOE_XRI:
6189 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6190 						   sizeof(unsigned long),
6191 						   GFP_KERNEL);
6192 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6193 			rc = -ENOMEM;
6194 			goto err_exit;
6195 		}
6196 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6197 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6198 						 sizeof(uint16_t),
6199 						 GFP_KERNEL);
6200 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6201 			kfree(phba->sli4_hba.xri_bmask);
6202 			rc = -ENOMEM;
6203 			goto err_exit;
6204 		}
6205 
6206 		/* Initialize local ptrs for common extent processing later. */
6207 		bmask = phba->sli4_hba.xri_bmask;
6208 		ids = phba->sli4_hba.xri_ids;
6209 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6210 		break;
6211 	case LPFC_RSC_TYPE_FCOE_VFI:
6212 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6213 						   sizeof(unsigned long),
6214 						   GFP_KERNEL);
6215 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6216 			rc = -ENOMEM;
6217 			goto err_exit;
6218 		}
6219 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6220 						 sizeof(uint16_t),
6221 						 GFP_KERNEL);
6222 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6223 			kfree(phba->sli4_hba.vfi_bmask);
6224 			rc = -ENOMEM;
6225 			goto err_exit;
6226 		}
6227 
6228 		/* Initialize local ptrs for common extent processing later. */
6229 		bmask = phba->sli4_hba.vfi_bmask;
6230 		ids = phba->sli4_hba.vfi_ids;
6231 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6232 		break;
6233 	default:
6234 		/* Unsupported Opcode.  Fail call. */
6235 		id_array = NULL;
6236 		bmask = NULL;
6237 		ids = NULL;
6238 		ext_blk_list = NULL;
6239 		goto err_exit;
6240 	}
6241 
6242 	/*
6243 	 * Complete initializing the extent configuration with the
6244 	 * allocated ids assigned to this function.  The bitmask serves
6245 	 * as an index into the array and manages the available ids.  The
6246 	 * array just stores the ids communicated to the port via the wqes.
6247 	 */
6248 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6249 		if ((i % 2) == 0)
6250 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6251 					 &id_array[k]);
6252 		else
6253 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6254 					 &id_array[k]);
6255 
6256 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6257 		if (unlikely(!rsrc_blks)) {
6258 			rc = -ENOMEM;
6259 			kfree(bmask);
6260 			kfree(ids);
6261 			goto err_exit;
6262 		}
6263 		rsrc_blks->rsrc_start = rsrc_id;
6264 		rsrc_blks->rsrc_size = rsrc_size;
6265 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6266 		rsrc_start = rsrc_id;
6267 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6268 			phba->sli4_hba.io_xri_start = rsrc_start +
6269 				lpfc_sli4_get_iocb_cnt(phba);
6270 		}
6271 
6272 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6273 			ids[j] = rsrc_id;
6274 			rsrc_id++;
6275 			j++;
6276 		}
6277 		/* Entire word processed.  Get next word.*/
6278 		if ((i % 2) == 1)
6279 			k++;
6280 	}
6281  err_exit:
6282 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6283 	return rc;
6284 }
6285 
6286 
6287 
6288 /**
6289  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6290  * @phba: Pointer to HBA context object.
6291  * @type: the extent's type.
6292  *
6293  * This function deallocates all extents of a particular resource type.
6294  * SLI4 does not allow for deallocating a particular extent range.  It
6295  * is the caller's responsibility to release all kernel memory resources.
6296  **/
6297 static int
6298 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6299 {
6300 	int rc;
6301 	uint32_t length, mbox_tmo = 0;
6302 	LPFC_MBOXQ_t *mbox;
6303 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6304 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6305 
6306 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6307 	if (!mbox)
6308 		return -ENOMEM;
6309 
6310 	/*
6311 	 * This function sends an embedded mailbox because it only sends the
6312 	 * the resource type.  All extents of this type are released by the
6313 	 * port.
6314 	 */
6315 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6316 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6317 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6318 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6319 			 length, LPFC_SLI4_MBX_EMBED);
6320 
6321 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6322 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6323 					LPFC_SLI4_MBX_EMBED);
6324 	if (unlikely(rc)) {
6325 		rc = -EIO;
6326 		goto out_free_mbox;
6327 	}
6328 	if (!phba->sli4_hba.intr_enable)
6329 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6330 	else {
6331 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6332 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6333 	}
6334 	if (unlikely(rc)) {
6335 		rc = -EIO;
6336 		goto out_free_mbox;
6337 	}
6338 
6339 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6340 	if (bf_get(lpfc_mbox_hdr_status,
6341 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6342 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6343 				"2919 Failed to release resource extents "
6344 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6345 				"Resource memory not released.\n",
6346 				type,
6347 				bf_get(lpfc_mbox_hdr_status,
6348 				    &dealloc_rsrc->header.cfg_shdr.response),
6349 				bf_get(lpfc_mbox_hdr_add_status,
6350 				    &dealloc_rsrc->header.cfg_shdr.response));
6351 		rc = -EIO;
6352 		goto out_free_mbox;
6353 	}
6354 
6355 	/* Release kernel memory resources for the specific type. */
6356 	switch (type) {
6357 	case LPFC_RSC_TYPE_FCOE_VPI:
6358 		kfree(phba->vpi_bmask);
6359 		kfree(phba->vpi_ids);
6360 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6361 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6362 				    &phba->lpfc_vpi_blk_list, list) {
6363 			list_del_init(&rsrc_blk->list);
6364 			kfree(rsrc_blk);
6365 		}
6366 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6367 		break;
6368 	case LPFC_RSC_TYPE_FCOE_XRI:
6369 		kfree(phba->sli4_hba.xri_bmask);
6370 		kfree(phba->sli4_hba.xri_ids);
6371 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6372 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6373 			list_del_init(&rsrc_blk->list);
6374 			kfree(rsrc_blk);
6375 		}
6376 		break;
6377 	case LPFC_RSC_TYPE_FCOE_VFI:
6378 		kfree(phba->sli4_hba.vfi_bmask);
6379 		kfree(phba->sli4_hba.vfi_ids);
6380 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6381 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6382 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6383 			list_del_init(&rsrc_blk->list);
6384 			kfree(rsrc_blk);
6385 		}
6386 		break;
6387 	case LPFC_RSC_TYPE_FCOE_RPI:
6388 		/* RPI bitmask and physical id array are cleaned up earlier. */
6389 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6390 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6391 			list_del_init(&rsrc_blk->list);
6392 			kfree(rsrc_blk);
6393 		}
6394 		break;
6395 	default:
6396 		break;
6397 	}
6398 
6399 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6400 
6401  out_free_mbox:
6402 	mempool_free(mbox, phba->mbox_mem_pool);
6403 	return rc;
6404 }
6405 
6406 static void
6407 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6408 		  uint32_t feature)
6409 {
6410 	uint32_t len;
6411 
6412 	len = sizeof(struct lpfc_mbx_set_feature) -
6413 		sizeof(struct lpfc_sli4_cfg_mhdr);
6414 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6415 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6416 			 LPFC_SLI4_MBX_EMBED);
6417 
6418 	switch (feature) {
6419 	case LPFC_SET_UE_RECOVERY:
6420 		bf_set(lpfc_mbx_set_feature_UER,
6421 		       &mbox->u.mqe.un.set_feature, 1);
6422 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6423 		mbox->u.mqe.un.set_feature.param_len = 8;
6424 		break;
6425 	case LPFC_SET_MDS_DIAGS:
6426 		bf_set(lpfc_mbx_set_feature_mds,
6427 		       &mbox->u.mqe.un.set_feature, 1);
6428 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6429 		       &mbox->u.mqe.un.set_feature, 1);
6430 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6431 		mbox->u.mqe.un.set_feature.param_len = 8;
6432 		break;
6433 	case LPFC_SET_DUAL_DUMP:
6434 		bf_set(lpfc_mbx_set_feature_dd,
6435 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6436 		bf_set(lpfc_mbx_set_feature_ddquery,
6437 		       &mbox->u.mqe.un.set_feature, 0);
6438 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6439 		mbox->u.mqe.un.set_feature.param_len = 4;
6440 		break;
6441 	}
6442 
6443 	return;
6444 }
6445 
6446 /**
6447  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6448  * @phba: Pointer to HBA context object.
6449  *
6450  * Disable FW logging into host memory on the adapter. To
6451  * be done before reading logs from the host memory.
6452  **/
6453 void
6454 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6455 {
6456 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6457 
6458 	spin_lock_irq(&phba->hbalock);
6459 	ras_fwlog->state = INACTIVE;
6460 	spin_unlock_irq(&phba->hbalock);
6461 
6462 	/* Disable FW logging to host memory */
6463 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6464 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6465 
6466 	/* Wait 10ms for firmware to stop using DMA buffer */
6467 	usleep_range(10 * 1000, 20 * 1000);
6468 }
6469 
6470 /**
6471  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6472  * @phba: Pointer to HBA context object.
6473  *
6474  * This function is called to free memory allocated for RAS FW logging
6475  * support in the driver.
6476  **/
6477 void
6478 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6479 {
6480 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6481 	struct lpfc_dmabuf *dmabuf, *next;
6482 
6483 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6484 		list_for_each_entry_safe(dmabuf, next,
6485 				    &ras_fwlog->fwlog_buff_list,
6486 				    list) {
6487 			list_del(&dmabuf->list);
6488 			dma_free_coherent(&phba->pcidev->dev,
6489 					  LPFC_RAS_MAX_ENTRY_SIZE,
6490 					  dmabuf->virt, dmabuf->phys);
6491 			kfree(dmabuf);
6492 		}
6493 	}
6494 
6495 	if (ras_fwlog->lwpd.virt) {
6496 		dma_free_coherent(&phba->pcidev->dev,
6497 				  sizeof(uint32_t) * 2,
6498 				  ras_fwlog->lwpd.virt,
6499 				  ras_fwlog->lwpd.phys);
6500 		ras_fwlog->lwpd.virt = NULL;
6501 	}
6502 
6503 	spin_lock_irq(&phba->hbalock);
6504 	ras_fwlog->state = INACTIVE;
6505 	spin_unlock_irq(&phba->hbalock);
6506 }
6507 
6508 /**
6509  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6510  * @phba: Pointer to HBA context object.
6511  * @fwlog_buff_count: Count of buffers to be created.
6512  *
6513  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6514  * to update FW log is posted to the adapter.
6515  * Buffer count is calculated based on module param ras_fwlog_buffsize
6516  * Size of each buffer posted to FW is 64K.
6517  **/
6518 
6519 static int
6520 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6521 			uint32_t fwlog_buff_count)
6522 {
6523 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6524 	struct lpfc_dmabuf *dmabuf;
6525 	int rc = 0, i = 0;
6526 
6527 	/* Initialize List */
6528 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6529 
6530 	/* Allocate memory for the LWPD */
6531 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6532 					    sizeof(uint32_t) * 2,
6533 					    &ras_fwlog->lwpd.phys,
6534 					    GFP_KERNEL);
6535 	if (!ras_fwlog->lwpd.virt) {
6536 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6537 				"6185 LWPD Memory Alloc Failed\n");
6538 
6539 		return -ENOMEM;
6540 	}
6541 
6542 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6543 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6544 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6545 				 GFP_KERNEL);
6546 		if (!dmabuf) {
6547 			rc = -ENOMEM;
6548 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6549 					"6186 Memory Alloc failed FW logging");
6550 			goto free_mem;
6551 		}
6552 
6553 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6554 						  LPFC_RAS_MAX_ENTRY_SIZE,
6555 						  &dmabuf->phys, GFP_KERNEL);
6556 		if (!dmabuf->virt) {
6557 			kfree(dmabuf);
6558 			rc = -ENOMEM;
6559 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6560 					"6187 DMA Alloc Failed FW logging");
6561 			goto free_mem;
6562 		}
6563 		dmabuf->buffer_tag = i;
6564 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6565 	}
6566 
6567 free_mem:
6568 	if (rc)
6569 		lpfc_sli4_ras_dma_free(phba);
6570 
6571 	return rc;
6572 }
6573 
6574 /**
6575  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6576  * @phba: pointer to lpfc hba data structure.
6577  * @pmb: pointer to the driver internal queue element for mailbox command.
6578  *
6579  * Completion handler for driver's RAS MBX command to the device.
6580  **/
6581 static void
6582 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6583 {
6584 	MAILBOX_t *mb;
6585 	union lpfc_sli4_cfg_shdr *shdr;
6586 	uint32_t shdr_status, shdr_add_status;
6587 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6588 
6589 	mb = &pmb->u.mb;
6590 
6591 	shdr = (union lpfc_sli4_cfg_shdr *)
6592 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6593 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6594 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6595 
6596 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6597 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6598 				"6188 FW LOG mailbox "
6599 				"completed with status x%x add_status x%x,"
6600 				" mbx status x%x\n",
6601 				shdr_status, shdr_add_status, mb->mbxStatus);
6602 
6603 		ras_fwlog->ras_hwsupport = false;
6604 		goto disable_ras;
6605 	}
6606 
6607 	spin_lock_irq(&phba->hbalock);
6608 	ras_fwlog->state = ACTIVE;
6609 	spin_unlock_irq(&phba->hbalock);
6610 	mempool_free(pmb, phba->mbox_mem_pool);
6611 
6612 	return;
6613 
6614 disable_ras:
6615 	/* Free RAS DMA memory */
6616 	lpfc_sli4_ras_dma_free(phba);
6617 	mempool_free(pmb, phba->mbox_mem_pool);
6618 }
6619 
6620 /**
6621  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
6622  * @phba: pointer to lpfc hba data structure.
6623  * @fwlog_level: Logging verbosity level.
6624  * @fwlog_enable: Enable/Disable logging.
6625  *
6626  * Initialize memory and post mailbox command to enable FW logging in host
6627  * memory.
6628  **/
6629 int
6630 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
6631 			 uint32_t fwlog_level,
6632 			 uint32_t fwlog_enable)
6633 {
6634 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6635 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
6636 	struct lpfc_dmabuf *dmabuf;
6637 	LPFC_MBOXQ_t *mbox;
6638 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
6639 	int rc = 0;
6640 
6641 	spin_lock_irq(&phba->hbalock);
6642 	ras_fwlog->state = INACTIVE;
6643 	spin_unlock_irq(&phba->hbalock);
6644 
6645 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
6646 			  phba->cfg_ras_fwlog_buffsize);
6647 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
6648 
6649 	/*
6650 	 * If re-enabling FW logging support use earlier allocated
6651 	 * DMA buffers while posting MBX command.
6652 	 **/
6653 	if (!ras_fwlog->lwpd.virt) {
6654 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
6655 		if (rc) {
6656 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6657 					"6189 FW Log Memory Allocation Failed");
6658 			return rc;
6659 		}
6660 	}
6661 
6662 	/* Setup Mailbox command */
6663 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6664 	if (!mbox) {
6665 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6666 				"6190 RAS MBX Alloc Failed");
6667 		rc = -ENOMEM;
6668 		goto mem_free;
6669 	}
6670 
6671 	ras_fwlog->fw_loglevel = fwlog_level;
6672 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
6673 		sizeof(struct lpfc_sli4_cfg_mhdr));
6674 
6675 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
6676 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
6677 			 len, LPFC_SLI4_MBX_EMBED);
6678 
6679 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
6680 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
6681 	       fwlog_enable);
6682 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
6683 	       ras_fwlog->fw_loglevel);
6684 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
6685 	       ras_fwlog->fw_buffcount);
6686 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
6687 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
6688 
6689 	/* Update DMA buffer address */
6690 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
6691 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
6692 
6693 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
6694 			putPaddrLow(dmabuf->phys);
6695 
6696 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
6697 			putPaddrHigh(dmabuf->phys);
6698 	}
6699 
6700 	/* Update LPWD address */
6701 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
6702 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
6703 
6704 	spin_lock_irq(&phba->hbalock);
6705 	ras_fwlog->state = REG_INPROGRESS;
6706 	spin_unlock_irq(&phba->hbalock);
6707 	mbox->vport = phba->pport;
6708 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
6709 
6710 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
6711 
6712 	if (rc == MBX_NOT_FINISHED) {
6713 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6714 				"6191 FW-Log Mailbox failed. "
6715 				"status %d mbxStatus : x%x", rc,
6716 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
6717 		mempool_free(mbox, phba->mbox_mem_pool);
6718 		rc = -EIO;
6719 		goto mem_free;
6720 	} else
6721 		rc = 0;
6722 mem_free:
6723 	if (rc)
6724 		lpfc_sli4_ras_dma_free(phba);
6725 
6726 	return rc;
6727 }
6728 
6729 /**
6730  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
6731  * @phba: Pointer to HBA context object.
6732  *
6733  * Check if RAS is supported on the adapter and initialize it.
6734  **/
6735 void
6736 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
6737 {
6738 	/* Check RAS FW Log needs to be enabled or not */
6739 	if (lpfc_check_fwlog_support(phba))
6740 		return;
6741 
6742 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
6743 				 LPFC_RAS_ENABLE_LOGGING);
6744 }
6745 
6746 /**
6747  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
6748  * @phba: Pointer to HBA context object.
6749  *
6750  * This function allocates all SLI4 resource identifiers.
6751  **/
6752 int
6753 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
6754 {
6755 	int i, rc, error = 0;
6756 	uint16_t count, base;
6757 	unsigned long longs;
6758 
6759 	if (!phba->sli4_hba.rpi_hdrs_in_use)
6760 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
6761 	if (phba->sli4_hba.extents_in_use) {
6762 		/*
6763 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
6764 		 * resource extent count must be read and allocated before
6765 		 * provisioning the resource id arrays.
6766 		 */
6767 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6768 		    LPFC_IDX_RSRC_RDY) {
6769 			/*
6770 			 * Extent-based resources are set - the driver could
6771 			 * be in a port reset. Figure out if any corrective
6772 			 * actions need to be taken.
6773 			 */
6774 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6775 						 LPFC_RSC_TYPE_FCOE_VFI);
6776 			if (rc != 0)
6777 				error++;
6778 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6779 						 LPFC_RSC_TYPE_FCOE_VPI);
6780 			if (rc != 0)
6781 				error++;
6782 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6783 						 LPFC_RSC_TYPE_FCOE_XRI);
6784 			if (rc != 0)
6785 				error++;
6786 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6787 						 LPFC_RSC_TYPE_FCOE_RPI);
6788 			if (rc != 0)
6789 				error++;
6790 
6791 			/*
6792 			 * It's possible that the number of resources
6793 			 * provided to this port instance changed between
6794 			 * resets.  Detect this condition and reallocate
6795 			 * resources.  Otherwise, there is no action.
6796 			 */
6797 			if (error) {
6798 				lpfc_printf_log(phba, KERN_INFO,
6799 						LOG_MBOX | LOG_INIT,
6800 						"2931 Detected extent resource "
6801 						"change.  Reallocating all "
6802 						"extents.\n");
6803 				rc = lpfc_sli4_dealloc_extent(phba,
6804 						 LPFC_RSC_TYPE_FCOE_VFI);
6805 				rc = lpfc_sli4_dealloc_extent(phba,
6806 						 LPFC_RSC_TYPE_FCOE_VPI);
6807 				rc = lpfc_sli4_dealloc_extent(phba,
6808 						 LPFC_RSC_TYPE_FCOE_XRI);
6809 				rc = lpfc_sli4_dealloc_extent(phba,
6810 						 LPFC_RSC_TYPE_FCOE_RPI);
6811 			} else
6812 				return 0;
6813 		}
6814 
6815 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6816 		if (unlikely(rc))
6817 			goto err_exit;
6818 
6819 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6820 		if (unlikely(rc))
6821 			goto err_exit;
6822 
6823 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6824 		if (unlikely(rc))
6825 			goto err_exit;
6826 
6827 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6828 		if (unlikely(rc))
6829 			goto err_exit;
6830 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6831 		       LPFC_IDX_RSRC_RDY);
6832 		return rc;
6833 	} else {
6834 		/*
6835 		 * The port does not support resource extents.  The XRI, VPI,
6836 		 * VFI, RPI resource ids were determined from READ_CONFIG.
6837 		 * Just allocate the bitmasks and provision the resource id
6838 		 * arrays.  If a port reset is active, the resources don't
6839 		 * need any action - just exit.
6840 		 */
6841 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6842 		    LPFC_IDX_RSRC_RDY) {
6843 			lpfc_sli4_dealloc_resource_identifiers(phba);
6844 			lpfc_sli4_remove_rpis(phba);
6845 		}
6846 		/* RPIs. */
6847 		count = phba->sli4_hba.max_cfg_param.max_rpi;
6848 		if (count <= 0) {
6849 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6850 					"3279 Invalid provisioning of "
6851 					"rpi:%d\n", count);
6852 			rc = -EINVAL;
6853 			goto err_exit;
6854 		}
6855 		base = phba->sli4_hba.max_cfg_param.rpi_base;
6856 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6857 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6858 						   sizeof(unsigned long),
6859 						   GFP_KERNEL);
6860 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6861 			rc = -ENOMEM;
6862 			goto err_exit;
6863 		}
6864 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
6865 						 GFP_KERNEL);
6866 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6867 			rc = -ENOMEM;
6868 			goto free_rpi_bmask;
6869 		}
6870 
6871 		for (i = 0; i < count; i++)
6872 			phba->sli4_hba.rpi_ids[i] = base + i;
6873 
6874 		/* VPIs. */
6875 		count = phba->sli4_hba.max_cfg_param.max_vpi;
6876 		if (count <= 0) {
6877 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6878 					"3280 Invalid provisioning of "
6879 					"vpi:%d\n", count);
6880 			rc = -EINVAL;
6881 			goto free_rpi_ids;
6882 		}
6883 		base = phba->sli4_hba.max_cfg_param.vpi_base;
6884 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6885 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6886 					  GFP_KERNEL);
6887 		if (unlikely(!phba->vpi_bmask)) {
6888 			rc = -ENOMEM;
6889 			goto free_rpi_ids;
6890 		}
6891 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
6892 					GFP_KERNEL);
6893 		if (unlikely(!phba->vpi_ids)) {
6894 			rc = -ENOMEM;
6895 			goto free_vpi_bmask;
6896 		}
6897 
6898 		for (i = 0; i < count; i++)
6899 			phba->vpi_ids[i] = base + i;
6900 
6901 		/* XRIs. */
6902 		count = phba->sli4_hba.max_cfg_param.max_xri;
6903 		if (count <= 0) {
6904 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6905 					"3281 Invalid provisioning of "
6906 					"xri:%d\n", count);
6907 			rc = -EINVAL;
6908 			goto free_vpi_ids;
6909 		}
6910 		base = phba->sli4_hba.max_cfg_param.xri_base;
6911 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6912 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6913 						   sizeof(unsigned long),
6914 						   GFP_KERNEL);
6915 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6916 			rc = -ENOMEM;
6917 			goto free_vpi_ids;
6918 		}
6919 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6920 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
6921 						 GFP_KERNEL);
6922 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6923 			rc = -ENOMEM;
6924 			goto free_xri_bmask;
6925 		}
6926 
6927 		for (i = 0; i < count; i++)
6928 			phba->sli4_hba.xri_ids[i] = base + i;
6929 
6930 		/* VFIs. */
6931 		count = phba->sli4_hba.max_cfg_param.max_vfi;
6932 		if (count <= 0) {
6933 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6934 					"3282 Invalid provisioning of "
6935 					"vfi:%d\n", count);
6936 			rc = -EINVAL;
6937 			goto free_xri_ids;
6938 		}
6939 		base = phba->sli4_hba.max_cfg_param.vfi_base;
6940 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6941 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6942 						   sizeof(unsigned long),
6943 						   GFP_KERNEL);
6944 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6945 			rc = -ENOMEM;
6946 			goto free_xri_ids;
6947 		}
6948 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
6949 						 GFP_KERNEL);
6950 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6951 			rc = -ENOMEM;
6952 			goto free_vfi_bmask;
6953 		}
6954 
6955 		for (i = 0; i < count; i++)
6956 			phba->sli4_hba.vfi_ids[i] = base + i;
6957 
6958 		/*
6959 		 * Mark all resources ready.  An HBA reset doesn't need
6960 		 * to reset the initialization.
6961 		 */
6962 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6963 		       LPFC_IDX_RSRC_RDY);
6964 		return 0;
6965 	}
6966 
6967  free_vfi_bmask:
6968 	kfree(phba->sli4_hba.vfi_bmask);
6969 	phba->sli4_hba.vfi_bmask = NULL;
6970  free_xri_ids:
6971 	kfree(phba->sli4_hba.xri_ids);
6972 	phba->sli4_hba.xri_ids = NULL;
6973  free_xri_bmask:
6974 	kfree(phba->sli4_hba.xri_bmask);
6975 	phba->sli4_hba.xri_bmask = NULL;
6976  free_vpi_ids:
6977 	kfree(phba->vpi_ids);
6978 	phba->vpi_ids = NULL;
6979  free_vpi_bmask:
6980 	kfree(phba->vpi_bmask);
6981 	phba->vpi_bmask = NULL;
6982  free_rpi_ids:
6983 	kfree(phba->sli4_hba.rpi_ids);
6984 	phba->sli4_hba.rpi_ids = NULL;
6985  free_rpi_bmask:
6986 	kfree(phba->sli4_hba.rpi_bmask);
6987 	phba->sli4_hba.rpi_bmask = NULL;
6988  err_exit:
6989 	return rc;
6990 }
6991 
6992 /**
6993  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
6994  * @phba: Pointer to HBA context object.
6995  *
6996  * This function allocates the number of elements for the specified
6997  * resource type.
6998  **/
6999 int
7000 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7001 {
7002 	if (phba->sli4_hba.extents_in_use) {
7003 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7004 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7005 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7006 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7007 	} else {
7008 		kfree(phba->vpi_bmask);
7009 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
7010 		kfree(phba->vpi_ids);
7011 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7012 		kfree(phba->sli4_hba.xri_bmask);
7013 		kfree(phba->sli4_hba.xri_ids);
7014 		kfree(phba->sli4_hba.vfi_bmask);
7015 		kfree(phba->sli4_hba.vfi_ids);
7016 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7017 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7018 	}
7019 
7020 	return 0;
7021 }
7022 
7023 /**
7024  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7025  * @phba: Pointer to HBA context object.
7026  * @type: The resource extent type.
7027  * @extnt_cnt: buffer to hold port extent count response
7028  * @extnt_size: buffer to hold port extent size response.
7029  *
7030  * This function calls the port to read the host allocated extents
7031  * for a particular type.
7032  **/
7033 int
7034 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7035 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
7036 {
7037 	bool emb;
7038 	int rc = 0;
7039 	uint16_t curr_blks = 0;
7040 	uint32_t req_len, emb_len;
7041 	uint32_t alloc_len, mbox_tmo;
7042 	struct list_head *blk_list_head;
7043 	struct lpfc_rsrc_blks *rsrc_blk;
7044 	LPFC_MBOXQ_t *mbox;
7045 	void *virtaddr = NULL;
7046 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7047 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7048 	union  lpfc_sli4_cfg_shdr *shdr;
7049 
7050 	switch (type) {
7051 	case LPFC_RSC_TYPE_FCOE_VPI:
7052 		blk_list_head = &phba->lpfc_vpi_blk_list;
7053 		break;
7054 	case LPFC_RSC_TYPE_FCOE_XRI:
7055 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7056 		break;
7057 	case LPFC_RSC_TYPE_FCOE_VFI:
7058 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7059 		break;
7060 	case LPFC_RSC_TYPE_FCOE_RPI:
7061 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7062 		break;
7063 	default:
7064 		return -EIO;
7065 	}
7066 
7067 	/* Count the number of extents currently allocatd for this type. */
7068 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
7069 		if (curr_blks == 0) {
7070 			/*
7071 			 * The GET_ALLOCATED mailbox does not return the size,
7072 			 * just the count.  The size should be just the size
7073 			 * stored in the current allocated block and all sizes
7074 			 * for an extent type are the same so set the return
7075 			 * value now.
7076 			 */
7077 			*extnt_size = rsrc_blk->rsrc_size;
7078 		}
7079 		curr_blks++;
7080 	}
7081 
7082 	/*
7083 	 * Calculate the size of an embedded mailbox.  The uint32_t
7084 	 * accounts for extents-specific word.
7085 	 */
7086 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7087 		sizeof(uint32_t);
7088 
7089 	/*
7090 	 * Presume the allocation and response will fit into an embedded
7091 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7092 	 */
7093 	emb = LPFC_SLI4_MBX_EMBED;
7094 	req_len = emb_len;
7095 	if (req_len > emb_len) {
7096 		req_len = curr_blks * sizeof(uint16_t) +
7097 			sizeof(union lpfc_sli4_cfg_shdr) +
7098 			sizeof(uint32_t);
7099 		emb = LPFC_SLI4_MBX_NEMBED;
7100 	}
7101 
7102 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7103 	if (!mbox)
7104 		return -ENOMEM;
7105 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7106 
7107 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7108 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7109 				     req_len, emb);
7110 	if (alloc_len < req_len) {
7111 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7112 			"2983 Allocated DMA memory size (x%x) is "
7113 			"less than the requested DMA memory "
7114 			"size (x%x)\n", alloc_len, req_len);
7115 		rc = -ENOMEM;
7116 		goto err_exit;
7117 	}
7118 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7119 	if (unlikely(rc)) {
7120 		rc = -EIO;
7121 		goto err_exit;
7122 	}
7123 
7124 	if (!phba->sli4_hba.intr_enable)
7125 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7126 	else {
7127 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7128 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7129 	}
7130 
7131 	if (unlikely(rc)) {
7132 		rc = -EIO;
7133 		goto err_exit;
7134 	}
7135 
7136 	/*
7137 	 * Figure out where the response is located.  Then get local pointers
7138 	 * to the response data.  The port does not guarantee to respond to
7139 	 * all extents counts request so update the local variable with the
7140 	 * allocated count from the port.
7141 	 */
7142 	if (emb == LPFC_SLI4_MBX_EMBED) {
7143 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7144 		shdr = &rsrc_ext->header.cfg_shdr;
7145 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7146 	} else {
7147 		virtaddr = mbox->sge_array->addr[0];
7148 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7149 		shdr = &n_rsrc->cfg_shdr;
7150 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7151 	}
7152 
7153 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7154 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7155 			"2984 Failed to read allocated resources "
7156 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7157 			type,
7158 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7159 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7160 		rc = -EIO;
7161 		goto err_exit;
7162 	}
7163  err_exit:
7164 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7165 	return rc;
7166 }
7167 
7168 /**
7169  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7170  * @phba: pointer to lpfc hba data structure.
7171  * @sgl_list: linked link of sgl buffers to post
7172  * @cnt: number of linked list buffers
7173  *
7174  * This routine walks the list of buffers that have been allocated and
7175  * repost them to the port by using SGL block post. This is needed after a
7176  * pci_function_reset/warm_start or start. It attempts to construct blocks
7177  * of buffer sgls which contains contiguous xris and uses the non-embedded
7178  * SGL block post mailbox commands to post them to the port. For single
7179  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7180  * mailbox command for posting.
7181  *
7182  * Returns: 0 = success, non-zero failure.
7183  **/
7184 static int
7185 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7186 			  struct list_head *sgl_list, int cnt)
7187 {
7188 	struct lpfc_sglq *sglq_entry = NULL;
7189 	struct lpfc_sglq *sglq_entry_next = NULL;
7190 	struct lpfc_sglq *sglq_entry_first = NULL;
7191 	int status, total_cnt;
7192 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7193 	int last_xritag = NO_XRI;
7194 	LIST_HEAD(prep_sgl_list);
7195 	LIST_HEAD(blck_sgl_list);
7196 	LIST_HEAD(allc_sgl_list);
7197 	LIST_HEAD(post_sgl_list);
7198 	LIST_HEAD(free_sgl_list);
7199 
7200 	spin_lock_irq(&phba->hbalock);
7201 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7202 	list_splice_init(sgl_list, &allc_sgl_list);
7203 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7204 	spin_unlock_irq(&phba->hbalock);
7205 
7206 	total_cnt = cnt;
7207 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7208 				 &allc_sgl_list, list) {
7209 		list_del_init(&sglq_entry->list);
7210 		block_cnt++;
7211 		if ((last_xritag != NO_XRI) &&
7212 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7213 			/* a hole in xri block, form a sgl posting block */
7214 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7215 			post_cnt = block_cnt - 1;
7216 			/* prepare list for next posting block */
7217 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7218 			block_cnt = 1;
7219 		} else {
7220 			/* prepare list for next posting block */
7221 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7222 			/* enough sgls for non-embed sgl mbox command */
7223 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7224 				list_splice_init(&prep_sgl_list,
7225 						 &blck_sgl_list);
7226 				post_cnt = block_cnt;
7227 				block_cnt = 0;
7228 			}
7229 		}
7230 		num_posted++;
7231 
7232 		/* keep track of last sgl's xritag */
7233 		last_xritag = sglq_entry->sli4_xritag;
7234 
7235 		/* end of repost sgl list condition for buffers */
7236 		if (num_posted == total_cnt) {
7237 			if (post_cnt == 0) {
7238 				list_splice_init(&prep_sgl_list,
7239 						 &blck_sgl_list);
7240 				post_cnt = block_cnt;
7241 			} else if (block_cnt == 1) {
7242 				status = lpfc_sli4_post_sgl(phba,
7243 						sglq_entry->phys, 0,
7244 						sglq_entry->sli4_xritag);
7245 				if (!status) {
7246 					/* successful, put sgl to posted list */
7247 					list_add_tail(&sglq_entry->list,
7248 						      &post_sgl_list);
7249 				} else {
7250 					/* Failure, put sgl to free list */
7251 					lpfc_printf_log(phba, KERN_WARNING,
7252 						LOG_SLI,
7253 						"3159 Failed to post "
7254 						"sgl, xritag:x%x\n",
7255 						sglq_entry->sli4_xritag);
7256 					list_add_tail(&sglq_entry->list,
7257 						      &free_sgl_list);
7258 					total_cnt--;
7259 				}
7260 			}
7261 		}
7262 
7263 		/* continue until a nembed page worth of sgls */
7264 		if (post_cnt == 0)
7265 			continue;
7266 
7267 		/* post the buffer list sgls as a block */
7268 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7269 						 post_cnt);
7270 
7271 		if (!status) {
7272 			/* success, put sgl list to posted sgl list */
7273 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7274 		} else {
7275 			/* Failure, put sgl list to free sgl list */
7276 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7277 							    struct lpfc_sglq,
7278 							    list);
7279 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7280 					"3160 Failed to post sgl-list, "
7281 					"xritag:x%x-x%x\n",
7282 					sglq_entry_first->sli4_xritag,
7283 					(sglq_entry_first->sli4_xritag +
7284 					 post_cnt - 1));
7285 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7286 			total_cnt -= post_cnt;
7287 		}
7288 
7289 		/* don't reset xirtag due to hole in xri block */
7290 		if (block_cnt == 0)
7291 			last_xritag = NO_XRI;
7292 
7293 		/* reset sgl post count for next round of posting */
7294 		post_cnt = 0;
7295 	}
7296 
7297 	/* free the sgls failed to post */
7298 	lpfc_free_sgl_list(phba, &free_sgl_list);
7299 
7300 	/* push sgls posted to the available list */
7301 	if (!list_empty(&post_sgl_list)) {
7302 		spin_lock_irq(&phba->hbalock);
7303 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7304 		list_splice_init(&post_sgl_list, sgl_list);
7305 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7306 		spin_unlock_irq(&phba->hbalock);
7307 	} else {
7308 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7309 				"3161 Failure to post sgl to port.\n");
7310 		return -EIO;
7311 	}
7312 
7313 	/* return the number of XRIs actually posted */
7314 	return total_cnt;
7315 }
7316 
7317 /**
7318  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7319  * @phba: pointer to lpfc hba data structure.
7320  *
7321  * This routine walks the list of nvme buffers that have been allocated and
7322  * repost them to the port by using SGL block post. This is needed after a
7323  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7324  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7325  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7326  *
7327  * Returns: 0 = success, non-zero failure.
7328  **/
7329 static int
7330 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7331 {
7332 	LIST_HEAD(post_nblist);
7333 	int num_posted, rc = 0;
7334 
7335 	/* get all NVME buffers need to repost to a local list */
7336 	lpfc_io_buf_flush(phba, &post_nblist);
7337 
7338 	/* post the list of nvme buffer sgls to port if available */
7339 	if (!list_empty(&post_nblist)) {
7340 		num_posted = lpfc_sli4_post_io_sgl_list(
7341 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7342 		/* failed to post any nvme buffer, return error */
7343 		if (num_posted == 0)
7344 			rc = -EIO;
7345 	}
7346 	return rc;
7347 }
7348 
7349 static void
7350 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7351 {
7352 	uint32_t len;
7353 
7354 	len = sizeof(struct lpfc_mbx_set_host_data) -
7355 		sizeof(struct lpfc_sli4_cfg_mhdr);
7356 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7357 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7358 			 LPFC_SLI4_MBX_EMBED);
7359 
7360 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7361 	mbox->u.mqe.un.set_host_data.param_len =
7362 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7363 	snprintf(mbox->u.mqe.un.set_host_data.data,
7364 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7365 		 "Linux %s v"LPFC_DRIVER_VERSION,
7366 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7367 }
7368 
7369 int
7370 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7371 		    struct lpfc_queue *drq, int count, int idx)
7372 {
7373 	int rc, i;
7374 	struct lpfc_rqe hrqe;
7375 	struct lpfc_rqe drqe;
7376 	struct lpfc_rqb *rqbp;
7377 	unsigned long flags;
7378 	struct rqb_dmabuf *rqb_buffer;
7379 	LIST_HEAD(rqb_buf_list);
7380 
7381 	rqbp = hrq->rqbp;
7382 	for (i = 0; i < count; i++) {
7383 		spin_lock_irqsave(&phba->hbalock, flags);
7384 		/* IF RQ is already full, don't bother */
7385 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7386 			spin_unlock_irqrestore(&phba->hbalock, flags);
7387 			break;
7388 		}
7389 		spin_unlock_irqrestore(&phba->hbalock, flags);
7390 
7391 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7392 		if (!rqb_buffer)
7393 			break;
7394 		rqb_buffer->hrq = hrq;
7395 		rqb_buffer->drq = drq;
7396 		rqb_buffer->idx = idx;
7397 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7398 	}
7399 
7400 	spin_lock_irqsave(&phba->hbalock, flags);
7401 	while (!list_empty(&rqb_buf_list)) {
7402 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7403 				 hbuf.list);
7404 
7405 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7406 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7407 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7408 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7409 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7410 		if (rc < 0) {
7411 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7412 					"6421 Cannot post to HRQ %d: %x %x %x "
7413 					"DRQ %x %x\n",
7414 					hrq->queue_id,
7415 					hrq->host_index,
7416 					hrq->hba_index,
7417 					hrq->entry_count,
7418 					drq->host_index,
7419 					drq->hba_index);
7420 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7421 		} else {
7422 			list_add_tail(&rqb_buffer->hbuf.list,
7423 				      &rqbp->rqb_buffer_list);
7424 			rqbp->buffer_count++;
7425 		}
7426 	}
7427 	spin_unlock_irqrestore(&phba->hbalock, flags);
7428 	return 1;
7429 }
7430 
7431 /**
7432  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7433  * @phba: pointer to lpfc hba data structure.
7434  *
7435  * This routine initializes the per-cq idle_stat to dynamically dictate
7436  * polling decisions.
7437  *
7438  * Return codes:
7439  *   None
7440  **/
7441 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
7442 {
7443 	int i;
7444 	struct lpfc_sli4_hdw_queue *hdwq;
7445 	struct lpfc_queue *cq;
7446 	struct lpfc_idle_stat *idle_stat;
7447 	u64 wall;
7448 
7449 	for_each_present_cpu(i) {
7450 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
7451 		cq = hdwq->io_cq;
7452 
7453 		/* Skip if we've already handled this cq's primary CPU */
7454 		if (cq->chann != i)
7455 			continue;
7456 
7457 		idle_stat = &phba->sli4_hba.idle_stat[i];
7458 
7459 		idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
7460 		idle_stat->prev_wall = wall;
7461 
7462 		if (phba->nvmet_support)
7463 			cq->poll_mode = LPFC_QUEUE_WORK;
7464 		else
7465 			cq->poll_mode = LPFC_IRQ_POLL;
7466 	}
7467 
7468 	if (!phba->nvmet_support)
7469 		schedule_delayed_work(&phba->idle_stat_delay_work,
7470 				      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
7471 }
7472 
7473 static void lpfc_sli4_dip(struct lpfc_hba *phba)
7474 {
7475 	uint32_t if_type;
7476 
7477 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
7478 	if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
7479 	    if_type == LPFC_SLI_INTF_IF_TYPE_6) {
7480 		struct lpfc_register reg_data;
7481 
7482 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
7483 			       &reg_data.word0))
7484 			return;
7485 
7486 		if (bf_get(lpfc_sliport_status_dip, &reg_data))
7487 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7488 					"2904 Firmware Dump Image Present"
7489 					" on Adapter");
7490 	}
7491 }
7492 
7493 /**
7494  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
7495  * @phba: Pointer to HBA context object.
7496  *
7497  * This function is the main SLI4 device initialization PCI function. This
7498  * function is called by the HBA initialization code, HBA reset code and
7499  * HBA error attention handler code. Caller is not required to hold any
7500  * locks.
7501  **/
7502 int
7503 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
7504 {
7505 	int rc, i, cnt, len, dd;
7506 	LPFC_MBOXQ_t *mboxq;
7507 	struct lpfc_mqe *mqe;
7508 	uint8_t *vpd;
7509 	uint32_t vpd_size;
7510 	uint32_t ftr_rsp = 0;
7511 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
7512 	struct lpfc_vport *vport = phba->pport;
7513 	struct lpfc_dmabuf *mp;
7514 	struct lpfc_rqb *rqbp;
7515 
7516 	/* Perform a PCI function reset to start from clean */
7517 	rc = lpfc_pci_function_reset(phba);
7518 	if (unlikely(rc))
7519 		return -ENODEV;
7520 
7521 	/* Check the HBA Host Status Register for readyness */
7522 	rc = lpfc_sli4_post_status_check(phba);
7523 	if (unlikely(rc))
7524 		return -ENODEV;
7525 	else {
7526 		spin_lock_irq(&phba->hbalock);
7527 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
7528 		spin_unlock_irq(&phba->hbalock);
7529 	}
7530 
7531 	lpfc_sli4_dip(phba);
7532 
7533 	/*
7534 	 * Allocate a single mailbox container for initializing the
7535 	 * port.
7536 	 */
7537 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7538 	if (!mboxq)
7539 		return -ENOMEM;
7540 
7541 	/* Issue READ_REV to collect vpd and FW information. */
7542 	vpd_size = SLI4_PAGE_SIZE;
7543 	vpd = kzalloc(vpd_size, GFP_KERNEL);
7544 	if (!vpd) {
7545 		rc = -ENOMEM;
7546 		goto out_free_mbox;
7547 	}
7548 
7549 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
7550 	if (unlikely(rc)) {
7551 		kfree(vpd);
7552 		goto out_free_mbox;
7553 	}
7554 
7555 	mqe = &mboxq->u.mqe;
7556 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
7557 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
7558 		phba->hba_flag |= HBA_FCOE_MODE;
7559 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
7560 	} else {
7561 		phba->hba_flag &= ~HBA_FCOE_MODE;
7562 	}
7563 
7564 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
7565 		LPFC_DCBX_CEE_MODE)
7566 		phba->hba_flag |= HBA_FIP_SUPPORT;
7567 	else
7568 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
7569 
7570 	phba->hba_flag &= ~HBA_IOQ_FLUSH;
7571 
7572 	if (phba->sli_rev != LPFC_SLI_REV4) {
7573 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7574 			"0376 READ_REV Error. SLI Level %d "
7575 			"FCoE enabled %d\n",
7576 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
7577 		rc = -EIO;
7578 		kfree(vpd);
7579 		goto out_free_mbox;
7580 	}
7581 
7582 	/*
7583 	 * Continue initialization with default values even if driver failed
7584 	 * to read FCoE param config regions, only read parameters if the
7585 	 * board is FCoE
7586 	 */
7587 	if (phba->hba_flag & HBA_FCOE_MODE &&
7588 	    lpfc_sli4_read_fcoe_params(phba))
7589 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
7590 			"2570 Failed to read FCoE parameters\n");
7591 
7592 	/*
7593 	 * Retrieve sli4 device physical port name, failure of doing it
7594 	 * is considered as non-fatal.
7595 	 */
7596 	rc = lpfc_sli4_retrieve_pport_name(phba);
7597 	if (!rc)
7598 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7599 				"3080 Successful retrieving SLI4 device "
7600 				"physical port name: %s.\n", phba->Port);
7601 
7602 	rc = lpfc_sli4_get_ctl_attr(phba);
7603 	if (!rc)
7604 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7605 				"8351 Successful retrieving SLI4 device "
7606 				"CTL ATTR\n");
7607 
7608 	/*
7609 	 * Evaluate the read rev and vpd data. Populate the driver
7610 	 * state with the results. If this routine fails, the failure
7611 	 * is not fatal as the driver will use generic values.
7612 	 */
7613 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
7614 	if (unlikely(!rc)) {
7615 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7616 				"0377 Error %d parsing vpd. "
7617 				"Using defaults.\n", rc);
7618 		rc = 0;
7619 	}
7620 	kfree(vpd);
7621 
7622 	/* Save information as VPD data */
7623 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
7624 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
7625 
7626 	/*
7627 	 * This is because first G7 ASIC doesn't support the standard
7628 	 * 0x5a NVME cmd descriptor type/subtype
7629 	 */
7630 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7631 			LPFC_SLI_INTF_IF_TYPE_6) &&
7632 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
7633 	    (phba->vpd.rev.smRev == 0) &&
7634 	    (phba->cfg_nvme_embed_cmd == 1))
7635 		phba->cfg_nvme_embed_cmd = 0;
7636 
7637 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
7638 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
7639 					 &mqe->un.read_rev);
7640 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
7641 				       &mqe->un.read_rev);
7642 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
7643 					    &mqe->un.read_rev);
7644 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
7645 					   &mqe->un.read_rev);
7646 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
7647 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
7648 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
7649 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
7650 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
7651 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
7652 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7653 			"(%d):0380 READ_REV Status x%x "
7654 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
7655 			mboxq->vport ? mboxq->vport->vpi : 0,
7656 			bf_get(lpfc_mqe_status, mqe),
7657 			phba->vpd.rev.opFwName,
7658 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
7659 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
7660 
7661 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7662 	    LPFC_SLI_INTF_IF_TYPE_0) {
7663 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
7664 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7665 		if (rc == MBX_SUCCESS) {
7666 			phba->hba_flag |= HBA_RECOVERABLE_UE;
7667 			/* Set 1Sec interval to detect UE */
7668 			phba->eratt_poll_interval = 1;
7669 			phba->sli4_hba.ue_to_sr = bf_get(
7670 					lpfc_mbx_set_feature_UESR,
7671 					&mboxq->u.mqe.un.set_feature);
7672 			phba->sli4_hba.ue_to_rp = bf_get(
7673 					lpfc_mbx_set_feature_UERP,
7674 					&mboxq->u.mqe.un.set_feature);
7675 		}
7676 	}
7677 
7678 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
7679 		/* Enable MDS Diagnostics only if the SLI Port supports it */
7680 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
7681 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7682 		if (rc != MBX_SUCCESS)
7683 			phba->mds_diags_support = 0;
7684 	}
7685 
7686 	/*
7687 	 * Discover the port's supported feature set and match it against the
7688 	 * hosts requests.
7689 	 */
7690 	lpfc_request_features(phba, mboxq);
7691 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7692 	if (unlikely(rc)) {
7693 		rc = -EIO;
7694 		goto out_free_mbox;
7695 	}
7696 
7697 	/*
7698 	 * The port must support FCP initiator mode as this is the
7699 	 * only mode running in the host.
7700 	 */
7701 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
7702 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7703 				"0378 No support for fcpi mode.\n");
7704 		ftr_rsp++;
7705 	}
7706 
7707 	/* Performance Hints are ONLY for FCoE */
7708 	if (phba->hba_flag & HBA_FCOE_MODE) {
7709 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
7710 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
7711 		else
7712 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
7713 	}
7714 
7715 	/*
7716 	 * If the port cannot support the host's requested features
7717 	 * then turn off the global config parameters to disable the
7718 	 * feature in the driver.  This is not a fatal error.
7719 	 */
7720 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
7721 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
7722 			phba->cfg_enable_bg = 0;
7723 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
7724 			ftr_rsp++;
7725 		}
7726 	}
7727 
7728 	if (phba->max_vpi && phba->cfg_enable_npiv &&
7729 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7730 		ftr_rsp++;
7731 
7732 	if (ftr_rsp) {
7733 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7734 				"0379 Feature Mismatch Data: x%08x %08x "
7735 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
7736 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
7737 				phba->cfg_enable_npiv, phba->max_vpi);
7738 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
7739 			phba->cfg_enable_bg = 0;
7740 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7741 			phba->cfg_enable_npiv = 0;
7742 	}
7743 
7744 	/* These SLI3 features are assumed in SLI4 */
7745 	spin_lock_irq(&phba->hbalock);
7746 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
7747 	spin_unlock_irq(&phba->hbalock);
7748 
7749 	/* Always try to enable dual dump feature if we can */
7750 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
7751 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7752 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
7753 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
7754 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7755 				"6448 Dual Dump is enabled\n");
7756 	else
7757 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
7758 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
7759 				"rc:x%x dd:x%x\n",
7760 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7761 				lpfc_sli_config_mbox_subsys_get(
7762 					phba, mboxq),
7763 				lpfc_sli_config_mbox_opcode_get(
7764 					phba, mboxq),
7765 				rc, dd);
7766 	/*
7767 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
7768 	 * calls depends on these resources to complete port setup.
7769 	 */
7770 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
7771 	if (rc) {
7772 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7773 				"2920 Failed to alloc Resource IDs "
7774 				"rc = x%x\n", rc);
7775 		goto out_free_mbox;
7776 	}
7777 
7778 	lpfc_set_host_data(phba, mboxq);
7779 
7780 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7781 	if (rc) {
7782 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7783 				"2134 Failed to set host os driver version %x",
7784 				rc);
7785 	}
7786 
7787 	/* Read the port's service parameters. */
7788 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
7789 	if (rc) {
7790 		phba->link_state = LPFC_HBA_ERROR;
7791 		rc = -ENOMEM;
7792 		goto out_free_mbox;
7793 	}
7794 
7795 	mboxq->vport = vport;
7796 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7797 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
7798 	if (rc == MBX_SUCCESS) {
7799 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
7800 		rc = 0;
7801 	}
7802 
7803 	/*
7804 	 * This memory was allocated by the lpfc_read_sparam routine. Release
7805 	 * it to the mbuf pool.
7806 	 */
7807 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
7808 	kfree(mp);
7809 	mboxq->ctx_buf = NULL;
7810 	if (unlikely(rc)) {
7811 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7812 				"0382 READ_SPARAM command failed "
7813 				"status %d, mbxStatus x%x\n",
7814 				rc, bf_get(lpfc_mqe_status, mqe));
7815 		phba->link_state = LPFC_HBA_ERROR;
7816 		rc = -EIO;
7817 		goto out_free_mbox;
7818 	}
7819 
7820 	lpfc_update_vport_wwn(vport);
7821 
7822 	/* Update the fc_host data structures with new wwn. */
7823 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
7824 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
7825 
7826 	/* Create all the SLI4 queues */
7827 	rc = lpfc_sli4_queue_create(phba);
7828 	if (rc) {
7829 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7830 				"3089 Failed to allocate queues\n");
7831 		rc = -ENODEV;
7832 		goto out_free_mbox;
7833 	}
7834 	/* Set up all the queues to the device */
7835 	rc = lpfc_sli4_queue_setup(phba);
7836 	if (unlikely(rc)) {
7837 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7838 				"0381 Error %d during queue setup.\n ", rc);
7839 		goto out_stop_timers;
7840 	}
7841 	/* Initialize the driver internal SLI layer lists. */
7842 	lpfc_sli4_setup(phba);
7843 	lpfc_sli4_queue_init(phba);
7844 
7845 	/* update host els xri-sgl sizes and mappings */
7846 	rc = lpfc_sli4_els_sgl_update(phba);
7847 	if (unlikely(rc)) {
7848 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7849 				"1400 Failed to update xri-sgl size and "
7850 				"mapping: %d\n", rc);
7851 		goto out_destroy_queue;
7852 	}
7853 
7854 	/* register the els sgl pool to the port */
7855 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
7856 				       phba->sli4_hba.els_xri_cnt);
7857 	if (unlikely(rc < 0)) {
7858 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7859 				"0582 Error %d during els sgl post "
7860 				"operation\n", rc);
7861 		rc = -ENODEV;
7862 		goto out_destroy_queue;
7863 	}
7864 	phba->sli4_hba.els_xri_cnt = rc;
7865 
7866 	if (phba->nvmet_support) {
7867 		/* update host nvmet xri-sgl sizes and mappings */
7868 		rc = lpfc_sli4_nvmet_sgl_update(phba);
7869 		if (unlikely(rc)) {
7870 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7871 					"6308 Failed to update nvmet-sgl size "
7872 					"and mapping: %d\n", rc);
7873 			goto out_destroy_queue;
7874 		}
7875 
7876 		/* register the nvmet sgl pool to the port */
7877 		rc = lpfc_sli4_repost_sgl_list(
7878 			phba,
7879 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
7880 			phba->sli4_hba.nvmet_xri_cnt);
7881 		if (unlikely(rc < 0)) {
7882 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7883 					"3117 Error %d during nvmet "
7884 					"sgl post\n", rc);
7885 			rc = -ENODEV;
7886 			goto out_destroy_queue;
7887 		}
7888 		phba->sli4_hba.nvmet_xri_cnt = rc;
7889 
7890 		/* We allocate an iocbq for every receive context SGL.
7891 		 * The additional allocation is for abort and ls handling.
7892 		 */
7893 		cnt = phba->sli4_hba.nvmet_xri_cnt +
7894 			phba->sli4_hba.max_cfg_param.max_xri;
7895 	} else {
7896 		/* update host common xri-sgl sizes and mappings */
7897 		rc = lpfc_sli4_io_sgl_update(phba);
7898 		if (unlikely(rc)) {
7899 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7900 					"6082 Failed to update nvme-sgl size "
7901 					"and mapping: %d\n", rc);
7902 			goto out_destroy_queue;
7903 		}
7904 
7905 		/* register the allocated common sgl pool to the port */
7906 		rc = lpfc_sli4_repost_io_sgl_list(phba);
7907 		if (unlikely(rc)) {
7908 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7909 					"6116 Error %d during nvme sgl post "
7910 					"operation\n", rc);
7911 			/* Some NVME buffers were moved to abort nvme list */
7912 			/* A pci function reset will repost them */
7913 			rc = -ENODEV;
7914 			goto out_destroy_queue;
7915 		}
7916 		/* Each lpfc_io_buf job structure has an iocbq element.
7917 		 * This cnt provides for abort, els, ct and ls requests.
7918 		 */
7919 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
7920 	}
7921 
7922 	if (!phba->sli.iocbq_lookup) {
7923 		/* Initialize and populate the iocb list per host */
7924 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7925 				"2821 initialize iocb list with %d entries\n",
7926 				cnt);
7927 		rc = lpfc_init_iocb_list(phba, cnt);
7928 		if (rc) {
7929 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7930 					"1413 Failed to init iocb list.\n");
7931 			goto out_destroy_queue;
7932 		}
7933 	}
7934 
7935 	if (phba->nvmet_support)
7936 		lpfc_nvmet_create_targetport(phba);
7937 
7938 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
7939 		/* Post initial buffers to all RQs created */
7940 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
7941 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
7942 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
7943 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
7944 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
7945 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
7946 			rqbp->buffer_count = 0;
7947 
7948 			lpfc_post_rq_buffer(
7949 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
7950 				phba->sli4_hba.nvmet_mrq_data[i],
7951 				phba->cfg_nvmet_mrq_post, i);
7952 		}
7953 	}
7954 
7955 	/* Post the rpi header region to the device. */
7956 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
7957 	if (unlikely(rc)) {
7958 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7959 				"0393 Error %d during rpi post operation\n",
7960 				rc);
7961 		rc = -ENODEV;
7962 		goto out_destroy_queue;
7963 	}
7964 	lpfc_sli4_node_prep(phba);
7965 
7966 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
7967 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
7968 			/*
7969 			 * The FC Port needs to register FCFI (index 0)
7970 			 */
7971 			lpfc_reg_fcfi(phba, mboxq);
7972 			mboxq->vport = phba->pport;
7973 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7974 			if (rc != MBX_SUCCESS)
7975 				goto out_unset_queue;
7976 			rc = 0;
7977 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
7978 						&mboxq->u.mqe.un.reg_fcfi);
7979 		} else {
7980 			/* We are a NVME Target mode with MRQ > 1 */
7981 
7982 			/* First register the FCFI */
7983 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
7984 			mboxq->vport = phba->pport;
7985 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7986 			if (rc != MBX_SUCCESS)
7987 				goto out_unset_queue;
7988 			rc = 0;
7989 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
7990 						&mboxq->u.mqe.un.reg_fcfi_mrq);
7991 
7992 			/* Next register the MRQs */
7993 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
7994 			mboxq->vport = phba->pport;
7995 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7996 			if (rc != MBX_SUCCESS)
7997 				goto out_unset_queue;
7998 			rc = 0;
7999 		}
8000 		/* Check if the port is configured to be disabled */
8001 		lpfc_sli_read_link_ste(phba);
8002 	}
8003 
8004 	/* Don't post more new bufs if repost already recovered
8005 	 * the nvme sgls.
8006 	 */
8007 	if (phba->nvmet_support == 0) {
8008 		if (phba->sli4_hba.io_xri_cnt == 0) {
8009 			len = lpfc_new_io_buf(
8010 					      phba, phba->sli4_hba.io_xri_max);
8011 			if (len == 0) {
8012 				rc = -ENOMEM;
8013 				goto out_unset_queue;
8014 			}
8015 
8016 			if (phba->cfg_xri_rebalancing)
8017 				lpfc_create_multixri_pools(phba);
8018 		}
8019 	} else {
8020 		phba->cfg_xri_rebalancing = 0;
8021 	}
8022 
8023 	/* Allow asynchronous mailbox command to go through */
8024 	spin_lock_irq(&phba->hbalock);
8025 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8026 	spin_unlock_irq(&phba->hbalock);
8027 
8028 	/* Post receive buffers to the device */
8029 	lpfc_sli4_rb_setup(phba);
8030 
8031 	/* Reset HBA FCF states after HBA reset */
8032 	phba->fcf.fcf_flag = 0;
8033 	phba->fcf.current_rec.flag = 0;
8034 
8035 	/* Start the ELS watchdog timer */
8036 	mod_timer(&vport->els_tmofunc,
8037 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
8038 
8039 	/* Start heart beat timer */
8040 	mod_timer(&phba->hb_tmofunc,
8041 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
8042 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
8043 	phba->last_completion_time = jiffies;
8044 
8045 	/* start eq_delay heartbeat */
8046 	if (phba->cfg_auto_imax)
8047 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
8048 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
8049 
8050 	/* start per phba idle_stat_delay heartbeat */
8051 	lpfc_init_idle_stat_hb(phba);
8052 
8053 	/* Start error attention (ERATT) polling timer */
8054 	mod_timer(&phba->eratt_poll,
8055 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
8056 
8057 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
8058 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
8059 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
8060 		if (!rc) {
8061 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8062 					"2829 This device supports "
8063 					"Advanced Error Reporting (AER)\n");
8064 			spin_lock_irq(&phba->hbalock);
8065 			phba->hba_flag |= HBA_AER_ENABLED;
8066 			spin_unlock_irq(&phba->hbalock);
8067 		} else {
8068 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8069 					"2830 This device does not support "
8070 					"Advanced Error Reporting (AER)\n");
8071 			phba->cfg_aer_support = 0;
8072 		}
8073 		rc = 0;
8074 	}
8075 
8076 	/*
8077 	 * The port is ready, set the host's link state to LINK_DOWN
8078 	 * in preparation for link interrupts.
8079 	 */
8080 	spin_lock_irq(&phba->hbalock);
8081 	phba->link_state = LPFC_LINK_DOWN;
8082 
8083 	/* Check if physical ports are trunked */
8084 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
8085 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
8086 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
8087 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
8088 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
8089 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
8090 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
8091 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
8092 	spin_unlock_irq(&phba->hbalock);
8093 
8094 	/* Arm the CQs and then EQs on device */
8095 	lpfc_sli4_arm_cqeq_intr(phba);
8096 
8097 	/* Indicate device interrupt mode */
8098 	phba->sli4_hba.intr_enable = 1;
8099 
8100 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
8101 	    (phba->hba_flag & LINK_DISABLED)) {
8102 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8103 				"3103 Adapter Link is disabled.\n");
8104 		lpfc_down_link(phba, mboxq);
8105 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8106 		if (rc != MBX_SUCCESS) {
8107 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8108 					"3104 Adapter failed to issue "
8109 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
8110 			goto out_io_buff_free;
8111 		}
8112 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
8113 		/* don't perform init_link on SLI4 FC port loopback test */
8114 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
8115 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
8116 			if (rc)
8117 				goto out_io_buff_free;
8118 		}
8119 	}
8120 	mempool_free(mboxq, phba->mbox_mem_pool);
8121 	return rc;
8122 out_io_buff_free:
8123 	/* Free allocated IO Buffers */
8124 	lpfc_io_free(phba);
8125 out_unset_queue:
8126 	/* Unset all the queues set up in this routine when error out */
8127 	lpfc_sli4_queue_unset(phba);
8128 out_destroy_queue:
8129 	lpfc_free_iocb_list(phba);
8130 	lpfc_sli4_queue_destroy(phba);
8131 out_stop_timers:
8132 	lpfc_stop_hba_timers(phba);
8133 out_free_mbox:
8134 	mempool_free(mboxq, phba->mbox_mem_pool);
8135 	return rc;
8136 }
8137 
8138 /**
8139  * lpfc_mbox_timeout - Timeout call back function for mbox timer
8140  * @t: Context to fetch pointer to hba structure from.
8141  *
8142  * This is the callback function for mailbox timer. The mailbox
8143  * timer is armed when a new mailbox command is issued and the timer
8144  * is deleted when the mailbox complete. The function is called by
8145  * the kernel timer code when a mailbox does not complete within
8146  * expected time. This function wakes up the worker thread to
8147  * process the mailbox timeout and returns. All the processing is
8148  * done by the worker thread function lpfc_mbox_timeout_handler.
8149  **/
8150 void
8151 lpfc_mbox_timeout(struct timer_list *t)
8152 {
8153 	struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
8154 	unsigned long iflag;
8155 	uint32_t tmo_posted;
8156 
8157 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
8158 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
8159 	if (!tmo_posted)
8160 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
8161 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
8162 
8163 	if (!tmo_posted)
8164 		lpfc_worker_wake_up(phba);
8165 	return;
8166 }
8167 
8168 /**
8169  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
8170  *                                    are pending
8171  * @phba: Pointer to HBA context object.
8172  *
8173  * This function checks if any mailbox completions are present on the mailbox
8174  * completion queue.
8175  **/
8176 static bool
8177 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
8178 {
8179 
8180 	uint32_t idx;
8181 	struct lpfc_queue *mcq;
8182 	struct lpfc_mcqe *mcqe;
8183 	bool pending_completions = false;
8184 	uint8_t	qe_valid;
8185 
8186 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8187 		return false;
8188 
8189 	/* Check for completions on mailbox completion queue */
8190 
8191 	mcq = phba->sli4_hba.mbx_cq;
8192 	idx = mcq->hba_index;
8193 	qe_valid = mcq->qe_valid;
8194 	while (bf_get_le32(lpfc_cqe_valid,
8195 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
8196 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
8197 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
8198 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
8199 			pending_completions = true;
8200 			break;
8201 		}
8202 		idx = (idx + 1) % mcq->entry_count;
8203 		if (mcq->hba_index == idx)
8204 			break;
8205 
8206 		/* if the index wrapped around, toggle the valid bit */
8207 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
8208 			qe_valid = (qe_valid) ? 0 : 1;
8209 	}
8210 	return pending_completions;
8211 
8212 }
8213 
8214 /**
8215  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
8216  *					      that were missed.
8217  * @phba: Pointer to HBA context object.
8218  *
8219  * For sli4, it is possible to miss an interrupt. As such mbox completions
8220  * maybe missed causing erroneous mailbox timeouts to occur. This function
8221  * checks to see if mbox completions are on the mailbox completion queue
8222  * and will process all the completions associated with the eq for the
8223  * mailbox completion queue.
8224  **/
8225 static bool
8226 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
8227 {
8228 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
8229 	uint32_t eqidx;
8230 	struct lpfc_queue *fpeq = NULL;
8231 	struct lpfc_queue *eq;
8232 	bool mbox_pending;
8233 
8234 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8235 		return false;
8236 
8237 	/* Find the EQ associated with the mbox CQ */
8238 	if (sli4_hba->hdwq) {
8239 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
8240 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
8241 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
8242 				fpeq = eq;
8243 				break;
8244 			}
8245 		}
8246 	}
8247 	if (!fpeq)
8248 		return false;
8249 
8250 	/* Turn off interrupts from this EQ */
8251 
8252 	sli4_hba->sli4_eq_clr_intr(fpeq);
8253 
8254 	/* Check to see if a mbox completion is pending */
8255 
8256 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
8257 
8258 	/*
8259 	 * If a mbox completion is pending, process all the events on EQ
8260 	 * associated with the mbox completion queue (this could include
8261 	 * mailbox commands, async events, els commands, receive queue data
8262 	 * and fcp commands)
8263 	 */
8264 
8265 	if (mbox_pending)
8266 		/* process and rearm the EQ */
8267 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
8268 	else
8269 		/* Always clear and re-arm the EQ */
8270 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
8271 
8272 	return mbox_pending;
8273 
8274 }
8275 
8276 /**
8277  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
8278  * @phba: Pointer to HBA context object.
8279  *
8280  * This function is called from worker thread when a mailbox command times out.
8281  * The caller is not required to hold any locks. This function will reset the
8282  * HBA and recover all the pending commands.
8283  **/
8284 void
8285 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
8286 {
8287 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
8288 	MAILBOX_t *mb = NULL;
8289 
8290 	struct lpfc_sli *psli = &phba->sli;
8291 
8292 	/* If the mailbox completed, process the completion */
8293 	lpfc_sli4_process_missed_mbox_completions(phba);
8294 
8295 	if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
8296 		return;
8297 
8298 	if (pmbox != NULL)
8299 		mb = &pmbox->u.mb;
8300 	/* Check the pmbox pointer first.  There is a race condition
8301 	 * between the mbox timeout handler getting executed in the
8302 	 * worklist and the mailbox actually completing. When this
8303 	 * race condition occurs, the mbox_active will be NULL.
8304 	 */
8305 	spin_lock_irq(&phba->hbalock);
8306 	if (pmbox == NULL) {
8307 		lpfc_printf_log(phba, KERN_WARNING,
8308 				LOG_MBOX | LOG_SLI,
8309 				"0353 Active Mailbox cleared - mailbox timeout "
8310 				"exiting\n");
8311 		spin_unlock_irq(&phba->hbalock);
8312 		return;
8313 	}
8314 
8315 	/* Mbox cmd <mbxCommand> timeout */
8316 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8317 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
8318 			mb->mbxCommand,
8319 			phba->pport->port_state,
8320 			phba->sli.sli_flag,
8321 			phba->sli.mbox_active);
8322 	spin_unlock_irq(&phba->hbalock);
8323 
8324 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
8325 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
8326 	 * it to fail all outstanding SCSI IO.
8327 	 */
8328 	spin_lock_irq(&phba->pport->work_port_lock);
8329 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
8330 	spin_unlock_irq(&phba->pport->work_port_lock);
8331 	spin_lock_irq(&phba->hbalock);
8332 	phba->link_state = LPFC_LINK_UNKNOWN;
8333 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
8334 	spin_unlock_irq(&phba->hbalock);
8335 
8336 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8337 			"0345 Resetting board due to mailbox timeout\n");
8338 
8339 	/* Reset the HBA device */
8340 	lpfc_reset_hba(phba);
8341 }
8342 
8343 /**
8344  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
8345  * @phba: Pointer to HBA context object.
8346  * @pmbox: Pointer to mailbox object.
8347  * @flag: Flag indicating how the mailbox need to be processed.
8348  *
8349  * This function is called by discovery code and HBA management code
8350  * to submit a mailbox command to firmware with SLI-3 interface spec. This
8351  * function gets the hbalock to protect the data structures.
8352  * The mailbox command can be submitted in polling mode, in which case
8353  * this function will wait in a polling loop for the completion of the
8354  * mailbox.
8355  * If the mailbox is submitted in no_wait mode (not polling) the
8356  * function will submit the command and returns immediately without waiting
8357  * for the mailbox completion. The no_wait is supported only when HBA
8358  * is in SLI2/SLI3 mode - interrupts are enabled.
8359  * The SLI interface allows only one mailbox pending at a time. If the
8360  * mailbox is issued in polling mode and there is already a mailbox
8361  * pending, then the function will return an error. If the mailbox is issued
8362  * in NO_WAIT mode and there is a mailbox pending already, the function
8363  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
8364  * The sli layer owns the mailbox object until the completion of mailbox
8365  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
8366  * return codes the caller owns the mailbox command after the return of
8367  * the function.
8368  **/
8369 static int
8370 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
8371 		       uint32_t flag)
8372 {
8373 	MAILBOX_t *mbx;
8374 	struct lpfc_sli *psli = &phba->sli;
8375 	uint32_t status, evtctr;
8376 	uint32_t ha_copy, hc_copy;
8377 	int i;
8378 	unsigned long timeout;
8379 	unsigned long drvr_flag = 0;
8380 	uint32_t word0, ldata;
8381 	void __iomem *to_slim;
8382 	int processing_queue = 0;
8383 
8384 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
8385 	if (!pmbox) {
8386 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8387 		/* processing mbox queue from intr_handler */
8388 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8389 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8390 			return MBX_SUCCESS;
8391 		}
8392 		processing_queue = 1;
8393 		pmbox = lpfc_mbox_get(phba);
8394 		if (!pmbox) {
8395 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8396 			return MBX_SUCCESS;
8397 		}
8398 	}
8399 
8400 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
8401 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
8402 		if(!pmbox->vport) {
8403 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8404 			lpfc_printf_log(phba, KERN_ERR,
8405 					LOG_MBOX | LOG_VPORT,
8406 					"1806 Mbox x%x failed. No vport\n",
8407 					pmbox->u.mb.mbxCommand);
8408 			dump_stack();
8409 			goto out_not_finished;
8410 		}
8411 	}
8412 
8413 	/* If the PCI channel is in offline state, do not post mbox. */
8414 	if (unlikely(pci_channel_offline(phba->pcidev))) {
8415 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8416 		goto out_not_finished;
8417 	}
8418 
8419 	/* If HBA has a deferred error attention, fail the iocb. */
8420 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
8421 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8422 		goto out_not_finished;
8423 	}
8424 
8425 	psli = &phba->sli;
8426 
8427 	mbx = &pmbox->u.mb;
8428 	status = MBX_SUCCESS;
8429 
8430 	if (phba->link_state == LPFC_HBA_ERROR) {
8431 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8432 
8433 		/* Mbox command <mbxCommand> cannot issue */
8434 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8435 				"(%d):0311 Mailbox command x%x cannot "
8436 				"issue Data: x%x x%x\n",
8437 				pmbox->vport ? pmbox->vport->vpi : 0,
8438 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8439 		goto out_not_finished;
8440 	}
8441 
8442 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
8443 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
8444 			!(hc_copy & HC_MBINT_ENA)) {
8445 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8446 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8447 				"(%d):2528 Mailbox command x%x cannot "
8448 				"issue Data: x%x x%x\n",
8449 				pmbox->vport ? pmbox->vport->vpi : 0,
8450 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8451 			goto out_not_finished;
8452 		}
8453 	}
8454 
8455 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8456 		/* Polling for a mbox command when another one is already active
8457 		 * is not allowed in SLI. Also, the driver must have established
8458 		 * SLI2 mode to queue and process multiple mbox commands.
8459 		 */
8460 
8461 		if (flag & MBX_POLL) {
8462 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8463 
8464 			/* Mbox command <mbxCommand> cannot issue */
8465 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8466 					"(%d):2529 Mailbox command x%x "
8467 					"cannot issue Data: x%x x%x\n",
8468 					pmbox->vport ? pmbox->vport->vpi : 0,
8469 					pmbox->u.mb.mbxCommand,
8470 					psli->sli_flag, flag);
8471 			goto out_not_finished;
8472 		}
8473 
8474 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
8475 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8476 			/* Mbox command <mbxCommand> cannot issue */
8477 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8478 					"(%d):2530 Mailbox command x%x "
8479 					"cannot issue Data: x%x x%x\n",
8480 					pmbox->vport ? pmbox->vport->vpi : 0,
8481 					pmbox->u.mb.mbxCommand,
8482 					psli->sli_flag, flag);
8483 			goto out_not_finished;
8484 		}
8485 
8486 		/* Another mailbox command is still being processed, queue this
8487 		 * command to be processed later.
8488 		 */
8489 		lpfc_mbox_put(phba, pmbox);
8490 
8491 		/* Mbox cmd issue - BUSY */
8492 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8493 				"(%d):0308 Mbox cmd issue - BUSY Data: "
8494 				"x%x x%x x%x x%x\n",
8495 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
8496 				mbx->mbxCommand,
8497 				phba->pport ? phba->pport->port_state : 0xff,
8498 				psli->sli_flag, flag);
8499 
8500 		psli->slistat.mbox_busy++;
8501 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8502 
8503 		if (pmbox->vport) {
8504 			lpfc_debugfs_disc_trc(pmbox->vport,
8505 				LPFC_DISC_TRC_MBOX_VPORT,
8506 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
8507 				(uint32_t)mbx->mbxCommand,
8508 				mbx->un.varWords[0], mbx->un.varWords[1]);
8509 		}
8510 		else {
8511 			lpfc_debugfs_disc_trc(phba->pport,
8512 				LPFC_DISC_TRC_MBOX,
8513 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
8514 				(uint32_t)mbx->mbxCommand,
8515 				mbx->un.varWords[0], mbx->un.varWords[1]);
8516 		}
8517 
8518 		return MBX_BUSY;
8519 	}
8520 
8521 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8522 
8523 	/* If we are not polling, we MUST be in SLI2 mode */
8524 	if (flag != MBX_POLL) {
8525 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
8526 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
8527 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8528 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8529 			/* Mbox command <mbxCommand> cannot issue */
8530 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8531 					"(%d):2531 Mailbox command x%x "
8532 					"cannot issue Data: x%x x%x\n",
8533 					pmbox->vport ? pmbox->vport->vpi : 0,
8534 					pmbox->u.mb.mbxCommand,
8535 					psli->sli_flag, flag);
8536 			goto out_not_finished;
8537 		}
8538 		/* timeout active mbox command */
8539 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8540 					   1000);
8541 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
8542 	}
8543 
8544 	/* Mailbox cmd <cmd> issue */
8545 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8546 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
8547 			"x%x\n",
8548 			pmbox->vport ? pmbox->vport->vpi : 0,
8549 			mbx->mbxCommand,
8550 			phba->pport ? phba->pport->port_state : 0xff,
8551 			psli->sli_flag, flag);
8552 
8553 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
8554 		if (pmbox->vport) {
8555 			lpfc_debugfs_disc_trc(pmbox->vport,
8556 				LPFC_DISC_TRC_MBOX_VPORT,
8557 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
8558 				(uint32_t)mbx->mbxCommand,
8559 				mbx->un.varWords[0], mbx->un.varWords[1]);
8560 		}
8561 		else {
8562 			lpfc_debugfs_disc_trc(phba->pport,
8563 				LPFC_DISC_TRC_MBOX,
8564 				"MBOX Send:       cmd:x%x mb:x%x x%x",
8565 				(uint32_t)mbx->mbxCommand,
8566 				mbx->un.varWords[0], mbx->un.varWords[1]);
8567 		}
8568 	}
8569 
8570 	psli->slistat.mbox_cmd++;
8571 	evtctr = psli->slistat.mbox_event;
8572 
8573 	/* next set own bit for the adapter and copy over command word */
8574 	mbx->mbxOwner = OWN_CHIP;
8575 
8576 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8577 		/* Populate mbox extension offset word. */
8578 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
8579 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8580 				= (uint8_t *)phba->mbox_ext
8581 				  - (uint8_t *)phba->mbox;
8582 		}
8583 
8584 		/* Copy the mailbox extension data */
8585 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
8586 			lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
8587 					      (uint8_t *)phba->mbox_ext,
8588 					      pmbox->in_ext_byte_len);
8589 		}
8590 		/* Copy command data to host SLIM area */
8591 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
8592 	} else {
8593 		/* Populate mbox extension offset word. */
8594 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
8595 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8596 				= MAILBOX_HBA_EXT_OFFSET;
8597 
8598 		/* Copy the mailbox extension data */
8599 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
8600 			lpfc_memcpy_to_slim(phba->MBslimaddr +
8601 				MAILBOX_HBA_EXT_OFFSET,
8602 				pmbox->ctx_buf, pmbox->in_ext_byte_len);
8603 
8604 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8605 			/* copy command data into host mbox for cmpl */
8606 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
8607 					      MAILBOX_CMD_SIZE);
8608 
8609 		/* First copy mbox command data to HBA SLIM, skip past first
8610 		   word */
8611 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
8612 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
8613 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
8614 
8615 		/* Next copy over first word, with mbxOwner set */
8616 		ldata = *((uint32_t *)mbx);
8617 		to_slim = phba->MBslimaddr;
8618 		writel(ldata, to_slim);
8619 		readl(to_slim); /* flush */
8620 
8621 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8622 			/* switch over to host mailbox */
8623 			psli->sli_flag |= LPFC_SLI_ACTIVE;
8624 	}
8625 
8626 	wmb();
8627 
8628 	switch (flag) {
8629 	case MBX_NOWAIT:
8630 		/* Set up reference to mailbox command */
8631 		psli->mbox_active = pmbox;
8632 		/* Interrupt board to do it */
8633 		writel(CA_MBATT, phba->CAregaddr);
8634 		readl(phba->CAregaddr); /* flush */
8635 		/* Don't wait for it to finish, just return */
8636 		break;
8637 
8638 	case MBX_POLL:
8639 		/* Set up null reference to mailbox command */
8640 		psli->mbox_active = NULL;
8641 		/* Interrupt board to do it */
8642 		writel(CA_MBATT, phba->CAregaddr);
8643 		readl(phba->CAregaddr); /* flush */
8644 
8645 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8646 			/* First read mbox status word */
8647 			word0 = *((uint32_t *)phba->mbox);
8648 			word0 = le32_to_cpu(word0);
8649 		} else {
8650 			/* First read mbox status word */
8651 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
8652 				spin_unlock_irqrestore(&phba->hbalock,
8653 						       drvr_flag);
8654 				goto out_not_finished;
8655 			}
8656 		}
8657 
8658 		/* Read the HBA Host Attention Register */
8659 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8660 			spin_unlock_irqrestore(&phba->hbalock,
8661 						       drvr_flag);
8662 			goto out_not_finished;
8663 		}
8664 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8665 							1000) + jiffies;
8666 		i = 0;
8667 		/* Wait for command to complete */
8668 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
8669 		       (!(ha_copy & HA_MBATT) &&
8670 			(phba->link_state > LPFC_WARM_START))) {
8671 			if (time_after(jiffies, timeout)) {
8672 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8673 				spin_unlock_irqrestore(&phba->hbalock,
8674 						       drvr_flag);
8675 				goto out_not_finished;
8676 			}
8677 
8678 			/* Check if we took a mbox interrupt while we were
8679 			   polling */
8680 			if (((word0 & OWN_CHIP) != OWN_CHIP)
8681 			    && (evtctr != psli->slistat.mbox_event))
8682 				break;
8683 
8684 			if (i++ > 10) {
8685 				spin_unlock_irqrestore(&phba->hbalock,
8686 						       drvr_flag);
8687 				msleep(1);
8688 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
8689 			}
8690 
8691 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8692 				/* First copy command data */
8693 				word0 = *((uint32_t *)phba->mbox);
8694 				word0 = le32_to_cpu(word0);
8695 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
8696 					MAILBOX_t *slimmb;
8697 					uint32_t slimword0;
8698 					/* Check real SLIM for any errors */
8699 					slimword0 = readl(phba->MBslimaddr);
8700 					slimmb = (MAILBOX_t *) & slimword0;
8701 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
8702 					    && slimmb->mbxStatus) {
8703 						psli->sli_flag &=
8704 						    ~LPFC_SLI_ACTIVE;
8705 						word0 = slimword0;
8706 					}
8707 				}
8708 			} else {
8709 				/* First copy command data */
8710 				word0 = readl(phba->MBslimaddr);
8711 			}
8712 			/* Read the HBA Host Attention Register */
8713 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8714 				spin_unlock_irqrestore(&phba->hbalock,
8715 						       drvr_flag);
8716 				goto out_not_finished;
8717 			}
8718 		}
8719 
8720 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8721 			/* copy results back to user */
8722 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
8723 						MAILBOX_CMD_SIZE);
8724 			/* Copy the mailbox extension data */
8725 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8726 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
8727 						      pmbox->ctx_buf,
8728 						      pmbox->out_ext_byte_len);
8729 			}
8730 		} else {
8731 			/* First copy command data */
8732 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
8733 						MAILBOX_CMD_SIZE);
8734 			/* Copy the mailbox extension data */
8735 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8736 				lpfc_memcpy_from_slim(
8737 					pmbox->ctx_buf,
8738 					phba->MBslimaddr +
8739 					MAILBOX_HBA_EXT_OFFSET,
8740 					pmbox->out_ext_byte_len);
8741 			}
8742 		}
8743 
8744 		writel(HA_MBATT, phba->HAregaddr);
8745 		readl(phba->HAregaddr); /* flush */
8746 
8747 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8748 		status = mbx->mbxStatus;
8749 	}
8750 
8751 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8752 	return status;
8753 
8754 out_not_finished:
8755 	if (processing_queue) {
8756 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
8757 		lpfc_mbox_cmpl_put(phba, pmbox);
8758 	}
8759 	return MBX_NOT_FINISHED;
8760 }
8761 
8762 /**
8763  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
8764  * @phba: Pointer to HBA context object.
8765  *
8766  * The function blocks the posting of SLI4 asynchronous mailbox commands from
8767  * the driver internal pending mailbox queue. It will then try to wait out the
8768  * possible outstanding mailbox command before return.
8769  *
8770  * Returns:
8771  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
8772  * 	the outstanding mailbox command timed out.
8773  **/
8774 static int
8775 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
8776 {
8777 	struct lpfc_sli *psli = &phba->sli;
8778 	int rc = 0;
8779 	unsigned long timeout = 0;
8780 
8781 	/* Mark the asynchronous mailbox command posting as blocked */
8782 	spin_lock_irq(&phba->hbalock);
8783 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
8784 	/* Determine how long we might wait for the active mailbox
8785 	 * command to be gracefully completed by firmware.
8786 	 */
8787 	if (phba->sli.mbox_active)
8788 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
8789 						phba->sli.mbox_active) *
8790 						1000) + jiffies;
8791 	spin_unlock_irq(&phba->hbalock);
8792 
8793 	/* Make sure the mailbox is really active */
8794 	if (timeout)
8795 		lpfc_sli4_process_missed_mbox_completions(phba);
8796 
8797 	/* Wait for the outstnading mailbox command to complete */
8798 	while (phba->sli.mbox_active) {
8799 		/* Check active mailbox complete status every 2ms */
8800 		msleep(2);
8801 		if (time_after(jiffies, timeout)) {
8802 			/* Timeout, marked the outstanding cmd not complete */
8803 			rc = 1;
8804 			break;
8805 		}
8806 	}
8807 
8808 	/* Can not cleanly block async mailbox command, fails it */
8809 	if (rc) {
8810 		spin_lock_irq(&phba->hbalock);
8811 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8812 		spin_unlock_irq(&phba->hbalock);
8813 	}
8814 	return rc;
8815 }
8816 
8817 /**
8818  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
8819  * @phba: Pointer to HBA context object.
8820  *
8821  * The function unblocks and resume posting of SLI4 asynchronous mailbox
8822  * commands from the driver internal pending mailbox queue. It makes sure
8823  * that there is no outstanding mailbox command before resuming posting
8824  * asynchronous mailbox commands. If, for any reason, there is outstanding
8825  * mailbox command, it will try to wait it out before resuming asynchronous
8826  * mailbox command posting.
8827  **/
8828 static void
8829 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
8830 {
8831 	struct lpfc_sli *psli = &phba->sli;
8832 
8833 	spin_lock_irq(&phba->hbalock);
8834 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8835 		/* Asynchronous mailbox posting is not blocked, do nothing */
8836 		spin_unlock_irq(&phba->hbalock);
8837 		return;
8838 	}
8839 
8840 	/* Outstanding synchronous mailbox command is guaranteed to be done,
8841 	 * successful or timeout, after timing-out the outstanding mailbox
8842 	 * command shall always be removed, so just unblock posting async
8843 	 * mailbox command and resume
8844 	 */
8845 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8846 	spin_unlock_irq(&phba->hbalock);
8847 
8848 	/* wake up worker thread to post asynchronous mailbox command */
8849 	lpfc_worker_wake_up(phba);
8850 }
8851 
8852 /**
8853  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
8854  * @phba: Pointer to HBA context object.
8855  * @mboxq: Pointer to mailbox object.
8856  *
8857  * The function waits for the bootstrap mailbox register ready bit from
8858  * port for twice the regular mailbox command timeout value.
8859  *
8860  *      0 - no timeout on waiting for bootstrap mailbox register ready.
8861  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
8862  **/
8863 static int
8864 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8865 {
8866 	uint32_t db_ready;
8867 	unsigned long timeout;
8868 	struct lpfc_register bmbx_reg;
8869 
8870 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
8871 				   * 1000) + jiffies;
8872 
8873 	do {
8874 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
8875 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
8876 		if (!db_ready)
8877 			mdelay(2);
8878 
8879 		if (time_after(jiffies, timeout))
8880 			return MBXERR_ERROR;
8881 	} while (!db_ready);
8882 
8883 	return 0;
8884 }
8885 
8886 /**
8887  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
8888  * @phba: Pointer to HBA context object.
8889  * @mboxq: Pointer to mailbox object.
8890  *
8891  * The function posts a mailbox to the port.  The mailbox is expected
8892  * to be comletely filled in and ready for the port to operate on it.
8893  * This routine executes a synchronous completion operation on the
8894  * mailbox by polling for its completion.
8895  *
8896  * The caller must not be holding any locks when calling this routine.
8897  *
8898  * Returns:
8899  *	MBX_SUCCESS - mailbox posted successfully
8900  *	Any of the MBX error values.
8901  **/
8902 static int
8903 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8904 {
8905 	int rc = MBX_SUCCESS;
8906 	unsigned long iflag;
8907 	uint32_t mcqe_status;
8908 	uint32_t mbx_cmnd;
8909 	struct lpfc_sli *psli = &phba->sli;
8910 	struct lpfc_mqe *mb = &mboxq->u.mqe;
8911 	struct lpfc_bmbx_create *mbox_rgn;
8912 	struct dma_address *dma_address;
8913 
8914 	/*
8915 	 * Only one mailbox can be active to the bootstrap mailbox region
8916 	 * at a time and there is no queueing provided.
8917 	 */
8918 	spin_lock_irqsave(&phba->hbalock, iflag);
8919 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8920 		spin_unlock_irqrestore(&phba->hbalock, iflag);
8921 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8922 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
8923 				"cannot issue Data: x%x x%x\n",
8924 				mboxq->vport ? mboxq->vport->vpi : 0,
8925 				mboxq->u.mb.mbxCommand,
8926 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8927 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8928 				psli->sli_flag, MBX_POLL);
8929 		return MBXERR_ERROR;
8930 	}
8931 	/* The server grabs the token and owns it until release */
8932 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8933 	phba->sli.mbox_active = mboxq;
8934 	spin_unlock_irqrestore(&phba->hbalock, iflag);
8935 
8936 	/* wait for bootstrap mbox register for readyness */
8937 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8938 	if (rc)
8939 		goto exit;
8940 	/*
8941 	 * Initialize the bootstrap memory region to avoid stale data areas
8942 	 * in the mailbox post.  Then copy the caller's mailbox contents to
8943 	 * the bmbx mailbox region.
8944 	 */
8945 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
8946 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
8947 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
8948 			       sizeof(struct lpfc_mqe));
8949 
8950 	/* Post the high mailbox dma address to the port and wait for ready. */
8951 	dma_address = &phba->sli4_hba.bmbx.dma_address;
8952 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
8953 
8954 	/* wait for bootstrap mbox register for hi-address write done */
8955 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8956 	if (rc)
8957 		goto exit;
8958 
8959 	/* Post the low mailbox dma address to the port. */
8960 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
8961 
8962 	/* wait for bootstrap mbox register for low address write done */
8963 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8964 	if (rc)
8965 		goto exit;
8966 
8967 	/*
8968 	 * Read the CQ to ensure the mailbox has completed.
8969 	 * If so, update the mailbox status so that the upper layers
8970 	 * can complete the request normally.
8971 	 */
8972 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
8973 			       sizeof(struct lpfc_mqe));
8974 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
8975 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
8976 			       sizeof(struct lpfc_mcqe));
8977 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
8978 	/*
8979 	 * When the CQE status indicates a failure and the mailbox status
8980 	 * indicates success then copy the CQE status into the mailbox status
8981 	 * (and prefix it with x4000).
8982 	 */
8983 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
8984 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
8985 			bf_set(lpfc_mqe_status, mb,
8986 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
8987 		rc = MBXERR_ERROR;
8988 	} else
8989 		lpfc_sli4_swap_str(phba, mboxq);
8990 
8991 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8992 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
8993 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
8994 			" x%x x%x CQ: x%x x%x x%x x%x\n",
8995 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
8996 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8997 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8998 			bf_get(lpfc_mqe_status, mb),
8999 			mb->un.mb_words[0], mb->un.mb_words[1],
9000 			mb->un.mb_words[2], mb->un.mb_words[3],
9001 			mb->un.mb_words[4], mb->un.mb_words[5],
9002 			mb->un.mb_words[6], mb->un.mb_words[7],
9003 			mb->un.mb_words[8], mb->un.mb_words[9],
9004 			mb->un.mb_words[10], mb->un.mb_words[11],
9005 			mb->un.mb_words[12], mboxq->mcqe.word0,
9006 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
9007 			mboxq->mcqe.trailer);
9008 exit:
9009 	/* We are holding the token, no needed for lock when release */
9010 	spin_lock_irqsave(&phba->hbalock, iflag);
9011 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9012 	phba->sli.mbox_active = NULL;
9013 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9014 	return rc;
9015 }
9016 
9017 /**
9018  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
9019  * @phba: Pointer to HBA context object.
9020  * @mboxq: Pointer to mailbox object.
9021  * @flag: Flag indicating how the mailbox need to be processed.
9022  *
9023  * This function is called by discovery code and HBA management code to submit
9024  * a mailbox command to firmware with SLI-4 interface spec.
9025  *
9026  * Return codes the caller owns the mailbox command after the return of the
9027  * function.
9028  **/
9029 static int
9030 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
9031 		       uint32_t flag)
9032 {
9033 	struct lpfc_sli *psli = &phba->sli;
9034 	unsigned long iflags;
9035 	int rc;
9036 
9037 	/* dump from issue mailbox command if setup */
9038 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
9039 
9040 	rc = lpfc_mbox_dev_check(phba);
9041 	if (unlikely(rc)) {
9042 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9043 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
9044 				"cannot issue Data: x%x x%x\n",
9045 				mboxq->vport ? mboxq->vport->vpi : 0,
9046 				mboxq->u.mb.mbxCommand,
9047 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9048 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9049 				psli->sli_flag, flag);
9050 		goto out_not_finished;
9051 	}
9052 
9053 	/* Detect polling mode and jump to a handler */
9054 	if (!phba->sli4_hba.intr_enable) {
9055 		if (flag == MBX_POLL)
9056 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
9057 		else
9058 			rc = -EIO;
9059 		if (rc != MBX_SUCCESS)
9060 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
9061 					"(%d):2541 Mailbox command x%x "
9062 					"(x%x/x%x) failure: "
9063 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
9064 					"Data: x%x x%x\n,",
9065 					mboxq->vport ? mboxq->vport->vpi : 0,
9066 					mboxq->u.mb.mbxCommand,
9067 					lpfc_sli_config_mbox_subsys_get(phba,
9068 									mboxq),
9069 					lpfc_sli_config_mbox_opcode_get(phba,
9070 									mboxq),
9071 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
9072 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
9073 					bf_get(lpfc_mcqe_ext_status,
9074 					       &mboxq->mcqe),
9075 					psli->sli_flag, flag);
9076 		return rc;
9077 	} else if (flag == MBX_POLL) {
9078 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
9079 				"(%d):2542 Try to issue mailbox command "
9080 				"x%x (x%x/x%x) synchronously ahead of async "
9081 				"mailbox command queue: x%x x%x\n",
9082 				mboxq->vport ? mboxq->vport->vpi : 0,
9083 				mboxq->u.mb.mbxCommand,
9084 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9085 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9086 				psli->sli_flag, flag);
9087 		/* Try to block the asynchronous mailbox posting */
9088 		rc = lpfc_sli4_async_mbox_block(phba);
9089 		if (!rc) {
9090 			/* Successfully blocked, now issue sync mbox cmd */
9091 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
9092 			if (rc != MBX_SUCCESS)
9093 				lpfc_printf_log(phba, KERN_WARNING,
9094 					LOG_MBOX | LOG_SLI,
9095 					"(%d):2597 Sync Mailbox command "
9096 					"x%x (x%x/x%x) failure: "
9097 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
9098 					"Data: x%x x%x\n,",
9099 					mboxq->vport ? mboxq->vport->vpi : 0,
9100 					mboxq->u.mb.mbxCommand,
9101 					lpfc_sli_config_mbox_subsys_get(phba,
9102 									mboxq),
9103 					lpfc_sli_config_mbox_opcode_get(phba,
9104 									mboxq),
9105 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
9106 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
9107 					bf_get(lpfc_mcqe_ext_status,
9108 					       &mboxq->mcqe),
9109 					psli->sli_flag, flag);
9110 			/* Unblock the async mailbox posting afterward */
9111 			lpfc_sli4_async_mbox_unblock(phba);
9112 		}
9113 		return rc;
9114 	}
9115 
9116 	/* Now, interrupt mode asynchronous mailbox command */
9117 	rc = lpfc_mbox_cmd_check(phba, mboxq);
9118 	if (rc) {
9119 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9120 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
9121 				"cannot issue Data: x%x x%x\n",
9122 				mboxq->vport ? mboxq->vport->vpi : 0,
9123 				mboxq->u.mb.mbxCommand,
9124 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9125 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9126 				psli->sli_flag, flag);
9127 		goto out_not_finished;
9128 	}
9129 
9130 	/* Put the mailbox command to the driver internal FIFO */
9131 	psli->slistat.mbox_busy++;
9132 	spin_lock_irqsave(&phba->hbalock, iflags);
9133 	lpfc_mbox_put(phba, mboxq);
9134 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9135 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9136 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
9137 			"x%x (x%x/x%x) x%x x%x x%x\n",
9138 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
9139 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
9140 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9141 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9142 			phba->pport->port_state,
9143 			psli->sli_flag, MBX_NOWAIT);
9144 	/* Wake up worker thread to transport mailbox command from head */
9145 	lpfc_worker_wake_up(phba);
9146 
9147 	return MBX_BUSY;
9148 
9149 out_not_finished:
9150 	return MBX_NOT_FINISHED;
9151 }
9152 
9153 /**
9154  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
9155  * @phba: Pointer to HBA context object.
9156  *
9157  * This function is called by worker thread to send a mailbox command to
9158  * SLI4 HBA firmware.
9159  *
9160  **/
9161 int
9162 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
9163 {
9164 	struct lpfc_sli *psli = &phba->sli;
9165 	LPFC_MBOXQ_t *mboxq;
9166 	int rc = MBX_SUCCESS;
9167 	unsigned long iflags;
9168 	struct lpfc_mqe *mqe;
9169 	uint32_t mbx_cmnd;
9170 
9171 	/* Check interrupt mode before post async mailbox command */
9172 	if (unlikely(!phba->sli4_hba.intr_enable))
9173 		return MBX_NOT_FINISHED;
9174 
9175 	/* Check for mailbox command service token */
9176 	spin_lock_irqsave(&phba->hbalock, iflags);
9177 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9178 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9179 		return MBX_NOT_FINISHED;
9180 	}
9181 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9182 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9183 		return MBX_NOT_FINISHED;
9184 	}
9185 	if (unlikely(phba->sli.mbox_active)) {
9186 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9187 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9188 				"0384 There is pending active mailbox cmd\n");
9189 		return MBX_NOT_FINISHED;
9190 	}
9191 	/* Take the mailbox command service token */
9192 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9193 
9194 	/* Get the next mailbox command from head of queue */
9195 	mboxq = lpfc_mbox_get(phba);
9196 
9197 	/* If no more mailbox command waiting for post, we're done */
9198 	if (!mboxq) {
9199 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9200 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9201 		return MBX_SUCCESS;
9202 	}
9203 	phba->sli.mbox_active = mboxq;
9204 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9205 
9206 	/* Check device readiness for posting mailbox command */
9207 	rc = lpfc_mbox_dev_check(phba);
9208 	if (unlikely(rc))
9209 		/* Driver clean routine will clean up pending mailbox */
9210 		goto out_not_finished;
9211 
9212 	/* Prepare the mbox command to be posted */
9213 	mqe = &mboxq->u.mqe;
9214 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
9215 
9216 	/* Start timer for the mbox_tmo and log some mailbox post messages */
9217 	mod_timer(&psli->mbox_tmo, (jiffies +
9218 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
9219 
9220 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9221 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
9222 			"x%x x%x\n",
9223 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
9224 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9225 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9226 			phba->pport->port_state, psli->sli_flag);
9227 
9228 	if (mbx_cmnd != MBX_HEARTBEAT) {
9229 		if (mboxq->vport) {
9230 			lpfc_debugfs_disc_trc(mboxq->vport,
9231 				LPFC_DISC_TRC_MBOX_VPORT,
9232 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9233 				mbx_cmnd, mqe->un.mb_words[0],
9234 				mqe->un.mb_words[1]);
9235 		} else {
9236 			lpfc_debugfs_disc_trc(phba->pport,
9237 				LPFC_DISC_TRC_MBOX,
9238 				"MBOX Send: cmd:x%x mb:x%x x%x",
9239 				mbx_cmnd, mqe->un.mb_words[0],
9240 				mqe->un.mb_words[1]);
9241 		}
9242 	}
9243 	psli->slistat.mbox_cmd++;
9244 
9245 	/* Post the mailbox command to the port */
9246 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
9247 	if (rc != MBX_SUCCESS) {
9248 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9249 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
9250 				"cannot issue Data: x%x x%x\n",
9251 				mboxq->vport ? mboxq->vport->vpi : 0,
9252 				mboxq->u.mb.mbxCommand,
9253 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9254 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9255 				psli->sli_flag, MBX_NOWAIT);
9256 		goto out_not_finished;
9257 	}
9258 
9259 	return rc;
9260 
9261 out_not_finished:
9262 	spin_lock_irqsave(&phba->hbalock, iflags);
9263 	if (phba->sli.mbox_active) {
9264 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
9265 		__lpfc_mbox_cmpl_put(phba, mboxq);
9266 		/* Release the token */
9267 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9268 		phba->sli.mbox_active = NULL;
9269 	}
9270 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9271 
9272 	return MBX_NOT_FINISHED;
9273 }
9274 
9275 /**
9276  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
9277  * @phba: Pointer to HBA context object.
9278  * @pmbox: Pointer to mailbox object.
9279  * @flag: Flag indicating how the mailbox need to be processed.
9280  *
9281  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
9282  * the API jump table function pointer from the lpfc_hba struct.
9283  *
9284  * Return codes the caller owns the mailbox command after the return of the
9285  * function.
9286  **/
9287 int
9288 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
9289 {
9290 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
9291 }
9292 
9293 /**
9294  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
9295  * @phba: The hba struct for which this call is being executed.
9296  * @dev_grp: The HBA PCI-Device group number.
9297  *
9298  * This routine sets up the mbox interface API function jump table in @phba
9299  * struct.
9300  * Returns: 0 - success, -ENODEV - failure.
9301  **/
9302 int
9303 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
9304 {
9305 
9306 	switch (dev_grp) {
9307 	case LPFC_PCI_DEV_LP:
9308 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
9309 		phba->lpfc_sli_handle_slow_ring_event =
9310 				lpfc_sli_handle_slow_ring_event_s3;
9311 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
9312 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
9313 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
9314 		break;
9315 	case LPFC_PCI_DEV_OC:
9316 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
9317 		phba->lpfc_sli_handle_slow_ring_event =
9318 				lpfc_sli_handle_slow_ring_event_s4;
9319 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
9320 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
9321 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
9322 		break;
9323 	default:
9324 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9325 				"1420 Invalid HBA PCI-device group: 0x%x\n",
9326 				dev_grp);
9327 		return -ENODEV;
9328 	}
9329 	return 0;
9330 }
9331 
9332 /**
9333  * __lpfc_sli_ringtx_put - Add an iocb to the txq
9334  * @phba: Pointer to HBA context object.
9335  * @pring: Pointer to driver SLI ring object.
9336  * @piocb: Pointer to address of newly added command iocb.
9337  *
9338  * This function is called with hbalock held for SLI3 ports or
9339  * the ring lock held for SLI4 ports to add a command
9340  * iocb to the txq when SLI layer cannot submit the command iocb
9341  * to the ring.
9342  **/
9343 void
9344 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9345 		    struct lpfc_iocbq *piocb)
9346 {
9347 	if (phba->sli_rev == LPFC_SLI_REV4)
9348 		lockdep_assert_held(&pring->ring_lock);
9349 	else
9350 		lockdep_assert_held(&phba->hbalock);
9351 	/* Insert the caller's iocb in the txq tail for later processing. */
9352 	list_add_tail(&piocb->list, &pring->txq);
9353 }
9354 
9355 /**
9356  * lpfc_sli_next_iocb - Get the next iocb in the txq
9357  * @phba: Pointer to HBA context object.
9358  * @pring: Pointer to driver SLI ring object.
9359  * @piocb: Pointer to address of newly added command iocb.
9360  *
9361  * This function is called with hbalock held before a new
9362  * iocb is submitted to the firmware. This function checks
9363  * txq to flush the iocbs in txq to Firmware before
9364  * submitting new iocbs to the Firmware.
9365  * If there are iocbs in the txq which need to be submitted
9366  * to firmware, lpfc_sli_next_iocb returns the first element
9367  * of the txq after dequeuing it from txq.
9368  * If there is no iocb in the txq then the function will return
9369  * *piocb and *piocb is set to NULL. Caller needs to check
9370  * *piocb to find if there are more commands in the txq.
9371  **/
9372 static struct lpfc_iocbq *
9373 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9374 		   struct lpfc_iocbq **piocb)
9375 {
9376 	struct lpfc_iocbq * nextiocb;
9377 
9378 	lockdep_assert_held(&phba->hbalock);
9379 
9380 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
9381 	if (!nextiocb) {
9382 		nextiocb = *piocb;
9383 		*piocb = NULL;
9384 	}
9385 
9386 	return nextiocb;
9387 }
9388 
9389 /**
9390  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
9391  * @phba: Pointer to HBA context object.
9392  * @ring_number: SLI ring number to issue iocb on.
9393  * @piocb: Pointer to command iocb.
9394  * @flag: Flag indicating if this command can be put into txq.
9395  *
9396  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
9397  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
9398  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
9399  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
9400  * this function allows only iocbs for posting buffers. This function finds
9401  * next available slot in the command ring and posts the command to the
9402  * available slot and writes the port attention register to request HBA start
9403  * processing new iocb. If there is no slot available in the ring and
9404  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
9405  * the function returns IOCB_BUSY.
9406  *
9407  * This function is called with hbalock held. The function will return success
9408  * after it successfully submit the iocb to firmware or after adding to the
9409  * txq.
9410  **/
9411 static int
9412 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
9413 		    struct lpfc_iocbq *piocb, uint32_t flag)
9414 {
9415 	struct lpfc_iocbq *nextiocb;
9416 	IOCB_t *iocb;
9417 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
9418 
9419 	lockdep_assert_held(&phba->hbalock);
9420 
9421 	if (piocb->iocb_cmpl && (!piocb->vport) &&
9422 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
9423 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
9424 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9425 				"1807 IOCB x%x failed. No vport\n",
9426 				piocb->iocb.ulpCommand);
9427 		dump_stack();
9428 		return IOCB_ERROR;
9429 	}
9430 
9431 
9432 	/* If the PCI channel is in offline state, do not post iocbs. */
9433 	if (unlikely(pci_channel_offline(phba->pcidev)))
9434 		return IOCB_ERROR;
9435 
9436 	/* If HBA has a deferred error attention, fail the iocb. */
9437 	if (unlikely(phba->hba_flag & DEFER_ERATT))
9438 		return IOCB_ERROR;
9439 
9440 	/*
9441 	 * We should never get an IOCB if we are in a < LINK_DOWN state
9442 	 */
9443 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
9444 		return IOCB_ERROR;
9445 
9446 	/*
9447 	 * Check to see if we are blocking IOCB processing because of a
9448 	 * outstanding event.
9449 	 */
9450 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
9451 		goto iocb_busy;
9452 
9453 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
9454 		/*
9455 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
9456 		 * can be issued if the link is not up.
9457 		 */
9458 		switch (piocb->iocb.ulpCommand) {
9459 		case CMD_GEN_REQUEST64_CR:
9460 		case CMD_GEN_REQUEST64_CX:
9461 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
9462 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
9463 					FC_RCTL_DD_UNSOL_CMD) ||
9464 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
9465 					MENLO_TRANSPORT_TYPE))
9466 
9467 				goto iocb_busy;
9468 			break;
9469 		case CMD_QUE_RING_BUF_CN:
9470 		case CMD_QUE_RING_BUF64_CN:
9471 			/*
9472 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
9473 			 * completion, iocb_cmpl MUST be 0.
9474 			 */
9475 			if (piocb->iocb_cmpl)
9476 				piocb->iocb_cmpl = NULL;
9477 			fallthrough;
9478 		case CMD_CREATE_XRI_CR:
9479 		case CMD_CLOSE_XRI_CN:
9480 		case CMD_CLOSE_XRI_CX:
9481 			break;
9482 		default:
9483 			goto iocb_busy;
9484 		}
9485 
9486 	/*
9487 	 * For FCP commands, we must be in a state where we can process link
9488 	 * attention events.
9489 	 */
9490 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
9491 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
9492 		goto iocb_busy;
9493 	}
9494 
9495 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
9496 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
9497 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
9498 
9499 	if (iocb)
9500 		lpfc_sli_update_ring(phba, pring);
9501 	else
9502 		lpfc_sli_update_full_ring(phba, pring);
9503 
9504 	if (!piocb)
9505 		return IOCB_SUCCESS;
9506 
9507 	goto out_busy;
9508 
9509  iocb_busy:
9510 	pring->stats.iocb_cmd_delay++;
9511 
9512  out_busy:
9513 
9514 	if (!(flag & SLI_IOCB_RET_IOCB)) {
9515 		__lpfc_sli_ringtx_put(phba, pring, piocb);
9516 		return IOCB_SUCCESS;
9517 	}
9518 
9519 	return IOCB_BUSY;
9520 }
9521 
9522 /**
9523  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
9524  * @phba: Pointer to HBA context object.
9525  * @piocbq: Pointer to command iocb.
9526  * @sglq: Pointer to the scatter gather queue object.
9527  *
9528  * This routine converts the bpl or bde that is in the IOCB
9529  * to a sgl list for the sli4 hardware. The physical address
9530  * of the bpl/bde is converted back to a virtual address.
9531  * If the IOCB contains a BPL then the list of BDE's is
9532  * converted to sli4_sge's. If the IOCB contains a single
9533  * BDE then it is converted to a single sli_sge.
9534  * The IOCB is still in cpu endianess so the contents of
9535  * the bpl can be used without byte swapping.
9536  *
9537  * Returns valid XRI = Success, NO_XRI = Failure.
9538 **/
9539 static uint16_t
9540 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
9541 		struct lpfc_sglq *sglq)
9542 {
9543 	uint16_t xritag = NO_XRI;
9544 	struct ulp_bde64 *bpl = NULL;
9545 	struct ulp_bde64 bde;
9546 	struct sli4_sge *sgl  = NULL;
9547 	struct lpfc_dmabuf *dmabuf;
9548 	IOCB_t *icmd;
9549 	int numBdes = 0;
9550 	int i = 0;
9551 	uint32_t offset = 0; /* accumulated offset in the sg request list */
9552 	int inbound = 0; /* number of sg reply entries inbound from firmware */
9553 
9554 	if (!piocbq || !sglq)
9555 		return xritag;
9556 
9557 	sgl  = (struct sli4_sge *)sglq->sgl;
9558 	icmd = &piocbq->iocb;
9559 	if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
9560 		return sglq->sli4_xritag;
9561 	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9562 		numBdes = icmd->un.genreq64.bdl.bdeSize /
9563 				sizeof(struct ulp_bde64);
9564 		/* The addrHigh and addrLow fields within the IOCB
9565 		 * have not been byteswapped yet so there is no
9566 		 * need to swap them back.
9567 		 */
9568 		if (piocbq->context3)
9569 			dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
9570 		else
9571 			return xritag;
9572 
9573 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
9574 		if (!bpl)
9575 			return xritag;
9576 
9577 		for (i = 0; i < numBdes; i++) {
9578 			/* Should already be byte swapped. */
9579 			sgl->addr_hi = bpl->addrHigh;
9580 			sgl->addr_lo = bpl->addrLow;
9581 
9582 			sgl->word2 = le32_to_cpu(sgl->word2);
9583 			if ((i+1) == numBdes)
9584 				bf_set(lpfc_sli4_sge_last, sgl, 1);
9585 			else
9586 				bf_set(lpfc_sli4_sge_last, sgl, 0);
9587 			/* swap the size field back to the cpu so we
9588 			 * can assign it to the sgl.
9589 			 */
9590 			bde.tus.w = le32_to_cpu(bpl->tus.w);
9591 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
9592 			/* The offsets in the sgl need to be accumulated
9593 			 * separately for the request and reply lists.
9594 			 * The request is always first, the reply follows.
9595 			 */
9596 			if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
9597 				/* add up the reply sg entries */
9598 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
9599 					inbound++;
9600 				/* first inbound? reset the offset */
9601 				if (inbound == 1)
9602 					offset = 0;
9603 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
9604 				bf_set(lpfc_sli4_sge_type, sgl,
9605 					LPFC_SGE_TYPE_DATA);
9606 				offset += bde.tus.f.bdeSize;
9607 			}
9608 			sgl->word2 = cpu_to_le32(sgl->word2);
9609 			bpl++;
9610 			sgl++;
9611 		}
9612 	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
9613 			/* The addrHigh and addrLow fields of the BDE have not
9614 			 * been byteswapped yet so they need to be swapped
9615 			 * before putting them in the sgl.
9616 			 */
9617 			sgl->addr_hi =
9618 				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
9619 			sgl->addr_lo =
9620 				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
9621 			sgl->word2 = le32_to_cpu(sgl->word2);
9622 			bf_set(lpfc_sli4_sge_last, sgl, 1);
9623 			sgl->word2 = cpu_to_le32(sgl->word2);
9624 			sgl->sge_len =
9625 				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
9626 	}
9627 	return sglq->sli4_xritag;
9628 }
9629 
9630 /**
9631  * lpfc_sli4_iocb2wqe - Convert the IOCB to a work queue entry.
9632  * @phba: Pointer to HBA context object.
9633  * @iocbq: Pointer to command iocb.
9634  * @wqe: Pointer to the work queue entry.
9635  *
9636  * This routine converts the iocb command to its Work Queue Entry
9637  * equivalent. The wqe pointer should not have any fields set when
9638  * this routine is called because it will memcpy over them.
9639  * This routine does not set the CQ_ID or the WQEC bits in the
9640  * wqe.
9641  *
9642  * Returns: 0 = Success, IOCB_ERROR = Failure.
9643  **/
9644 static int
9645 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
9646 		union lpfc_wqe128 *wqe)
9647 {
9648 	uint32_t xmit_len = 0, total_len = 0;
9649 	uint8_t ct = 0;
9650 	uint32_t fip;
9651 	uint32_t abort_tag;
9652 	uint8_t command_type = ELS_COMMAND_NON_FIP;
9653 	uint8_t cmnd;
9654 	uint16_t xritag;
9655 	uint16_t abrt_iotag;
9656 	struct lpfc_iocbq *abrtiocbq;
9657 	struct ulp_bde64 *bpl = NULL;
9658 	uint32_t els_id = LPFC_ELS_ID_DEFAULT;
9659 	int numBdes, i;
9660 	struct ulp_bde64 bde;
9661 	struct lpfc_nodelist *ndlp;
9662 	uint32_t *pcmd;
9663 	uint32_t if_type;
9664 
9665 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
9666 	/* The fcp commands will set command type */
9667 	if (iocbq->iocb_flag &  LPFC_IO_FCP)
9668 		command_type = FCP_COMMAND;
9669 	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
9670 		command_type = ELS_COMMAND_FIP;
9671 	else
9672 		command_type = ELS_COMMAND_NON_FIP;
9673 
9674 	if (phba->fcp_embed_io)
9675 		memset(wqe, 0, sizeof(union lpfc_wqe128));
9676 	/* Some of the fields are in the right position already */
9677 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
9678 	/* The ct field has moved so reset */
9679 	wqe->generic.wqe_com.word7 = 0;
9680 	wqe->generic.wqe_com.word10 = 0;
9681 
9682 	abort_tag = (uint32_t) iocbq->iotag;
9683 	xritag = iocbq->sli4_xritag;
9684 	/* words0-2 bpl convert bde */
9685 	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9686 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
9687 				sizeof(struct ulp_bde64);
9688 		bpl  = (struct ulp_bde64 *)
9689 			((struct lpfc_dmabuf *)iocbq->context3)->virt;
9690 		if (!bpl)
9691 			return IOCB_ERROR;
9692 
9693 		/* Should already be byte swapped. */
9694 		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
9695 		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
9696 		/* swap the size field back to the cpu so we
9697 		 * can assign it to the sgl.
9698 		 */
9699 		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
9700 		xmit_len = wqe->generic.bde.tus.f.bdeSize;
9701 		total_len = 0;
9702 		for (i = 0; i < numBdes; i++) {
9703 			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
9704 			total_len += bde.tus.f.bdeSize;
9705 		}
9706 	} else
9707 		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
9708 
9709 	iocbq->iocb.ulpIoTag = iocbq->iotag;
9710 	cmnd = iocbq->iocb.ulpCommand;
9711 
9712 	switch (iocbq->iocb.ulpCommand) {
9713 	case CMD_ELS_REQUEST64_CR:
9714 		if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
9715 			ndlp = iocbq->context_un.ndlp;
9716 		else
9717 			ndlp = (struct lpfc_nodelist *)iocbq->context1;
9718 		if (!iocbq->iocb.ulpLe) {
9719 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9720 				"2007 Only Limited Edition cmd Format"
9721 				" supported 0x%x\n",
9722 				iocbq->iocb.ulpCommand);
9723 			return IOCB_ERROR;
9724 		}
9725 
9726 		wqe->els_req.payload_len = xmit_len;
9727 		/* Els_reguest64 has a TMO */
9728 		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
9729 			iocbq->iocb.ulpTimeout);
9730 		/* Need a VF for word 4 set the vf bit*/
9731 		bf_set(els_req64_vf, &wqe->els_req, 0);
9732 		/* And a VFID for word 12 */
9733 		bf_set(els_req64_vfid, &wqe->els_req, 0);
9734 		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
9735 		bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9736 		       iocbq->iocb.ulpContext);
9737 		bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
9738 		bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
9739 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
9740 		if (command_type == ELS_COMMAND_FIP)
9741 			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
9742 					>> LPFC_FIP_ELS_ID_SHIFT);
9743 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9744 					iocbq->context2)->virt);
9745 		if_type = bf_get(lpfc_sli_intf_if_type,
9746 					&phba->sli4_hba.sli_intf);
9747 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9748 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
9749 				*pcmd == ELS_CMD_SCR ||
9750 				*pcmd == ELS_CMD_RDF ||
9751 				*pcmd == ELS_CMD_RSCN_XMT ||
9752 				*pcmd == ELS_CMD_FDISC ||
9753 				*pcmd == ELS_CMD_LOGO ||
9754 				*pcmd == ELS_CMD_PLOGI)) {
9755 				bf_set(els_req64_sp, &wqe->els_req, 1);
9756 				bf_set(els_req64_sid, &wqe->els_req,
9757 					iocbq->vport->fc_myDID);
9758 				if ((*pcmd == ELS_CMD_FLOGI) &&
9759 					!(phba->fc_topology ==
9760 						LPFC_TOPOLOGY_LOOP))
9761 					bf_set(els_req64_sid, &wqe->els_req, 0);
9762 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
9763 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9764 					phba->vpi_ids[iocbq->vport->vpi]);
9765 			} else if (pcmd && iocbq->context1) {
9766 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
9767 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9768 					phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9769 			}
9770 		}
9771 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
9772 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9773 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
9774 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
9775 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
9776 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
9777 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
9778 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
9779 		wqe->els_req.max_response_payload_len = total_len - xmit_len;
9780 		break;
9781 	case CMD_XMIT_SEQUENCE64_CX:
9782 		bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
9783 		       iocbq->iocb.un.ulpWord[3]);
9784 		bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
9785 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
9786 		/* The entire sequence is transmitted for this IOCB */
9787 		xmit_len = total_len;
9788 		cmnd = CMD_XMIT_SEQUENCE64_CR;
9789 		if (phba->link_flag & LS_LOOPBACK_MODE)
9790 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
9791 		fallthrough;
9792 	case CMD_XMIT_SEQUENCE64_CR:
9793 		/* word3 iocb=io_tag32 wqe=reserved */
9794 		wqe->xmit_sequence.rsvd3 = 0;
9795 		/* word4 relative_offset memcpy */
9796 		/* word5 r_ctl/df_ctl memcpy */
9797 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
9798 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
9799 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
9800 		       LPFC_WQE_IOD_WRITE);
9801 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
9802 		       LPFC_WQE_LENLOC_WORD12);
9803 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
9804 		wqe->xmit_sequence.xmit_len = xmit_len;
9805 		command_type = OTHER_COMMAND;
9806 		break;
9807 	case CMD_XMIT_BCAST64_CN:
9808 		/* word3 iocb=iotag32 wqe=seq_payload_len */
9809 		wqe->xmit_bcast64.seq_payload_len = xmit_len;
9810 		/* word4 iocb=rsvd wqe=rsvd */
9811 		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
9812 		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
9813 		bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
9814 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9815 		bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
9816 		bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
9817 		bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
9818 		       LPFC_WQE_LENLOC_WORD3);
9819 		bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
9820 		break;
9821 	case CMD_FCP_IWRITE64_CR:
9822 		command_type = FCP_COMMAND_DATA_OUT;
9823 		/* word3 iocb=iotag wqe=payload_offset_len */
9824 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9825 		bf_set(payload_offset_len, &wqe->fcp_iwrite,
9826 		       xmit_len + sizeof(struct fcp_rsp));
9827 		bf_set(cmd_buff_len, &wqe->fcp_iwrite,
9828 		       0);
9829 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9830 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9831 		bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
9832 		       iocbq->iocb.ulpFCP2Rcvy);
9833 		bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
9834 		/* Always open the exchange */
9835 		bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
9836 		bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
9837 		       LPFC_WQE_LENLOC_WORD4);
9838 		bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
9839 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
9840 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9841 			bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
9842 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
9843 			if (iocbq->priority) {
9844 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9845 				       (iocbq->priority << 1));
9846 			} else {
9847 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9848 				       (phba->cfg_XLanePriority << 1));
9849 			}
9850 		}
9851 		/* Note, word 10 is already initialized to 0 */
9852 
9853 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9854 		if (phba->cfg_enable_pbde)
9855 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 1);
9856 		else
9857 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
9858 
9859 		if (phba->fcp_embed_io) {
9860 			struct lpfc_io_buf *lpfc_cmd;
9861 			struct sli4_sge *sgl;
9862 			struct fcp_cmnd *fcp_cmnd;
9863 			uint32_t *ptr;
9864 
9865 			/* 128 byte wqe support here */
9866 
9867 			lpfc_cmd = iocbq->context1;
9868 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9869 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9870 
9871 			/* Word 0-2 - FCP_CMND */
9872 			wqe->generic.bde.tus.f.bdeFlags =
9873 				BUFF_TYPE_BDE_IMMED;
9874 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9875 			wqe->generic.bde.addrHigh = 0;
9876 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9877 
9878 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
9879 			bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
9880 
9881 			/* Word 22-29  FCP CMND Payload */
9882 			ptr = &wqe->words[22];
9883 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9884 		}
9885 		break;
9886 	case CMD_FCP_IREAD64_CR:
9887 		/* word3 iocb=iotag wqe=payload_offset_len */
9888 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9889 		bf_set(payload_offset_len, &wqe->fcp_iread,
9890 		       xmit_len + sizeof(struct fcp_rsp));
9891 		bf_set(cmd_buff_len, &wqe->fcp_iread,
9892 		       0);
9893 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9894 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9895 		bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
9896 		       iocbq->iocb.ulpFCP2Rcvy);
9897 		bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
9898 		/* Always open the exchange */
9899 		bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
9900 		bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
9901 		       LPFC_WQE_LENLOC_WORD4);
9902 		bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
9903 		bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
9904 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9905 			bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
9906 			bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
9907 			if (iocbq->priority) {
9908 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9909 				       (iocbq->priority << 1));
9910 			} else {
9911 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9912 				       (phba->cfg_XLanePriority << 1));
9913 			}
9914 		}
9915 		/* Note, word 10 is already initialized to 0 */
9916 
9917 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9918 		if (phba->cfg_enable_pbde)
9919 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 1);
9920 		else
9921 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
9922 
9923 		if (phba->fcp_embed_io) {
9924 			struct lpfc_io_buf *lpfc_cmd;
9925 			struct sli4_sge *sgl;
9926 			struct fcp_cmnd *fcp_cmnd;
9927 			uint32_t *ptr;
9928 
9929 			/* 128 byte wqe support here */
9930 
9931 			lpfc_cmd = iocbq->context1;
9932 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9933 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9934 
9935 			/* Word 0-2 - FCP_CMND */
9936 			wqe->generic.bde.tus.f.bdeFlags =
9937 				BUFF_TYPE_BDE_IMMED;
9938 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9939 			wqe->generic.bde.addrHigh = 0;
9940 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9941 
9942 			bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
9943 			bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
9944 
9945 			/* Word 22-29  FCP CMND Payload */
9946 			ptr = &wqe->words[22];
9947 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9948 		}
9949 		break;
9950 	case CMD_FCP_ICMND64_CR:
9951 		/* word3 iocb=iotag wqe=payload_offset_len */
9952 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9953 		bf_set(payload_offset_len, &wqe->fcp_icmd,
9954 		       xmit_len + sizeof(struct fcp_rsp));
9955 		bf_set(cmd_buff_len, &wqe->fcp_icmd,
9956 		       0);
9957 		/* word3 iocb=IO_TAG wqe=reserved */
9958 		bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
9959 		/* Always open the exchange */
9960 		bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
9961 		bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
9962 		bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
9963 		bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
9964 		       LPFC_WQE_LENLOC_NONE);
9965 		bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
9966 		       iocbq->iocb.ulpFCP2Rcvy);
9967 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9968 			bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
9969 			bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
9970 			if (iocbq->priority) {
9971 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9972 				       (iocbq->priority << 1));
9973 			} else {
9974 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9975 				       (phba->cfg_XLanePriority << 1));
9976 			}
9977 		}
9978 		/* Note, word 10 is already initialized to 0 */
9979 
9980 		if (phba->fcp_embed_io) {
9981 			struct lpfc_io_buf *lpfc_cmd;
9982 			struct sli4_sge *sgl;
9983 			struct fcp_cmnd *fcp_cmnd;
9984 			uint32_t *ptr;
9985 
9986 			/* 128 byte wqe support here */
9987 
9988 			lpfc_cmd = iocbq->context1;
9989 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9990 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9991 
9992 			/* Word 0-2 - FCP_CMND */
9993 			wqe->generic.bde.tus.f.bdeFlags =
9994 				BUFF_TYPE_BDE_IMMED;
9995 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9996 			wqe->generic.bde.addrHigh = 0;
9997 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9998 
9999 			bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
10000 			bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
10001 
10002 			/* Word 22-29  FCP CMND Payload */
10003 			ptr = &wqe->words[22];
10004 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10005 		}
10006 		break;
10007 	case CMD_GEN_REQUEST64_CR:
10008 		/* For this command calculate the xmit length of the
10009 		 * request bde.
10010 		 */
10011 		xmit_len = 0;
10012 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
10013 			sizeof(struct ulp_bde64);
10014 		for (i = 0; i < numBdes; i++) {
10015 			bde.tus.w = le32_to_cpu(bpl[i].tus.w);
10016 			if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
10017 				break;
10018 			xmit_len += bde.tus.f.bdeSize;
10019 		}
10020 		/* word3 iocb=IO_TAG wqe=request_payload_len */
10021 		wqe->gen_req.request_payload_len = xmit_len;
10022 		/* word4 iocb=parameter wqe=relative_offset memcpy */
10023 		/* word5 [rctl, type, df_ctl, la] copied in memcpy */
10024 		/* word6 context tag copied in memcpy */
10025 		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
10026 			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
10027 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10028 				"2015 Invalid CT %x command 0x%x\n",
10029 				ct, iocbq->iocb.ulpCommand);
10030 			return IOCB_ERROR;
10031 		}
10032 		bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
10033 		bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
10034 		bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
10035 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
10036 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
10037 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
10038 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
10039 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
10040 		wqe->gen_req.max_response_payload_len = total_len - xmit_len;
10041 		command_type = OTHER_COMMAND;
10042 		break;
10043 	case CMD_XMIT_ELS_RSP64_CX:
10044 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
10045 		/* words0-2 BDE memcpy */
10046 		/* word3 iocb=iotag32 wqe=response_payload_len */
10047 		wqe->xmit_els_rsp.response_payload_len = xmit_len;
10048 		/* word4 */
10049 		wqe->xmit_els_rsp.word4 = 0;
10050 		/* word5 iocb=rsvd wge=did */
10051 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
10052 			 iocbq->iocb.un.xseq64.xmit_els_remoteID);
10053 
10054 		if_type = bf_get(lpfc_sli_intf_if_type,
10055 					&phba->sli4_hba.sli_intf);
10056 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10057 			if (iocbq->vport->fc_flag & FC_PT2PT) {
10058 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
10059 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
10060 					iocbq->vport->fc_myDID);
10061 				if (iocbq->vport->fc_myDID == Fabric_DID) {
10062 					bf_set(wqe_els_did,
10063 						&wqe->xmit_els_rsp.wqe_dest, 0);
10064 				}
10065 			}
10066 		}
10067 		bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
10068 		       ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
10069 		bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
10070 		bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
10071 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
10072 		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
10073 			bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
10074 			       phba->vpi_ids[iocbq->vport->vpi]);
10075 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
10076 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
10077 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
10078 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
10079 		       LPFC_WQE_LENLOC_WORD3);
10080 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
10081 		bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
10082 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
10083 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
10084 					iocbq->context2)->virt);
10085 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
10086 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
10087 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
10088 					iocbq->vport->fc_myDID);
10089 				bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
10090 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
10091 					phba->vpi_ids[phba->pport->vpi]);
10092 		}
10093 		command_type = OTHER_COMMAND;
10094 		break;
10095 	case CMD_CLOSE_XRI_CN:
10096 	case CMD_ABORT_XRI_CN:
10097 	case CMD_ABORT_XRI_CX:
10098 		/* words 0-2 memcpy should be 0 rserved */
10099 		/* port will send abts */
10100 		abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
10101 		if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
10102 			abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
10103 			fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
10104 		} else
10105 			fip = 0;
10106 
10107 		if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
10108 			/*
10109 			 * The link is down, or the command was ELS_FIP
10110 			 * so the fw does not need to send abts
10111 			 * on the wire.
10112 			 */
10113 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
10114 		else
10115 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
10116 		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
10117 		/* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
10118 		wqe->abort_cmd.rsrvd5 = 0;
10119 		bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
10120 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
10121 		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
10122 		/*
10123 		 * The abort handler will send us CMD_ABORT_XRI_CN or
10124 		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
10125 		 */
10126 		bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
10127 		bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
10128 		bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
10129 		       LPFC_WQE_LENLOC_NONE);
10130 		cmnd = CMD_ABORT_XRI_CX;
10131 		command_type = OTHER_COMMAND;
10132 		xritag = 0;
10133 		break;
10134 	case CMD_XMIT_BLS_RSP64_CX:
10135 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
10136 		/* As BLS ABTS RSP WQE is very different from other WQEs,
10137 		 * we re-construct this WQE here based on information in
10138 		 * iocbq from scratch.
10139 		 */
10140 		memset(wqe, 0, sizeof(*wqe));
10141 		/* OX_ID is invariable to who sent ABTS to CT exchange */
10142 		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
10143 		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
10144 		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
10145 		    LPFC_ABTS_UNSOL_INT) {
10146 			/* ABTS sent by initiator to CT exchange, the
10147 			 * RX_ID field will be filled with the newly
10148 			 * allocated responder XRI.
10149 			 */
10150 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10151 			       iocbq->sli4_xritag);
10152 		} else {
10153 			/* ABTS sent by responder to CT exchange, the
10154 			 * RX_ID field will be filled with the responder
10155 			 * RX_ID from ABTS.
10156 			 */
10157 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10158 			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
10159 		}
10160 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
10161 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
10162 
10163 		/* Use CT=VPI */
10164 		bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
10165 			ndlp->nlp_DID);
10166 		bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
10167 			iocbq->iocb.ulpContext);
10168 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
10169 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
10170 			phba->vpi_ids[phba->pport->vpi]);
10171 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
10172 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
10173 		       LPFC_WQE_LENLOC_NONE);
10174 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
10175 		command_type = OTHER_COMMAND;
10176 		if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
10177 			bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
10178 			       bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
10179 			bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
10180 			       bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
10181 			bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
10182 			       bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
10183 		}
10184 
10185 		break;
10186 	case CMD_SEND_FRAME:
10187 		bf_set(wqe_cmnd, &wqe->generic.wqe_com, CMD_SEND_FRAME);
10188 		bf_set(wqe_sof, &wqe->generic.wqe_com, 0x2E); /* SOF byte */
10189 		bf_set(wqe_eof, &wqe->generic.wqe_com, 0x41); /* EOF byte */
10190 		bf_set(wqe_lenloc, &wqe->generic.wqe_com, 1);
10191 		bf_set(wqe_xbl, &wqe->generic.wqe_com, 1);
10192 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10193 		bf_set(wqe_xc, &wqe->generic.wqe_com, 1);
10194 		bf_set(wqe_cmd_type, &wqe->generic.wqe_com, 0xA);
10195 		bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10196 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10197 		bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10198 		return 0;
10199 	case CMD_XRI_ABORTED_CX:
10200 	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
10201 	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
10202 	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
10203 	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
10204 	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
10205 	default:
10206 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10207 				"2014 Invalid command 0x%x\n",
10208 				iocbq->iocb.ulpCommand);
10209 		return IOCB_ERROR;
10210 	}
10211 
10212 	if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
10213 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
10214 	else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
10215 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
10216 	else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
10217 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
10218 	iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
10219 			      LPFC_IO_DIF_INSERT);
10220 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10221 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10222 	wqe->generic.wqe_com.abort_tag = abort_tag;
10223 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
10224 	bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
10225 	bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
10226 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10227 	return 0;
10228 }
10229 
10230 /**
10231  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10232  * @phba: Pointer to HBA context object.
10233  * @ring_number: SLI ring number to issue wqe on.
10234  * @piocb: Pointer to command iocb.
10235  * @flag: Flag indicating if this command can be put into txq.
10236  *
10237  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10238  * send  an iocb command to an HBA with SLI-4 interface spec.
10239  *
10240  * This function takes the hbalock before invoking the lockless version.
10241  * The function will return success after it successfully submit the wqe to
10242  * firmware or after adding to the txq.
10243  **/
10244 static int
10245 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10246 			   struct lpfc_iocbq *piocb, uint32_t flag)
10247 {
10248 	unsigned long iflags;
10249 	int rc;
10250 
10251 	spin_lock_irqsave(&phba->hbalock, iflags);
10252 	rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10253 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10254 
10255 	return rc;
10256 }
10257 
10258 /**
10259  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10260  * @phba: Pointer to HBA context object.
10261  * @ring_number: SLI ring number to issue wqe on.
10262  * @piocb: Pointer to command iocb.
10263  * @flag: Flag indicating if this command can be put into txq.
10264  *
10265  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10266  * an wqe command to an HBA with SLI-4 interface spec.
10267  *
10268  * This function is a lockless version. The function will return success
10269  * after it successfully submit the wqe to firmware or after adding to the
10270  * txq.
10271  **/
10272 static int
10273 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10274 			   struct lpfc_iocbq *piocb, uint32_t flag)
10275 {
10276 	int rc;
10277 	struct lpfc_io_buf *lpfc_cmd =
10278 		(struct lpfc_io_buf *)piocb->context1;
10279 	union lpfc_wqe128 *wqe = &piocb->wqe;
10280 	struct sli4_sge *sgl;
10281 
10282 	/* 128 byte wqe support here */
10283 	sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10284 
10285 	if (phba->fcp_embed_io) {
10286 		struct fcp_cmnd *fcp_cmnd;
10287 		u32 *ptr;
10288 
10289 		fcp_cmnd = lpfc_cmd->fcp_cmnd;
10290 
10291 		/* Word 0-2 - FCP_CMND */
10292 		wqe->generic.bde.tus.f.bdeFlags =
10293 			BUFF_TYPE_BDE_IMMED;
10294 		wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10295 		wqe->generic.bde.addrHigh = 0;
10296 		wqe->generic.bde.addrLow =  88;  /* Word 22 */
10297 
10298 		bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10299 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10300 
10301 		/* Word 22-29  FCP CMND Payload */
10302 		ptr = &wqe->words[22];
10303 		memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10304 	} else {
10305 		/* Word 0-2 - Inline BDE */
10306 		wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
10307 		wqe->generic.bde.tus.f.bdeSize = sizeof(struct fcp_cmnd);
10308 		wqe->generic.bde.addrHigh = sgl->addr_hi;
10309 		wqe->generic.bde.addrLow =  sgl->addr_lo;
10310 
10311 		/* Word 10 */
10312 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10313 		bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
10314 	}
10315 
10316 	rc = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
10317 	return rc;
10318 }
10319 
10320 /**
10321  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10322  * @phba: Pointer to HBA context object.
10323  * @ring_number: SLI ring number to issue iocb on.
10324  * @piocb: Pointer to command iocb.
10325  * @flag: Flag indicating if this command can be put into txq.
10326  *
10327  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10328  * an iocb command to an HBA with SLI-4 interface spec.
10329  *
10330  * This function is called with ringlock held. The function will return success
10331  * after it successfully submit the iocb to firmware or after adding to the
10332  * txq.
10333  **/
10334 static int
10335 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10336 			 struct lpfc_iocbq *piocb, uint32_t flag)
10337 {
10338 	struct lpfc_sglq *sglq;
10339 	union lpfc_wqe128 wqe;
10340 	struct lpfc_queue *wq;
10341 	struct lpfc_sli_ring *pring;
10342 
10343 	/* Get the WQ */
10344 	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
10345 	    (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
10346 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10347 	} else {
10348 		wq = phba->sli4_hba.els_wq;
10349 	}
10350 
10351 	/* Get corresponding ring */
10352 	pring = wq->pring;
10353 
10354 	/*
10355 	 * The WQE can be either 64 or 128 bytes,
10356 	 */
10357 
10358 	lockdep_assert_held(&pring->ring_lock);
10359 
10360 	if (piocb->sli4_xritag == NO_XRI) {
10361 		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
10362 		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
10363 			sglq = NULL;
10364 		else {
10365 			if (!list_empty(&pring->txq)) {
10366 				if (!(flag & SLI_IOCB_RET_IOCB)) {
10367 					__lpfc_sli_ringtx_put(phba,
10368 						pring, piocb);
10369 					return IOCB_SUCCESS;
10370 				} else {
10371 					return IOCB_BUSY;
10372 				}
10373 			} else {
10374 				sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10375 				if (!sglq) {
10376 					if (!(flag & SLI_IOCB_RET_IOCB)) {
10377 						__lpfc_sli_ringtx_put(phba,
10378 								pring,
10379 								piocb);
10380 						return IOCB_SUCCESS;
10381 					} else
10382 						return IOCB_BUSY;
10383 				}
10384 			}
10385 		}
10386 	} else if (piocb->iocb_flag &  LPFC_IO_FCP) {
10387 		/* These IO's already have an XRI and a mapped sgl. */
10388 		sglq = NULL;
10389 	}
10390 	else {
10391 		/*
10392 		 * This is a continuation of a commandi,(CX) so this
10393 		 * sglq is on the active list
10394 		 */
10395 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10396 		if (!sglq)
10397 			return IOCB_ERROR;
10398 	}
10399 
10400 	if (sglq) {
10401 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10402 		piocb->sli4_xritag = sglq->sli4_xritag;
10403 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
10404 			return IOCB_ERROR;
10405 	}
10406 
10407 	if (lpfc_sli4_iocb2wqe(phba, piocb, &wqe))
10408 		return IOCB_ERROR;
10409 
10410 	if (lpfc_sli4_wq_put(wq, &wqe))
10411 		return IOCB_ERROR;
10412 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10413 
10414 	return 0;
10415 }
10416 
10417 /*
10418  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
10419  *
10420  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
10421  * or IOCB for sli-3  function.
10422  * pointer from the lpfc_hba struct.
10423  *
10424  * Return codes:
10425  * IOCB_ERROR - Error
10426  * IOCB_SUCCESS - Success
10427  * IOCB_BUSY - Busy
10428  **/
10429 int
10430 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
10431 		      struct lpfc_iocbq *piocb, uint32_t flag)
10432 {
10433 	return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
10434 }
10435 
10436 /*
10437  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10438  *
10439  * This routine wraps the actual lockless version for issusing IOCB function
10440  * pointer from the lpfc_hba struct.
10441  *
10442  * Return codes:
10443  * IOCB_ERROR - Error
10444  * IOCB_SUCCESS - Success
10445  * IOCB_BUSY - Busy
10446  **/
10447 int
10448 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10449 		struct lpfc_iocbq *piocb, uint32_t flag)
10450 {
10451 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10452 }
10453 
10454 /**
10455  * lpfc_sli_api_table_setup - Set up sli api function jump table
10456  * @phba: The hba struct for which this call is being executed.
10457  * @dev_grp: The HBA PCI-Device group number.
10458  *
10459  * This routine sets up the SLI interface API function jump table in @phba
10460  * struct.
10461  * Returns: 0 - success, -ENODEV - failure.
10462  **/
10463 int
10464 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10465 {
10466 
10467 	switch (dev_grp) {
10468 	case LPFC_PCI_DEV_LP:
10469 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
10470 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
10471 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
10472 		break;
10473 	case LPFC_PCI_DEV_OC:
10474 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
10475 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
10476 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
10477 		break;
10478 	default:
10479 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10480 				"1419 Invalid HBA PCI-device group: 0x%x\n",
10481 				dev_grp);
10482 		return -ENODEV;
10483 	}
10484 	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
10485 	return 0;
10486 }
10487 
10488 /**
10489  * lpfc_sli4_calc_ring - Calculates which ring to use
10490  * @phba: Pointer to HBA context object.
10491  * @piocb: Pointer to command iocb.
10492  *
10493  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
10494  * hba_wqidx, thus we need to calculate the corresponding ring.
10495  * Since ABORTS must go on the same WQ of the command they are
10496  * aborting, we use command's hba_wqidx.
10497  */
10498 struct lpfc_sli_ring *
10499 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
10500 {
10501 	struct lpfc_io_buf *lpfc_cmd;
10502 
10503 	if (piocb->iocb_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
10504 		if (unlikely(!phba->sli4_hba.hdwq))
10505 			return NULL;
10506 		/*
10507 		 * for abort iocb hba_wqidx should already
10508 		 * be setup based on what work queue we used.
10509 		 */
10510 		if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
10511 			lpfc_cmd = (struct lpfc_io_buf *)piocb->context1;
10512 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
10513 		}
10514 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
10515 	} else {
10516 		if (unlikely(!phba->sli4_hba.els_wq))
10517 			return NULL;
10518 		piocb->hba_wqidx = 0;
10519 		return phba->sli4_hba.els_wq->pring;
10520 	}
10521 }
10522 
10523 /**
10524  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
10525  * @phba: Pointer to HBA context object.
10526  * @ring_number: Ring number
10527  * @piocb: Pointer to command iocb.
10528  * @flag: Flag indicating if this command can be put into txq.
10529  *
10530  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
10531  * function. This function gets the hbalock and calls
10532  * __lpfc_sli_issue_iocb function and will return the error returned
10533  * by __lpfc_sli_issue_iocb function. This wrapper is used by
10534  * functions which do not hold hbalock.
10535  **/
10536 int
10537 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10538 		    struct lpfc_iocbq *piocb, uint32_t flag)
10539 {
10540 	struct lpfc_sli_ring *pring;
10541 	struct lpfc_queue *eq;
10542 	unsigned long iflags;
10543 	int rc;
10544 
10545 	if (phba->sli_rev == LPFC_SLI_REV4) {
10546 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
10547 
10548 		pring = lpfc_sli4_calc_ring(phba, piocb);
10549 		if (unlikely(pring == NULL))
10550 			return IOCB_ERROR;
10551 
10552 		spin_lock_irqsave(&pring->ring_lock, iflags);
10553 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10554 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
10555 
10556 		lpfc_sli4_poll_eq(eq, LPFC_POLL_FASTPATH);
10557 	} else {
10558 		/* For now, SLI2/3 will still use hbalock */
10559 		spin_lock_irqsave(&phba->hbalock, iflags);
10560 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10561 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10562 	}
10563 	return rc;
10564 }
10565 
10566 /**
10567  * lpfc_extra_ring_setup - Extra ring setup function
10568  * @phba: Pointer to HBA context object.
10569  *
10570  * This function is called while driver attaches with the
10571  * HBA to setup the extra ring. The extra ring is used
10572  * only when driver needs to support target mode functionality
10573  * or IP over FC functionalities.
10574  *
10575  * This function is called with no lock held. SLI3 only.
10576  **/
10577 static int
10578 lpfc_extra_ring_setup( struct lpfc_hba *phba)
10579 {
10580 	struct lpfc_sli *psli;
10581 	struct lpfc_sli_ring *pring;
10582 
10583 	psli = &phba->sli;
10584 
10585 	/* Adjust cmd/rsp ring iocb entries more evenly */
10586 
10587 	/* Take some away from the FCP ring */
10588 	pring = &psli->sli3_ring[LPFC_FCP_RING];
10589 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10590 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10591 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10592 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10593 
10594 	/* and give them to the extra ring */
10595 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
10596 
10597 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10598 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10599 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10600 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10601 
10602 	/* Setup default profile for this ring */
10603 	pring->iotag_max = 4096;
10604 	pring->num_mask = 1;
10605 	pring->prt[0].profile = 0;      /* Mask 0 */
10606 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
10607 	pring->prt[0].type = phba->cfg_multi_ring_type;
10608 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
10609 	return 0;
10610 }
10611 
10612 static void
10613 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
10614 			     struct lpfc_nodelist *ndlp)
10615 {
10616 	unsigned long iflags;
10617 	struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
10618 
10619 	spin_lock_irqsave(&phba->hbalock, iflags);
10620 	if (!list_empty(&evtp->evt_listp)) {
10621 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10622 		return;
10623 	}
10624 
10625 	/* Incrementing the reference count until the queued work is done. */
10626 	evtp->evt_arg1  = lpfc_nlp_get(ndlp);
10627 	if (!evtp->evt_arg1) {
10628 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10629 		return;
10630 	}
10631 	evtp->evt = LPFC_EVT_RECOVER_PORT;
10632 	list_add_tail(&evtp->evt_listp, &phba->work_list);
10633 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10634 
10635 	lpfc_worker_wake_up(phba);
10636 }
10637 
10638 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
10639  * @phba: Pointer to HBA context object.
10640  * @iocbq: Pointer to iocb object.
10641  *
10642  * The async_event handler calls this routine when it receives
10643  * an ASYNC_STATUS_CN event from the port.  The port generates
10644  * this event when an Abort Sequence request to an rport fails
10645  * twice in succession.  The abort could be originated by the
10646  * driver or by the port.  The ABTS could have been for an ELS
10647  * or FCP IO.  The port only generates this event when an ABTS
10648  * fails to complete after one retry.
10649  */
10650 static void
10651 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
10652 			  struct lpfc_iocbq *iocbq)
10653 {
10654 	struct lpfc_nodelist *ndlp = NULL;
10655 	uint16_t rpi = 0, vpi = 0;
10656 	struct lpfc_vport *vport = NULL;
10657 
10658 	/* The rpi in the ulpContext is vport-sensitive. */
10659 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
10660 	rpi = iocbq->iocb.ulpContext;
10661 
10662 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10663 			"3092 Port generated ABTS async event "
10664 			"on vpi %d rpi %d status 0x%x\n",
10665 			vpi, rpi, iocbq->iocb.ulpStatus);
10666 
10667 	vport = lpfc_find_vport_by_vpid(phba, vpi);
10668 	if (!vport)
10669 		goto err_exit;
10670 	ndlp = lpfc_findnode_rpi(vport, rpi);
10671 	if (!ndlp)
10672 		goto err_exit;
10673 
10674 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
10675 		lpfc_sli_abts_recover_port(vport, ndlp);
10676 	return;
10677 
10678  err_exit:
10679 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10680 			"3095 Event Context not found, no "
10681 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
10682 			iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
10683 			vpi, rpi);
10684 }
10685 
10686 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
10687  * @phba: pointer to HBA context object.
10688  * @ndlp: nodelist pointer for the impacted rport.
10689  * @axri: pointer to the wcqe containing the failed exchange.
10690  *
10691  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
10692  * port.  The port generates this event when an abort exchange request to an
10693  * rport fails twice in succession with no reply.  The abort could be originated
10694  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
10695  */
10696 void
10697 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
10698 			   struct lpfc_nodelist *ndlp,
10699 			   struct sli4_wcqe_xri_aborted *axri)
10700 {
10701 	uint32_t ext_status = 0;
10702 
10703 	if (!ndlp) {
10704 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10705 				"3115 Node Context not found, driver "
10706 				"ignoring abts err event\n");
10707 		return;
10708 	}
10709 
10710 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10711 			"3116 Port generated FCP XRI ABORT event on "
10712 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
10713 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
10714 			bf_get(lpfc_wcqe_xa_xri, axri),
10715 			bf_get(lpfc_wcqe_xa_status, axri),
10716 			axri->parameter);
10717 
10718 	/*
10719 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
10720 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
10721 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
10722 	 */
10723 	ext_status = axri->parameter & IOERR_PARAM_MASK;
10724 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
10725 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
10726 		lpfc_sli_post_recovery_event(phba, ndlp);
10727 }
10728 
10729 /**
10730  * lpfc_sli_async_event_handler - ASYNC iocb handler function
10731  * @phba: Pointer to HBA context object.
10732  * @pring: Pointer to driver SLI ring object.
10733  * @iocbq: Pointer to iocb object.
10734  *
10735  * This function is called by the slow ring event handler
10736  * function when there is an ASYNC event iocb in the ring.
10737  * This function is called with no lock held.
10738  * Currently this function handles only temperature related
10739  * ASYNC events. The function decodes the temperature sensor
10740  * event message and posts events for the management applications.
10741  **/
10742 static void
10743 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
10744 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
10745 {
10746 	IOCB_t *icmd;
10747 	uint16_t evt_code;
10748 	struct temp_event temp_event_data;
10749 	struct Scsi_Host *shost;
10750 	uint32_t *iocb_w;
10751 
10752 	icmd = &iocbq->iocb;
10753 	evt_code = icmd->un.asyncstat.evt_code;
10754 
10755 	switch (evt_code) {
10756 	case ASYNC_TEMP_WARN:
10757 	case ASYNC_TEMP_SAFE:
10758 		temp_event_data.data = (uint32_t) icmd->ulpContext;
10759 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
10760 		if (evt_code == ASYNC_TEMP_WARN) {
10761 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
10762 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10763 				"0347 Adapter is very hot, please take "
10764 				"corrective action. temperature : %d Celsius\n",
10765 				(uint32_t) icmd->ulpContext);
10766 		} else {
10767 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
10768 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10769 				"0340 Adapter temperature is OK now. "
10770 				"temperature : %d Celsius\n",
10771 				(uint32_t) icmd->ulpContext);
10772 		}
10773 
10774 		/* Send temperature change event to applications */
10775 		shost = lpfc_shost_from_vport(phba->pport);
10776 		fc_host_post_vendor_event(shost, fc_get_event_number(),
10777 			sizeof(temp_event_data), (char *) &temp_event_data,
10778 			LPFC_NL_VENDOR_ID);
10779 		break;
10780 	case ASYNC_STATUS_CN:
10781 		lpfc_sli_abts_err_handler(phba, iocbq);
10782 		break;
10783 	default:
10784 		iocb_w = (uint32_t *) icmd;
10785 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10786 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
10787 			" evt_code 0x%x\n"
10788 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
10789 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
10790 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
10791 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
10792 			pring->ringno, icmd->un.asyncstat.evt_code,
10793 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
10794 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
10795 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
10796 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
10797 
10798 		break;
10799 	}
10800 }
10801 
10802 
10803 /**
10804  * lpfc_sli4_setup - SLI ring setup function
10805  * @phba: Pointer to HBA context object.
10806  *
10807  * lpfc_sli_setup sets up rings of the SLI interface with
10808  * number of iocbs per ring and iotags. This function is
10809  * called while driver attach to the HBA and before the
10810  * interrupts are enabled. So there is no need for locking.
10811  *
10812  * This function always returns 0.
10813  **/
10814 int
10815 lpfc_sli4_setup(struct lpfc_hba *phba)
10816 {
10817 	struct lpfc_sli_ring *pring;
10818 
10819 	pring = phba->sli4_hba.els_wq->pring;
10820 	pring->num_mask = LPFC_MAX_RING_MASK;
10821 	pring->prt[0].profile = 0;	/* Mask 0 */
10822 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10823 	pring->prt[0].type = FC_TYPE_ELS;
10824 	pring->prt[0].lpfc_sli_rcv_unsol_event =
10825 	    lpfc_els_unsol_event;
10826 	pring->prt[1].profile = 0;	/* Mask 1 */
10827 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
10828 	pring->prt[1].type = FC_TYPE_ELS;
10829 	pring->prt[1].lpfc_sli_rcv_unsol_event =
10830 	    lpfc_els_unsol_event;
10831 	pring->prt[2].profile = 0;	/* Mask 2 */
10832 	/* NameServer Inquiry */
10833 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10834 	/* NameServer */
10835 	pring->prt[2].type = FC_TYPE_CT;
10836 	pring->prt[2].lpfc_sli_rcv_unsol_event =
10837 	    lpfc_ct_unsol_event;
10838 	pring->prt[3].profile = 0;	/* Mask 3 */
10839 	/* NameServer response */
10840 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10841 	/* NameServer */
10842 	pring->prt[3].type = FC_TYPE_CT;
10843 	pring->prt[3].lpfc_sli_rcv_unsol_event =
10844 	    lpfc_ct_unsol_event;
10845 	return 0;
10846 }
10847 
10848 /**
10849  * lpfc_sli_setup - SLI ring setup function
10850  * @phba: Pointer to HBA context object.
10851  *
10852  * lpfc_sli_setup sets up rings of the SLI interface with
10853  * number of iocbs per ring and iotags. This function is
10854  * called while driver attach to the HBA and before the
10855  * interrupts are enabled. So there is no need for locking.
10856  *
10857  * This function always returns 0. SLI3 only.
10858  **/
10859 int
10860 lpfc_sli_setup(struct lpfc_hba *phba)
10861 {
10862 	int i, totiocbsize = 0;
10863 	struct lpfc_sli *psli = &phba->sli;
10864 	struct lpfc_sli_ring *pring;
10865 
10866 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
10867 	psli->sli_flag = 0;
10868 
10869 	psli->iocbq_lookup = NULL;
10870 	psli->iocbq_lookup_len = 0;
10871 	psli->last_iotag = 0;
10872 
10873 	for (i = 0; i < psli->num_rings; i++) {
10874 		pring = &psli->sli3_ring[i];
10875 		switch (i) {
10876 		case LPFC_FCP_RING:	/* ring 0 - FCP */
10877 			/* numCiocb and numRiocb are used in config_port */
10878 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
10879 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
10880 			pring->sli.sli3.numCiocb +=
10881 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10882 			pring->sli.sli3.numRiocb +=
10883 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10884 			pring->sli.sli3.numCiocb +=
10885 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10886 			pring->sli.sli3.numRiocb +=
10887 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10888 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10889 							SLI3_IOCB_CMD_SIZE :
10890 							SLI2_IOCB_CMD_SIZE;
10891 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10892 							SLI3_IOCB_RSP_SIZE :
10893 							SLI2_IOCB_RSP_SIZE;
10894 			pring->iotag_ctr = 0;
10895 			pring->iotag_max =
10896 			    (phba->cfg_hba_queue_depth * 2);
10897 			pring->fast_iotag = pring->iotag_max;
10898 			pring->num_mask = 0;
10899 			break;
10900 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
10901 			/* numCiocb and numRiocb are used in config_port */
10902 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
10903 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
10904 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10905 							SLI3_IOCB_CMD_SIZE :
10906 							SLI2_IOCB_CMD_SIZE;
10907 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10908 							SLI3_IOCB_RSP_SIZE :
10909 							SLI2_IOCB_RSP_SIZE;
10910 			pring->iotag_max = phba->cfg_hba_queue_depth;
10911 			pring->num_mask = 0;
10912 			break;
10913 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
10914 			/* numCiocb and numRiocb are used in config_port */
10915 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
10916 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
10917 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10918 							SLI3_IOCB_CMD_SIZE :
10919 							SLI2_IOCB_CMD_SIZE;
10920 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10921 							SLI3_IOCB_RSP_SIZE :
10922 							SLI2_IOCB_RSP_SIZE;
10923 			pring->fast_iotag = 0;
10924 			pring->iotag_ctr = 0;
10925 			pring->iotag_max = 4096;
10926 			pring->lpfc_sli_rcv_async_status =
10927 				lpfc_sli_async_event_handler;
10928 			pring->num_mask = LPFC_MAX_RING_MASK;
10929 			pring->prt[0].profile = 0;	/* Mask 0 */
10930 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10931 			pring->prt[0].type = FC_TYPE_ELS;
10932 			pring->prt[0].lpfc_sli_rcv_unsol_event =
10933 			    lpfc_els_unsol_event;
10934 			pring->prt[1].profile = 0;	/* Mask 1 */
10935 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
10936 			pring->prt[1].type = FC_TYPE_ELS;
10937 			pring->prt[1].lpfc_sli_rcv_unsol_event =
10938 			    lpfc_els_unsol_event;
10939 			pring->prt[2].profile = 0;	/* Mask 2 */
10940 			/* NameServer Inquiry */
10941 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10942 			/* NameServer */
10943 			pring->prt[2].type = FC_TYPE_CT;
10944 			pring->prt[2].lpfc_sli_rcv_unsol_event =
10945 			    lpfc_ct_unsol_event;
10946 			pring->prt[3].profile = 0;	/* Mask 3 */
10947 			/* NameServer response */
10948 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10949 			/* NameServer */
10950 			pring->prt[3].type = FC_TYPE_CT;
10951 			pring->prt[3].lpfc_sli_rcv_unsol_event =
10952 			    lpfc_ct_unsol_event;
10953 			break;
10954 		}
10955 		totiocbsize += (pring->sli.sli3.numCiocb *
10956 			pring->sli.sli3.sizeCiocb) +
10957 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
10958 	}
10959 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
10960 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
10961 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
10962 		       "SLI2 SLIM Data: x%x x%lx\n",
10963 		       phba->brd_no, totiocbsize,
10964 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
10965 	}
10966 	if (phba->cfg_multi_ring_support == 2)
10967 		lpfc_extra_ring_setup(phba);
10968 
10969 	return 0;
10970 }
10971 
10972 /**
10973  * lpfc_sli4_queue_init - Queue initialization function
10974  * @phba: Pointer to HBA context object.
10975  *
10976  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
10977  * ring. This function also initializes ring indices of each ring.
10978  * This function is called during the initialization of the SLI
10979  * interface of an HBA.
10980  * This function is called with no lock held and always returns
10981  * 1.
10982  **/
10983 void
10984 lpfc_sli4_queue_init(struct lpfc_hba *phba)
10985 {
10986 	struct lpfc_sli *psli;
10987 	struct lpfc_sli_ring *pring;
10988 	int i;
10989 
10990 	psli = &phba->sli;
10991 	spin_lock_irq(&phba->hbalock);
10992 	INIT_LIST_HEAD(&psli->mboxq);
10993 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
10994 	/* Initialize list headers for txq and txcmplq as double linked lists */
10995 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
10996 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
10997 		pring->flag = 0;
10998 		pring->ringno = LPFC_FCP_RING;
10999 		pring->txcmplq_cnt = 0;
11000 		INIT_LIST_HEAD(&pring->txq);
11001 		INIT_LIST_HEAD(&pring->txcmplq);
11002 		INIT_LIST_HEAD(&pring->iocb_continueq);
11003 		spin_lock_init(&pring->ring_lock);
11004 	}
11005 	pring = phba->sli4_hba.els_wq->pring;
11006 	pring->flag = 0;
11007 	pring->ringno = LPFC_ELS_RING;
11008 	pring->txcmplq_cnt = 0;
11009 	INIT_LIST_HEAD(&pring->txq);
11010 	INIT_LIST_HEAD(&pring->txcmplq);
11011 	INIT_LIST_HEAD(&pring->iocb_continueq);
11012 	spin_lock_init(&pring->ring_lock);
11013 
11014 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11015 		pring = phba->sli4_hba.nvmels_wq->pring;
11016 		pring->flag = 0;
11017 		pring->ringno = LPFC_ELS_RING;
11018 		pring->txcmplq_cnt = 0;
11019 		INIT_LIST_HEAD(&pring->txq);
11020 		INIT_LIST_HEAD(&pring->txcmplq);
11021 		INIT_LIST_HEAD(&pring->iocb_continueq);
11022 		spin_lock_init(&pring->ring_lock);
11023 	}
11024 
11025 	spin_unlock_irq(&phba->hbalock);
11026 }
11027 
11028 /**
11029  * lpfc_sli_queue_init - Queue initialization function
11030  * @phba: Pointer to HBA context object.
11031  *
11032  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11033  * ring. This function also initializes ring indices of each ring.
11034  * This function is called during the initialization of the SLI
11035  * interface of an HBA.
11036  * This function is called with no lock held and always returns
11037  * 1.
11038  **/
11039 void
11040 lpfc_sli_queue_init(struct lpfc_hba *phba)
11041 {
11042 	struct lpfc_sli *psli;
11043 	struct lpfc_sli_ring *pring;
11044 	int i;
11045 
11046 	psli = &phba->sli;
11047 	spin_lock_irq(&phba->hbalock);
11048 	INIT_LIST_HEAD(&psli->mboxq);
11049 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11050 	/* Initialize list headers for txq and txcmplq as double linked lists */
11051 	for (i = 0; i < psli->num_rings; i++) {
11052 		pring = &psli->sli3_ring[i];
11053 		pring->ringno = i;
11054 		pring->sli.sli3.next_cmdidx  = 0;
11055 		pring->sli.sli3.local_getidx = 0;
11056 		pring->sli.sli3.cmdidx = 0;
11057 		INIT_LIST_HEAD(&pring->iocb_continueq);
11058 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11059 		INIT_LIST_HEAD(&pring->postbufq);
11060 		pring->flag = 0;
11061 		INIT_LIST_HEAD(&pring->txq);
11062 		INIT_LIST_HEAD(&pring->txcmplq);
11063 		spin_lock_init(&pring->ring_lock);
11064 	}
11065 	spin_unlock_irq(&phba->hbalock);
11066 }
11067 
11068 /**
11069  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11070  * @phba: Pointer to HBA context object.
11071  *
11072  * This routine flushes the mailbox command subsystem. It will unconditionally
11073  * flush all the mailbox commands in the three possible stages in the mailbox
11074  * command sub-system: pending mailbox command queue; the outstanding mailbox
11075  * command; and completed mailbox command queue. It is caller's responsibility
11076  * to make sure that the driver is in the proper state to flush the mailbox
11077  * command sub-system. Namely, the posting of mailbox commands into the
11078  * pending mailbox command queue from the various clients must be stopped;
11079  * either the HBA is in a state that it will never works on the outstanding
11080  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11081  * mailbox command has been completed.
11082  **/
11083 static void
11084 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11085 {
11086 	LIST_HEAD(completions);
11087 	struct lpfc_sli *psli = &phba->sli;
11088 	LPFC_MBOXQ_t *pmb;
11089 	unsigned long iflag;
11090 
11091 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11092 	local_bh_disable();
11093 
11094 	/* Flush all the mailbox commands in the mbox system */
11095 	spin_lock_irqsave(&phba->hbalock, iflag);
11096 
11097 	/* The pending mailbox command queue */
11098 	list_splice_init(&phba->sli.mboxq, &completions);
11099 	/* The outstanding active mailbox command */
11100 	if (psli->mbox_active) {
11101 		list_add_tail(&psli->mbox_active->list, &completions);
11102 		psli->mbox_active = NULL;
11103 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11104 	}
11105 	/* The completed mailbox command queue */
11106 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11107 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11108 
11109 	/* Enable softirqs again, done with phba->hbalock */
11110 	local_bh_enable();
11111 
11112 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11113 	while (!list_empty(&completions)) {
11114 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11115 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11116 		if (pmb->mbox_cmpl)
11117 			pmb->mbox_cmpl(phba, pmb);
11118 	}
11119 }
11120 
11121 /**
11122  * lpfc_sli_host_down - Vport cleanup function
11123  * @vport: Pointer to virtual port object.
11124  *
11125  * lpfc_sli_host_down is called to clean up the resources
11126  * associated with a vport before destroying virtual
11127  * port data structures.
11128  * This function does following operations:
11129  * - Free discovery resources associated with this virtual
11130  *   port.
11131  * - Free iocbs associated with this virtual port in
11132  *   the txq.
11133  * - Send abort for all iocb commands associated with this
11134  *   vport in txcmplq.
11135  *
11136  * This function is called with no lock held and always returns 1.
11137  **/
11138 int
11139 lpfc_sli_host_down(struct lpfc_vport *vport)
11140 {
11141 	LIST_HEAD(completions);
11142 	struct lpfc_hba *phba = vport->phba;
11143 	struct lpfc_sli *psli = &phba->sli;
11144 	struct lpfc_queue *qp = NULL;
11145 	struct lpfc_sli_ring *pring;
11146 	struct lpfc_iocbq *iocb, *next_iocb;
11147 	int i;
11148 	unsigned long flags = 0;
11149 	uint16_t prev_pring_flag;
11150 
11151 	lpfc_cleanup_discovery_resources(vport);
11152 
11153 	spin_lock_irqsave(&phba->hbalock, flags);
11154 
11155 	/*
11156 	 * Error everything on the txq since these iocbs
11157 	 * have not been given to the FW yet.
11158 	 * Also issue ABTS for everything on the txcmplq
11159 	 */
11160 	if (phba->sli_rev != LPFC_SLI_REV4) {
11161 		for (i = 0; i < psli->num_rings; i++) {
11162 			pring = &psli->sli3_ring[i];
11163 			prev_pring_flag = pring->flag;
11164 			/* Only slow rings */
11165 			if (pring->ringno == LPFC_ELS_RING) {
11166 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11167 				/* Set the lpfc data pending flag */
11168 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11169 			}
11170 			list_for_each_entry_safe(iocb, next_iocb,
11171 						 &pring->txq, list) {
11172 				if (iocb->vport != vport)
11173 					continue;
11174 				list_move_tail(&iocb->list, &completions);
11175 			}
11176 			list_for_each_entry_safe(iocb, next_iocb,
11177 						 &pring->txcmplq, list) {
11178 				if (iocb->vport != vport)
11179 					continue;
11180 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11181 							   NULL);
11182 			}
11183 			pring->flag = prev_pring_flag;
11184 		}
11185 	} else {
11186 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11187 			pring = qp->pring;
11188 			if (!pring)
11189 				continue;
11190 			if (pring == phba->sli4_hba.els_wq->pring) {
11191 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11192 				/* Set the lpfc data pending flag */
11193 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11194 			}
11195 			prev_pring_flag = pring->flag;
11196 			spin_lock(&pring->ring_lock);
11197 			list_for_each_entry_safe(iocb, next_iocb,
11198 						 &pring->txq, list) {
11199 				if (iocb->vport != vport)
11200 					continue;
11201 				list_move_tail(&iocb->list, &completions);
11202 			}
11203 			spin_unlock(&pring->ring_lock);
11204 			list_for_each_entry_safe(iocb, next_iocb,
11205 						 &pring->txcmplq, list) {
11206 				if (iocb->vport != vport)
11207 					continue;
11208 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11209 							   NULL);
11210 			}
11211 			pring->flag = prev_pring_flag;
11212 		}
11213 	}
11214 	spin_unlock_irqrestore(&phba->hbalock, flags);
11215 
11216 	/* Make sure HBA is alive */
11217 	lpfc_issue_hb_tmo(phba);
11218 
11219 	/* Cancel all the IOCBs from the completions list */
11220 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11221 			      IOERR_SLI_DOWN);
11222 	return 1;
11223 }
11224 
11225 /**
11226  * lpfc_sli_hba_down - Resource cleanup function for the HBA
11227  * @phba: Pointer to HBA context object.
11228  *
11229  * This function cleans up all iocb, buffers, mailbox commands
11230  * while shutting down the HBA. This function is called with no
11231  * lock held and always returns 1.
11232  * This function does the following to cleanup driver resources:
11233  * - Free discovery resources for each virtual port
11234  * - Cleanup any pending fabric iocbs
11235  * - Iterate through the iocb txq and free each entry
11236  *   in the list.
11237  * - Free up any buffer posted to the HBA
11238  * - Free mailbox commands in the mailbox queue.
11239  **/
11240 int
11241 lpfc_sli_hba_down(struct lpfc_hba *phba)
11242 {
11243 	LIST_HEAD(completions);
11244 	struct lpfc_sli *psli = &phba->sli;
11245 	struct lpfc_queue *qp = NULL;
11246 	struct lpfc_sli_ring *pring;
11247 	struct lpfc_dmabuf *buf_ptr;
11248 	unsigned long flags = 0;
11249 	int i;
11250 
11251 	/* Shutdown the mailbox command sub-system */
11252 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
11253 
11254 	lpfc_hba_down_prep(phba);
11255 
11256 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11257 	local_bh_disable();
11258 
11259 	lpfc_fabric_abort_hba(phba);
11260 
11261 	spin_lock_irqsave(&phba->hbalock, flags);
11262 
11263 	/*
11264 	 * Error everything on the txq since these iocbs
11265 	 * have not been given to the FW yet.
11266 	 */
11267 	if (phba->sli_rev != LPFC_SLI_REV4) {
11268 		for (i = 0; i < psli->num_rings; i++) {
11269 			pring = &psli->sli3_ring[i];
11270 			/* Only slow rings */
11271 			if (pring->ringno == LPFC_ELS_RING) {
11272 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11273 				/* Set the lpfc data pending flag */
11274 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11275 			}
11276 			list_splice_init(&pring->txq, &completions);
11277 		}
11278 	} else {
11279 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11280 			pring = qp->pring;
11281 			if (!pring)
11282 				continue;
11283 			spin_lock(&pring->ring_lock);
11284 			list_splice_init(&pring->txq, &completions);
11285 			spin_unlock(&pring->ring_lock);
11286 			if (pring == phba->sli4_hba.els_wq->pring) {
11287 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11288 				/* Set the lpfc data pending flag */
11289 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11290 			}
11291 		}
11292 	}
11293 	spin_unlock_irqrestore(&phba->hbalock, flags);
11294 
11295 	/* Cancel all the IOCBs from the completions list */
11296 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11297 			      IOERR_SLI_DOWN);
11298 
11299 	spin_lock_irqsave(&phba->hbalock, flags);
11300 	list_splice_init(&phba->elsbuf, &completions);
11301 	phba->elsbuf_cnt = 0;
11302 	phba->elsbuf_prev_cnt = 0;
11303 	spin_unlock_irqrestore(&phba->hbalock, flags);
11304 
11305 	while (!list_empty(&completions)) {
11306 		list_remove_head(&completions, buf_ptr,
11307 			struct lpfc_dmabuf, list);
11308 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
11309 		kfree(buf_ptr);
11310 	}
11311 
11312 	/* Enable softirqs again, done with phba->hbalock */
11313 	local_bh_enable();
11314 
11315 	/* Return any active mbox cmds */
11316 	del_timer_sync(&psli->mbox_tmo);
11317 
11318 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
11319 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
11320 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
11321 
11322 	return 1;
11323 }
11324 
11325 /**
11326  * lpfc_sli_pcimem_bcopy - SLI memory copy function
11327  * @srcp: Source memory pointer.
11328  * @destp: Destination memory pointer.
11329  * @cnt: Number of words required to be copied.
11330  *
11331  * This function is used for copying data between driver memory
11332  * and the SLI memory. This function also changes the endianness
11333  * of each word if native endianness is different from SLI
11334  * endianness. This function can be called with or without
11335  * lock.
11336  **/
11337 void
11338 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
11339 {
11340 	uint32_t *src = srcp;
11341 	uint32_t *dest = destp;
11342 	uint32_t ldata;
11343 	int i;
11344 
11345 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
11346 		ldata = *src;
11347 		ldata = le32_to_cpu(ldata);
11348 		*dest = ldata;
11349 		src++;
11350 		dest++;
11351 	}
11352 }
11353 
11354 
11355 /**
11356  * lpfc_sli_bemem_bcopy - SLI memory copy function
11357  * @srcp: Source memory pointer.
11358  * @destp: Destination memory pointer.
11359  * @cnt: Number of words required to be copied.
11360  *
11361  * This function is used for copying data between a data structure
11362  * with big endian representation to local endianness.
11363  * This function can be called with or without lock.
11364  **/
11365 void
11366 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
11367 {
11368 	uint32_t *src = srcp;
11369 	uint32_t *dest = destp;
11370 	uint32_t ldata;
11371 	int i;
11372 
11373 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
11374 		ldata = *src;
11375 		ldata = be32_to_cpu(ldata);
11376 		*dest = ldata;
11377 		src++;
11378 		dest++;
11379 	}
11380 }
11381 
11382 /**
11383  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
11384  * @phba: Pointer to HBA context object.
11385  * @pring: Pointer to driver SLI ring object.
11386  * @mp: Pointer to driver buffer object.
11387  *
11388  * This function is called with no lock held.
11389  * It always return zero after adding the buffer to the postbufq
11390  * buffer list.
11391  **/
11392 int
11393 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11394 			 struct lpfc_dmabuf *mp)
11395 {
11396 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
11397 	   later */
11398 	spin_lock_irq(&phba->hbalock);
11399 	list_add_tail(&mp->list, &pring->postbufq);
11400 	pring->postbufq_cnt++;
11401 	spin_unlock_irq(&phba->hbalock);
11402 	return 0;
11403 }
11404 
11405 /**
11406  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
11407  * @phba: Pointer to HBA context object.
11408  *
11409  * When HBQ is enabled, buffers are searched based on tags. This function
11410  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
11411  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
11412  * does not conflict with tags of buffer posted for unsolicited events.
11413  * The function returns the allocated tag. The function is called with
11414  * no locks held.
11415  **/
11416 uint32_t
11417 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
11418 {
11419 	spin_lock_irq(&phba->hbalock);
11420 	phba->buffer_tag_count++;
11421 	/*
11422 	 * Always set the QUE_BUFTAG_BIT to distiguish between
11423 	 * a tag assigned by HBQ.
11424 	 */
11425 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
11426 	spin_unlock_irq(&phba->hbalock);
11427 	return phba->buffer_tag_count;
11428 }
11429 
11430 /**
11431  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
11432  * @phba: Pointer to HBA context object.
11433  * @pring: Pointer to driver SLI ring object.
11434  * @tag: Buffer tag.
11435  *
11436  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
11437  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
11438  * iocb is posted to the response ring with the tag of the buffer.
11439  * This function searches the pring->postbufq list using the tag
11440  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
11441  * iocb. If the buffer is found then lpfc_dmabuf object of the
11442  * buffer is returned to the caller else NULL is returned.
11443  * This function is called with no lock held.
11444  **/
11445 struct lpfc_dmabuf *
11446 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11447 			uint32_t tag)
11448 {
11449 	struct lpfc_dmabuf *mp, *next_mp;
11450 	struct list_head *slp = &pring->postbufq;
11451 
11452 	/* Search postbufq, from the beginning, looking for a match on tag */
11453 	spin_lock_irq(&phba->hbalock);
11454 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11455 		if (mp->buffer_tag == tag) {
11456 			list_del_init(&mp->list);
11457 			pring->postbufq_cnt--;
11458 			spin_unlock_irq(&phba->hbalock);
11459 			return mp;
11460 		}
11461 	}
11462 
11463 	spin_unlock_irq(&phba->hbalock);
11464 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11465 			"0402 Cannot find virtual addr for buffer tag on "
11466 			"ring %d Data x%lx x%px x%px x%x\n",
11467 			pring->ringno, (unsigned long) tag,
11468 			slp->next, slp->prev, pring->postbufq_cnt);
11469 
11470 	return NULL;
11471 }
11472 
11473 /**
11474  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
11475  * @phba: Pointer to HBA context object.
11476  * @pring: Pointer to driver SLI ring object.
11477  * @phys: DMA address of the buffer.
11478  *
11479  * This function searches the buffer list using the dma_address
11480  * of unsolicited event to find the driver's lpfc_dmabuf object
11481  * corresponding to the dma_address. The function returns the
11482  * lpfc_dmabuf object if a buffer is found else it returns NULL.
11483  * This function is called by the ct and els unsolicited event
11484  * handlers to get the buffer associated with the unsolicited
11485  * event.
11486  *
11487  * This function is called with no lock held.
11488  **/
11489 struct lpfc_dmabuf *
11490 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11491 			 dma_addr_t phys)
11492 {
11493 	struct lpfc_dmabuf *mp, *next_mp;
11494 	struct list_head *slp = &pring->postbufq;
11495 
11496 	/* Search postbufq, from the beginning, looking for a match on phys */
11497 	spin_lock_irq(&phba->hbalock);
11498 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11499 		if (mp->phys == phys) {
11500 			list_del_init(&mp->list);
11501 			pring->postbufq_cnt--;
11502 			spin_unlock_irq(&phba->hbalock);
11503 			return mp;
11504 		}
11505 	}
11506 
11507 	spin_unlock_irq(&phba->hbalock);
11508 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11509 			"0410 Cannot find virtual addr for mapped buf on "
11510 			"ring %d Data x%llx x%px x%px x%x\n",
11511 			pring->ringno, (unsigned long long)phys,
11512 			slp->next, slp->prev, pring->postbufq_cnt);
11513 	return NULL;
11514 }
11515 
11516 /**
11517  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
11518  * @phba: Pointer to HBA context object.
11519  * @cmdiocb: Pointer to driver command iocb object.
11520  * @rspiocb: Pointer to driver response iocb object.
11521  *
11522  * This function is the completion handler for the abort iocbs for
11523  * ELS commands. This function is called from the ELS ring event
11524  * handler with no lock held. This function frees memory resources
11525  * associated with the abort iocb.
11526  **/
11527 static void
11528 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11529 			struct lpfc_iocbq *rspiocb)
11530 {
11531 	IOCB_t *irsp = &rspiocb->iocb;
11532 	uint16_t abort_iotag, abort_context;
11533 	struct lpfc_iocbq *abort_iocb = NULL;
11534 
11535 	if (irsp->ulpStatus) {
11536 
11537 		/*
11538 		 * Assume that the port already completed and returned, or
11539 		 * will return the iocb. Just Log the message.
11540 		 */
11541 		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
11542 		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
11543 
11544 		spin_lock_irq(&phba->hbalock);
11545 		if (phba->sli_rev < LPFC_SLI_REV4) {
11546 			if (irsp->ulpCommand == CMD_ABORT_XRI_CX &&
11547 			    irsp->ulpStatus == IOSTAT_LOCAL_REJECT &&
11548 			    irsp->un.ulpWord[4] == IOERR_ABORT_REQUESTED) {
11549 				spin_unlock_irq(&phba->hbalock);
11550 				goto release_iocb;
11551 			}
11552 			if (abort_iotag != 0 &&
11553 				abort_iotag <= phba->sli.last_iotag)
11554 				abort_iocb =
11555 					phba->sli.iocbq_lookup[abort_iotag];
11556 		} else
11557 			/* For sli4 the abort_tag is the XRI,
11558 			 * so the abort routine puts the iotag  of the iocb
11559 			 * being aborted in the context field of the abort
11560 			 * IOCB.
11561 			 */
11562 			abort_iocb = phba->sli.iocbq_lookup[abort_context];
11563 
11564 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
11565 				"0327 Cannot abort els iocb x%px "
11566 				"with tag %x context %x, abort status %x, "
11567 				"abort code %x\n",
11568 				abort_iocb, abort_iotag, abort_context,
11569 				irsp->ulpStatus, irsp->un.ulpWord[4]);
11570 
11571 		spin_unlock_irq(&phba->hbalock);
11572 	}
11573 release_iocb:
11574 	lpfc_sli_release_iocbq(phba, cmdiocb);
11575 	return;
11576 }
11577 
11578 /**
11579  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
11580  * @phba: Pointer to HBA context object.
11581  * @cmdiocb: Pointer to driver command iocb object.
11582  * @rspiocb: Pointer to driver response iocb object.
11583  *
11584  * The function is called from SLI ring event handler with no
11585  * lock held. This function is the completion handler for ELS commands
11586  * which are aborted. The function frees memory resources used for
11587  * the aborted ELS commands.
11588  **/
11589 void
11590 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11591 		     struct lpfc_iocbq *rspiocb)
11592 {
11593 	IOCB_t *irsp = &rspiocb->iocb;
11594 
11595 	/* ELS cmd tag <ulpIoTag> completes */
11596 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
11597 			"0139 Ignoring ELS cmd tag x%x completion Data: "
11598 			"x%x x%x x%x\n",
11599 			irsp->ulpIoTag, irsp->ulpStatus,
11600 			irsp->un.ulpWord[4], irsp->ulpTimeout);
11601 	lpfc_nlp_put((struct lpfc_nodelist *)cmdiocb->context1);
11602 	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
11603 		lpfc_ct_free_iocb(phba, cmdiocb);
11604 	else
11605 		lpfc_els_free_iocb(phba, cmdiocb);
11606 }
11607 
11608 /**
11609  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
11610  * @phba: Pointer to HBA context object.
11611  * @pring: Pointer to driver SLI ring object.
11612  * @cmdiocb: Pointer to driver command iocb object.
11613  * @cmpl: completion function.
11614  *
11615  * This function issues an abort iocb for the provided command iocb. In case
11616  * of unloading, the abort iocb will not be issued to commands on the ELS
11617  * ring. Instead, the callback function shall be changed to those commands
11618  * so that nothing happens when them finishes. This function is called with
11619  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
11620  * when the command iocb is an abort request.
11621  *
11622  **/
11623 int
11624 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11625 			   struct lpfc_iocbq *cmdiocb, void *cmpl)
11626 {
11627 	struct lpfc_vport *vport = cmdiocb->vport;
11628 	struct lpfc_iocbq *abtsiocbp;
11629 	IOCB_t *icmd = NULL;
11630 	IOCB_t *iabt = NULL;
11631 	int retval = IOCB_ERROR;
11632 	unsigned long iflags;
11633 	struct lpfc_nodelist *ndlp;
11634 
11635 	/*
11636 	 * There are certain command types we don't want to abort.  And we
11637 	 * don't want to abort commands that are already in the process of
11638 	 * being aborted.
11639 	 */
11640 	icmd = &cmdiocb->iocb;
11641 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11642 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
11643 	    cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED)
11644 		return IOCB_ABORTING;
11645 
11646 	if (!pring) {
11647 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11648 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11649 		else
11650 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11651 		return retval;
11652 	}
11653 
11654 	/*
11655 	 * If we're unloading, don't abort iocb on the ELS ring, but change
11656 	 * the callback so that nothing happens when it finishes.
11657 	 */
11658 	if ((vport->load_flag & FC_UNLOADING) &&
11659 	    pring->ringno == LPFC_ELS_RING) {
11660 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11661 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11662 		else
11663 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11664 		return retval;
11665 	}
11666 
11667 	/* issue ABTS for this IOCB based on iotag */
11668 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
11669 	if (abtsiocbp == NULL)
11670 		return IOCB_NORESOURCE;
11671 
11672 	/* This signals the response to set the correct status
11673 	 * before calling the completion handler
11674 	 */
11675 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
11676 
11677 	iabt = &abtsiocbp->iocb;
11678 	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
11679 	iabt->un.acxri.abortContextTag = icmd->ulpContext;
11680 	if (phba->sli_rev == LPFC_SLI_REV4) {
11681 		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
11682 		if (pring->ringno == LPFC_ELS_RING)
11683 			iabt->un.acxri.abortContextTag = cmdiocb->iotag;
11684 	} else {
11685 		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
11686 		if (pring->ringno == LPFC_ELS_RING) {
11687 			ndlp = (struct lpfc_nodelist *)(cmdiocb->context1);
11688 			iabt->un.acxri.abortContextTag = ndlp->nlp_rpi;
11689 		}
11690 	}
11691 	iabt->ulpLe = 1;
11692 	iabt->ulpClass = icmd->ulpClass;
11693 
11694 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11695 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
11696 	if (cmdiocb->iocb_flag & LPFC_IO_FCP) {
11697 		abtsiocbp->iocb_flag |= LPFC_IO_FCP;
11698 		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
11699 	}
11700 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
11701 		abtsiocbp->iocb_flag |= LPFC_IO_FOF;
11702 
11703 	if (phba->link_state >= LPFC_LINK_UP)
11704 		iabt->ulpCommand = CMD_ABORT_XRI_CN;
11705 	else
11706 		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
11707 
11708 	if (cmpl)
11709 		abtsiocbp->iocb_cmpl = cmpl;
11710 	else
11711 		abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
11712 	abtsiocbp->vport = vport;
11713 
11714 	if (phba->sli_rev == LPFC_SLI_REV4) {
11715 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
11716 		if (unlikely(pring == NULL))
11717 			goto abort_iotag_exit;
11718 		/* Note: both hbalock and ring_lock need to be set here */
11719 		spin_lock_irqsave(&pring->ring_lock, iflags);
11720 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11721 			abtsiocbp, 0);
11722 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11723 	} else {
11724 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11725 			abtsiocbp, 0);
11726 	}
11727 
11728 abort_iotag_exit:
11729 
11730 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
11731 			 "0339 Abort xri x%x, original iotag x%x, "
11732 			 "abort cmd iotag x%x retval x%x\n",
11733 			 iabt->un.acxri.abortIoTag,
11734 			 iabt->un.acxri.abortContextTag,
11735 			 abtsiocbp->iotag, retval);
11736 
11737 	if (retval) {
11738 		cmdiocb->iocb_flag &= ~LPFC_DRIVER_ABORTED;
11739 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
11740 	}
11741 
11742 	/*
11743 	 * Caller to this routine should check for IOCB_ERROR
11744 	 * and handle it properly.  This routine no longer removes
11745 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
11746 	 */
11747 	return retval;
11748 }
11749 
11750 /**
11751  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
11752  * @phba: pointer to lpfc HBA data structure.
11753  *
11754  * This routine will abort all pending and outstanding iocbs to an HBA.
11755  **/
11756 void
11757 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
11758 {
11759 	struct lpfc_sli *psli = &phba->sli;
11760 	struct lpfc_sli_ring *pring;
11761 	struct lpfc_queue *qp = NULL;
11762 	int i;
11763 
11764 	if (phba->sli_rev != LPFC_SLI_REV4) {
11765 		for (i = 0; i < psli->num_rings; i++) {
11766 			pring = &psli->sli3_ring[i];
11767 			lpfc_sli_abort_iocb_ring(phba, pring);
11768 		}
11769 		return;
11770 	}
11771 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11772 		pring = qp->pring;
11773 		if (!pring)
11774 			continue;
11775 		lpfc_sli_abort_iocb_ring(phba, pring);
11776 	}
11777 }
11778 
11779 /**
11780  * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
11781  * @iocbq: Pointer to driver iocb object.
11782  * @vport: Pointer to driver virtual port object.
11783  * @tgt_id: SCSI ID of the target.
11784  * @lun_id: LUN ID of the scsi device.
11785  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
11786  *
11787  * This function acts as an iocb filter for functions which abort or count
11788  * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
11789  * 0 if the filtering criteria is met for the given iocb and will return
11790  * 1 if the filtering criteria is not met.
11791  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
11792  * given iocb is for the SCSI device specified by vport, tgt_id and
11793  * lun_id parameter.
11794  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
11795  * given iocb is for the SCSI target specified by vport and tgt_id
11796  * parameters.
11797  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
11798  * given iocb is for the SCSI host associated with the given vport.
11799  * This function is called with no locks held.
11800  **/
11801 static int
11802 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
11803 			   uint16_t tgt_id, uint64_t lun_id,
11804 			   lpfc_ctx_cmd ctx_cmd)
11805 {
11806 	struct lpfc_io_buf *lpfc_cmd;
11807 	IOCB_t *icmd = NULL;
11808 	int rc = 1;
11809 
11810 	if (!iocbq || iocbq->vport != vport)
11811 		return rc;
11812 
11813 	if (!(iocbq->iocb_flag & LPFC_IO_FCP) ||
11814 	    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ) ||
11815 	      iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
11816 		return rc;
11817 
11818 	icmd = &iocbq->iocb;
11819 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11820 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN)
11821 		return rc;
11822 
11823 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
11824 
11825 	if (lpfc_cmd->pCmd == NULL)
11826 		return rc;
11827 
11828 	switch (ctx_cmd) {
11829 	case LPFC_CTX_LUN:
11830 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11831 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
11832 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
11833 			rc = 0;
11834 		break;
11835 	case LPFC_CTX_TGT:
11836 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11837 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
11838 			rc = 0;
11839 		break;
11840 	case LPFC_CTX_HOST:
11841 		rc = 0;
11842 		break;
11843 	default:
11844 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
11845 			__func__, ctx_cmd);
11846 		break;
11847 	}
11848 
11849 	return rc;
11850 }
11851 
11852 /**
11853  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
11854  * @vport: Pointer to virtual port.
11855  * @tgt_id: SCSI ID of the target.
11856  * @lun_id: LUN ID of the scsi device.
11857  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11858  *
11859  * This function returns number of FCP commands pending for the vport.
11860  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
11861  * commands pending on the vport associated with SCSI device specified
11862  * by tgt_id and lun_id parameters.
11863  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
11864  * commands pending on the vport associated with SCSI target specified
11865  * by tgt_id parameter.
11866  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
11867  * commands pending on the vport.
11868  * This function returns the number of iocbs which satisfy the filter.
11869  * This function is called without any lock held.
11870  **/
11871 int
11872 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
11873 		  lpfc_ctx_cmd ctx_cmd)
11874 {
11875 	struct lpfc_hba *phba = vport->phba;
11876 	struct lpfc_iocbq *iocbq;
11877 	int sum, i;
11878 
11879 	spin_lock_irq(&phba->hbalock);
11880 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
11881 		iocbq = phba->sli.iocbq_lookup[i];
11882 
11883 		if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
11884 						ctx_cmd) == 0)
11885 			sum++;
11886 	}
11887 	spin_unlock_irq(&phba->hbalock);
11888 
11889 	return sum;
11890 }
11891 
11892 /**
11893  * lpfc_sli4_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
11894  * @phba: Pointer to HBA context object
11895  * @cmdiocb: Pointer to command iocb object.
11896  * @wcqe: pointer to the complete wcqe
11897  *
11898  * This function is called when an aborted FCP iocb completes. This
11899  * function is called by the ring event handler with no lock held.
11900  * This function frees the iocb. It is called for sli-4 adapters.
11901  **/
11902 void
11903 lpfc_sli4_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11904 			 struct lpfc_wcqe_complete *wcqe)
11905 {
11906 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11907 			"3017 ABORT_XRI_CN completing on rpi x%x "
11908 			"original iotag x%x, abort cmd iotag x%x "
11909 			"status 0x%x, reason 0x%x\n",
11910 			cmdiocb->iocb.un.acxri.abortContextTag,
11911 			cmdiocb->iocb.un.acxri.abortIoTag,
11912 			cmdiocb->iotag,
11913 			(bf_get(lpfc_wcqe_c_status, wcqe)
11914 			& LPFC_IOCB_STATUS_MASK),
11915 			wcqe->parameter);
11916 	lpfc_sli_release_iocbq(phba, cmdiocb);
11917 }
11918 
11919 /**
11920  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
11921  * @phba: Pointer to HBA context object
11922  * @cmdiocb: Pointer to command iocb object.
11923  * @rspiocb: Pointer to response iocb object.
11924  *
11925  * This function is called when an aborted FCP iocb completes. This
11926  * function is called by the ring event handler with no lock held.
11927  * This function frees the iocb.
11928  **/
11929 void
11930 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11931 			struct lpfc_iocbq *rspiocb)
11932 {
11933 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11934 			"3096 ABORT_XRI_CN completing on rpi x%x "
11935 			"original iotag x%x, abort cmd iotag x%x "
11936 			"status 0x%x, reason 0x%x\n",
11937 			cmdiocb->iocb.un.acxri.abortContextTag,
11938 			cmdiocb->iocb.un.acxri.abortIoTag,
11939 			cmdiocb->iotag, rspiocb->iocb.ulpStatus,
11940 			rspiocb->iocb.un.ulpWord[4]);
11941 	lpfc_sli_release_iocbq(phba, cmdiocb);
11942 	return;
11943 }
11944 
11945 /**
11946  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
11947  * @vport: Pointer to virtual port.
11948  * @tgt_id: SCSI ID of the target.
11949  * @lun_id: LUN ID of the scsi device.
11950  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11951  *
11952  * This function sends an abort command for every SCSI command
11953  * associated with the given virtual port pending on the ring
11954  * filtered by lpfc_sli_validate_fcp_iocb function.
11955  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
11956  * FCP iocbs associated with lun specified by tgt_id and lun_id
11957  * parameters
11958  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
11959  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
11960  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
11961  * FCP iocbs associated with virtual port.
11962  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
11963  * lpfc_sli4_calc_ring is used.
11964  * This function returns number of iocbs it failed to abort.
11965  * This function is called with no locks held.
11966  **/
11967 int
11968 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
11969 		    lpfc_ctx_cmd abort_cmd)
11970 {
11971 	struct lpfc_hba *phba = vport->phba;
11972 	struct lpfc_sli_ring *pring = NULL;
11973 	struct lpfc_iocbq *iocbq;
11974 	int errcnt = 0, ret_val = 0;
11975 	unsigned long iflags;
11976 	int i;
11977 	void *fcp_cmpl = NULL;
11978 
11979 	/* all I/Os are in process of being flushed */
11980 	if (phba->hba_flag & HBA_IOQ_FLUSH)
11981 		return errcnt;
11982 
11983 	for (i = 1; i <= phba->sli.last_iotag; i++) {
11984 		iocbq = phba->sli.iocbq_lookup[i];
11985 
11986 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
11987 					       abort_cmd) != 0)
11988 			continue;
11989 
11990 		spin_lock_irqsave(&phba->hbalock, iflags);
11991 		if (phba->sli_rev == LPFC_SLI_REV3) {
11992 			pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
11993 			fcp_cmpl = lpfc_sli_abort_fcp_cmpl;
11994 		} else if (phba->sli_rev == LPFC_SLI_REV4) {
11995 			pring = lpfc_sli4_calc_ring(phba, iocbq);
11996 			fcp_cmpl = lpfc_sli4_abort_fcp_cmpl;
11997 		}
11998 		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
11999 						     fcp_cmpl);
12000 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12001 		if (ret_val != IOCB_SUCCESS)
12002 			errcnt++;
12003 	}
12004 
12005 	return errcnt;
12006 }
12007 
12008 /**
12009  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12010  * @vport: Pointer to virtual port.
12011  * @pring: Pointer to driver SLI ring object.
12012  * @tgt_id: SCSI ID of the target.
12013  * @lun_id: LUN ID of the scsi device.
12014  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12015  *
12016  * This function sends an abort command for every SCSI command
12017  * associated with the given virtual port pending on the ring
12018  * filtered by lpfc_sli_validate_fcp_iocb function.
12019  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12020  * FCP iocbs associated with lun specified by tgt_id and lun_id
12021  * parameters
12022  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12023  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12024  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12025  * FCP iocbs associated with virtual port.
12026  * This function returns number of iocbs it aborted .
12027  * This function is called with no locks held right after a taskmgmt
12028  * command is sent.
12029  **/
12030 int
12031 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12032 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12033 {
12034 	struct lpfc_hba *phba = vport->phba;
12035 	struct lpfc_io_buf *lpfc_cmd;
12036 	struct lpfc_iocbq *abtsiocbq;
12037 	struct lpfc_nodelist *ndlp;
12038 	struct lpfc_iocbq *iocbq;
12039 	IOCB_t *icmd;
12040 	int sum, i, ret_val;
12041 	unsigned long iflags;
12042 	struct lpfc_sli_ring *pring_s4 = NULL;
12043 
12044 	spin_lock_irqsave(&phba->hbalock, iflags);
12045 
12046 	/* all I/Os are in process of being flushed */
12047 	if (phba->hba_flag & HBA_IOQ_FLUSH) {
12048 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12049 		return 0;
12050 	}
12051 	sum = 0;
12052 
12053 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12054 		iocbq = phba->sli.iocbq_lookup[i];
12055 
12056 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12057 					       cmd) != 0)
12058 			continue;
12059 
12060 		/* Guard against IO completion being called at same time */
12061 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12062 		spin_lock(&lpfc_cmd->buf_lock);
12063 
12064 		if (!lpfc_cmd->pCmd) {
12065 			spin_unlock(&lpfc_cmd->buf_lock);
12066 			continue;
12067 		}
12068 
12069 		if (phba->sli_rev == LPFC_SLI_REV4) {
12070 			pring_s4 =
12071 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12072 			if (!pring_s4) {
12073 				spin_unlock(&lpfc_cmd->buf_lock);
12074 				continue;
12075 			}
12076 			/* Note: both hbalock and ring_lock must be set here */
12077 			spin_lock(&pring_s4->ring_lock);
12078 		}
12079 
12080 		/*
12081 		 * If the iocbq is already being aborted, don't take a second
12082 		 * action, but do count it.
12083 		 */
12084 		if ((iocbq->iocb_flag & LPFC_DRIVER_ABORTED) ||
12085 		    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ)) {
12086 			if (phba->sli_rev == LPFC_SLI_REV4)
12087 				spin_unlock(&pring_s4->ring_lock);
12088 			spin_unlock(&lpfc_cmd->buf_lock);
12089 			continue;
12090 		}
12091 
12092 		/* issue ABTS for this IOCB based on iotag */
12093 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
12094 		if (!abtsiocbq) {
12095 			if (phba->sli_rev == LPFC_SLI_REV4)
12096 				spin_unlock(&pring_s4->ring_lock);
12097 			spin_unlock(&lpfc_cmd->buf_lock);
12098 			continue;
12099 		}
12100 
12101 		icmd = &iocbq->iocb;
12102 		abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
12103 		abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
12104 		if (phba->sli_rev == LPFC_SLI_REV4)
12105 			abtsiocbq->iocb.un.acxri.abortIoTag =
12106 							 iocbq->sli4_xritag;
12107 		else
12108 			abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
12109 		abtsiocbq->iocb.ulpLe = 1;
12110 		abtsiocbq->iocb.ulpClass = icmd->ulpClass;
12111 		abtsiocbq->vport = vport;
12112 
12113 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12114 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12115 		if (iocbq->iocb_flag & LPFC_IO_FCP)
12116 			abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
12117 		if (iocbq->iocb_flag & LPFC_IO_FOF)
12118 			abtsiocbq->iocb_flag |= LPFC_IO_FOF;
12119 
12120 		ndlp = lpfc_cmd->rdata->pnode;
12121 
12122 		if (lpfc_is_link_up(phba) &&
12123 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
12124 			abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
12125 		else
12126 			abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
12127 
12128 		/* Setup callback routine and issue the command. */
12129 		abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
12130 
12131 		/*
12132 		 * Indicate the IO is being aborted by the driver and set
12133 		 * the caller's flag into the aborted IO.
12134 		 */
12135 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
12136 
12137 		if (phba->sli_rev == LPFC_SLI_REV4) {
12138 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
12139 							abtsiocbq, 0);
12140 			spin_unlock(&pring_s4->ring_lock);
12141 		} else {
12142 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
12143 							abtsiocbq, 0);
12144 		}
12145 
12146 		spin_unlock(&lpfc_cmd->buf_lock);
12147 
12148 		if (ret_val == IOCB_ERROR)
12149 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
12150 		else
12151 			sum++;
12152 	}
12153 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12154 	return sum;
12155 }
12156 
12157 /**
12158  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
12159  * @phba: Pointer to HBA context object.
12160  * @cmdiocbq: Pointer to command iocb.
12161  * @rspiocbq: Pointer to response iocb.
12162  *
12163  * This function is the completion handler for iocbs issued using
12164  * lpfc_sli_issue_iocb_wait function. This function is called by the
12165  * ring event handler function without any lock held. This function
12166  * can be called from both worker thread context and interrupt
12167  * context. This function also can be called from other thread which
12168  * cleans up the SLI layer objects.
12169  * This function copy the contents of the response iocb to the
12170  * response iocb memory object provided by the caller of
12171  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
12172  * sleeps for the iocb completion.
12173  **/
12174 static void
12175 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
12176 			struct lpfc_iocbq *cmdiocbq,
12177 			struct lpfc_iocbq *rspiocbq)
12178 {
12179 	wait_queue_head_t *pdone_q;
12180 	unsigned long iflags;
12181 	struct lpfc_io_buf *lpfc_cmd;
12182 
12183 	spin_lock_irqsave(&phba->hbalock, iflags);
12184 	if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
12185 
12186 		/*
12187 		 * A time out has occurred for the iocb.  If a time out
12188 		 * completion handler has been supplied, call it.  Otherwise,
12189 		 * just free the iocbq.
12190 		 */
12191 
12192 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12193 		cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
12194 		cmdiocbq->wait_iocb_cmpl = NULL;
12195 		if (cmdiocbq->iocb_cmpl)
12196 			(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
12197 		else
12198 			lpfc_sli_release_iocbq(phba, cmdiocbq);
12199 		return;
12200 	}
12201 
12202 	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
12203 	if (cmdiocbq->context2 && rspiocbq)
12204 		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
12205 		       &rspiocbq->iocb, sizeof(IOCB_t));
12206 
12207 	/* Set the exchange busy flag for task management commands */
12208 	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
12209 		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
12210 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
12211 			cur_iocbq);
12212 		if (rspiocbq && (rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY))
12213 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
12214 		else
12215 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
12216 	}
12217 
12218 	pdone_q = cmdiocbq->context_un.wait_queue;
12219 	if (pdone_q)
12220 		wake_up(pdone_q);
12221 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12222 	return;
12223 }
12224 
12225 /**
12226  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
12227  * @phba: Pointer to HBA context object..
12228  * @piocbq: Pointer to command iocb.
12229  * @flag: Flag to test.
12230  *
12231  * This routine grabs the hbalock and then test the iocb_flag to
12232  * see if the passed in flag is set.
12233  * Returns:
12234  * 1 if flag is set.
12235  * 0 if flag is not set.
12236  **/
12237 static int
12238 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
12239 		 struct lpfc_iocbq *piocbq, uint32_t flag)
12240 {
12241 	unsigned long iflags;
12242 	int ret;
12243 
12244 	spin_lock_irqsave(&phba->hbalock, iflags);
12245 	ret = piocbq->iocb_flag & flag;
12246 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12247 	return ret;
12248 
12249 }
12250 
12251 /**
12252  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
12253  * @phba: Pointer to HBA context object..
12254  * @ring_number: Ring number
12255  * @piocb: Pointer to command iocb.
12256  * @prspiocbq: Pointer to response iocb.
12257  * @timeout: Timeout in number of seconds.
12258  *
12259  * This function issues the iocb to firmware and waits for the
12260  * iocb to complete. The iocb_cmpl field of the shall be used
12261  * to handle iocbs which time out. If the field is NULL, the
12262  * function shall free the iocbq structure.  If more clean up is
12263  * needed, the caller is expected to provide a completion function
12264  * that will provide the needed clean up.  If the iocb command is
12265  * not completed within timeout seconds, the function will either
12266  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
12267  * completion function set in the iocb_cmpl field and then return
12268  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
12269  * resources if this function returns IOCB_TIMEDOUT.
12270  * The function waits for the iocb completion using an
12271  * non-interruptible wait.
12272  * This function will sleep while waiting for iocb completion.
12273  * So, this function should not be called from any context which
12274  * does not allow sleeping. Due to the same reason, this function
12275  * cannot be called with interrupt disabled.
12276  * This function assumes that the iocb completions occur while
12277  * this function sleep. So, this function cannot be called from
12278  * the thread which process iocb completion for this ring.
12279  * This function clears the iocb_flag of the iocb object before
12280  * issuing the iocb and the iocb completion handler sets this
12281  * flag and wakes this thread when the iocb completes.
12282  * The contents of the response iocb will be copied to prspiocbq
12283  * by the completion handler when the command completes.
12284  * This function returns IOCB_SUCCESS when success.
12285  * This function is called with no lock held.
12286  **/
12287 int
12288 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
12289 			 uint32_t ring_number,
12290 			 struct lpfc_iocbq *piocb,
12291 			 struct lpfc_iocbq *prspiocbq,
12292 			 uint32_t timeout)
12293 {
12294 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
12295 	long timeleft, timeout_req = 0;
12296 	int retval = IOCB_SUCCESS;
12297 	uint32_t creg_val;
12298 	struct lpfc_iocbq *iocb;
12299 	int txq_cnt = 0;
12300 	int txcmplq_cnt = 0;
12301 	struct lpfc_sli_ring *pring;
12302 	unsigned long iflags;
12303 	bool iocb_completed = true;
12304 
12305 	if (phba->sli_rev >= LPFC_SLI_REV4)
12306 		pring = lpfc_sli4_calc_ring(phba, piocb);
12307 	else
12308 		pring = &phba->sli.sli3_ring[ring_number];
12309 	/*
12310 	 * If the caller has provided a response iocbq buffer, then context2
12311 	 * is NULL or its an error.
12312 	 */
12313 	if (prspiocbq) {
12314 		if (piocb->context2)
12315 			return IOCB_ERROR;
12316 		piocb->context2 = prspiocbq;
12317 	}
12318 
12319 	piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
12320 	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
12321 	piocb->context_un.wait_queue = &done_q;
12322 	piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
12323 
12324 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12325 		if (lpfc_readl(phba->HCregaddr, &creg_val))
12326 			return IOCB_ERROR;
12327 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
12328 		writel(creg_val, phba->HCregaddr);
12329 		readl(phba->HCregaddr); /* flush */
12330 	}
12331 
12332 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
12333 				     SLI_IOCB_RET_IOCB);
12334 	if (retval == IOCB_SUCCESS) {
12335 		timeout_req = msecs_to_jiffies(timeout * 1000);
12336 		timeleft = wait_event_timeout(done_q,
12337 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
12338 				timeout_req);
12339 		spin_lock_irqsave(&phba->hbalock, iflags);
12340 		if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
12341 
12342 			/*
12343 			 * IOCB timed out.  Inform the wake iocb wait
12344 			 * completion function and set local status
12345 			 */
12346 
12347 			iocb_completed = false;
12348 			piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
12349 		}
12350 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12351 		if (iocb_completed) {
12352 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12353 					"0331 IOCB wake signaled\n");
12354 			/* Note: we are not indicating if the IOCB has a success
12355 			 * status or not - that's for the caller to check.
12356 			 * IOCB_SUCCESS means just that the command was sent and
12357 			 * completed. Not that it completed successfully.
12358 			 * */
12359 		} else if (timeleft == 0) {
12360 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12361 					"0338 IOCB wait timeout error - no "
12362 					"wake response Data x%x\n", timeout);
12363 			retval = IOCB_TIMEDOUT;
12364 		} else {
12365 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12366 					"0330 IOCB wake NOT set, "
12367 					"Data x%x x%lx\n",
12368 					timeout, (timeleft / jiffies));
12369 			retval = IOCB_TIMEDOUT;
12370 		}
12371 	} else if (retval == IOCB_BUSY) {
12372 		if (phba->cfg_log_verbose & LOG_SLI) {
12373 			list_for_each_entry(iocb, &pring->txq, list) {
12374 				txq_cnt++;
12375 			}
12376 			list_for_each_entry(iocb, &pring->txcmplq, list) {
12377 				txcmplq_cnt++;
12378 			}
12379 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12380 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
12381 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
12382 		}
12383 		return retval;
12384 	} else {
12385 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12386 				"0332 IOCB wait issue failed, Data x%x\n",
12387 				retval);
12388 		retval = IOCB_ERROR;
12389 	}
12390 
12391 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12392 		if (lpfc_readl(phba->HCregaddr, &creg_val))
12393 			return IOCB_ERROR;
12394 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
12395 		writel(creg_val, phba->HCregaddr);
12396 		readl(phba->HCregaddr); /* flush */
12397 	}
12398 
12399 	if (prspiocbq)
12400 		piocb->context2 = NULL;
12401 
12402 	piocb->context_un.wait_queue = NULL;
12403 	piocb->iocb_cmpl = NULL;
12404 	return retval;
12405 }
12406 
12407 /**
12408  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
12409  * @phba: Pointer to HBA context object.
12410  * @pmboxq: Pointer to driver mailbox object.
12411  * @timeout: Timeout in number of seconds.
12412  *
12413  * This function issues the mailbox to firmware and waits for the
12414  * mailbox command to complete. If the mailbox command is not
12415  * completed within timeout seconds, it returns MBX_TIMEOUT.
12416  * The function waits for the mailbox completion using an
12417  * interruptible wait. If the thread is woken up due to a
12418  * signal, MBX_TIMEOUT error is returned to the caller. Caller
12419  * should not free the mailbox resources, if this function returns
12420  * MBX_TIMEOUT.
12421  * This function will sleep while waiting for mailbox completion.
12422  * So, this function should not be called from any context which
12423  * does not allow sleeping. Due to the same reason, this function
12424  * cannot be called with interrupt disabled.
12425  * This function assumes that the mailbox completion occurs while
12426  * this function sleep. So, this function cannot be called from
12427  * the worker thread which processes mailbox completion.
12428  * This function is called in the context of HBA management
12429  * applications.
12430  * This function returns MBX_SUCCESS when successful.
12431  * This function is called with no lock held.
12432  **/
12433 int
12434 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
12435 			 uint32_t timeout)
12436 {
12437 	struct completion mbox_done;
12438 	int retval;
12439 	unsigned long flag;
12440 
12441 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
12442 	/* setup wake call as IOCB callback */
12443 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
12444 
12445 	/* setup context3 field to pass wait_queue pointer to wake function  */
12446 	init_completion(&mbox_done);
12447 	pmboxq->context3 = &mbox_done;
12448 	/* now issue the command */
12449 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
12450 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
12451 		wait_for_completion_timeout(&mbox_done,
12452 					    msecs_to_jiffies(timeout * 1000));
12453 
12454 		spin_lock_irqsave(&phba->hbalock, flag);
12455 		pmboxq->context3 = NULL;
12456 		/*
12457 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
12458 		 * else do not free the resources.
12459 		 */
12460 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
12461 			retval = MBX_SUCCESS;
12462 		} else {
12463 			retval = MBX_TIMEOUT;
12464 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
12465 		}
12466 		spin_unlock_irqrestore(&phba->hbalock, flag);
12467 	}
12468 	return retval;
12469 }
12470 
12471 /**
12472  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
12473  * @phba: Pointer to HBA context.
12474  * @mbx_action: Mailbox shutdown options.
12475  *
12476  * This function is called to shutdown the driver's mailbox sub-system.
12477  * It first marks the mailbox sub-system is in a block state to prevent
12478  * the asynchronous mailbox command from issued off the pending mailbox
12479  * command queue. If the mailbox command sub-system shutdown is due to
12480  * HBA error conditions such as EEH or ERATT, this routine shall invoke
12481  * the mailbox sub-system flush routine to forcefully bring down the
12482  * mailbox sub-system. Otherwise, if it is due to normal condition (such
12483  * as with offline or HBA function reset), this routine will wait for the
12484  * outstanding mailbox command to complete before invoking the mailbox
12485  * sub-system flush routine to gracefully bring down mailbox sub-system.
12486  **/
12487 void
12488 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
12489 {
12490 	struct lpfc_sli *psli = &phba->sli;
12491 	unsigned long timeout;
12492 
12493 	if (mbx_action == LPFC_MBX_NO_WAIT) {
12494 		/* delay 100ms for port state */
12495 		msleep(100);
12496 		lpfc_sli_mbox_sys_flush(phba);
12497 		return;
12498 	}
12499 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
12500 
12501 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12502 	local_bh_disable();
12503 
12504 	spin_lock_irq(&phba->hbalock);
12505 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
12506 
12507 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
12508 		/* Determine how long we might wait for the active mailbox
12509 		 * command to be gracefully completed by firmware.
12510 		 */
12511 		if (phba->sli.mbox_active)
12512 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
12513 						phba->sli.mbox_active) *
12514 						1000) + jiffies;
12515 		spin_unlock_irq(&phba->hbalock);
12516 
12517 		/* Enable softirqs again, done with phba->hbalock */
12518 		local_bh_enable();
12519 
12520 		while (phba->sli.mbox_active) {
12521 			/* Check active mailbox complete status every 2ms */
12522 			msleep(2);
12523 			if (time_after(jiffies, timeout))
12524 				/* Timeout, let the mailbox flush routine to
12525 				 * forcefully release active mailbox command
12526 				 */
12527 				break;
12528 		}
12529 	} else {
12530 		spin_unlock_irq(&phba->hbalock);
12531 
12532 		/* Enable softirqs again, done with phba->hbalock */
12533 		local_bh_enable();
12534 	}
12535 
12536 	lpfc_sli_mbox_sys_flush(phba);
12537 }
12538 
12539 /**
12540  * lpfc_sli_eratt_read - read sli-3 error attention events
12541  * @phba: Pointer to HBA context.
12542  *
12543  * This function is called to read the SLI3 device error attention registers
12544  * for possible error attention events. The caller must hold the hostlock
12545  * with spin_lock_irq().
12546  *
12547  * This function returns 1 when there is Error Attention in the Host Attention
12548  * Register and returns 0 otherwise.
12549  **/
12550 static int
12551 lpfc_sli_eratt_read(struct lpfc_hba *phba)
12552 {
12553 	uint32_t ha_copy;
12554 
12555 	/* Read chip Host Attention (HA) register */
12556 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
12557 		goto unplug_err;
12558 
12559 	if (ha_copy & HA_ERATT) {
12560 		/* Read host status register to retrieve error event */
12561 		if (lpfc_sli_read_hs(phba))
12562 			goto unplug_err;
12563 
12564 		/* Check if there is a deferred error condition is active */
12565 		if ((HS_FFER1 & phba->work_hs) &&
12566 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12567 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
12568 			phba->hba_flag |= DEFER_ERATT;
12569 			/* Clear all interrupt enable conditions */
12570 			writel(0, phba->HCregaddr);
12571 			readl(phba->HCregaddr);
12572 		}
12573 
12574 		/* Set the driver HA work bitmap */
12575 		phba->work_ha |= HA_ERATT;
12576 		/* Indicate polling handles this ERATT */
12577 		phba->hba_flag |= HBA_ERATT_HANDLED;
12578 		return 1;
12579 	}
12580 	return 0;
12581 
12582 unplug_err:
12583 	/* Set the driver HS work bitmap */
12584 	phba->work_hs |= UNPLUG_ERR;
12585 	/* Set the driver HA work bitmap */
12586 	phba->work_ha |= HA_ERATT;
12587 	/* Indicate polling handles this ERATT */
12588 	phba->hba_flag |= HBA_ERATT_HANDLED;
12589 	return 1;
12590 }
12591 
12592 /**
12593  * lpfc_sli4_eratt_read - read sli-4 error attention events
12594  * @phba: Pointer to HBA context.
12595  *
12596  * This function is called to read the SLI4 device error attention registers
12597  * for possible error attention events. The caller must hold the hostlock
12598  * with spin_lock_irq().
12599  *
12600  * This function returns 1 when there is Error Attention in the Host Attention
12601  * Register and returns 0 otherwise.
12602  **/
12603 static int
12604 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
12605 {
12606 	uint32_t uerr_sta_hi, uerr_sta_lo;
12607 	uint32_t if_type, portsmphr;
12608 	struct lpfc_register portstat_reg;
12609 
12610 	/*
12611 	 * For now, use the SLI4 device internal unrecoverable error
12612 	 * registers for error attention. This can be changed later.
12613 	 */
12614 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12615 	switch (if_type) {
12616 	case LPFC_SLI_INTF_IF_TYPE_0:
12617 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
12618 			&uerr_sta_lo) ||
12619 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
12620 			&uerr_sta_hi)) {
12621 			phba->work_hs |= UNPLUG_ERR;
12622 			phba->work_ha |= HA_ERATT;
12623 			phba->hba_flag |= HBA_ERATT_HANDLED;
12624 			return 1;
12625 		}
12626 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
12627 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
12628 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12629 					"1423 HBA Unrecoverable error: "
12630 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
12631 					"ue_mask_lo_reg=0x%x, "
12632 					"ue_mask_hi_reg=0x%x\n",
12633 					uerr_sta_lo, uerr_sta_hi,
12634 					phba->sli4_hba.ue_mask_lo,
12635 					phba->sli4_hba.ue_mask_hi);
12636 			phba->work_status[0] = uerr_sta_lo;
12637 			phba->work_status[1] = uerr_sta_hi;
12638 			phba->work_ha |= HA_ERATT;
12639 			phba->hba_flag |= HBA_ERATT_HANDLED;
12640 			return 1;
12641 		}
12642 		break;
12643 	case LPFC_SLI_INTF_IF_TYPE_2:
12644 	case LPFC_SLI_INTF_IF_TYPE_6:
12645 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
12646 			&portstat_reg.word0) ||
12647 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
12648 			&portsmphr)){
12649 			phba->work_hs |= UNPLUG_ERR;
12650 			phba->work_ha |= HA_ERATT;
12651 			phba->hba_flag |= HBA_ERATT_HANDLED;
12652 			return 1;
12653 		}
12654 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
12655 			phba->work_status[0] =
12656 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
12657 			phba->work_status[1] =
12658 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
12659 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12660 					"2885 Port Status Event: "
12661 					"port status reg 0x%x, "
12662 					"port smphr reg 0x%x, "
12663 					"error 1=0x%x, error 2=0x%x\n",
12664 					portstat_reg.word0,
12665 					portsmphr,
12666 					phba->work_status[0],
12667 					phba->work_status[1]);
12668 			phba->work_ha |= HA_ERATT;
12669 			phba->hba_flag |= HBA_ERATT_HANDLED;
12670 			return 1;
12671 		}
12672 		break;
12673 	case LPFC_SLI_INTF_IF_TYPE_1:
12674 	default:
12675 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12676 				"2886 HBA Error Attention on unsupported "
12677 				"if type %d.", if_type);
12678 		return 1;
12679 	}
12680 
12681 	return 0;
12682 }
12683 
12684 /**
12685  * lpfc_sli_check_eratt - check error attention events
12686  * @phba: Pointer to HBA context.
12687  *
12688  * This function is called from timer soft interrupt context to check HBA's
12689  * error attention register bit for error attention events.
12690  *
12691  * This function returns 1 when there is Error Attention in the Host Attention
12692  * Register and returns 0 otherwise.
12693  **/
12694 int
12695 lpfc_sli_check_eratt(struct lpfc_hba *phba)
12696 {
12697 	uint32_t ha_copy;
12698 
12699 	/* If somebody is waiting to handle an eratt, don't process it
12700 	 * here. The brdkill function will do this.
12701 	 */
12702 	if (phba->link_flag & LS_IGNORE_ERATT)
12703 		return 0;
12704 
12705 	/* Check if interrupt handler handles this ERATT */
12706 	spin_lock_irq(&phba->hbalock);
12707 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
12708 		/* Interrupt handler has handled ERATT */
12709 		spin_unlock_irq(&phba->hbalock);
12710 		return 0;
12711 	}
12712 
12713 	/*
12714 	 * If there is deferred error attention, do not check for error
12715 	 * attention
12716 	 */
12717 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12718 		spin_unlock_irq(&phba->hbalock);
12719 		return 0;
12720 	}
12721 
12722 	/* If PCI channel is offline, don't process it */
12723 	if (unlikely(pci_channel_offline(phba->pcidev))) {
12724 		spin_unlock_irq(&phba->hbalock);
12725 		return 0;
12726 	}
12727 
12728 	switch (phba->sli_rev) {
12729 	case LPFC_SLI_REV2:
12730 	case LPFC_SLI_REV3:
12731 		/* Read chip Host Attention (HA) register */
12732 		ha_copy = lpfc_sli_eratt_read(phba);
12733 		break;
12734 	case LPFC_SLI_REV4:
12735 		/* Read device Uncoverable Error (UERR) registers */
12736 		ha_copy = lpfc_sli4_eratt_read(phba);
12737 		break;
12738 	default:
12739 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12740 				"0299 Invalid SLI revision (%d)\n",
12741 				phba->sli_rev);
12742 		ha_copy = 0;
12743 		break;
12744 	}
12745 	spin_unlock_irq(&phba->hbalock);
12746 
12747 	return ha_copy;
12748 }
12749 
12750 /**
12751  * lpfc_intr_state_check - Check device state for interrupt handling
12752  * @phba: Pointer to HBA context.
12753  *
12754  * This inline routine checks whether a device or its PCI slot is in a state
12755  * that the interrupt should be handled.
12756  *
12757  * This function returns 0 if the device or the PCI slot is in a state that
12758  * interrupt should be handled, otherwise -EIO.
12759  */
12760 static inline int
12761 lpfc_intr_state_check(struct lpfc_hba *phba)
12762 {
12763 	/* If the pci channel is offline, ignore all the interrupts */
12764 	if (unlikely(pci_channel_offline(phba->pcidev)))
12765 		return -EIO;
12766 
12767 	/* Update device level interrupt statistics */
12768 	phba->sli.slistat.sli_intr++;
12769 
12770 	/* Ignore all interrupts during initialization. */
12771 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
12772 		return -EIO;
12773 
12774 	return 0;
12775 }
12776 
12777 /**
12778  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
12779  * @irq: Interrupt number.
12780  * @dev_id: The device context pointer.
12781  *
12782  * This function is directly called from the PCI layer as an interrupt
12783  * service routine when device with SLI-3 interface spec is enabled with
12784  * MSI-X multi-message interrupt mode and there are slow-path events in
12785  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
12786  * interrupt mode, this function is called as part of the device-level
12787  * interrupt handler. When the PCI slot is in error recovery or the HBA
12788  * is undergoing initialization, the interrupt handler will not process
12789  * the interrupt. The link attention and ELS ring attention events are
12790  * handled by the worker thread. The interrupt handler signals the worker
12791  * thread and returns for these events. This function is called without
12792  * any lock held. It gets the hbalock to access and update SLI data
12793  * structures.
12794  *
12795  * This function returns IRQ_HANDLED when interrupt is handled else it
12796  * returns IRQ_NONE.
12797  **/
12798 irqreturn_t
12799 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
12800 {
12801 	struct lpfc_hba  *phba;
12802 	uint32_t ha_copy, hc_copy;
12803 	uint32_t work_ha_copy;
12804 	unsigned long status;
12805 	unsigned long iflag;
12806 	uint32_t control;
12807 
12808 	MAILBOX_t *mbox, *pmbox;
12809 	struct lpfc_vport *vport;
12810 	struct lpfc_nodelist *ndlp;
12811 	struct lpfc_dmabuf *mp;
12812 	LPFC_MBOXQ_t *pmb;
12813 	int rc;
12814 
12815 	/*
12816 	 * Get the driver's phba structure from the dev_id and
12817 	 * assume the HBA is not interrupting.
12818 	 */
12819 	phba = (struct lpfc_hba *)dev_id;
12820 
12821 	if (unlikely(!phba))
12822 		return IRQ_NONE;
12823 
12824 	/*
12825 	 * Stuff needs to be attented to when this function is invoked as an
12826 	 * individual interrupt handler in MSI-X multi-message interrupt mode
12827 	 */
12828 	if (phba->intr_type == MSIX) {
12829 		/* Check device state for handling interrupt */
12830 		if (lpfc_intr_state_check(phba))
12831 			return IRQ_NONE;
12832 		/* Need to read HA REG for slow-path events */
12833 		spin_lock_irqsave(&phba->hbalock, iflag);
12834 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
12835 			goto unplug_error;
12836 		/* If somebody is waiting to handle an eratt don't process it
12837 		 * here. The brdkill function will do this.
12838 		 */
12839 		if (phba->link_flag & LS_IGNORE_ERATT)
12840 			ha_copy &= ~HA_ERATT;
12841 		/* Check the need for handling ERATT in interrupt handler */
12842 		if (ha_copy & HA_ERATT) {
12843 			if (phba->hba_flag & HBA_ERATT_HANDLED)
12844 				/* ERATT polling has handled ERATT */
12845 				ha_copy &= ~HA_ERATT;
12846 			else
12847 				/* Indicate interrupt handler handles ERATT */
12848 				phba->hba_flag |= HBA_ERATT_HANDLED;
12849 		}
12850 
12851 		/*
12852 		 * If there is deferred error attention, do not check for any
12853 		 * interrupt.
12854 		 */
12855 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12856 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12857 			return IRQ_NONE;
12858 		}
12859 
12860 		/* Clear up only attention source related to slow-path */
12861 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
12862 			goto unplug_error;
12863 
12864 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
12865 			HC_LAINT_ENA | HC_ERINT_ENA),
12866 			phba->HCregaddr);
12867 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
12868 			phba->HAregaddr);
12869 		writel(hc_copy, phba->HCregaddr);
12870 		readl(phba->HAregaddr); /* flush */
12871 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12872 	} else
12873 		ha_copy = phba->ha_copy;
12874 
12875 	work_ha_copy = ha_copy & phba->work_ha_mask;
12876 
12877 	if (work_ha_copy) {
12878 		if (work_ha_copy & HA_LATT) {
12879 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
12880 				/*
12881 				 * Turn off Link Attention interrupts
12882 				 * until CLEAR_LA done
12883 				 */
12884 				spin_lock_irqsave(&phba->hbalock, iflag);
12885 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
12886 				if (lpfc_readl(phba->HCregaddr, &control))
12887 					goto unplug_error;
12888 				control &= ~HC_LAINT_ENA;
12889 				writel(control, phba->HCregaddr);
12890 				readl(phba->HCregaddr); /* flush */
12891 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12892 			}
12893 			else
12894 				work_ha_copy &= ~HA_LATT;
12895 		}
12896 
12897 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
12898 			/*
12899 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
12900 			 * the only slow ring.
12901 			 */
12902 			status = (work_ha_copy &
12903 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
12904 			status >>= (4*LPFC_ELS_RING);
12905 			if (status & HA_RXMASK) {
12906 				spin_lock_irqsave(&phba->hbalock, iflag);
12907 				if (lpfc_readl(phba->HCregaddr, &control))
12908 					goto unplug_error;
12909 
12910 				lpfc_debugfs_slow_ring_trc(phba,
12911 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
12912 				control, status,
12913 				(uint32_t)phba->sli.slistat.sli_intr);
12914 
12915 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
12916 					lpfc_debugfs_slow_ring_trc(phba,
12917 						"ISR Disable ring:"
12918 						"pwork:x%x hawork:x%x wait:x%x",
12919 						phba->work_ha, work_ha_copy,
12920 						(uint32_t)((unsigned long)
12921 						&phba->work_waitq));
12922 
12923 					control &=
12924 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
12925 					writel(control, phba->HCregaddr);
12926 					readl(phba->HCregaddr); /* flush */
12927 				}
12928 				else {
12929 					lpfc_debugfs_slow_ring_trc(phba,
12930 						"ISR slow ring:   pwork:"
12931 						"x%x hawork:x%x wait:x%x",
12932 						phba->work_ha, work_ha_copy,
12933 						(uint32_t)((unsigned long)
12934 						&phba->work_waitq));
12935 				}
12936 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12937 			}
12938 		}
12939 		spin_lock_irqsave(&phba->hbalock, iflag);
12940 		if (work_ha_copy & HA_ERATT) {
12941 			if (lpfc_sli_read_hs(phba))
12942 				goto unplug_error;
12943 			/*
12944 			 * Check if there is a deferred error condition
12945 			 * is active
12946 			 */
12947 			if ((HS_FFER1 & phba->work_hs) &&
12948 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12949 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
12950 				  phba->work_hs)) {
12951 				phba->hba_flag |= DEFER_ERATT;
12952 				/* Clear all interrupt enable conditions */
12953 				writel(0, phba->HCregaddr);
12954 				readl(phba->HCregaddr);
12955 			}
12956 		}
12957 
12958 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
12959 			pmb = phba->sli.mbox_active;
12960 			pmbox = &pmb->u.mb;
12961 			mbox = phba->mbox;
12962 			vport = pmb->vport;
12963 
12964 			/* First check out the status word */
12965 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
12966 			if (pmbox->mbxOwner != OWN_HOST) {
12967 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12968 				/*
12969 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
12970 				 * mbxStatus <status>
12971 				 */
12972 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12973 						"(%d):0304 Stray Mailbox "
12974 						"Interrupt mbxCommand x%x "
12975 						"mbxStatus x%x\n",
12976 						(vport ? vport->vpi : 0),
12977 						pmbox->mbxCommand,
12978 						pmbox->mbxStatus);
12979 				/* clear mailbox attention bit */
12980 				work_ha_copy &= ~HA_MBATT;
12981 			} else {
12982 				phba->sli.mbox_active = NULL;
12983 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12984 				phba->last_completion_time = jiffies;
12985 				del_timer(&phba->sli.mbox_tmo);
12986 				if (pmb->mbox_cmpl) {
12987 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
12988 							MAILBOX_CMD_SIZE);
12989 					if (pmb->out_ext_byte_len &&
12990 						pmb->ctx_buf)
12991 						lpfc_sli_pcimem_bcopy(
12992 						phba->mbox_ext,
12993 						pmb->ctx_buf,
12994 						pmb->out_ext_byte_len);
12995 				}
12996 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
12997 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
12998 
12999 					lpfc_debugfs_disc_trc(vport,
13000 						LPFC_DISC_TRC_MBOX_VPORT,
13001 						"MBOX dflt rpi: : "
13002 						"status:x%x rpi:x%x",
13003 						(uint32_t)pmbox->mbxStatus,
13004 						pmbox->un.varWords[0], 0);
13005 
13006 					if (!pmbox->mbxStatus) {
13007 						mp = (struct lpfc_dmabuf *)
13008 							(pmb->ctx_buf);
13009 						ndlp = (struct lpfc_nodelist *)
13010 							pmb->ctx_ndlp;
13011 
13012 						/* Reg_LOGIN of dflt RPI was
13013 						 * successful. new lets get
13014 						 * rid of the RPI using the
13015 						 * same mbox buffer.
13016 						 */
13017 						lpfc_unreg_login(phba,
13018 							vport->vpi,
13019 							pmbox->un.varWords[0],
13020 							pmb);
13021 						pmb->mbox_cmpl =
13022 							lpfc_mbx_cmpl_dflt_rpi;
13023 						pmb->ctx_buf = mp;
13024 						pmb->ctx_ndlp = ndlp;
13025 						pmb->vport = vport;
13026 						rc = lpfc_sli_issue_mbox(phba,
13027 								pmb,
13028 								MBX_NOWAIT);
13029 						if (rc != MBX_BUSY)
13030 							lpfc_printf_log(phba,
13031 							KERN_ERR,
13032 							LOG_TRACE_EVENT,
13033 							"0350 rc should have"
13034 							"been MBX_BUSY\n");
13035 						if (rc != MBX_NOT_FINISHED)
13036 							goto send_current_mbox;
13037 					}
13038 				}
13039 				spin_lock_irqsave(
13040 						&phba->pport->work_port_lock,
13041 						iflag);
13042 				phba->pport->work_port_events &=
13043 					~WORKER_MBOX_TMO;
13044 				spin_unlock_irqrestore(
13045 						&phba->pport->work_port_lock,
13046 						iflag);
13047 
13048 				/* Do NOT queue MBX_HEARTBEAT to the worker
13049 				 * thread for processing.
13050 				 */
13051 				if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13052 					/* Process mbox now */
13053 					phba->sli.mbox_active = NULL;
13054 					phba->sli.sli_flag &=
13055 						~LPFC_SLI_MBOX_ACTIVE;
13056 					if (pmb->mbox_cmpl)
13057 						pmb->mbox_cmpl(phba, pmb);
13058 				} else {
13059 					/* Queue to worker thread to process */
13060 					lpfc_mbox_cmpl_put(phba, pmb);
13061 				}
13062 			}
13063 		} else
13064 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13065 
13066 		if ((work_ha_copy & HA_MBATT) &&
13067 		    (phba->sli.mbox_active == NULL)) {
13068 send_current_mbox:
13069 			/* Process next mailbox command if there is one */
13070 			do {
13071 				rc = lpfc_sli_issue_mbox(phba, NULL,
13072 							 MBX_NOWAIT);
13073 			} while (rc == MBX_NOT_FINISHED);
13074 			if (rc != MBX_SUCCESS)
13075 				lpfc_printf_log(phba, KERN_ERR,
13076 						LOG_TRACE_EVENT,
13077 						"0349 rc should be "
13078 						"MBX_SUCCESS\n");
13079 		}
13080 
13081 		spin_lock_irqsave(&phba->hbalock, iflag);
13082 		phba->work_ha |= work_ha_copy;
13083 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13084 		lpfc_worker_wake_up(phba);
13085 	}
13086 	return IRQ_HANDLED;
13087 unplug_error:
13088 	spin_unlock_irqrestore(&phba->hbalock, iflag);
13089 	return IRQ_HANDLED;
13090 
13091 } /* lpfc_sli_sp_intr_handler */
13092 
13093 /**
13094  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13095  * @irq: Interrupt number.
13096  * @dev_id: The device context pointer.
13097  *
13098  * This function is directly called from the PCI layer as an interrupt
13099  * service routine when device with SLI-3 interface spec is enabled with
13100  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13101  * ring event in the HBA. However, when the device is enabled with either
13102  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13103  * device-level interrupt handler. When the PCI slot is in error recovery
13104  * or the HBA is undergoing initialization, the interrupt handler will not
13105  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13106  * the intrrupt context. This function is called without any lock held.
13107  * It gets the hbalock to access and update SLI data structures.
13108  *
13109  * This function returns IRQ_HANDLED when interrupt is handled else it
13110  * returns IRQ_NONE.
13111  **/
13112 irqreturn_t
13113 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13114 {
13115 	struct lpfc_hba  *phba;
13116 	uint32_t ha_copy;
13117 	unsigned long status;
13118 	unsigned long iflag;
13119 	struct lpfc_sli_ring *pring;
13120 
13121 	/* Get the driver's phba structure from the dev_id and
13122 	 * assume the HBA is not interrupting.
13123 	 */
13124 	phba = (struct lpfc_hba *) dev_id;
13125 
13126 	if (unlikely(!phba))
13127 		return IRQ_NONE;
13128 
13129 	/*
13130 	 * Stuff needs to be attented to when this function is invoked as an
13131 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13132 	 */
13133 	if (phba->intr_type == MSIX) {
13134 		/* Check device state for handling interrupt */
13135 		if (lpfc_intr_state_check(phba))
13136 			return IRQ_NONE;
13137 		/* Need to read HA REG for FCP ring and other ring events */
13138 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13139 			return IRQ_HANDLED;
13140 		/* Clear up only attention source related to fast-path */
13141 		spin_lock_irqsave(&phba->hbalock, iflag);
13142 		/*
13143 		 * If there is deferred error attention, do not check for
13144 		 * any interrupt.
13145 		 */
13146 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13147 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13148 			return IRQ_NONE;
13149 		}
13150 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
13151 			phba->HAregaddr);
13152 		readl(phba->HAregaddr); /* flush */
13153 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13154 	} else
13155 		ha_copy = phba->ha_copy;
13156 
13157 	/*
13158 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
13159 	 */
13160 	ha_copy &= ~(phba->work_ha_mask);
13161 
13162 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13163 	status >>= (4*LPFC_FCP_RING);
13164 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
13165 	if (status & HA_RXMASK)
13166 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
13167 
13168 	if (phba->cfg_multi_ring_support == 2) {
13169 		/*
13170 		 * Process all events on extra ring. Take the optimized path
13171 		 * for extra ring IO.
13172 		 */
13173 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13174 		status >>= (4*LPFC_EXTRA_RING);
13175 		if (status & HA_RXMASK) {
13176 			lpfc_sli_handle_fast_ring_event(phba,
13177 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
13178 					status);
13179 		}
13180 	}
13181 	return IRQ_HANDLED;
13182 }  /* lpfc_sli_fp_intr_handler */
13183 
13184 /**
13185  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
13186  * @irq: Interrupt number.
13187  * @dev_id: The device context pointer.
13188  *
13189  * This function is the HBA device-level interrupt handler to device with
13190  * SLI-3 interface spec, called from the PCI layer when either MSI or
13191  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
13192  * requires driver attention. This function invokes the slow-path interrupt
13193  * attention handling function and fast-path interrupt attention handling
13194  * function in turn to process the relevant HBA attention events. This
13195  * function is called without any lock held. It gets the hbalock to access
13196  * and update SLI data structures.
13197  *
13198  * This function returns IRQ_HANDLED when interrupt is handled, else it
13199  * returns IRQ_NONE.
13200  **/
13201 irqreturn_t
13202 lpfc_sli_intr_handler(int irq, void *dev_id)
13203 {
13204 	struct lpfc_hba  *phba;
13205 	irqreturn_t sp_irq_rc, fp_irq_rc;
13206 	unsigned long status1, status2;
13207 	uint32_t hc_copy;
13208 
13209 	/*
13210 	 * Get the driver's phba structure from the dev_id and
13211 	 * assume the HBA is not interrupting.
13212 	 */
13213 	phba = (struct lpfc_hba *) dev_id;
13214 
13215 	if (unlikely(!phba))
13216 		return IRQ_NONE;
13217 
13218 	/* Check device state for handling interrupt */
13219 	if (lpfc_intr_state_check(phba))
13220 		return IRQ_NONE;
13221 
13222 	spin_lock(&phba->hbalock);
13223 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
13224 		spin_unlock(&phba->hbalock);
13225 		return IRQ_HANDLED;
13226 	}
13227 
13228 	if (unlikely(!phba->ha_copy)) {
13229 		spin_unlock(&phba->hbalock);
13230 		return IRQ_NONE;
13231 	} else if (phba->ha_copy & HA_ERATT) {
13232 		if (phba->hba_flag & HBA_ERATT_HANDLED)
13233 			/* ERATT polling has handled ERATT */
13234 			phba->ha_copy &= ~HA_ERATT;
13235 		else
13236 			/* Indicate interrupt handler handles ERATT */
13237 			phba->hba_flag |= HBA_ERATT_HANDLED;
13238 	}
13239 
13240 	/*
13241 	 * If there is deferred error attention, do not check for any interrupt.
13242 	 */
13243 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13244 		spin_unlock(&phba->hbalock);
13245 		return IRQ_NONE;
13246 	}
13247 
13248 	/* Clear attention sources except link and error attentions */
13249 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
13250 		spin_unlock(&phba->hbalock);
13251 		return IRQ_HANDLED;
13252 	}
13253 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
13254 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
13255 		phba->HCregaddr);
13256 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
13257 	writel(hc_copy, phba->HCregaddr);
13258 	readl(phba->HAregaddr); /* flush */
13259 	spin_unlock(&phba->hbalock);
13260 
13261 	/*
13262 	 * Invokes slow-path host attention interrupt handling as appropriate.
13263 	 */
13264 
13265 	/* status of events with mailbox and link attention */
13266 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
13267 
13268 	/* status of events with ELS ring */
13269 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
13270 	status2 >>= (4*LPFC_ELS_RING);
13271 
13272 	if (status1 || (status2 & HA_RXMASK))
13273 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
13274 	else
13275 		sp_irq_rc = IRQ_NONE;
13276 
13277 	/*
13278 	 * Invoke fast-path host attention interrupt handling as appropriate.
13279 	 */
13280 
13281 	/* status of events with FCP ring */
13282 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13283 	status1 >>= (4*LPFC_FCP_RING);
13284 
13285 	/* status of events with extra ring */
13286 	if (phba->cfg_multi_ring_support == 2) {
13287 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13288 		status2 >>= (4*LPFC_EXTRA_RING);
13289 	} else
13290 		status2 = 0;
13291 
13292 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
13293 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
13294 	else
13295 		fp_irq_rc = IRQ_NONE;
13296 
13297 	/* Return device-level interrupt handling status */
13298 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
13299 }  /* lpfc_sli_intr_handler */
13300 
13301 /**
13302  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
13303  * @phba: pointer to lpfc hba data structure.
13304  *
13305  * This routine is invoked by the worker thread to process all the pending
13306  * SLI4 els abort xri events.
13307  **/
13308 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
13309 {
13310 	struct lpfc_cq_event *cq_event;
13311 	unsigned long iflags;
13312 
13313 	/* First, declare the els xri abort event has been handled */
13314 	spin_lock_irqsave(&phba->hbalock, iflags);
13315 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
13316 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13317 
13318 	/* Now, handle all the els xri abort events */
13319 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
13320 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
13321 		/* Get the first event from the head of the event queue */
13322 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
13323 				 cq_event, struct lpfc_cq_event, list);
13324 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
13325 				       iflags);
13326 		/* Notify aborted XRI for ELS work queue */
13327 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
13328 
13329 		/* Free the event processed back to the free pool */
13330 		lpfc_sli4_cq_event_release(phba, cq_event);
13331 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
13332 				  iflags);
13333 	}
13334 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
13335 }
13336 
13337 /**
13338  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
13339  * @phba: pointer to lpfc hba data structure
13340  * @pIocbIn: pointer to the rspiocbq
13341  * @pIocbOut: pointer to the cmdiocbq
13342  * @wcqe: pointer to the complete wcqe
13343  *
13344  * This routine transfers the fields of a command iocbq to a response iocbq
13345  * by copying all the IOCB fields from command iocbq and transferring the
13346  * completion status information from the complete wcqe.
13347  **/
13348 static void
13349 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
13350 			      struct lpfc_iocbq *pIocbIn,
13351 			      struct lpfc_iocbq *pIocbOut,
13352 			      struct lpfc_wcqe_complete *wcqe)
13353 {
13354 	int numBdes, i;
13355 	unsigned long iflags;
13356 	uint32_t status, max_response;
13357 	struct lpfc_dmabuf *dmabuf;
13358 	struct ulp_bde64 *bpl, bde;
13359 	size_t offset = offsetof(struct lpfc_iocbq, iocb);
13360 
13361 	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
13362 	       sizeof(struct lpfc_iocbq) - offset);
13363 	/* Map WCQE parameters into irspiocb parameters */
13364 	status = bf_get(lpfc_wcqe_c_status, wcqe);
13365 	pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
13366 	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
13367 		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
13368 			pIocbIn->iocb.un.fcpi.fcpi_parm =
13369 					pIocbOut->iocb.un.fcpi.fcpi_parm -
13370 					wcqe->total_data_placed;
13371 		else
13372 			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
13373 	else {
13374 		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
13375 		switch (pIocbOut->iocb.ulpCommand) {
13376 		case CMD_ELS_REQUEST64_CR:
13377 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
13378 			bpl  = (struct ulp_bde64 *)dmabuf->virt;
13379 			bde.tus.w = le32_to_cpu(bpl[1].tus.w);
13380 			max_response = bde.tus.f.bdeSize;
13381 			break;
13382 		case CMD_GEN_REQUEST64_CR:
13383 			max_response = 0;
13384 			if (!pIocbOut->context3)
13385 				break;
13386 			numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
13387 					sizeof(struct ulp_bde64);
13388 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
13389 			bpl = (struct ulp_bde64 *)dmabuf->virt;
13390 			for (i = 0; i < numBdes; i++) {
13391 				bde.tus.w = le32_to_cpu(bpl[i].tus.w);
13392 				if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
13393 					max_response += bde.tus.f.bdeSize;
13394 			}
13395 			break;
13396 		default:
13397 			max_response = wcqe->total_data_placed;
13398 			break;
13399 		}
13400 		if (max_response < wcqe->total_data_placed)
13401 			pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
13402 		else
13403 			pIocbIn->iocb.un.genreq64.bdl.bdeSize =
13404 				wcqe->total_data_placed;
13405 	}
13406 
13407 	/* Convert BG errors for completion status */
13408 	if (status == CQE_STATUS_DI_ERROR) {
13409 		pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
13410 
13411 		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
13412 			pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
13413 		else
13414 			pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
13415 
13416 		pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
13417 		if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
13418 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13419 				BGS_GUARD_ERR_MASK;
13420 		if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
13421 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13422 				BGS_APPTAG_ERR_MASK;
13423 		if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
13424 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13425 				BGS_REFTAG_ERR_MASK;
13426 
13427 		/* Check to see if there was any good data before the error */
13428 		if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
13429 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13430 				BGS_HI_WATER_MARK_PRESENT_MASK;
13431 			pIocbIn->iocb.unsli3.sli3_bg.bghm =
13432 				wcqe->total_data_placed;
13433 		}
13434 
13435 		/*
13436 		* Set ALL the error bits to indicate we don't know what
13437 		* type of error it is.
13438 		*/
13439 		if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
13440 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13441 				(BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
13442 				BGS_GUARD_ERR_MASK);
13443 	}
13444 
13445 	/* Pick up HBA exchange busy condition */
13446 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
13447 		spin_lock_irqsave(&phba->hbalock, iflags);
13448 		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
13449 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13450 	}
13451 }
13452 
13453 /**
13454  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
13455  * @phba: Pointer to HBA context object.
13456  * @irspiocbq: Pointer to work-queue completion queue entry.
13457  *
13458  * This routine handles an ELS work-queue completion event and construct
13459  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
13460  * discovery engine to handle.
13461  *
13462  * Return: Pointer to the receive IOCBQ, NULL otherwise.
13463  **/
13464 static struct lpfc_iocbq *
13465 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
13466 			       struct lpfc_iocbq *irspiocbq)
13467 {
13468 	struct lpfc_sli_ring *pring;
13469 	struct lpfc_iocbq *cmdiocbq;
13470 	struct lpfc_wcqe_complete *wcqe;
13471 	unsigned long iflags;
13472 
13473 	pring = lpfc_phba_elsring(phba);
13474 	if (unlikely(!pring))
13475 		return NULL;
13476 
13477 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
13478 	pring->stats.iocb_event++;
13479 	/* Look up the ELS command IOCB and create pseudo response IOCB */
13480 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
13481 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13482 	if (unlikely(!cmdiocbq)) {
13483 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13484 				"0386 ELS complete with no corresponding "
13485 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
13486 				wcqe->word0, wcqe->total_data_placed,
13487 				wcqe->parameter, wcqe->word3);
13488 		lpfc_sli_release_iocbq(phba, irspiocbq);
13489 		return NULL;
13490 	}
13491 
13492 	spin_lock_irqsave(&pring->ring_lock, iflags);
13493 	/* Put the iocb back on the txcmplq */
13494 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
13495 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
13496 
13497 	/* Fake the irspiocbq and copy necessary response information */
13498 	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
13499 
13500 	return irspiocbq;
13501 }
13502 
13503 inline struct lpfc_cq_event *
13504 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
13505 {
13506 	struct lpfc_cq_event *cq_event;
13507 
13508 	/* Allocate a new internal CQ_EVENT entry */
13509 	cq_event = lpfc_sli4_cq_event_alloc(phba);
13510 	if (!cq_event) {
13511 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13512 				"0602 Failed to alloc CQ_EVENT entry\n");
13513 		return NULL;
13514 	}
13515 
13516 	/* Move the CQE into the event */
13517 	memcpy(&cq_event->cqe, entry, size);
13518 	return cq_event;
13519 }
13520 
13521 /**
13522  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
13523  * @phba: Pointer to HBA context object.
13524  * @mcqe: Pointer to mailbox completion queue entry.
13525  *
13526  * This routine process a mailbox completion queue entry with asynchronous
13527  * event.
13528  *
13529  * Return: true if work posted to worker thread, otherwise false.
13530  **/
13531 static bool
13532 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13533 {
13534 	struct lpfc_cq_event *cq_event;
13535 	unsigned long iflags;
13536 
13537 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13538 			"0392 Async Event: word0:x%x, word1:x%x, "
13539 			"word2:x%x, word3:x%x\n", mcqe->word0,
13540 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
13541 
13542 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
13543 	if (!cq_event)
13544 		return false;
13545 
13546 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
13547 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
13548 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
13549 
13550 	/* Set the async event flag */
13551 	spin_lock_irqsave(&phba->hbalock, iflags);
13552 	phba->hba_flag |= ASYNC_EVENT;
13553 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13554 
13555 	return true;
13556 }
13557 
13558 /**
13559  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
13560  * @phba: Pointer to HBA context object.
13561  * @mcqe: Pointer to mailbox completion queue entry.
13562  *
13563  * This routine process a mailbox completion queue entry with mailbox
13564  * completion event.
13565  *
13566  * Return: true if work posted to worker thread, otherwise false.
13567  **/
13568 static bool
13569 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13570 {
13571 	uint32_t mcqe_status;
13572 	MAILBOX_t *mbox, *pmbox;
13573 	struct lpfc_mqe *mqe;
13574 	struct lpfc_vport *vport;
13575 	struct lpfc_nodelist *ndlp;
13576 	struct lpfc_dmabuf *mp;
13577 	unsigned long iflags;
13578 	LPFC_MBOXQ_t *pmb;
13579 	bool workposted = false;
13580 	int rc;
13581 
13582 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
13583 	if (!bf_get(lpfc_trailer_completed, mcqe))
13584 		goto out_no_mqe_complete;
13585 
13586 	/* Get the reference to the active mbox command */
13587 	spin_lock_irqsave(&phba->hbalock, iflags);
13588 	pmb = phba->sli.mbox_active;
13589 	if (unlikely(!pmb)) {
13590 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13591 				"1832 No pending MBOX command to handle\n");
13592 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13593 		goto out_no_mqe_complete;
13594 	}
13595 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13596 	mqe = &pmb->u.mqe;
13597 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
13598 	mbox = phba->mbox;
13599 	vport = pmb->vport;
13600 
13601 	/* Reset heartbeat timer */
13602 	phba->last_completion_time = jiffies;
13603 	del_timer(&phba->sli.mbox_tmo);
13604 
13605 	/* Move mbox data to caller's mailbox region, do endian swapping */
13606 	if (pmb->mbox_cmpl && mbox)
13607 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
13608 
13609 	/*
13610 	 * For mcqe errors, conditionally move a modified error code to
13611 	 * the mbox so that the error will not be missed.
13612 	 */
13613 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
13614 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
13615 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
13616 			bf_set(lpfc_mqe_status, mqe,
13617 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
13618 	}
13619 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13620 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13621 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
13622 				      "MBOX dflt rpi: status:x%x rpi:x%x",
13623 				      mcqe_status,
13624 				      pmbox->un.varWords[0], 0);
13625 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
13626 			mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
13627 			ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
13628 			/* Reg_LOGIN of dflt RPI was successful. Now lets get
13629 			 * RID of the PPI using the same mbox buffer.
13630 			 */
13631 			lpfc_unreg_login(phba, vport->vpi,
13632 					 pmbox->un.varWords[0], pmb);
13633 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
13634 			pmb->ctx_buf = mp;
13635 
13636 			/* No reference taken here.  This is a default
13637 			 * RPI reg/immediate unreg cycle. The reference was
13638 			 * taken in the reg rpi path and is released when
13639 			 * this mailbox completes.
13640 			 */
13641 			pmb->ctx_ndlp = ndlp;
13642 			pmb->vport = vport;
13643 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
13644 			if (rc != MBX_BUSY)
13645 				lpfc_printf_log(phba, KERN_ERR,
13646 						LOG_TRACE_EVENT,
13647 						"0385 rc should "
13648 						"have been MBX_BUSY\n");
13649 			if (rc != MBX_NOT_FINISHED)
13650 				goto send_current_mbox;
13651 		}
13652 	}
13653 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
13654 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
13655 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
13656 
13657 	/* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
13658 	if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13659 		spin_lock_irqsave(&phba->hbalock, iflags);
13660 		/* Release the mailbox command posting token */
13661 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13662 		phba->sli.mbox_active = NULL;
13663 		if (bf_get(lpfc_trailer_consumed, mcqe))
13664 			lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13665 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13666 
13667 		/* Post the next mbox command, if there is one */
13668 		lpfc_sli4_post_async_mbox(phba);
13669 
13670 		/* Process cmpl now */
13671 		if (pmb->mbox_cmpl)
13672 			pmb->mbox_cmpl(phba, pmb);
13673 		return false;
13674 	}
13675 
13676 	/* There is mailbox completion work to queue to the worker thread */
13677 	spin_lock_irqsave(&phba->hbalock, iflags);
13678 	__lpfc_mbox_cmpl_put(phba, pmb);
13679 	phba->work_ha |= HA_MBATT;
13680 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13681 	workposted = true;
13682 
13683 send_current_mbox:
13684 	spin_lock_irqsave(&phba->hbalock, iflags);
13685 	/* Release the mailbox command posting token */
13686 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13687 	/* Setting active mailbox pointer need to be in sync to flag clear */
13688 	phba->sli.mbox_active = NULL;
13689 	if (bf_get(lpfc_trailer_consumed, mcqe))
13690 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13691 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13692 	/* Wake up worker thread to post the next pending mailbox command */
13693 	lpfc_worker_wake_up(phba);
13694 	return workposted;
13695 
13696 out_no_mqe_complete:
13697 	spin_lock_irqsave(&phba->hbalock, iflags);
13698 	if (bf_get(lpfc_trailer_consumed, mcqe))
13699 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13700 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13701 	return false;
13702 }
13703 
13704 /**
13705  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
13706  * @phba: Pointer to HBA context object.
13707  * @cq: Pointer to associated CQ
13708  * @cqe: Pointer to mailbox completion queue entry.
13709  *
13710  * This routine process a mailbox completion queue entry, it invokes the
13711  * proper mailbox complete handling or asynchronous event handling routine
13712  * according to the MCQE's async bit.
13713  *
13714  * Return: true if work posted to worker thread, otherwise false.
13715  **/
13716 static bool
13717 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13718 			 struct lpfc_cqe *cqe)
13719 {
13720 	struct lpfc_mcqe mcqe;
13721 	bool workposted;
13722 
13723 	cq->CQ_mbox++;
13724 
13725 	/* Copy the mailbox MCQE and convert endian order as needed */
13726 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
13727 
13728 	/* Invoke the proper event handling routine */
13729 	if (!bf_get(lpfc_trailer_async, &mcqe))
13730 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
13731 	else
13732 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
13733 	return workposted;
13734 }
13735 
13736 /**
13737  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
13738  * @phba: Pointer to HBA context object.
13739  * @cq: Pointer to associated CQ
13740  * @wcqe: Pointer to work-queue completion queue entry.
13741  *
13742  * This routine handles an ELS work-queue completion event.
13743  *
13744  * Return: true if work posted to worker thread, otherwise false.
13745  **/
13746 static bool
13747 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13748 			     struct lpfc_wcqe_complete *wcqe)
13749 {
13750 	struct lpfc_iocbq *irspiocbq;
13751 	unsigned long iflags;
13752 	struct lpfc_sli_ring *pring = cq->pring;
13753 	int txq_cnt = 0;
13754 	int txcmplq_cnt = 0;
13755 
13756 	/* Check for response status */
13757 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
13758 		/* Log the error status */
13759 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13760 				"0357 ELS CQE error: status=x%x: "
13761 				"CQE: %08x %08x %08x %08x\n",
13762 				bf_get(lpfc_wcqe_c_status, wcqe),
13763 				wcqe->word0, wcqe->total_data_placed,
13764 				wcqe->parameter, wcqe->word3);
13765 	}
13766 
13767 	/* Get an irspiocbq for later ELS response processing use */
13768 	irspiocbq = lpfc_sli_get_iocbq(phba);
13769 	if (!irspiocbq) {
13770 		if (!list_empty(&pring->txq))
13771 			txq_cnt++;
13772 		if (!list_empty(&pring->txcmplq))
13773 			txcmplq_cnt++;
13774 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13775 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
13776 			"els_txcmplq_cnt=%d\n",
13777 			txq_cnt, phba->iocb_cnt,
13778 			txcmplq_cnt);
13779 		return false;
13780 	}
13781 
13782 	/* Save off the slow-path queue event for work thread to process */
13783 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
13784 	spin_lock_irqsave(&phba->hbalock, iflags);
13785 	list_add_tail(&irspiocbq->cq_event.list,
13786 		      &phba->sli4_hba.sp_queue_event);
13787 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
13788 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13789 
13790 	return true;
13791 }
13792 
13793 /**
13794  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
13795  * @phba: Pointer to HBA context object.
13796  * @wcqe: Pointer to work-queue completion queue entry.
13797  *
13798  * This routine handles slow-path WQ entry consumed event by invoking the
13799  * proper WQ release routine to the slow-path WQ.
13800  **/
13801 static void
13802 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
13803 			     struct lpfc_wcqe_release *wcqe)
13804 {
13805 	/* sanity check on queue memory */
13806 	if (unlikely(!phba->sli4_hba.els_wq))
13807 		return;
13808 	/* Check for the slow-path ELS work queue */
13809 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
13810 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
13811 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
13812 	else
13813 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13814 				"2579 Slow-path wqe consume event carries "
13815 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
13816 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
13817 				phba->sli4_hba.els_wq->queue_id);
13818 }
13819 
13820 /**
13821  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
13822  * @phba: Pointer to HBA context object.
13823  * @cq: Pointer to a WQ completion queue.
13824  * @wcqe: Pointer to work-queue completion queue entry.
13825  *
13826  * This routine handles an XRI abort event.
13827  *
13828  * Return: true if work posted to worker thread, otherwise false.
13829  **/
13830 static bool
13831 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
13832 				   struct lpfc_queue *cq,
13833 				   struct sli4_wcqe_xri_aborted *wcqe)
13834 {
13835 	bool workposted = false;
13836 	struct lpfc_cq_event *cq_event;
13837 	unsigned long iflags;
13838 
13839 	switch (cq->subtype) {
13840 	case LPFC_IO:
13841 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
13842 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13843 			/* Notify aborted XRI for NVME work queue */
13844 			if (phba->nvmet_support)
13845 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
13846 		}
13847 		workposted = false;
13848 		break;
13849 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
13850 	case LPFC_ELS:
13851 		cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
13852 		if (!cq_event) {
13853 			workposted = false;
13854 			break;
13855 		}
13856 		cq_event->hdwq = cq->hdwq;
13857 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
13858 				  iflags);
13859 		list_add_tail(&cq_event->list,
13860 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
13861 		/* Set the els xri abort event flag */
13862 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
13863 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
13864 				       iflags);
13865 		workposted = true;
13866 		break;
13867 	default:
13868 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13869 				"0603 Invalid CQ subtype %d: "
13870 				"%08x %08x %08x %08x\n",
13871 				cq->subtype, wcqe->word0, wcqe->parameter,
13872 				wcqe->word2, wcqe->word3);
13873 		workposted = false;
13874 		break;
13875 	}
13876 	return workposted;
13877 }
13878 
13879 #define FC_RCTL_MDS_DIAGS	0xF4
13880 
13881 /**
13882  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
13883  * @phba: Pointer to HBA context object.
13884  * @rcqe: Pointer to receive-queue completion queue entry.
13885  *
13886  * This routine process a receive-queue completion queue entry.
13887  *
13888  * Return: true if work posted to worker thread, otherwise false.
13889  **/
13890 static bool
13891 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
13892 {
13893 	bool workposted = false;
13894 	struct fc_frame_header *fc_hdr;
13895 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
13896 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
13897 	struct lpfc_nvmet_tgtport *tgtp;
13898 	struct hbq_dmabuf *dma_buf;
13899 	uint32_t status, rq_id;
13900 	unsigned long iflags;
13901 
13902 	/* sanity check on queue memory */
13903 	if (unlikely(!hrq) || unlikely(!drq))
13904 		return workposted;
13905 
13906 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
13907 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
13908 	else
13909 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
13910 	if (rq_id != hrq->queue_id)
13911 		goto out;
13912 
13913 	status = bf_get(lpfc_rcqe_status, rcqe);
13914 	switch (status) {
13915 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
13916 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13917 				"2537 Receive Frame Truncated!!\n");
13918 		fallthrough;
13919 	case FC_STATUS_RQ_SUCCESS:
13920 		spin_lock_irqsave(&phba->hbalock, iflags);
13921 		lpfc_sli4_rq_release(hrq, drq);
13922 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
13923 		if (!dma_buf) {
13924 			hrq->RQ_no_buf_found++;
13925 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13926 			goto out;
13927 		}
13928 		hrq->RQ_rcv_buf++;
13929 		hrq->RQ_buf_posted--;
13930 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
13931 
13932 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
13933 
13934 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
13935 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
13936 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13937 			/* Handle MDS Loopback frames */
13938 			if  (!(phba->pport->load_flag & FC_UNLOADING))
13939 				lpfc_sli4_handle_mds_loopback(phba->pport,
13940 							      dma_buf);
13941 			else
13942 				lpfc_in_buf_free(phba, &dma_buf->dbuf);
13943 			break;
13944 		}
13945 
13946 		/* save off the frame for the work thread to process */
13947 		list_add_tail(&dma_buf->cq_event.list,
13948 			      &phba->sli4_hba.sp_queue_event);
13949 		/* Frame received */
13950 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
13951 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13952 		workposted = true;
13953 		break;
13954 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
13955 		if (phba->nvmet_support) {
13956 			tgtp = phba->targetport->private;
13957 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13958 					"6402 RQE Error x%x, posted %d err_cnt "
13959 					"%d: %x %x %x\n",
13960 					status, hrq->RQ_buf_posted,
13961 					hrq->RQ_no_posted_buf,
13962 					atomic_read(&tgtp->rcv_fcp_cmd_in),
13963 					atomic_read(&tgtp->rcv_fcp_cmd_out),
13964 					atomic_read(&tgtp->xmt_fcp_release));
13965 		}
13966 		fallthrough;
13967 
13968 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
13969 		hrq->RQ_no_posted_buf++;
13970 		/* Post more buffers if possible */
13971 		spin_lock_irqsave(&phba->hbalock, iflags);
13972 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
13973 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13974 		workposted = true;
13975 		break;
13976 	}
13977 out:
13978 	return workposted;
13979 }
13980 
13981 /**
13982  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
13983  * @phba: Pointer to HBA context object.
13984  * @cq: Pointer to the completion queue.
13985  * @cqe: Pointer to a completion queue entry.
13986  *
13987  * This routine process a slow-path work-queue or receive queue completion queue
13988  * entry.
13989  *
13990  * Return: true if work posted to worker thread, otherwise false.
13991  **/
13992 static bool
13993 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13994 			 struct lpfc_cqe *cqe)
13995 {
13996 	struct lpfc_cqe cqevt;
13997 	bool workposted = false;
13998 
13999 	/* Copy the work queue CQE and convert endian order if needed */
14000 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14001 
14002 	/* Check and process for different type of WCQE and dispatch */
14003 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
14004 	case CQE_CODE_COMPL_WQE:
14005 		/* Process the WQ/RQ complete event */
14006 		phba->last_completion_time = jiffies;
14007 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14008 				(struct lpfc_wcqe_complete *)&cqevt);
14009 		break;
14010 	case CQE_CODE_RELEASE_WQE:
14011 		/* Process the WQ release event */
14012 		lpfc_sli4_sp_handle_rel_wcqe(phba,
14013 				(struct lpfc_wcqe_release *)&cqevt);
14014 		break;
14015 	case CQE_CODE_XRI_ABORTED:
14016 		/* Process the WQ XRI abort event */
14017 		phba->last_completion_time = jiffies;
14018 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14019 				(struct sli4_wcqe_xri_aborted *)&cqevt);
14020 		break;
14021 	case CQE_CODE_RECEIVE:
14022 	case CQE_CODE_RECEIVE_V1:
14023 		/* Process the RQ event */
14024 		phba->last_completion_time = jiffies;
14025 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
14026 				(struct lpfc_rcqe *)&cqevt);
14027 		break;
14028 	default:
14029 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14030 				"0388 Not a valid WCQE code: x%x\n",
14031 				bf_get(lpfc_cqe_code, &cqevt));
14032 		break;
14033 	}
14034 	return workposted;
14035 }
14036 
14037 /**
14038  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14039  * @phba: Pointer to HBA context object.
14040  * @eqe: Pointer to fast-path event queue entry.
14041  * @speq: Pointer to slow-path event queue.
14042  *
14043  * This routine process a event queue entry from the slow-path event queue.
14044  * It will check the MajorCode and MinorCode to determine this is for a
14045  * completion event on a completion queue, if not, an error shall be logged
14046  * and just return. Otherwise, it will get to the corresponding completion
14047  * queue and process all the entries on that completion queue, rearm the
14048  * completion queue, and then return.
14049  *
14050  **/
14051 static void
14052 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14053 	struct lpfc_queue *speq)
14054 {
14055 	struct lpfc_queue *cq = NULL, *childq;
14056 	uint16_t cqid;
14057 	int ret = 0;
14058 
14059 	/* Get the reference to the corresponding CQ */
14060 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14061 
14062 	list_for_each_entry(childq, &speq->child_list, list) {
14063 		if (childq->queue_id == cqid) {
14064 			cq = childq;
14065 			break;
14066 		}
14067 	}
14068 	if (unlikely(!cq)) {
14069 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14070 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14071 					"0365 Slow-path CQ identifier "
14072 					"(%d) does not exist\n", cqid);
14073 		return;
14074 	}
14075 
14076 	/* Save EQ associated with this CQ */
14077 	cq->assoc_qp = speq;
14078 
14079 	if (is_kdump_kernel())
14080 		ret = queue_work(phba->wq, &cq->spwork);
14081 	else
14082 		ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14083 
14084 	if (!ret)
14085 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14086 				"0390 Cannot schedule queue work "
14087 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14088 				cqid, cq->queue_id, raw_smp_processor_id());
14089 }
14090 
14091 /**
14092  * __lpfc_sli4_process_cq - Process elements of a CQ
14093  * @phba: Pointer to HBA context object.
14094  * @cq: Pointer to CQ to be processed
14095  * @handler: Routine to process each cqe
14096  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14097  * @poll_mode: Polling mode we were called from
14098  *
14099  * This routine processes completion queue entries in a CQ. While a valid
14100  * queue element is found, the handler is called. During processing checks
14101  * are made for periodic doorbell writes to let the hardware know of
14102  * element consumption.
14103  *
14104  * If the max limit on cqes to process is hit, or there are no more valid
14105  * entries, the loop stops. If we processed a sufficient number of elements,
14106  * meaning there is sufficient load, rather than rearming and generating
14107  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14108  * indicates no rescheduling.
14109  *
14110  * Returns True if work scheduled, False otherwise.
14111  **/
14112 static bool
14113 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14114 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14115 			struct lpfc_cqe *), unsigned long *delay,
14116 			enum lpfc_poll_mode poll_mode)
14117 {
14118 	struct lpfc_cqe *cqe;
14119 	bool workposted = false;
14120 	int count = 0, consumed = 0;
14121 	bool arm = true;
14122 
14123 	/* default - no reschedule */
14124 	*delay = 0;
14125 
14126 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14127 		goto rearm_and_exit;
14128 
14129 	/* Process all the entries to the CQ */
14130 	cq->q_flag = 0;
14131 	cqe = lpfc_sli4_cq_get(cq);
14132 	while (cqe) {
14133 		workposted |= handler(phba, cq, cqe);
14134 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
14135 
14136 		consumed++;
14137 		if (!(++count % cq->max_proc_limit))
14138 			break;
14139 
14140 		if (!(count % cq->notify_interval)) {
14141 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14142 						LPFC_QUEUE_NOARM);
14143 			consumed = 0;
14144 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14145 		}
14146 
14147 		if (count == LPFC_NVMET_CQ_NOTIFY)
14148 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14149 
14150 		cqe = lpfc_sli4_cq_get(cq);
14151 	}
14152 	if (count >= phba->cfg_cq_poll_threshold) {
14153 		*delay = 1;
14154 		arm = false;
14155 	}
14156 
14157 	/* Note: complete the irq_poll softirq before rearming CQ */
14158 	if (poll_mode == LPFC_IRQ_POLL)
14159 		irq_poll_complete(&cq->iop);
14160 
14161 	/* Track the max number of CQEs processed in 1 EQ */
14162 	if (count > cq->CQ_max_cqe)
14163 		cq->CQ_max_cqe = count;
14164 
14165 	cq->assoc_qp->EQ_cqe_cnt += count;
14166 
14167 	/* Catch the no cq entry condition */
14168 	if (unlikely(count == 0))
14169 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14170 				"0369 No entry from completion queue "
14171 				"qid=%d\n", cq->queue_id);
14172 
14173 	xchg(&cq->queue_claimed, 0);
14174 
14175 rearm_and_exit:
14176 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14177 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14178 
14179 	return workposted;
14180 }
14181 
14182 /**
14183  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14184  * @cq: pointer to CQ to process
14185  *
14186  * This routine calls the cq processing routine with a handler specific
14187  * to the type of queue bound to it.
14188  *
14189  * The CQ routine returns two values: the first is the calling status,
14190  * which indicates whether work was queued to the  background discovery
14191  * thread. If true, the routine should wakeup the discovery thread;
14192  * the second is the delay parameter. If non-zero, rather than rearming
14193  * the CQ and yet another interrupt, the CQ handler should be queued so
14194  * that it is processed in a subsequent polling action. The value of
14195  * the delay indicates when to reschedule it.
14196  **/
14197 static void
14198 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14199 {
14200 	struct lpfc_hba *phba = cq->phba;
14201 	unsigned long delay;
14202 	bool workposted = false;
14203 	int ret = 0;
14204 
14205 	/* Process and rearm the CQ */
14206 	switch (cq->type) {
14207 	case LPFC_MCQ:
14208 		workposted |= __lpfc_sli4_process_cq(phba, cq,
14209 						lpfc_sli4_sp_handle_mcqe,
14210 						&delay, LPFC_QUEUE_WORK);
14211 		break;
14212 	case LPFC_WCQ:
14213 		if (cq->subtype == LPFC_IO)
14214 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14215 						lpfc_sli4_fp_handle_cqe,
14216 						&delay, LPFC_QUEUE_WORK);
14217 		else
14218 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14219 						lpfc_sli4_sp_handle_cqe,
14220 						&delay, LPFC_QUEUE_WORK);
14221 		break;
14222 	default:
14223 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14224 				"0370 Invalid completion queue type (%d)\n",
14225 				cq->type);
14226 		return;
14227 	}
14228 
14229 	if (delay) {
14230 		if (is_kdump_kernel())
14231 			ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
14232 						delay);
14233 		else
14234 			ret = queue_delayed_work_on(cq->chann, phba->wq,
14235 						&cq->sched_spwork, delay);
14236 		if (!ret)
14237 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14238 				"0394 Cannot schedule queue work "
14239 				"for cqid=%d on CPU %d\n",
14240 				cq->queue_id, cq->chann);
14241 	}
14242 
14243 	/* wake up worker thread if there are works to be done */
14244 	if (workposted)
14245 		lpfc_worker_wake_up(phba);
14246 }
14247 
14248 /**
14249  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
14250  *   interrupt
14251  * @work: pointer to work element
14252  *
14253  * translates from the work handler and calls the slow-path handler.
14254  **/
14255 static void
14256 lpfc_sli4_sp_process_cq(struct work_struct *work)
14257 {
14258 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
14259 
14260 	__lpfc_sli4_sp_process_cq(cq);
14261 }
14262 
14263 /**
14264  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
14265  * @work: pointer to work element
14266  *
14267  * translates from the work handler and calls the slow-path handler.
14268  **/
14269 static void
14270 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
14271 {
14272 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
14273 					struct lpfc_queue, sched_spwork);
14274 
14275 	__lpfc_sli4_sp_process_cq(cq);
14276 }
14277 
14278 /**
14279  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
14280  * @phba: Pointer to HBA context object.
14281  * @cq: Pointer to associated CQ
14282  * @wcqe: Pointer to work-queue completion queue entry.
14283  *
14284  * This routine process a fast-path work queue completion entry from fast-path
14285  * event queue for FCP command response completion.
14286  **/
14287 static void
14288 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14289 			     struct lpfc_wcqe_complete *wcqe)
14290 {
14291 	struct lpfc_sli_ring *pring = cq->pring;
14292 	struct lpfc_iocbq *cmdiocbq;
14293 	struct lpfc_iocbq irspiocbq;
14294 	unsigned long iflags;
14295 
14296 	/* Check for response status */
14297 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14298 		/* If resource errors reported from HBA, reduce queue
14299 		 * depth of the SCSI device.
14300 		 */
14301 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
14302 		     IOSTAT_LOCAL_REJECT)) &&
14303 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
14304 		     IOERR_NO_RESOURCES))
14305 			phba->lpfc_rampdown_queue_depth(phba);
14306 
14307 		/* Log the cmpl status */
14308 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14309 				"0373 FCP CQE cmpl: status=x%x: "
14310 				"CQE: %08x %08x %08x %08x\n",
14311 				bf_get(lpfc_wcqe_c_status, wcqe),
14312 				wcqe->word0, wcqe->total_data_placed,
14313 				wcqe->parameter, wcqe->word3);
14314 	}
14315 
14316 	/* Look up the FCP command IOCB and create pseudo response IOCB */
14317 	spin_lock_irqsave(&pring->ring_lock, iflags);
14318 	pring->stats.iocb_event++;
14319 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
14320 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14321 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14322 	if (unlikely(!cmdiocbq)) {
14323 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14324 				"0374 FCP complete with no corresponding "
14325 				"cmdiocb: iotag (%d)\n",
14326 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14327 		return;
14328 	}
14329 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
14330 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
14331 #endif
14332 	if (cmdiocbq->iocb_cmpl == NULL) {
14333 		if (cmdiocbq->wqe_cmpl) {
14334 			/* For FCP the flag is cleared in wqe_cmpl */
14335 			if (!(cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
14336 			    cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
14337 				spin_lock_irqsave(&phba->hbalock, iflags);
14338 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
14339 				spin_unlock_irqrestore(&phba->hbalock, iflags);
14340 			}
14341 
14342 			/* Pass the cmd_iocb and the wcqe to the upper layer */
14343 			(cmdiocbq->wqe_cmpl)(phba, cmdiocbq, wcqe);
14344 			return;
14345 		}
14346 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14347 				"0375 FCP cmdiocb not callback function "
14348 				"iotag: (%d)\n",
14349 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14350 		return;
14351 	}
14352 
14353 	/* Only SLI4 non-IO commands stil use IOCB */
14354 	/* Fake the irspiocb and copy necessary response information */
14355 	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
14356 
14357 	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
14358 		spin_lock_irqsave(&phba->hbalock, iflags);
14359 		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
14360 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14361 	}
14362 
14363 	/* Pass the cmd_iocb and the rsp state to the upper layer */
14364 	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
14365 }
14366 
14367 /**
14368  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
14369  * @phba: Pointer to HBA context object.
14370  * @cq: Pointer to completion queue.
14371  * @wcqe: Pointer to work-queue completion queue entry.
14372  *
14373  * This routine handles an fast-path WQ entry consumed event by invoking the
14374  * proper WQ release routine to the slow-path WQ.
14375  **/
14376 static void
14377 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14378 			     struct lpfc_wcqe_release *wcqe)
14379 {
14380 	struct lpfc_queue *childwq;
14381 	bool wqid_matched = false;
14382 	uint16_t hba_wqid;
14383 
14384 	/* Check for fast-path FCP work queue release */
14385 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
14386 	list_for_each_entry(childwq, &cq->child_list, list) {
14387 		if (childwq->queue_id == hba_wqid) {
14388 			lpfc_sli4_wq_release(childwq,
14389 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14390 			if (childwq->q_flag & HBA_NVMET_WQFULL)
14391 				lpfc_nvmet_wqfull_process(phba, childwq);
14392 			wqid_matched = true;
14393 			break;
14394 		}
14395 	}
14396 	/* Report warning log message if no match found */
14397 	if (wqid_matched != true)
14398 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14399 				"2580 Fast-path wqe consume event carries "
14400 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
14401 }
14402 
14403 /**
14404  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
14405  * @phba: Pointer to HBA context object.
14406  * @cq: Pointer to completion queue.
14407  * @rcqe: Pointer to receive-queue completion queue entry.
14408  *
14409  * This routine process a receive-queue completion queue entry.
14410  *
14411  * Return: true if work posted to worker thread, otherwise false.
14412  **/
14413 static bool
14414 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14415 			    struct lpfc_rcqe *rcqe)
14416 {
14417 	bool workposted = false;
14418 	struct lpfc_queue *hrq;
14419 	struct lpfc_queue *drq;
14420 	struct rqb_dmabuf *dma_buf;
14421 	struct fc_frame_header *fc_hdr;
14422 	struct lpfc_nvmet_tgtport *tgtp;
14423 	uint32_t status, rq_id;
14424 	unsigned long iflags;
14425 	uint32_t fctl, idx;
14426 
14427 	if ((phba->nvmet_support == 0) ||
14428 	    (phba->sli4_hba.nvmet_cqset == NULL))
14429 		return workposted;
14430 
14431 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
14432 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
14433 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
14434 
14435 	/* sanity check on queue memory */
14436 	if (unlikely(!hrq) || unlikely(!drq))
14437 		return workposted;
14438 
14439 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14440 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14441 	else
14442 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14443 
14444 	if ((phba->nvmet_support == 0) ||
14445 	    (rq_id != hrq->queue_id))
14446 		return workposted;
14447 
14448 	status = bf_get(lpfc_rcqe_status, rcqe);
14449 	switch (status) {
14450 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14451 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14452 				"6126 Receive Frame Truncated!!\n");
14453 		fallthrough;
14454 	case FC_STATUS_RQ_SUCCESS:
14455 		spin_lock_irqsave(&phba->hbalock, iflags);
14456 		lpfc_sli4_rq_release(hrq, drq);
14457 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
14458 		if (!dma_buf) {
14459 			hrq->RQ_no_buf_found++;
14460 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14461 			goto out;
14462 		}
14463 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14464 		hrq->RQ_rcv_buf++;
14465 		hrq->RQ_buf_posted--;
14466 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14467 
14468 		/* Just some basic sanity checks on FCP Command frame */
14469 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
14470 			fc_hdr->fh_f_ctl[1] << 8 |
14471 			fc_hdr->fh_f_ctl[2]);
14472 		if (((fctl &
14473 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
14474 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
14475 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
14476 			goto drop;
14477 
14478 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
14479 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
14480 			lpfc_nvmet_unsol_fcp_event(
14481 				phba, idx, dma_buf, cq->isr_timestamp,
14482 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
14483 			return false;
14484 		}
14485 drop:
14486 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
14487 		break;
14488 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14489 		if (phba->nvmet_support) {
14490 			tgtp = phba->targetport->private;
14491 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14492 					"6401 RQE Error x%x, posted %d err_cnt "
14493 					"%d: %x %x %x\n",
14494 					status, hrq->RQ_buf_posted,
14495 					hrq->RQ_no_posted_buf,
14496 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14497 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14498 					atomic_read(&tgtp->xmt_fcp_release));
14499 		}
14500 		fallthrough;
14501 
14502 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14503 		hrq->RQ_no_posted_buf++;
14504 		/* Post more buffers if possible */
14505 		break;
14506 	}
14507 out:
14508 	return workposted;
14509 }
14510 
14511 /**
14512  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
14513  * @phba: adapter with cq
14514  * @cq: Pointer to the completion queue.
14515  * @cqe: Pointer to fast-path completion queue entry.
14516  *
14517  * This routine process a fast-path work queue completion entry from fast-path
14518  * event queue for FCP command response completion.
14519  *
14520  * Return: true if work posted to worker thread, otherwise false.
14521  **/
14522 static bool
14523 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14524 			 struct lpfc_cqe *cqe)
14525 {
14526 	struct lpfc_wcqe_release wcqe;
14527 	bool workposted = false;
14528 
14529 	/* Copy the work queue CQE and convert endian order if needed */
14530 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
14531 
14532 	/* Check and process for different type of WCQE and dispatch */
14533 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
14534 	case CQE_CODE_COMPL_WQE:
14535 	case CQE_CODE_NVME_ERSP:
14536 		cq->CQ_wq++;
14537 		/* Process the WQ complete event */
14538 		phba->last_completion_time = jiffies;
14539 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
14540 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
14541 				(struct lpfc_wcqe_complete *)&wcqe);
14542 		break;
14543 	case CQE_CODE_RELEASE_WQE:
14544 		cq->CQ_release_wqe++;
14545 		/* Process the WQ release event */
14546 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
14547 				(struct lpfc_wcqe_release *)&wcqe);
14548 		break;
14549 	case CQE_CODE_XRI_ABORTED:
14550 		cq->CQ_xri_aborted++;
14551 		/* Process the WQ XRI abort event */
14552 		phba->last_completion_time = jiffies;
14553 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14554 				(struct sli4_wcqe_xri_aborted *)&wcqe);
14555 		break;
14556 	case CQE_CODE_RECEIVE_V1:
14557 	case CQE_CODE_RECEIVE:
14558 		phba->last_completion_time = jiffies;
14559 		if (cq->subtype == LPFC_NVMET) {
14560 			workposted = lpfc_sli4_nvmet_handle_rcqe(
14561 				phba, cq, (struct lpfc_rcqe *)&wcqe);
14562 		}
14563 		break;
14564 	default:
14565 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14566 				"0144 Not a valid CQE code: x%x\n",
14567 				bf_get(lpfc_wcqe_c_code, &wcqe));
14568 		break;
14569 	}
14570 	return workposted;
14571 }
14572 
14573 /**
14574  * lpfc_sli4_sched_cq_work - Schedules cq work
14575  * @phba: Pointer to HBA context object.
14576  * @cq: Pointer to CQ
14577  * @cqid: CQ ID
14578  *
14579  * This routine checks the poll mode of the CQ corresponding to
14580  * cq->chann, then either schedules a softirq or queue_work to complete
14581  * cq work.
14582  *
14583  * queue_work path is taken if in NVMET mode, or if poll_mode is in
14584  * LPFC_QUEUE_WORK mode.  Otherwise, softirq path is taken.
14585  *
14586  **/
14587 static void lpfc_sli4_sched_cq_work(struct lpfc_hba *phba,
14588 				    struct lpfc_queue *cq, uint16_t cqid)
14589 {
14590 	int ret = 0;
14591 
14592 	switch (cq->poll_mode) {
14593 	case LPFC_IRQ_POLL:
14594 		irq_poll_sched(&cq->iop);
14595 		break;
14596 	case LPFC_QUEUE_WORK:
14597 	default:
14598 		if (is_kdump_kernel())
14599 			ret = queue_work(phba->wq, &cq->irqwork);
14600 		else
14601 			ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
14602 		if (!ret)
14603 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14604 					"0383 Cannot schedule queue work "
14605 					"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14606 					cqid, cq->queue_id,
14607 					raw_smp_processor_id());
14608 	}
14609 }
14610 
14611 /**
14612  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
14613  * @phba: Pointer to HBA context object.
14614  * @eq: Pointer to the queue structure.
14615  * @eqe: Pointer to fast-path event queue entry.
14616  *
14617  * This routine process a event queue entry from the fast-path event queue.
14618  * It will check the MajorCode and MinorCode to determine this is for a
14619  * completion event on a completion queue, if not, an error shall be logged
14620  * and just return. Otherwise, it will get to the corresponding completion
14621  * queue and process all the entries on the completion queue, rearm the
14622  * completion queue, and then return.
14623  **/
14624 static void
14625 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
14626 			 struct lpfc_eqe *eqe)
14627 {
14628 	struct lpfc_queue *cq = NULL;
14629 	uint32_t qidx = eq->hdwq;
14630 	uint16_t cqid, id;
14631 
14632 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
14633 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14634 				"0366 Not a valid completion "
14635 				"event: majorcode=x%x, minorcode=x%x\n",
14636 				bf_get_le32(lpfc_eqe_major_code, eqe),
14637 				bf_get_le32(lpfc_eqe_minor_code, eqe));
14638 		return;
14639 	}
14640 
14641 	/* Get the reference to the corresponding CQ */
14642 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14643 
14644 	/* Use the fast lookup method first */
14645 	if (cqid <= phba->sli4_hba.cq_max) {
14646 		cq = phba->sli4_hba.cq_lookup[cqid];
14647 		if (cq)
14648 			goto  work_cq;
14649 	}
14650 
14651 	/* Next check for NVMET completion */
14652 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
14653 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
14654 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
14655 			/* Process NVMET unsol rcv */
14656 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
14657 			goto  process_cq;
14658 		}
14659 	}
14660 
14661 	if (phba->sli4_hba.nvmels_cq &&
14662 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
14663 		/* Process NVME unsol rcv */
14664 		cq = phba->sli4_hba.nvmels_cq;
14665 	}
14666 
14667 	/* Otherwise this is a Slow path event */
14668 	if (cq == NULL) {
14669 		lpfc_sli4_sp_handle_eqe(phba, eqe,
14670 					phba->sli4_hba.hdwq[qidx].hba_eq);
14671 		return;
14672 	}
14673 
14674 process_cq:
14675 	if (unlikely(cqid != cq->queue_id)) {
14676 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14677 				"0368 Miss-matched fast-path completion "
14678 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
14679 				cqid, cq->queue_id);
14680 		return;
14681 	}
14682 
14683 work_cq:
14684 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
14685 	if (phba->ktime_on)
14686 		cq->isr_timestamp = ktime_get_ns();
14687 	else
14688 		cq->isr_timestamp = 0;
14689 #endif
14690 	lpfc_sli4_sched_cq_work(phba, cq, cqid);
14691 }
14692 
14693 /**
14694  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
14695  * @cq: Pointer to CQ to be processed
14696  * @poll_mode: Enum lpfc_poll_state to determine poll mode
14697  *
14698  * This routine calls the cq processing routine with the handler for
14699  * fast path CQEs.
14700  *
14701  * The CQ routine returns two values: the first is the calling status,
14702  * which indicates whether work was queued to the  background discovery
14703  * thread. If true, the routine should wakeup the discovery thread;
14704  * the second is the delay parameter. If non-zero, rather than rearming
14705  * the CQ and yet another interrupt, the CQ handler should be queued so
14706  * that it is processed in a subsequent polling action. The value of
14707  * the delay indicates when to reschedule it.
14708  **/
14709 static void
14710 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq,
14711 			   enum lpfc_poll_mode poll_mode)
14712 {
14713 	struct lpfc_hba *phba = cq->phba;
14714 	unsigned long delay;
14715 	bool workposted = false;
14716 	int ret = 0;
14717 
14718 	/* process and rearm the CQ */
14719 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
14720 					     &delay, poll_mode);
14721 
14722 	if (delay) {
14723 		if (is_kdump_kernel())
14724 			ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
14725 						delay);
14726 		else
14727 			ret = queue_delayed_work_on(cq->chann, phba->wq,
14728 						&cq->sched_irqwork, delay);
14729 		if (!ret)
14730 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14731 					"0367 Cannot schedule queue work "
14732 					"for cqid=%d on CPU %d\n",
14733 					cq->queue_id, cq->chann);
14734 	}
14735 
14736 	/* wake up worker thread if there are works to be done */
14737 	if (workposted)
14738 		lpfc_worker_wake_up(phba);
14739 }
14740 
14741 /**
14742  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
14743  *   interrupt
14744  * @work: pointer to work element
14745  *
14746  * translates from the work handler and calls the fast-path handler.
14747  **/
14748 static void
14749 lpfc_sli4_hba_process_cq(struct work_struct *work)
14750 {
14751 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
14752 
14753 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
14754 }
14755 
14756 /**
14757  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
14758  * @work: pointer to work element
14759  *
14760  * translates from the work handler and calls the fast-path handler.
14761  **/
14762 static void
14763 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
14764 {
14765 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
14766 					struct lpfc_queue, sched_irqwork);
14767 
14768 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
14769 }
14770 
14771 /**
14772  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
14773  * @irq: Interrupt number.
14774  * @dev_id: The device context pointer.
14775  *
14776  * This function is directly called from the PCI layer as an interrupt
14777  * service routine when device with SLI-4 interface spec is enabled with
14778  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
14779  * ring event in the HBA. However, when the device is enabled with either
14780  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
14781  * device-level interrupt handler. When the PCI slot is in error recovery
14782  * or the HBA is undergoing initialization, the interrupt handler will not
14783  * process the interrupt. The SCSI FCP fast-path ring event are handled in
14784  * the intrrupt context. This function is called without any lock held.
14785  * It gets the hbalock to access and update SLI data structures. Note that,
14786  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
14787  * equal to that of FCP CQ index.
14788  *
14789  * The link attention and ELS ring attention events are handled
14790  * by the worker thread. The interrupt handler signals the worker thread
14791  * and returns for these events. This function is called without any lock
14792  * held. It gets the hbalock to access and update SLI data structures.
14793  *
14794  * This function returns IRQ_HANDLED when interrupt is handled else it
14795  * returns IRQ_NONE.
14796  **/
14797 irqreturn_t
14798 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
14799 {
14800 	struct lpfc_hba *phba;
14801 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
14802 	struct lpfc_queue *fpeq;
14803 	unsigned long iflag;
14804 	int ecount = 0;
14805 	int hba_eqidx;
14806 	struct lpfc_eq_intr_info *eqi;
14807 
14808 	/* Get the driver's phba structure from the dev_id */
14809 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
14810 	phba = hba_eq_hdl->phba;
14811 	hba_eqidx = hba_eq_hdl->idx;
14812 
14813 	if (unlikely(!phba))
14814 		return IRQ_NONE;
14815 	if (unlikely(!phba->sli4_hba.hdwq))
14816 		return IRQ_NONE;
14817 
14818 	/* Get to the EQ struct associated with this vector */
14819 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
14820 	if (unlikely(!fpeq))
14821 		return IRQ_NONE;
14822 
14823 	/* Check device state for handling interrupt */
14824 	if (unlikely(lpfc_intr_state_check(phba))) {
14825 		/* Check again for link_state with lock held */
14826 		spin_lock_irqsave(&phba->hbalock, iflag);
14827 		if (phba->link_state < LPFC_LINK_DOWN)
14828 			/* Flush, clear interrupt, and rearm the EQ */
14829 			lpfc_sli4_eqcq_flush(phba, fpeq);
14830 		spin_unlock_irqrestore(&phba->hbalock, iflag);
14831 		return IRQ_NONE;
14832 	}
14833 
14834 	eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
14835 	eqi->icnt++;
14836 
14837 	fpeq->last_cpu = raw_smp_processor_id();
14838 
14839 	if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
14840 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
14841 	    phba->cfg_auto_imax &&
14842 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
14843 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
14844 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
14845 
14846 	/* process and rearm the EQ */
14847 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
14848 
14849 	if (unlikely(ecount == 0)) {
14850 		fpeq->EQ_no_entry++;
14851 		if (phba->intr_type == MSIX)
14852 			/* MSI-X treated interrupt served as no EQ share INT */
14853 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14854 					"0358 MSI-X interrupt with no EQE\n");
14855 		else
14856 			/* Non MSI-X treated on interrupt as EQ share INT */
14857 			return IRQ_NONE;
14858 	}
14859 
14860 	return IRQ_HANDLED;
14861 } /* lpfc_sli4_hba_intr_handler */
14862 
14863 /**
14864  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
14865  * @irq: Interrupt number.
14866  * @dev_id: The device context pointer.
14867  *
14868  * This function is the device-level interrupt handler to device with SLI-4
14869  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
14870  * interrupt mode is enabled and there is an event in the HBA which requires
14871  * driver attention. This function invokes the slow-path interrupt attention
14872  * handling function and fast-path interrupt attention handling function in
14873  * turn to process the relevant HBA attention events. This function is called
14874  * without any lock held. It gets the hbalock to access and update SLI data
14875  * structures.
14876  *
14877  * This function returns IRQ_HANDLED when interrupt is handled, else it
14878  * returns IRQ_NONE.
14879  **/
14880 irqreturn_t
14881 lpfc_sli4_intr_handler(int irq, void *dev_id)
14882 {
14883 	struct lpfc_hba  *phba;
14884 	irqreturn_t hba_irq_rc;
14885 	bool hba_handled = false;
14886 	int qidx;
14887 
14888 	/* Get the driver's phba structure from the dev_id */
14889 	phba = (struct lpfc_hba *)dev_id;
14890 
14891 	if (unlikely(!phba))
14892 		return IRQ_NONE;
14893 
14894 	/*
14895 	 * Invoke fast-path host attention interrupt handling as appropriate.
14896 	 */
14897 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
14898 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
14899 					&phba->sli4_hba.hba_eq_hdl[qidx]);
14900 		if (hba_irq_rc == IRQ_HANDLED)
14901 			hba_handled |= true;
14902 	}
14903 
14904 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
14905 } /* lpfc_sli4_intr_handler */
14906 
14907 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
14908 {
14909 	struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
14910 	struct lpfc_queue *eq;
14911 	int i = 0;
14912 
14913 	rcu_read_lock();
14914 
14915 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
14916 		i += lpfc_sli4_poll_eq(eq, LPFC_POLL_SLOWPATH);
14917 	if (!list_empty(&phba->poll_list))
14918 		mod_timer(&phba->cpuhp_poll_timer,
14919 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
14920 
14921 	rcu_read_unlock();
14922 }
14923 
14924 inline int lpfc_sli4_poll_eq(struct lpfc_queue *eq, uint8_t path)
14925 {
14926 	struct lpfc_hba *phba = eq->phba;
14927 	int i = 0;
14928 
14929 	/*
14930 	 * Unlocking an irq is one of the entry point to check
14931 	 * for re-schedule, but we are good for io submission
14932 	 * path as midlayer does a get_cpu to glue us in. Flush
14933 	 * out the invalidate queue so we can see the updated
14934 	 * value for flag.
14935 	 */
14936 	smp_rmb();
14937 
14938 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
14939 		/* We will not likely get the completion for the caller
14940 		 * during this iteration but i guess that's fine.
14941 		 * Future io's coming on this eq should be able to
14942 		 * pick it up.  As for the case of single io's, they
14943 		 * will be handled through a sched from polling timer
14944 		 * function which is currently triggered every 1msec.
14945 		 */
14946 		i = lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM);
14947 
14948 	return i;
14949 }
14950 
14951 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
14952 {
14953 	struct lpfc_hba *phba = eq->phba;
14954 
14955 	/* kickstart slowpath processing if needed */
14956 	if (list_empty(&phba->poll_list))
14957 		mod_timer(&phba->cpuhp_poll_timer,
14958 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
14959 
14960 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
14961 	synchronize_rcu();
14962 }
14963 
14964 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
14965 {
14966 	struct lpfc_hba *phba = eq->phba;
14967 
14968 	/* Disable slowpath processing for this eq.  Kick start the eq
14969 	 * by RE-ARMING the eq's ASAP
14970 	 */
14971 	list_del_rcu(&eq->_poll_list);
14972 	synchronize_rcu();
14973 
14974 	if (list_empty(&phba->poll_list))
14975 		del_timer_sync(&phba->cpuhp_poll_timer);
14976 }
14977 
14978 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
14979 {
14980 	struct lpfc_queue *eq, *next;
14981 
14982 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
14983 		list_del(&eq->_poll_list);
14984 
14985 	INIT_LIST_HEAD(&phba->poll_list);
14986 	synchronize_rcu();
14987 }
14988 
14989 static inline void
14990 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
14991 {
14992 	if (mode == eq->mode)
14993 		return;
14994 	/*
14995 	 * currently this function is only called during a hotplug
14996 	 * event and the cpu on which this function is executing
14997 	 * is going offline.  By now the hotplug has instructed
14998 	 * the scheduler to remove this cpu from cpu active mask.
14999 	 * So we don't need to work about being put aside by the
15000 	 * scheduler for a high priority process.  Yes, the inte-
15001 	 * rrupts could come but they are known to retire ASAP.
15002 	 */
15003 
15004 	/* Disable polling in the fastpath */
15005 	WRITE_ONCE(eq->mode, mode);
15006 	/* flush out the store buffer */
15007 	smp_wmb();
15008 
15009 	/*
15010 	 * Add this eq to the polling list and start polling. For
15011 	 * a grace period both interrupt handler and poller will
15012 	 * try to process the eq _but_ that's fine.  We have a
15013 	 * synchronization mechanism in place (queue_claimed) to
15014 	 * deal with it.  This is just a draining phase for int-
15015 	 * errupt handler (not eq's) as we have guranteed through
15016 	 * barrier that all the CPUs have seen the new CQ_POLLED
15017 	 * state. which will effectively disable the REARMING of
15018 	 * the EQ.  The whole idea is eq's die off eventually as
15019 	 * we are not rearming EQ's anymore.
15020 	 */
15021 	mode ? lpfc_sli4_add_to_poll_list(eq) :
15022 	       lpfc_sli4_remove_from_poll_list(eq);
15023 }
15024 
15025 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15026 {
15027 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15028 }
15029 
15030 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15031 {
15032 	struct lpfc_hba *phba = eq->phba;
15033 
15034 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15035 
15036 	/* Kick start for the pending io's in h/w.
15037 	 * Once we switch back to interrupt processing on a eq
15038 	 * the io path completion will only arm eq's when it
15039 	 * receives a completion.  But since eq's are in disa-
15040 	 * rmed state it doesn't receive a completion.  This
15041 	 * creates a deadlock scenaro.
15042 	 */
15043 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15044 }
15045 
15046 /**
15047  * lpfc_sli4_queue_free - free a queue structure and associated memory
15048  * @queue: The queue structure to free.
15049  *
15050  * This function frees a queue structure and the DMAable memory used for
15051  * the host resident queue. This function must be called after destroying the
15052  * queue on the HBA.
15053  **/
15054 void
15055 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15056 {
15057 	struct lpfc_dmabuf *dmabuf;
15058 
15059 	if (!queue)
15060 		return;
15061 
15062 	if (!list_empty(&queue->wq_list))
15063 		list_del(&queue->wq_list);
15064 
15065 	while (!list_empty(&queue->page_list)) {
15066 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15067 				 list);
15068 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15069 				  dmabuf->virt, dmabuf->phys);
15070 		kfree(dmabuf);
15071 	}
15072 	if (queue->rqbp) {
15073 		lpfc_free_rq_buffer(queue->phba, queue);
15074 		kfree(queue->rqbp);
15075 	}
15076 
15077 	if (!list_empty(&queue->cpu_list))
15078 		list_del(&queue->cpu_list);
15079 
15080 	kfree(queue);
15081 	return;
15082 }
15083 
15084 /**
15085  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15086  * @phba: The HBA that this queue is being created on.
15087  * @page_size: The size of a queue page
15088  * @entry_size: The size of each queue entry for this queue.
15089  * @entry_count: The number of entries that this queue will handle.
15090  * @cpu: The cpu that will primarily utilize this queue.
15091  *
15092  * This function allocates a queue structure and the DMAable memory used for
15093  * the host resident queue. This function must be called before creating the
15094  * queue on the HBA.
15095  **/
15096 struct lpfc_queue *
15097 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15098 		      uint32_t entry_size, uint32_t entry_count, int cpu)
15099 {
15100 	struct lpfc_queue *queue;
15101 	struct lpfc_dmabuf *dmabuf;
15102 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15103 	uint16_t x, pgcnt;
15104 
15105 	if (!phba->sli4_hba.pc_sli4_params.supported)
15106 		hw_page_size = page_size;
15107 
15108 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15109 
15110 	/* If needed, Adjust page count to match the max the adapter supports */
15111 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15112 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15113 
15114 	queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
15115 			     GFP_KERNEL, cpu_to_node(cpu));
15116 	if (!queue)
15117 		return NULL;
15118 
15119 	INIT_LIST_HEAD(&queue->list);
15120 	INIT_LIST_HEAD(&queue->_poll_list);
15121 	INIT_LIST_HEAD(&queue->wq_list);
15122 	INIT_LIST_HEAD(&queue->wqfull_list);
15123 	INIT_LIST_HEAD(&queue->page_list);
15124 	INIT_LIST_HEAD(&queue->child_list);
15125 	INIT_LIST_HEAD(&queue->cpu_list);
15126 
15127 	/* Set queue parameters now.  If the system cannot provide memory
15128 	 * resources, the free routine needs to know what was allocated.
15129 	 */
15130 	queue->page_count = pgcnt;
15131 	queue->q_pgs = (void **)&queue[1];
15132 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
15133 	queue->entry_size = entry_size;
15134 	queue->entry_count = entry_count;
15135 	queue->page_size = hw_page_size;
15136 	queue->phba = phba;
15137 
15138 	for (x = 0; x < queue->page_count; x++) {
15139 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15140 				      dev_to_node(&phba->pcidev->dev));
15141 		if (!dmabuf)
15142 			goto out_fail;
15143 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15144 						  hw_page_size, &dmabuf->phys,
15145 						  GFP_KERNEL);
15146 		if (!dmabuf->virt) {
15147 			kfree(dmabuf);
15148 			goto out_fail;
15149 		}
15150 		dmabuf->buffer_tag = x;
15151 		list_add_tail(&dmabuf->list, &queue->page_list);
15152 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
15153 		queue->q_pgs[x] = dmabuf->virt;
15154 	}
15155 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15156 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15157 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15158 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15159 
15160 	/* notify_interval will be set during q creation */
15161 
15162 	return queue;
15163 out_fail:
15164 	lpfc_sli4_queue_free(queue);
15165 	return NULL;
15166 }
15167 
15168 /**
15169  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15170  * @phba: HBA structure that indicates port to create a queue on.
15171  * @pci_barset: PCI BAR set flag.
15172  *
15173  * This function shall perform iomap of the specified PCI BAR address to host
15174  * memory address if not already done so and return it. The returned host
15175  * memory address can be NULL.
15176  */
15177 static void __iomem *
15178 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15179 {
15180 	if (!phba->pcidev)
15181 		return NULL;
15182 
15183 	switch (pci_barset) {
15184 	case WQ_PCI_BAR_0_AND_1:
15185 		return phba->pci_bar0_memmap_p;
15186 	case WQ_PCI_BAR_2_AND_3:
15187 		return phba->pci_bar2_memmap_p;
15188 	case WQ_PCI_BAR_4_AND_5:
15189 		return phba->pci_bar4_memmap_p;
15190 	default:
15191 		break;
15192 	}
15193 	return NULL;
15194 }
15195 
15196 /**
15197  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
15198  * @phba: HBA structure that EQs are on.
15199  * @startq: The starting EQ index to modify
15200  * @numq: The number of EQs (consecutive indexes) to modify
15201  * @usdelay: amount of delay
15202  *
15203  * This function revises the EQ delay on 1 or more EQs. The EQ delay
15204  * is set either by writing to a register (if supported by the SLI Port)
15205  * or by mailbox command. The mailbox command allows several EQs to be
15206  * updated at once.
15207  *
15208  * The @phba struct is used to send a mailbox command to HBA. The @startq
15209  * is used to get the starting EQ index to change. The @numq value is
15210  * used to specify how many consecutive EQ indexes, starting at EQ index,
15211  * are to be changed. This function is asynchronous and will wait for any
15212  * mailbox commands to finish before returning.
15213  *
15214  * On success this function will return a zero. If unable to allocate
15215  * enough memory this function will return -ENOMEM. If a mailbox command
15216  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
15217  * have had their delay multipler changed.
15218  **/
15219 void
15220 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
15221 			 uint32_t numq, uint32_t usdelay)
15222 {
15223 	struct lpfc_mbx_modify_eq_delay *eq_delay;
15224 	LPFC_MBOXQ_t *mbox;
15225 	struct lpfc_queue *eq;
15226 	int cnt = 0, rc, length;
15227 	uint32_t shdr_status, shdr_add_status;
15228 	uint32_t dmult;
15229 	int qidx;
15230 	union lpfc_sli4_cfg_shdr *shdr;
15231 
15232 	if (startq >= phba->cfg_irq_chann)
15233 		return;
15234 
15235 	if (usdelay > 0xFFFF) {
15236 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
15237 				"6429 usdelay %d too large. Scaled down to "
15238 				"0xFFFF.\n", usdelay);
15239 		usdelay = 0xFFFF;
15240 	}
15241 
15242 	/* set values by EQ_DELAY register if supported */
15243 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
15244 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15245 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15246 			if (!eq)
15247 				continue;
15248 
15249 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
15250 
15251 			if (++cnt >= numq)
15252 				break;
15253 		}
15254 		return;
15255 	}
15256 
15257 	/* Otherwise, set values by mailbox cmd */
15258 
15259 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15260 	if (!mbox) {
15261 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15262 				"6428 Failed allocating mailbox cmd buffer."
15263 				" EQ delay was not set.\n");
15264 		return;
15265 	}
15266 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
15267 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15268 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15269 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
15270 			 length, LPFC_SLI4_MBX_EMBED);
15271 	eq_delay = &mbox->u.mqe.un.eq_delay;
15272 
15273 	/* Calculate delay multiper from maximum interrupt per second */
15274 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
15275 	if (dmult)
15276 		dmult--;
15277 	if (dmult > LPFC_DMULT_MAX)
15278 		dmult = LPFC_DMULT_MAX;
15279 
15280 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15281 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15282 		if (!eq)
15283 			continue;
15284 		eq->q_mode = usdelay;
15285 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
15286 		eq_delay->u.request.eq[cnt].phase = 0;
15287 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
15288 
15289 		if (++cnt >= numq)
15290 			break;
15291 	}
15292 	eq_delay->u.request.num_eq = cnt;
15293 
15294 	mbox->vport = phba->pport;
15295 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15296 	mbox->ctx_buf = NULL;
15297 	mbox->ctx_ndlp = NULL;
15298 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15299 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
15300 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15301 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15302 	if (shdr_status || shdr_add_status || rc) {
15303 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15304 				"2512 MODIFY_EQ_DELAY mailbox failed with "
15305 				"status x%x add_status x%x, mbx status x%x\n",
15306 				shdr_status, shdr_add_status, rc);
15307 	}
15308 	mempool_free(mbox, phba->mbox_mem_pool);
15309 	return;
15310 }
15311 
15312 /**
15313  * lpfc_eq_create - Create an Event Queue on the HBA
15314  * @phba: HBA structure that indicates port to create a queue on.
15315  * @eq: The queue structure to use to create the event queue.
15316  * @imax: The maximum interrupt per second limit.
15317  *
15318  * This function creates an event queue, as detailed in @eq, on a port,
15319  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
15320  *
15321  * The @phba struct is used to send mailbox command to HBA. The @eq struct
15322  * is used to get the entry count and entry size that are necessary to
15323  * determine the number of pages to allocate and use for this queue. This
15324  * function will send the EQ_CREATE mailbox command to the HBA to setup the
15325  * event queue. This function is asynchronous and will wait for the mailbox
15326  * command to finish before continuing.
15327  *
15328  * On success this function will return a zero. If unable to allocate enough
15329  * memory this function will return -ENOMEM. If the queue create mailbox command
15330  * fails this function will return -ENXIO.
15331  **/
15332 int
15333 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
15334 {
15335 	struct lpfc_mbx_eq_create *eq_create;
15336 	LPFC_MBOXQ_t *mbox;
15337 	int rc, length, status = 0;
15338 	struct lpfc_dmabuf *dmabuf;
15339 	uint32_t shdr_status, shdr_add_status;
15340 	union lpfc_sli4_cfg_shdr *shdr;
15341 	uint16_t dmult;
15342 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15343 
15344 	/* sanity check on queue memory */
15345 	if (!eq)
15346 		return -ENODEV;
15347 	if (!phba->sli4_hba.pc_sli4_params.supported)
15348 		hw_page_size = SLI4_PAGE_SIZE;
15349 
15350 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15351 	if (!mbox)
15352 		return -ENOMEM;
15353 	length = (sizeof(struct lpfc_mbx_eq_create) -
15354 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15355 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15356 			 LPFC_MBOX_OPCODE_EQ_CREATE,
15357 			 length, LPFC_SLI4_MBX_EMBED);
15358 	eq_create = &mbox->u.mqe.un.eq_create;
15359 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
15360 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
15361 	       eq->page_count);
15362 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
15363 	       LPFC_EQE_SIZE);
15364 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
15365 
15366 	/* Use version 2 of CREATE_EQ if eqav is set */
15367 	if (phba->sli4_hba.pc_sli4_params.eqav) {
15368 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
15369 		       LPFC_Q_CREATE_VERSION_2);
15370 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
15371 		       phba->sli4_hba.pc_sli4_params.eqav);
15372 	}
15373 
15374 	/* don't setup delay multiplier using EQ_CREATE */
15375 	dmult = 0;
15376 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
15377 	       dmult);
15378 	switch (eq->entry_count) {
15379 	default:
15380 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15381 				"0360 Unsupported EQ count. (%d)\n",
15382 				eq->entry_count);
15383 		if (eq->entry_count < 256) {
15384 			status = -EINVAL;
15385 			goto out;
15386 		}
15387 		fallthrough;	/* otherwise default to smallest count */
15388 	case 256:
15389 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15390 		       LPFC_EQ_CNT_256);
15391 		break;
15392 	case 512:
15393 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15394 		       LPFC_EQ_CNT_512);
15395 		break;
15396 	case 1024:
15397 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15398 		       LPFC_EQ_CNT_1024);
15399 		break;
15400 	case 2048:
15401 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15402 		       LPFC_EQ_CNT_2048);
15403 		break;
15404 	case 4096:
15405 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15406 		       LPFC_EQ_CNT_4096);
15407 		break;
15408 	}
15409 	list_for_each_entry(dmabuf, &eq->page_list, list) {
15410 		memset(dmabuf->virt, 0, hw_page_size);
15411 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15412 					putPaddrLow(dmabuf->phys);
15413 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15414 					putPaddrHigh(dmabuf->phys);
15415 	}
15416 	mbox->vport = phba->pport;
15417 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15418 	mbox->ctx_buf = NULL;
15419 	mbox->ctx_ndlp = NULL;
15420 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15421 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15422 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15423 	if (shdr_status || shdr_add_status || rc) {
15424 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15425 				"2500 EQ_CREATE mailbox failed with "
15426 				"status x%x add_status x%x, mbx status x%x\n",
15427 				shdr_status, shdr_add_status, rc);
15428 		status = -ENXIO;
15429 	}
15430 	eq->type = LPFC_EQ;
15431 	eq->subtype = LPFC_NONE;
15432 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
15433 	if (eq->queue_id == 0xFFFF)
15434 		status = -ENXIO;
15435 	eq->host_index = 0;
15436 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
15437 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
15438 out:
15439 	mempool_free(mbox, phba->mbox_mem_pool);
15440 	return status;
15441 }
15442 
15443 static int lpfc_cq_poll_hdler(struct irq_poll *iop, int budget)
15444 {
15445 	struct lpfc_queue *cq = container_of(iop, struct lpfc_queue, iop);
15446 
15447 	__lpfc_sli4_hba_process_cq(cq, LPFC_IRQ_POLL);
15448 
15449 	return 1;
15450 }
15451 
15452 /**
15453  * lpfc_cq_create - Create a Completion Queue on the HBA
15454  * @phba: HBA structure that indicates port to create a queue on.
15455  * @cq: The queue structure to use to create the completion queue.
15456  * @eq: The event queue to bind this completion queue to.
15457  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
15458  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
15459  *
15460  * This function creates a completion queue, as detailed in @wq, on a port,
15461  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
15462  *
15463  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15464  * is used to get the entry count and entry size that are necessary to
15465  * determine the number of pages to allocate and use for this queue. The @eq
15466  * is used to indicate which event queue to bind this completion queue to. This
15467  * function will send the CQ_CREATE mailbox command to the HBA to setup the
15468  * completion queue. This function is asynchronous and will wait for the mailbox
15469  * command to finish before continuing.
15470  *
15471  * On success this function will return a zero. If unable to allocate enough
15472  * memory this function will return -ENOMEM. If the queue create mailbox command
15473  * fails this function will return -ENXIO.
15474  **/
15475 int
15476 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
15477 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
15478 {
15479 	struct lpfc_mbx_cq_create *cq_create;
15480 	struct lpfc_dmabuf *dmabuf;
15481 	LPFC_MBOXQ_t *mbox;
15482 	int rc, length, status = 0;
15483 	uint32_t shdr_status, shdr_add_status;
15484 	union lpfc_sli4_cfg_shdr *shdr;
15485 
15486 	/* sanity check on queue memory */
15487 	if (!cq || !eq)
15488 		return -ENODEV;
15489 
15490 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15491 	if (!mbox)
15492 		return -ENOMEM;
15493 	length = (sizeof(struct lpfc_mbx_cq_create) -
15494 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15495 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15496 			 LPFC_MBOX_OPCODE_CQ_CREATE,
15497 			 length, LPFC_SLI4_MBX_EMBED);
15498 	cq_create = &mbox->u.mqe.un.cq_create;
15499 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
15500 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
15501 		    cq->page_count);
15502 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
15503 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
15504 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15505 	       phba->sli4_hba.pc_sli4_params.cqv);
15506 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
15507 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
15508 		       (cq->page_size / SLI4_PAGE_SIZE));
15509 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
15510 		       eq->queue_id);
15511 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
15512 		       phba->sli4_hba.pc_sli4_params.cqav);
15513 	} else {
15514 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
15515 		       eq->queue_id);
15516 	}
15517 	switch (cq->entry_count) {
15518 	case 2048:
15519 	case 4096:
15520 		if (phba->sli4_hba.pc_sli4_params.cqv ==
15521 		    LPFC_Q_CREATE_VERSION_2) {
15522 			cq_create->u.request.context.lpfc_cq_context_count =
15523 				cq->entry_count;
15524 			bf_set(lpfc_cq_context_count,
15525 			       &cq_create->u.request.context,
15526 			       LPFC_CQ_CNT_WORD7);
15527 			break;
15528 		}
15529 		fallthrough;
15530 	default:
15531 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15532 				"0361 Unsupported CQ count: "
15533 				"entry cnt %d sz %d pg cnt %d\n",
15534 				cq->entry_count, cq->entry_size,
15535 				cq->page_count);
15536 		if (cq->entry_count < 256) {
15537 			status = -EINVAL;
15538 			goto out;
15539 		}
15540 		fallthrough;	/* otherwise default to smallest count */
15541 	case 256:
15542 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15543 		       LPFC_CQ_CNT_256);
15544 		break;
15545 	case 512:
15546 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15547 		       LPFC_CQ_CNT_512);
15548 		break;
15549 	case 1024:
15550 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15551 		       LPFC_CQ_CNT_1024);
15552 		break;
15553 	}
15554 	list_for_each_entry(dmabuf, &cq->page_list, list) {
15555 		memset(dmabuf->virt, 0, cq->page_size);
15556 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15557 					putPaddrLow(dmabuf->phys);
15558 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15559 					putPaddrHigh(dmabuf->phys);
15560 	}
15561 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15562 
15563 	/* The IOCTL status is embedded in the mailbox subheader. */
15564 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15565 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15566 	if (shdr_status || shdr_add_status || rc) {
15567 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15568 				"2501 CQ_CREATE mailbox failed with "
15569 				"status x%x add_status x%x, mbx status x%x\n",
15570 				shdr_status, shdr_add_status, rc);
15571 		status = -ENXIO;
15572 		goto out;
15573 	}
15574 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15575 	if (cq->queue_id == 0xFFFF) {
15576 		status = -ENXIO;
15577 		goto out;
15578 	}
15579 	/* link the cq onto the parent eq child list */
15580 	list_add_tail(&cq->list, &eq->child_list);
15581 	/* Set up completion queue's type and subtype */
15582 	cq->type = type;
15583 	cq->subtype = subtype;
15584 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15585 	cq->assoc_qid = eq->queue_id;
15586 	cq->assoc_qp = eq;
15587 	cq->host_index = 0;
15588 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15589 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
15590 
15591 	if (cq->queue_id > phba->sli4_hba.cq_max)
15592 		phba->sli4_hba.cq_max = cq->queue_id;
15593 
15594 	irq_poll_init(&cq->iop, LPFC_IRQ_POLL_WEIGHT, lpfc_cq_poll_hdler);
15595 out:
15596 	mempool_free(mbox, phba->mbox_mem_pool);
15597 	return status;
15598 }
15599 
15600 /**
15601  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
15602  * @phba: HBA structure that indicates port to create a queue on.
15603  * @cqp: The queue structure array to use to create the completion queues.
15604  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
15605  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
15606  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
15607  *
15608  * This function creates a set of  completion queue, s to support MRQ
15609  * as detailed in @cqp, on a port,
15610  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
15611  *
15612  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15613  * is used to get the entry count and entry size that are necessary to
15614  * determine the number of pages to allocate and use for this queue. The @eq
15615  * is used to indicate which event queue to bind this completion queue to. This
15616  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
15617  * completion queue. This function is asynchronous and will wait for the mailbox
15618  * command to finish before continuing.
15619  *
15620  * On success this function will return a zero. If unable to allocate enough
15621  * memory this function will return -ENOMEM. If the queue create mailbox command
15622  * fails this function will return -ENXIO.
15623  **/
15624 int
15625 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
15626 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
15627 		   uint32_t subtype)
15628 {
15629 	struct lpfc_queue *cq;
15630 	struct lpfc_queue *eq;
15631 	struct lpfc_mbx_cq_create_set *cq_set;
15632 	struct lpfc_dmabuf *dmabuf;
15633 	LPFC_MBOXQ_t *mbox;
15634 	int rc, length, alloclen, status = 0;
15635 	int cnt, idx, numcq, page_idx = 0;
15636 	uint32_t shdr_status, shdr_add_status;
15637 	union lpfc_sli4_cfg_shdr *shdr;
15638 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15639 
15640 	/* sanity check on queue memory */
15641 	numcq = phba->cfg_nvmet_mrq;
15642 	if (!cqp || !hdwq || !numcq)
15643 		return -ENODEV;
15644 
15645 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15646 	if (!mbox)
15647 		return -ENOMEM;
15648 
15649 	length = sizeof(struct lpfc_mbx_cq_create_set);
15650 	length += ((numcq * cqp[0]->page_count) *
15651 		   sizeof(struct dma_address));
15652 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15653 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
15654 			LPFC_SLI4_MBX_NEMBED);
15655 	if (alloclen < length) {
15656 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15657 				"3098 Allocated DMA memory size (%d) is "
15658 				"less than the requested DMA memory size "
15659 				"(%d)\n", alloclen, length);
15660 		status = -ENOMEM;
15661 		goto out;
15662 	}
15663 	cq_set = mbox->sge_array->addr[0];
15664 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
15665 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
15666 
15667 	for (idx = 0; idx < numcq; idx++) {
15668 		cq = cqp[idx];
15669 		eq = hdwq[idx].hba_eq;
15670 		if (!cq || !eq) {
15671 			status = -ENOMEM;
15672 			goto out;
15673 		}
15674 		if (!phba->sli4_hba.pc_sli4_params.supported)
15675 			hw_page_size = cq->page_size;
15676 
15677 		switch (idx) {
15678 		case 0:
15679 			bf_set(lpfc_mbx_cq_create_set_page_size,
15680 			       &cq_set->u.request,
15681 			       (hw_page_size / SLI4_PAGE_SIZE));
15682 			bf_set(lpfc_mbx_cq_create_set_num_pages,
15683 			       &cq_set->u.request, cq->page_count);
15684 			bf_set(lpfc_mbx_cq_create_set_evt,
15685 			       &cq_set->u.request, 1);
15686 			bf_set(lpfc_mbx_cq_create_set_valid,
15687 			       &cq_set->u.request, 1);
15688 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
15689 			       &cq_set->u.request, 0);
15690 			bf_set(lpfc_mbx_cq_create_set_num_cq,
15691 			       &cq_set->u.request, numcq);
15692 			bf_set(lpfc_mbx_cq_create_set_autovalid,
15693 			       &cq_set->u.request,
15694 			       phba->sli4_hba.pc_sli4_params.cqav);
15695 			switch (cq->entry_count) {
15696 			case 2048:
15697 			case 4096:
15698 				if (phba->sli4_hba.pc_sli4_params.cqv ==
15699 				    LPFC_Q_CREATE_VERSION_2) {
15700 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15701 					       &cq_set->u.request,
15702 						cq->entry_count);
15703 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15704 					       &cq_set->u.request,
15705 					       LPFC_CQ_CNT_WORD7);
15706 					break;
15707 				}
15708 				fallthrough;
15709 			default:
15710 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15711 						"3118 Bad CQ count. (%d)\n",
15712 						cq->entry_count);
15713 				if (cq->entry_count < 256) {
15714 					status = -EINVAL;
15715 					goto out;
15716 				}
15717 				fallthrough;	/* otherwise default to smallest */
15718 			case 256:
15719 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15720 				       &cq_set->u.request, LPFC_CQ_CNT_256);
15721 				break;
15722 			case 512:
15723 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15724 				       &cq_set->u.request, LPFC_CQ_CNT_512);
15725 				break;
15726 			case 1024:
15727 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15728 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
15729 				break;
15730 			}
15731 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
15732 			       &cq_set->u.request, eq->queue_id);
15733 			break;
15734 		case 1:
15735 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
15736 			       &cq_set->u.request, eq->queue_id);
15737 			break;
15738 		case 2:
15739 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
15740 			       &cq_set->u.request, eq->queue_id);
15741 			break;
15742 		case 3:
15743 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
15744 			       &cq_set->u.request, eq->queue_id);
15745 			break;
15746 		case 4:
15747 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
15748 			       &cq_set->u.request, eq->queue_id);
15749 			break;
15750 		case 5:
15751 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
15752 			       &cq_set->u.request, eq->queue_id);
15753 			break;
15754 		case 6:
15755 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
15756 			       &cq_set->u.request, eq->queue_id);
15757 			break;
15758 		case 7:
15759 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
15760 			       &cq_set->u.request, eq->queue_id);
15761 			break;
15762 		case 8:
15763 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
15764 			       &cq_set->u.request, eq->queue_id);
15765 			break;
15766 		case 9:
15767 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
15768 			       &cq_set->u.request, eq->queue_id);
15769 			break;
15770 		case 10:
15771 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
15772 			       &cq_set->u.request, eq->queue_id);
15773 			break;
15774 		case 11:
15775 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
15776 			       &cq_set->u.request, eq->queue_id);
15777 			break;
15778 		case 12:
15779 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
15780 			       &cq_set->u.request, eq->queue_id);
15781 			break;
15782 		case 13:
15783 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
15784 			       &cq_set->u.request, eq->queue_id);
15785 			break;
15786 		case 14:
15787 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
15788 			       &cq_set->u.request, eq->queue_id);
15789 			break;
15790 		case 15:
15791 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
15792 			       &cq_set->u.request, eq->queue_id);
15793 			break;
15794 		}
15795 
15796 		/* link the cq onto the parent eq child list */
15797 		list_add_tail(&cq->list, &eq->child_list);
15798 		/* Set up completion queue's type and subtype */
15799 		cq->type = type;
15800 		cq->subtype = subtype;
15801 		cq->assoc_qid = eq->queue_id;
15802 		cq->assoc_qp = eq;
15803 		cq->host_index = 0;
15804 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15805 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
15806 					 cq->entry_count);
15807 		cq->chann = idx;
15808 
15809 		rc = 0;
15810 		list_for_each_entry(dmabuf, &cq->page_list, list) {
15811 			memset(dmabuf->virt, 0, hw_page_size);
15812 			cnt = page_idx + dmabuf->buffer_tag;
15813 			cq_set->u.request.page[cnt].addr_lo =
15814 					putPaddrLow(dmabuf->phys);
15815 			cq_set->u.request.page[cnt].addr_hi =
15816 					putPaddrHigh(dmabuf->phys);
15817 			rc++;
15818 		}
15819 		page_idx += rc;
15820 	}
15821 
15822 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15823 
15824 	/* The IOCTL status is embedded in the mailbox subheader. */
15825 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15826 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15827 	if (shdr_status || shdr_add_status || rc) {
15828 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15829 				"3119 CQ_CREATE_SET mailbox failed with "
15830 				"status x%x add_status x%x, mbx status x%x\n",
15831 				shdr_status, shdr_add_status, rc);
15832 		status = -ENXIO;
15833 		goto out;
15834 	}
15835 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
15836 	if (rc == 0xFFFF) {
15837 		status = -ENXIO;
15838 		goto out;
15839 	}
15840 
15841 	for (idx = 0; idx < numcq; idx++) {
15842 		cq = cqp[idx];
15843 		cq->queue_id = rc + idx;
15844 		if (cq->queue_id > phba->sli4_hba.cq_max)
15845 			phba->sli4_hba.cq_max = cq->queue_id;
15846 	}
15847 
15848 out:
15849 	lpfc_sli4_mbox_cmd_free(phba, mbox);
15850 	return status;
15851 }
15852 
15853 /**
15854  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
15855  * @phba: HBA structure that indicates port to create a queue on.
15856  * @mq: The queue structure to use to create the mailbox queue.
15857  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
15858  * @cq: The completion queue to associate with this cq.
15859  *
15860  * This function provides failback (fb) functionality when the
15861  * mq_create_ext fails on older FW generations.  It's purpose is identical
15862  * to mq_create_ext otherwise.
15863  *
15864  * This routine cannot fail as all attributes were previously accessed and
15865  * initialized in mq_create_ext.
15866  **/
15867 static void
15868 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
15869 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
15870 {
15871 	struct lpfc_mbx_mq_create *mq_create;
15872 	struct lpfc_dmabuf *dmabuf;
15873 	int length;
15874 
15875 	length = (sizeof(struct lpfc_mbx_mq_create) -
15876 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15877 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15878 			 LPFC_MBOX_OPCODE_MQ_CREATE,
15879 			 length, LPFC_SLI4_MBX_EMBED);
15880 	mq_create = &mbox->u.mqe.un.mq_create;
15881 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
15882 	       mq->page_count);
15883 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
15884 	       cq->queue_id);
15885 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
15886 	switch (mq->entry_count) {
15887 	case 16:
15888 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15889 		       LPFC_MQ_RING_SIZE_16);
15890 		break;
15891 	case 32:
15892 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15893 		       LPFC_MQ_RING_SIZE_32);
15894 		break;
15895 	case 64:
15896 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15897 		       LPFC_MQ_RING_SIZE_64);
15898 		break;
15899 	case 128:
15900 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15901 		       LPFC_MQ_RING_SIZE_128);
15902 		break;
15903 	}
15904 	list_for_each_entry(dmabuf, &mq->page_list, list) {
15905 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15906 			putPaddrLow(dmabuf->phys);
15907 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15908 			putPaddrHigh(dmabuf->phys);
15909 	}
15910 }
15911 
15912 /**
15913  * lpfc_mq_create - Create a mailbox Queue on the HBA
15914  * @phba: HBA structure that indicates port to create a queue on.
15915  * @mq: The queue structure to use to create the mailbox queue.
15916  * @cq: The completion queue to associate with this cq.
15917  * @subtype: The queue's subtype.
15918  *
15919  * This function creates a mailbox queue, as detailed in @mq, on a port,
15920  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
15921  *
15922  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15923  * is used to get the entry count and entry size that are necessary to
15924  * determine the number of pages to allocate and use for this queue. This
15925  * function will send the MQ_CREATE mailbox command to the HBA to setup the
15926  * mailbox queue. This function is asynchronous and will wait for the mailbox
15927  * command to finish before continuing.
15928  *
15929  * On success this function will return a zero. If unable to allocate enough
15930  * memory this function will return -ENOMEM. If the queue create mailbox command
15931  * fails this function will return -ENXIO.
15932  **/
15933 int32_t
15934 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
15935 	       struct lpfc_queue *cq, uint32_t subtype)
15936 {
15937 	struct lpfc_mbx_mq_create *mq_create;
15938 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
15939 	struct lpfc_dmabuf *dmabuf;
15940 	LPFC_MBOXQ_t *mbox;
15941 	int rc, length, status = 0;
15942 	uint32_t shdr_status, shdr_add_status;
15943 	union lpfc_sli4_cfg_shdr *shdr;
15944 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15945 
15946 	/* sanity check on queue memory */
15947 	if (!mq || !cq)
15948 		return -ENODEV;
15949 	if (!phba->sli4_hba.pc_sli4_params.supported)
15950 		hw_page_size = SLI4_PAGE_SIZE;
15951 
15952 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15953 	if (!mbox)
15954 		return -ENOMEM;
15955 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
15956 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15957 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15958 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
15959 			 length, LPFC_SLI4_MBX_EMBED);
15960 
15961 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
15962 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
15963 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
15964 	       &mq_create_ext->u.request, mq->page_count);
15965 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
15966 	       &mq_create_ext->u.request, 1);
15967 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
15968 	       &mq_create_ext->u.request, 1);
15969 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
15970 	       &mq_create_ext->u.request, 1);
15971 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
15972 	       &mq_create_ext->u.request, 1);
15973 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
15974 	       &mq_create_ext->u.request, 1);
15975 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
15976 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15977 	       phba->sli4_hba.pc_sli4_params.mqv);
15978 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
15979 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
15980 		       cq->queue_id);
15981 	else
15982 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
15983 		       cq->queue_id);
15984 	switch (mq->entry_count) {
15985 	default:
15986 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15987 				"0362 Unsupported MQ count. (%d)\n",
15988 				mq->entry_count);
15989 		if (mq->entry_count < 16) {
15990 			status = -EINVAL;
15991 			goto out;
15992 		}
15993 		fallthrough;	/* otherwise default to smallest count */
15994 	case 16:
15995 		bf_set(lpfc_mq_context_ring_size,
15996 		       &mq_create_ext->u.request.context,
15997 		       LPFC_MQ_RING_SIZE_16);
15998 		break;
15999 	case 32:
16000 		bf_set(lpfc_mq_context_ring_size,
16001 		       &mq_create_ext->u.request.context,
16002 		       LPFC_MQ_RING_SIZE_32);
16003 		break;
16004 	case 64:
16005 		bf_set(lpfc_mq_context_ring_size,
16006 		       &mq_create_ext->u.request.context,
16007 		       LPFC_MQ_RING_SIZE_64);
16008 		break;
16009 	case 128:
16010 		bf_set(lpfc_mq_context_ring_size,
16011 		       &mq_create_ext->u.request.context,
16012 		       LPFC_MQ_RING_SIZE_128);
16013 		break;
16014 	}
16015 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16016 		memset(dmabuf->virt, 0, hw_page_size);
16017 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16018 					putPaddrLow(dmabuf->phys);
16019 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16020 					putPaddrHigh(dmabuf->phys);
16021 	}
16022 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16023 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16024 			      &mq_create_ext->u.response);
16025 	if (rc != MBX_SUCCESS) {
16026 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16027 				"2795 MQ_CREATE_EXT failed with "
16028 				"status x%x. Failback to MQ_CREATE.\n",
16029 				rc);
16030 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16031 		mq_create = &mbox->u.mqe.un.mq_create;
16032 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16033 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16034 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16035 				      &mq_create->u.response);
16036 	}
16037 
16038 	/* The IOCTL status is embedded in the mailbox subheader. */
16039 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16040 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16041 	if (shdr_status || shdr_add_status || rc) {
16042 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16043 				"2502 MQ_CREATE mailbox failed with "
16044 				"status x%x add_status x%x, mbx status x%x\n",
16045 				shdr_status, shdr_add_status, rc);
16046 		status = -ENXIO;
16047 		goto out;
16048 	}
16049 	if (mq->queue_id == 0xFFFF) {
16050 		status = -ENXIO;
16051 		goto out;
16052 	}
16053 	mq->type = LPFC_MQ;
16054 	mq->assoc_qid = cq->queue_id;
16055 	mq->subtype = subtype;
16056 	mq->host_index = 0;
16057 	mq->hba_index = 0;
16058 
16059 	/* link the mq onto the parent cq child list */
16060 	list_add_tail(&mq->list, &cq->child_list);
16061 out:
16062 	mempool_free(mbox, phba->mbox_mem_pool);
16063 	return status;
16064 }
16065 
16066 /**
16067  * lpfc_wq_create - Create a Work Queue on the HBA
16068  * @phba: HBA structure that indicates port to create a queue on.
16069  * @wq: The queue structure to use to create the work queue.
16070  * @cq: The completion queue to bind this work queue to.
16071  * @subtype: The subtype of the work queue indicating its functionality.
16072  *
16073  * This function creates a work queue, as detailed in @wq, on a port, described
16074  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16075  *
16076  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16077  * is used to get the entry count and entry size that are necessary to
16078  * determine the number of pages to allocate and use for this queue. The @cq
16079  * is used to indicate which completion queue to bind this work queue to. This
16080  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16081  * work queue. This function is asynchronous and will wait for the mailbox
16082  * command to finish before continuing.
16083  *
16084  * On success this function will return a zero. If unable to allocate enough
16085  * memory this function will return -ENOMEM. If the queue create mailbox command
16086  * fails this function will return -ENXIO.
16087  **/
16088 int
16089 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16090 	       struct lpfc_queue *cq, uint32_t subtype)
16091 {
16092 	struct lpfc_mbx_wq_create *wq_create;
16093 	struct lpfc_dmabuf *dmabuf;
16094 	LPFC_MBOXQ_t *mbox;
16095 	int rc, length, status = 0;
16096 	uint32_t shdr_status, shdr_add_status;
16097 	union lpfc_sli4_cfg_shdr *shdr;
16098 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16099 	struct dma_address *page;
16100 	void __iomem *bar_memmap_p;
16101 	uint32_t db_offset;
16102 	uint16_t pci_barset;
16103 	uint8_t dpp_barset;
16104 	uint32_t dpp_offset;
16105 	uint8_t wq_create_version;
16106 #ifdef CONFIG_X86
16107 	unsigned long pg_addr;
16108 #endif
16109 
16110 	/* sanity check on queue memory */
16111 	if (!wq || !cq)
16112 		return -ENODEV;
16113 	if (!phba->sli4_hba.pc_sli4_params.supported)
16114 		hw_page_size = wq->page_size;
16115 
16116 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16117 	if (!mbox)
16118 		return -ENOMEM;
16119 	length = (sizeof(struct lpfc_mbx_wq_create) -
16120 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16121 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16122 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16123 			 length, LPFC_SLI4_MBX_EMBED);
16124 	wq_create = &mbox->u.mqe.un.wq_create;
16125 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16126 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16127 		    wq->page_count);
16128 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16129 		    cq->queue_id);
16130 
16131 	/* wqv is the earliest version supported, NOT the latest */
16132 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16133 	       phba->sli4_hba.pc_sli4_params.wqv);
16134 
16135 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16136 	    (wq->page_size > SLI4_PAGE_SIZE))
16137 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
16138 	else
16139 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
16140 
16141 	switch (wq_create_version) {
16142 	case LPFC_Q_CREATE_VERSION_1:
16143 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
16144 		       wq->entry_count);
16145 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16146 		       LPFC_Q_CREATE_VERSION_1);
16147 
16148 		switch (wq->entry_size) {
16149 		default:
16150 		case 64:
16151 			bf_set(lpfc_mbx_wq_create_wqe_size,
16152 			       &wq_create->u.request_1,
16153 			       LPFC_WQ_WQE_SIZE_64);
16154 			break;
16155 		case 128:
16156 			bf_set(lpfc_mbx_wq_create_wqe_size,
16157 			       &wq_create->u.request_1,
16158 			       LPFC_WQ_WQE_SIZE_128);
16159 			break;
16160 		}
16161 		/* Request DPP by default */
16162 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
16163 		bf_set(lpfc_mbx_wq_create_page_size,
16164 		       &wq_create->u.request_1,
16165 		       (wq->page_size / SLI4_PAGE_SIZE));
16166 		page = wq_create->u.request_1.page;
16167 		break;
16168 	default:
16169 		page = wq_create->u.request.page;
16170 		break;
16171 	}
16172 
16173 	list_for_each_entry(dmabuf, &wq->page_list, list) {
16174 		memset(dmabuf->virt, 0, hw_page_size);
16175 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
16176 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
16177 	}
16178 
16179 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16180 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
16181 
16182 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16183 	/* The IOCTL status is embedded in the mailbox subheader. */
16184 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16185 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16186 	if (shdr_status || shdr_add_status || rc) {
16187 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16188 				"2503 WQ_CREATE mailbox failed with "
16189 				"status x%x add_status x%x, mbx status x%x\n",
16190 				shdr_status, shdr_add_status, rc);
16191 		status = -ENXIO;
16192 		goto out;
16193 	}
16194 
16195 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
16196 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
16197 					&wq_create->u.response);
16198 	else
16199 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
16200 					&wq_create->u.response_1);
16201 
16202 	if (wq->queue_id == 0xFFFF) {
16203 		status = -ENXIO;
16204 		goto out;
16205 	}
16206 
16207 	wq->db_format = LPFC_DB_LIST_FORMAT;
16208 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
16209 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16210 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
16211 					       &wq_create->u.response);
16212 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
16213 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
16214 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16215 						"3265 WQ[%d] doorbell format "
16216 						"not supported: x%x\n",
16217 						wq->queue_id, wq->db_format);
16218 				status = -EINVAL;
16219 				goto out;
16220 			}
16221 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
16222 					    &wq_create->u.response);
16223 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16224 								   pci_barset);
16225 			if (!bar_memmap_p) {
16226 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16227 						"3263 WQ[%d] failed to memmap "
16228 						"pci barset:x%x\n",
16229 						wq->queue_id, pci_barset);
16230 				status = -ENOMEM;
16231 				goto out;
16232 			}
16233 			db_offset = wq_create->u.response.doorbell_offset;
16234 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
16235 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
16236 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16237 						"3252 WQ[%d] doorbell offset "
16238 						"not supported: x%x\n",
16239 						wq->queue_id, db_offset);
16240 				status = -EINVAL;
16241 				goto out;
16242 			}
16243 			wq->db_regaddr = bar_memmap_p + db_offset;
16244 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16245 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
16246 					"format:x%x\n", wq->queue_id,
16247 					pci_barset, db_offset, wq->db_format);
16248 		} else
16249 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
16250 	} else {
16251 		/* Check if DPP was honored by the firmware */
16252 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
16253 				    &wq_create->u.response_1);
16254 		if (wq->dpp_enable) {
16255 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
16256 					    &wq_create->u.response_1);
16257 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16258 								   pci_barset);
16259 			if (!bar_memmap_p) {
16260 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16261 						"3267 WQ[%d] failed to memmap "
16262 						"pci barset:x%x\n",
16263 						wq->queue_id, pci_barset);
16264 				status = -ENOMEM;
16265 				goto out;
16266 			}
16267 			db_offset = wq_create->u.response_1.doorbell_offset;
16268 			wq->db_regaddr = bar_memmap_p + db_offset;
16269 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
16270 					    &wq_create->u.response_1);
16271 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
16272 					    &wq_create->u.response_1);
16273 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16274 								   dpp_barset);
16275 			if (!bar_memmap_p) {
16276 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16277 						"3268 WQ[%d] failed to memmap "
16278 						"pci barset:x%x\n",
16279 						wq->queue_id, dpp_barset);
16280 				status = -ENOMEM;
16281 				goto out;
16282 			}
16283 			dpp_offset = wq_create->u.response_1.dpp_offset;
16284 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
16285 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16286 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
16287 					"dpp_id:x%x dpp_barset:x%x "
16288 					"dpp_offset:x%x\n",
16289 					wq->queue_id, pci_barset, db_offset,
16290 					wq->dpp_id, dpp_barset, dpp_offset);
16291 
16292 #ifdef CONFIG_X86
16293 			/* Enable combined writes for DPP aperture */
16294 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
16295 			rc = set_memory_wc(pg_addr, 1);
16296 			if (rc) {
16297 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16298 					"3272 Cannot setup Combined "
16299 					"Write on WQ[%d] - disable DPP\n",
16300 					wq->queue_id);
16301 				phba->cfg_enable_dpp = 0;
16302 			}
16303 #else
16304 			phba->cfg_enable_dpp = 0;
16305 #endif
16306 		} else
16307 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
16308 	}
16309 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
16310 	if (wq->pring == NULL) {
16311 		status = -ENOMEM;
16312 		goto out;
16313 	}
16314 	wq->type = LPFC_WQ;
16315 	wq->assoc_qid = cq->queue_id;
16316 	wq->subtype = subtype;
16317 	wq->host_index = 0;
16318 	wq->hba_index = 0;
16319 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
16320 
16321 	/* link the wq onto the parent cq child list */
16322 	list_add_tail(&wq->list, &cq->child_list);
16323 out:
16324 	mempool_free(mbox, phba->mbox_mem_pool);
16325 	return status;
16326 }
16327 
16328 /**
16329  * lpfc_rq_create - Create a Receive Queue on the HBA
16330  * @phba: HBA structure that indicates port to create a queue on.
16331  * @hrq: The queue structure to use to create the header receive queue.
16332  * @drq: The queue structure to use to create the data receive queue.
16333  * @cq: The completion queue to bind this work queue to.
16334  * @subtype: The subtype of the work queue indicating its functionality.
16335  *
16336  * This function creates a receive buffer queue pair , as detailed in @hrq and
16337  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
16338  * to the HBA.
16339  *
16340  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
16341  * struct is used to get the entry count that is necessary to determine the
16342  * number of pages to use for this queue. The @cq is used to indicate which
16343  * completion queue to bind received buffers that are posted to these queues to.
16344  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
16345  * receive queue pair. This function is asynchronous and will wait for the
16346  * mailbox command to finish before continuing.
16347  *
16348  * On success this function will return a zero. If unable to allocate enough
16349  * memory this function will return -ENOMEM. If the queue create mailbox command
16350  * fails this function will return -ENXIO.
16351  **/
16352 int
16353 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
16354 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
16355 {
16356 	struct lpfc_mbx_rq_create *rq_create;
16357 	struct lpfc_dmabuf *dmabuf;
16358 	LPFC_MBOXQ_t *mbox;
16359 	int rc, length, status = 0;
16360 	uint32_t shdr_status, shdr_add_status;
16361 	union lpfc_sli4_cfg_shdr *shdr;
16362 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16363 	void __iomem *bar_memmap_p;
16364 	uint32_t db_offset;
16365 	uint16_t pci_barset;
16366 
16367 	/* sanity check on queue memory */
16368 	if (!hrq || !drq || !cq)
16369 		return -ENODEV;
16370 	if (!phba->sli4_hba.pc_sli4_params.supported)
16371 		hw_page_size = SLI4_PAGE_SIZE;
16372 
16373 	if (hrq->entry_count != drq->entry_count)
16374 		return -EINVAL;
16375 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16376 	if (!mbox)
16377 		return -ENOMEM;
16378 	length = (sizeof(struct lpfc_mbx_rq_create) -
16379 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16380 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16381 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
16382 			 length, LPFC_SLI4_MBX_EMBED);
16383 	rq_create = &mbox->u.mqe.un.rq_create;
16384 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
16385 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16386 	       phba->sli4_hba.pc_sli4_params.rqv);
16387 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
16388 		bf_set(lpfc_rq_context_rqe_count_1,
16389 		       &rq_create->u.request.context,
16390 		       hrq->entry_count);
16391 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
16392 		bf_set(lpfc_rq_context_rqe_size,
16393 		       &rq_create->u.request.context,
16394 		       LPFC_RQE_SIZE_8);
16395 		bf_set(lpfc_rq_context_page_size,
16396 		       &rq_create->u.request.context,
16397 		       LPFC_RQ_PAGE_SIZE_4096);
16398 	} else {
16399 		switch (hrq->entry_count) {
16400 		default:
16401 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16402 					"2535 Unsupported RQ count. (%d)\n",
16403 					hrq->entry_count);
16404 			if (hrq->entry_count < 512) {
16405 				status = -EINVAL;
16406 				goto out;
16407 			}
16408 			fallthrough;	/* otherwise default to smallest count */
16409 		case 512:
16410 			bf_set(lpfc_rq_context_rqe_count,
16411 			       &rq_create->u.request.context,
16412 			       LPFC_RQ_RING_SIZE_512);
16413 			break;
16414 		case 1024:
16415 			bf_set(lpfc_rq_context_rqe_count,
16416 			       &rq_create->u.request.context,
16417 			       LPFC_RQ_RING_SIZE_1024);
16418 			break;
16419 		case 2048:
16420 			bf_set(lpfc_rq_context_rqe_count,
16421 			       &rq_create->u.request.context,
16422 			       LPFC_RQ_RING_SIZE_2048);
16423 			break;
16424 		case 4096:
16425 			bf_set(lpfc_rq_context_rqe_count,
16426 			       &rq_create->u.request.context,
16427 			       LPFC_RQ_RING_SIZE_4096);
16428 			break;
16429 		}
16430 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
16431 		       LPFC_HDR_BUF_SIZE);
16432 	}
16433 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16434 	       cq->queue_id);
16435 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16436 	       hrq->page_count);
16437 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
16438 		memset(dmabuf->virt, 0, hw_page_size);
16439 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16440 					putPaddrLow(dmabuf->phys);
16441 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16442 					putPaddrHigh(dmabuf->phys);
16443 	}
16444 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16445 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16446 
16447 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16448 	/* The IOCTL status is embedded in the mailbox subheader. */
16449 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16450 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16451 	if (shdr_status || shdr_add_status || rc) {
16452 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16453 				"2504 RQ_CREATE mailbox failed with "
16454 				"status x%x add_status x%x, mbx status x%x\n",
16455 				shdr_status, shdr_add_status, rc);
16456 		status = -ENXIO;
16457 		goto out;
16458 	}
16459 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16460 	if (hrq->queue_id == 0xFFFF) {
16461 		status = -ENXIO;
16462 		goto out;
16463 	}
16464 
16465 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16466 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
16467 					&rq_create->u.response);
16468 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
16469 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
16470 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16471 					"3262 RQ [%d] doorbell format not "
16472 					"supported: x%x\n", hrq->queue_id,
16473 					hrq->db_format);
16474 			status = -EINVAL;
16475 			goto out;
16476 		}
16477 
16478 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
16479 				    &rq_create->u.response);
16480 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
16481 		if (!bar_memmap_p) {
16482 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16483 					"3269 RQ[%d] failed to memmap pci "
16484 					"barset:x%x\n", hrq->queue_id,
16485 					pci_barset);
16486 			status = -ENOMEM;
16487 			goto out;
16488 		}
16489 
16490 		db_offset = rq_create->u.response.doorbell_offset;
16491 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
16492 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
16493 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16494 					"3270 RQ[%d] doorbell offset not "
16495 					"supported: x%x\n", hrq->queue_id,
16496 					db_offset);
16497 			status = -EINVAL;
16498 			goto out;
16499 		}
16500 		hrq->db_regaddr = bar_memmap_p + db_offset;
16501 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16502 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
16503 				"format:x%x\n", hrq->queue_id, pci_barset,
16504 				db_offset, hrq->db_format);
16505 	} else {
16506 		hrq->db_format = LPFC_DB_RING_FORMAT;
16507 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16508 	}
16509 	hrq->type = LPFC_HRQ;
16510 	hrq->assoc_qid = cq->queue_id;
16511 	hrq->subtype = subtype;
16512 	hrq->host_index = 0;
16513 	hrq->hba_index = 0;
16514 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16515 
16516 	/* now create the data queue */
16517 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16518 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
16519 			 length, LPFC_SLI4_MBX_EMBED);
16520 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16521 	       phba->sli4_hba.pc_sli4_params.rqv);
16522 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
16523 		bf_set(lpfc_rq_context_rqe_count_1,
16524 		       &rq_create->u.request.context, hrq->entry_count);
16525 		if (subtype == LPFC_NVMET)
16526 			rq_create->u.request.context.buffer_size =
16527 				LPFC_NVMET_DATA_BUF_SIZE;
16528 		else
16529 			rq_create->u.request.context.buffer_size =
16530 				LPFC_DATA_BUF_SIZE;
16531 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
16532 		       LPFC_RQE_SIZE_8);
16533 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
16534 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
16535 	} else {
16536 		switch (drq->entry_count) {
16537 		default:
16538 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16539 					"2536 Unsupported RQ count. (%d)\n",
16540 					drq->entry_count);
16541 			if (drq->entry_count < 512) {
16542 				status = -EINVAL;
16543 				goto out;
16544 			}
16545 			fallthrough;	/* otherwise default to smallest count */
16546 		case 512:
16547 			bf_set(lpfc_rq_context_rqe_count,
16548 			       &rq_create->u.request.context,
16549 			       LPFC_RQ_RING_SIZE_512);
16550 			break;
16551 		case 1024:
16552 			bf_set(lpfc_rq_context_rqe_count,
16553 			       &rq_create->u.request.context,
16554 			       LPFC_RQ_RING_SIZE_1024);
16555 			break;
16556 		case 2048:
16557 			bf_set(lpfc_rq_context_rqe_count,
16558 			       &rq_create->u.request.context,
16559 			       LPFC_RQ_RING_SIZE_2048);
16560 			break;
16561 		case 4096:
16562 			bf_set(lpfc_rq_context_rqe_count,
16563 			       &rq_create->u.request.context,
16564 			       LPFC_RQ_RING_SIZE_4096);
16565 			break;
16566 		}
16567 		if (subtype == LPFC_NVMET)
16568 			bf_set(lpfc_rq_context_buf_size,
16569 			       &rq_create->u.request.context,
16570 			       LPFC_NVMET_DATA_BUF_SIZE);
16571 		else
16572 			bf_set(lpfc_rq_context_buf_size,
16573 			       &rq_create->u.request.context,
16574 			       LPFC_DATA_BUF_SIZE);
16575 	}
16576 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16577 	       cq->queue_id);
16578 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16579 	       drq->page_count);
16580 	list_for_each_entry(dmabuf, &drq->page_list, list) {
16581 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16582 					putPaddrLow(dmabuf->phys);
16583 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16584 					putPaddrHigh(dmabuf->phys);
16585 	}
16586 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16587 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16588 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16589 	/* The IOCTL status is embedded in the mailbox subheader. */
16590 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
16591 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16592 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16593 	if (shdr_status || shdr_add_status || rc) {
16594 		status = -ENXIO;
16595 		goto out;
16596 	}
16597 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16598 	if (drq->queue_id == 0xFFFF) {
16599 		status = -ENXIO;
16600 		goto out;
16601 	}
16602 	drq->type = LPFC_DRQ;
16603 	drq->assoc_qid = cq->queue_id;
16604 	drq->subtype = subtype;
16605 	drq->host_index = 0;
16606 	drq->hba_index = 0;
16607 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16608 
16609 	/* link the header and data RQs onto the parent cq child list */
16610 	list_add_tail(&hrq->list, &cq->child_list);
16611 	list_add_tail(&drq->list, &cq->child_list);
16612 
16613 out:
16614 	mempool_free(mbox, phba->mbox_mem_pool);
16615 	return status;
16616 }
16617 
16618 /**
16619  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
16620  * @phba: HBA structure that indicates port to create a queue on.
16621  * @hrqp: The queue structure array to use to create the header receive queues.
16622  * @drqp: The queue structure array to use to create the data receive queues.
16623  * @cqp: The completion queue array to bind these receive queues to.
16624  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16625  *
16626  * This function creates a receive buffer queue pair , as detailed in @hrq and
16627  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
16628  * to the HBA.
16629  *
16630  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
16631  * struct is used to get the entry count that is necessary to determine the
16632  * number of pages to use for this queue. The @cq is used to indicate which
16633  * completion queue to bind received buffers that are posted to these queues to.
16634  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
16635  * receive queue pair. This function is asynchronous and will wait for the
16636  * mailbox command to finish before continuing.
16637  *
16638  * On success this function will return a zero. If unable to allocate enough
16639  * memory this function will return -ENOMEM. If the queue create mailbox command
16640  * fails this function will return -ENXIO.
16641  **/
16642 int
16643 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
16644 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
16645 		uint32_t subtype)
16646 {
16647 	struct lpfc_queue *hrq, *drq, *cq;
16648 	struct lpfc_mbx_rq_create_v2 *rq_create;
16649 	struct lpfc_dmabuf *dmabuf;
16650 	LPFC_MBOXQ_t *mbox;
16651 	int rc, length, alloclen, status = 0;
16652 	int cnt, idx, numrq, page_idx = 0;
16653 	uint32_t shdr_status, shdr_add_status;
16654 	union lpfc_sli4_cfg_shdr *shdr;
16655 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16656 
16657 	numrq = phba->cfg_nvmet_mrq;
16658 	/* sanity check on array memory */
16659 	if (!hrqp || !drqp || !cqp || !numrq)
16660 		return -ENODEV;
16661 	if (!phba->sli4_hba.pc_sli4_params.supported)
16662 		hw_page_size = SLI4_PAGE_SIZE;
16663 
16664 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16665 	if (!mbox)
16666 		return -ENOMEM;
16667 
16668 	length = sizeof(struct lpfc_mbx_rq_create_v2);
16669 	length += ((2 * numrq * hrqp[0]->page_count) *
16670 		   sizeof(struct dma_address));
16671 
16672 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16673 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
16674 				    LPFC_SLI4_MBX_NEMBED);
16675 	if (alloclen < length) {
16676 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16677 				"3099 Allocated DMA memory size (%d) is "
16678 				"less than the requested DMA memory size "
16679 				"(%d)\n", alloclen, length);
16680 		status = -ENOMEM;
16681 		goto out;
16682 	}
16683 
16684 
16685 
16686 	rq_create = mbox->sge_array->addr[0];
16687 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
16688 
16689 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
16690 	cnt = 0;
16691 
16692 	for (idx = 0; idx < numrq; idx++) {
16693 		hrq = hrqp[idx];
16694 		drq = drqp[idx];
16695 		cq  = cqp[idx];
16696 
16697 		/* sanity check on queue memory */
16698 		if (!hrq || !drq || !cq) {
16699 			status = -ENODEV;
16700 			goto out;
16701 		}
16702 
16703 		if (hrq->entry_count != drq->entry_count) {
16704 			status = -EINVAL;
16705 			goto out;
16706 		}
16707 
16708 		if (idx == 0) {
16709 			bf_set(lpfc_mbx_rq_create_num_pages,
16710 			       &rq_create->u.request,
16711 			       hrq->page_count);
16712 			bf_set(lpfc_mbx_rq_create_rq_cnt,
16713 			       &rq_create->u.request, (numrq * 2));
16714 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
16715 			       1);
16716 			bf_set(lpfc_rq_context_base_cq,
16717 			       &rq_create->u.request.context,
16718 			       cq->queue_id);
16719 			bf_set(lpfc_rq_context_data_size,
16720 			       &rq_create->u.request.context,
16721 			       LPFC_NVMET_DATA_BUF_SIZE);
16722 			bf_set(lpfc_rq_context_hdr_size,
16723 			       &rq_create->u.request.context,
16724 			       LPFC_HDR_BUF_SIZE);
16725 			bf_set(lpfc_rq_context_rqe_count_1,
16726 			       &rq_create->u.request.context,
16727 			       hrq->entry_count);
16728 			bf_set(lpfc_rq_context_rqe_size,
16729 			       &rq_create->u.request.context,
16730 			       LPFC_RQE_SIZE_8);
16731 			bf_set(lpfc_rq_context_page_size,
16732 			       &rq_create->u.request.context,
16733 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
16734 		}
16735 		rc = 0;
16736 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
16737 			memset(dmabuf->virt, 0, hw_page_size);
16738 			cnt = page_idx + dmabuf->buffer_tag;
16739 			rq_create->u.request.page[cnt].addr_lo =
16740 					putPaddrLow(dmabuf->phys);
16741 			rq_create->u.request.page[cnt].addr_hi =
16742 					putPaddrHigh(dmabuf->phys);
16743 			rc++;
16744 		}
16745 		page_idx += rc;
16746 
16747 		rc = 0;
16748 		list_for_each_entry(dmabuf, &drq->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 		hrq->db_format = LPFC_DB_RING_FORMAT;
16760 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16761 		hrq->type = LPFC_HRQ;
16762 		hrq->assoc_qid = cq->queue_id;
16763 		hrq->subtype = subtype;
16764 		hrq->host_index = 0;
16765 		hrq->hba_index = 0;
16766 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16767 
16768 		drq->db_format = LPFC_DB_RING_FORMAT;
16769 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16770 		drq->type = LPFC_DRQ;
16771 		drq->assoc_qid = cq->queue_id;
16772 		drq->subtype = subtype;
16773 		drq->host_index = 0;
16774 		drq->hba_index = 0;
16775 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16776 
16777 		list_add_tail(&hrq->list, &cq->child_list);
16778 		list_add_tail(&drq->list, &cq->child_list);
16779 	}
16780 
16781 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16782 	/* The IOCTL status is embedded in the mailbox subheader. */
16783 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16784 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16785 	if (shdr_status || shdr_add_status || rc) {
16786 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16787 				"3120 RQ_CREATE mailbox failed with "
16788 				"status x%x add_status x%x, mbx status x%x\n",
16789 				shdr_status, shdr_add_status, rc);
16790 		status = -ENXIO;
16791 		goto out;
16792 	}
16793 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16794 	if (rc == 0xFFFF) {
16795 		status = -ENXIO;
16796 		goto out;
16797 	}
16798 
16799 	/* Initialize all RQs with associated queue id */
16800 	for (idx = 0; idx < numrq; idx++) {
16801 		hrq = hrqp[idx];
16802 		hrq->queue_id = rc + (2 * idx);
16803 		drq = drqp[idx];
16804 		drq->queue_id = rc + (2 * idx) + 1;
16805 	}
16806 
16807 out:
16808 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16809 	return status;
16810 }
16811 
16812 /**
16813  * lpfc_eq_destroy - Destroy an event Queue on the HBA
16814  * @phba: HBA structure that indicates port to destroy a queue on.
16815  * @eq: The queue structure associated with the queue to destroy.
16816  *
16817  * This function destroys a queue, as detailed in @eq by sending an mailbox
16818  * command, specific to the type of queue, to the HBA.
16819  *
16820  * The @eq struct is used to get the queue ID of the queue to destroy.
16821  *
16822  * On success this function will return a zero. If the queue destroy mailbox
16823  * command fails this function will return -ENXIO.
16824  **/
16825 int
16826 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
16827 {
16828 	LPFC_MBOXQ_t *mbox;
16829 	int rc, length, status = 0;
16830 	uint32_t shdr_status, shdr_add_status;
16831 	union lpfc_sli4_cfg_shdr *shdr;
16832 
16833 	/* sanity check on queue memory */
16834 	if (!eq)
16835 		return -ENODEV;
16836 
16837 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
16838 	if (!mbox)
16839 		return -ENOMEM;
16840 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
16841 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16842 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16843 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
16844 			 length, LPFC_SLI4_MBX_EMBED);
16845 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
16846 	       eq->queue_id);
16847 	mbox->vport = eq->phba->pport;
16848 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16849 
16850 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
16851 	/* The IOCTL status is embedded in the mailbox subheader. */
16852 	shdr = (union lpfc_sli4_cfg_shdr *)
16853 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
16854 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16855 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16856 	if (shdr_status || shdr_add_status || rc) {
16857 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16858 				"2505 EQ_DESTROY mailbox failed with "
16859 				"status x%x add_status x%x, mbx status x%x\n",
16860 				shdr_status, shdr_add_status, rc);
16861 		status = -ENXIO;
16862 	}
16863 
16864 	/* Remove eq from any list */
16865 	list_del_init(&eq->list);
16866 	mempool_free(mbox, eq->phba->mbox_mem_pool);
16867 	return status;
16868 }
16869 
16870 /**
16871  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
16872  * @phba: HBA structure that indicates port to destroy a queue on.
16873  * @cq: The queue structure associated with the queue to destroy.
16874  *
16875  * This function destroys a queue, as detailed in @cq by sending an mailbox
16876  * command, specific to the type of queue, to the HBA.
16877  *
16878  * The @cq struct is used to get the queue ID of the queue to destroy.
16879  *
16880  * On success this function will return a zero. If the queue destroy mailbox
16881  * command fails this function will return -ENXIO.
16882  **/
16883 int
16884 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
16885 {
16886 	LPFC_MBOXQ_t *mbox;
16887 	int rc, length, status = 0;
16888 	uint32_t shdr_status, shdr_add_status;
16889 	union lpfc_sli4_cfg_shdr *shdr;
16890 
16891 	/* sanity check on queue memory */
16892 	if (!cq)
16893 		return -ENODEV;
16894 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
16895 	if (!mbox)
16896 		return -ENOMEM;
16897 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
16898 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16899 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16900 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
16901 			 length, LPFC_SLI4_MBX_EMBED);
16902 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
16903 	       cq->queue_id);
16904 	mbox->vport = cq->phba->pport;
16905 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16906 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
16907 	/* The IOCTL status is embedded in the mailbox subheader. */
16908 	shdr = (union lpfc_sli4_cfg_shdr *)
16909 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
16910 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16911 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16912 	if (shdr_status || shdr_add_status || rc) {
16913 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16914 				"2506 CQ_DESTROY mailbox failed with "
16915 				"status x%x add_status x%x, mbx status x%x\n",
16916 				shdr_status, shdr_add_status, rc);
16917 		status = -ENXIO;
16918 	}
16919 	/* Remove cq from any list */
16920 	list_del_init(&cq->list);
16921 	mempool_free(mbox, cq->phba->mbox_mem_pool);
16922 	return status;
16923 }
16924 
16925 /**
16926  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
16927  * @phba: HBA structure that indicates port to destroy a queue on.
16928  * @mq: The queue structure associated with the queue to destroy.
16929  *
16930  * This function destroys a queue, as detailed in @mq by sending an mailbox
16931  * command, specific to the type of queue, to the HBA.
16932  *
16933  * The @mq struct is used to get the queue ID of the queue to destroy.
16934  *
16935  * On success this function will return a zero. If the queue destroy mailbox
16936  * command fails this function will return -ENXIO.
16937  **/
16938 int
16939 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
16940 {
16941 	LPFC_MBOXQ_t *mbox;
16942 	int rc, length, status = 0;
16943 	uint32_t shdr_status, shdr_add_status;
16944 	union lpfc_sli4_cfg_shdr *shdr;
16945 
16946 	/* sanity check on queue memory */
16947 	if (!mq)
16948 		return -ENODEV;
16949 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
16950 	if (!mbox)
16951 		return -ENOMEM;
16952 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
16953 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16954 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16955 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
16956 			 length, LPFC_SLI4_MBX_EMBED);
16957 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
16958 	       mq->queue_id);
16959 	mbox->vport = mq->phba->pport;
16960 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16961 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
16962 	/* The IOCTL status is embedded in the mailbox subheader. */
16963 	shdr = (union lpfc_sli4_cfg_shdr *)
16964 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
16965 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16966 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16967 	if (shdr_status || shdr_add_status || rc) {
16968 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16969 				"2507 MQ_DESTROY mailbox failed with "
16970 				"status x%x add_status x%x, mbx status x%x\n",
16971 				shdr_status, shdr_add_status, rc);
16972 		status = -ENXIO;
16973 	}
16974 	/* Remove mq from any list */
16975 	list_del_init(&mq->list);
16976 	mempool_free(mbox, mq->phba->mbox_mem_pool);
16977 	return status;
16978 }
16979 
16980 /**
16981  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
16982  * @phba: HBA structure that indicates port to destroy a queue on.
16983  * @wq: The queue structure associated with the queue to destroy.
16984  *
16985  * This function destroys a queue, as detailed in @wq by sending an mailbox
16986  * command, specific to the type of queue, to the HBA.
16987  *
16988  * The @wq struct is used to get the queue ID of the queue to destroy.
16989  *
16990  * On success this function will return a zero. If the queue destroy mailbox
16991  * command fails this function will return -ENXIO.
16992  **/
16993 int
16994 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
16995 {
16996 	LPFC_MBOXQ_t *mbox;
16997 	int rc, length, status = 0;
16998 	uint32_t shdr_status, shdr_add_status;
16999 	union lpfc_sli4_cfg_shdr *shdr;
17000 
17001 	/* sanity check on queue memory */
17002 	if (!wq)
17003 		return -ENODEV;
17004 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17005 	if (!mbox)
17006 		return -ENOMEM;
17007 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
17008 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17009 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17010 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17011 			 length, LPFC_SLI4_MBX_EMBED);
17012 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17013 	       wq->queue_id);
17014 	mbox->vport = wq->phba->pport;
17015 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17016 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17017 	shdr = (union lpfc_sli4_cfg_shdr *)
17018 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17019 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17020 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17021 	if (shdr_status || shdr_add_status || rc) {
17022 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17023 				"2508 WQ_DESTROY mailbox failed with "
17024 				"status x%x add_status x%x, mbx status x%x\n",
17025 				shdr_status, shdr_add_status, rc);
17026 		status = -ENXIO;
17027 	}
17028 	/* Remove wq from any list */
17029 	list_del_init(&wq->list);
17030 	kfree(wq->pring);
17031 	wq->pring = NULL;
17032 	mempool_free(mbox, wq->phba->mbox_mem_pool);
17033 	return status;
17034 }
17035 
17036 /**
17037  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17038  * @phba: HBA structure that indicates port to destroy a queue on.
17039  * @hrq: The queue structure associated with the queue to destroy.
17040  * @drq: The queue structure associated with the queue to destroy.
17041  *
17042  * This function destroys a queue, as detailed in @rq by sending an mailbox
17043  * command, specific to the type of queue, to the HBA.
17044  *
17045  * The @rq struct is used to get the queue ID of the queue to destroy.
17046  *
17047  * On success this function will return a zero. If the queue destroy mailbox
17048  * command fails this function will return -ENXIO.
17049  **/
17050 int
17051 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17052 		struct lpfc_queue *drq)
17053 {
17054 	LPFC_MBOXQ_t *mbox;
17055 	int rc, length, status = 0;
17056 	uint32_t shdr_status, shdr_add_status;
17057 	union lpfc_sli4_cfg_shdr *shdr;
17058 
17059 	/* sanity check on queue memory */
17060 	if (!hrq || !drq)
17061 		return -ENODEV;
17062 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17063 	if (!mbox)
17064 		return -ENOMEM;
17065 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
17066 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17067 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17068 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17069 			 length, LPFC_SLI4_MBX_EMBED);
17070 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17071 	       hrq->queue_id);
17072 	mbox->vport = hrq->phba->pport;
17073 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17074 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17075 	/* The IOCTL status is embedded in the mailbox subheader. */
17076 	shdr = (union lpfc_sli4_cfg_shdr *)
17077 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17078 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17079 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17080 	if (shdr_status || shdr_add_status || rc) {
17081 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17082 				"2509 RQ_DESTROY mailbox failed with "
17083 				"status x%x add_status x%x, mbx status x%x\n",
17084 				shdr_status, shdr_add_status, rc);
17085 		mempool_free(mbox, hrq->phba->mbox_mem_pool);
17086 		return -ENXIO;
17087 	}
17088 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17089 	       drq->queue_id);
17090 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17091 	shdr = (union lpfc_sli4_cfg_shdr *)
17092 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17093 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17094 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17095 	if (shdr_status || shdr_add_status || rc) {
17096 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17097 				"2510 RQ_DESTROY mailbox failed with "
17098 				"status x%x add_status x%x, mbx status x%x\n",
17099 				shdr_status, shdr_add_status, rc);
17100 		status = -ENXIO;
17101 	}
17102 	list_del_init(&hrq->list);
17103 	list_del_init(&drq->list);
17104 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
17105 	return status;
17106 }
17107 
17108 /**
17109  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17110  * @phba: The virtual port for which this call being executed.
17111  * @pdma_phys_addr0: Physical address of the 1st SGL page.
17112  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
17113  * @xritag: the xritag that ties this io to the SGL pages.
17114  *
17115  * This routine will post the sgl pages for the IO that has the xritag
17116  * that is in the iocbq structure. The xritag is assigned during iocbq
17117  * creation and persists for as long as the driver is loaded.
17118  * if the caller has fewer than 256 scatter gather segments to map then
17119  * pdma_phys_addr1 should be 0.
17120  * If the caller needs to map more than 256 scatter gather segment then
17121  * pdma_phys_addr1 should be a valid physical address.
17122  * physical address for SGLs must be 64 byte aligned.
17123  * If you are going to map 2 SGL's then the first one must have 256 entries
17124  * the second sgl can have between 1 and 256 entries.
17125  *
17126  * Return codes:
17127  * 	0 - Success
17128  * 	-ENXIO, -ENOMEM - Failure
17129  **/
17130 int
17131 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
17132 		dma_addr_t pdma_phys_addr0,
17133 		dma_addr_t pdma_phys_addr1,
17134 		uint16_t xritag)
17135 {
17136 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
17137 	LPFC_MBOXQ_t *mbox;
17138 	int rc;
17139 	uint32_t shdr_status, shdr_add_status;
17140 	uint32_t mbox_tmo;
17141 	union lpfc_sli4_cfg_shdr *shdr;
17142 
17143 	if (xritag == NO_XRI) {
17144 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17145 				"0364 Invalid param:\n");
17146 		return -EINVAL;
17147 	}
17148 
17149 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17150 	if (!mbox)
17151 		return -ENOMEM;
17152 
17153 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17154 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17155 			sizeof(struct lpfc_mbx_post_sgl_pages) -
17156 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17157 
17158 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
17159 				&mbox->u.mqe.un.post_sgl_pages;
17160 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
17161 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
17162 
17163 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
17164 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
17165 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
17166 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
17167 
17168 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
17169 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
17170 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
17171 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
17172 	if (!phba->sli4_hba.intr_enable)
17173 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17174 	else {
17175 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17176 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17177 	}
17178 	/* The IOCTL status is embedded in the mailbox subheader. */
17179 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
17180 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17181 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17182 	if (!phba->sli4_hba.intr_enable)
17183 		mempool_free(mbox, phba->mbox_mem_pool);
17184 	else if (rc != MBX_TIMEOUT)
17185 		mempool_free(mbox, phba->mbox_mem_pool);
17186 	if (shdr_status || shdr_add_status || rc) {
17187 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17188 				"2511 POST_SGL mailbox failed with "
17189 				"status x%x add_status x%x, mbx status x%x\n",
17190 				shdr_status, shdr_add_status, rc);
17191 	}
17192 	return 0;
17193 }
17194 
17195 /**
17196  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
17197  * @phba: pointer to lpfc hba data structure.
17198  *
17199  * This routine is invoked to post rpi header templates to the
17200  * HBA consistent with the SLI-4 interface spec.  This routine
17201  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
17202  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
17203  *
17204  * Returns
17205  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
17206  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
17207  **/
17208 static uint16_t
17209 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
17210 {
17211 	unsigned long xri;
17212 
17213 	/*
17214 	 * Fetch the next logical xri.  Because this index is logical,
17215 	 * the driver starts at 0 each time.
17216 	 */
17217 	spin_lock_irq(&phba->hbalock);
17218 	xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
17219 				 phba->sli4_hba.max_cfg_param.max_xri, 0);
17220 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
17221 		spin_unlock_irq(&phba->hbalock);
17222 		return NO_XRI;
17223 	} else {
17224 		set_bit(xri, phba->sli4_hba.xri_bmask);
17225 		phba->sli4_hba.max_cfg_param.xri_used++;
17226 	}
17227 	spin_unlock_irq(&phba->hbalock);
17228 	return xri;
17229 }
17230 
17231 /**
17232  * __lpfc_sli4_free_xri - Release an xri for reuse.
17233  * @phba: pointer to lpfc hba data structure.
17234  * @xri: xri to release.
17235  *
17236  * This routine is invoked to release an xri to the pool of
17237  * available rpis maintained by the driver.
17238  **/
17239 static void
17240 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
17241 {
17242 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
17243 		phba->sli4_hba.max_cfg_param.xri_used--;
17244 	}
17245 }
17246 
17247 /**
17248  * lpfc_sli4_free_xri - Release an xri for reuse.
17249  * @phba: pointer to lpfc hba data structure.
17250  * @xri: xri to release.
17251  *
17252  * This routine is invoked to release an xri to the pool of
17253  * available rpis maintained by the driver.
17254  **/
17255 void
17256 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
17257 {
17258 	spin_lock_irq(&phba->hbalock);
17259 	__lpfc_sli4_free_xri(phba, xri);
17260 	spin_unlock_irq(&phba->hbalock);
17261 }
17262 
17263 /**
17264  * lpfc_sli4_next_xritag - Get an xritag for the io
17265  * @phba: Pointer to HBA context object.
17266  *
17267  * This function gets an xritag for the iocb. If there is no unused xritag
17268  * it will return 0xffff.
17269  * The function returns the allocated xritag if successful, else returns zero.
17270  * Zero is not a valid xritag.
17271  * The caller is not required to hold any lock.
17272  **/
17273 uint16_t
17274 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
17275 {
17276 	uint16_t xri_index;
17277 
17278 	xri_index = lpfc_sli4_alloc_xri(phba);
17279 	if (xri_index == NO_XRI)
17280 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
17281 				"2004 Failed to allocate XRI.last XRITAG is %d"
17282 				" Max XRI is %d, Used XRI is %d\n",
17283 				xri_index,
17284 				phba->sli4_hba.max_cfg_param.max_xri,
17285 				phba->sli4_hba.max_cfg_param.xri_used);
17286 	return xri_index;
17287 }
17288 
17289 /**
17290  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
17291  * @phba: pointer to lpfc hba data structure.
17292  * @post_sgl_list: pointer to els sgl entry list.
17293  * @post_cnt: number of els sgl entries on the list.
17294  *
17295  * This routine is invoked to post a block of driver's sgl pages to the
17296  * HBA using non-embedded mailbox command. No Lock is held. This routine
17297  * is only called when the driver is loading and after all IO has been
17298  * stopped.
17299  **/
17300 static int
17301 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
17302 			    struct list_head *post_sgl_list,
17303 			    int post_cnt)
17304 {
17305 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
17306 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
17307 	struct sgl_page_pairs *sgl_pg_pairs;
17308 	void *viraddr;
17309 	LPFC_MBOXQ_t *mbox;
17310 	uint32_t reqlen, alloclen, pg_pairs;
17311 	uint32_t mbox_tmo;
17312 	uint16_t xritag_start = 0;
17313 	int rc = 0;
17314 	uint32_t shdr_status, shdr_add_status;
17315 	union lpfc_sli4_cfg_shdr *shdr;
17316 
17317 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
17318 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
17319 	if (reqlen > SLI4_PAGE_SIZE) {
17320 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17321 				"2559 Block sgl registration required DMA "
17322 				"size (%d) great than a page\n", reqlen);
17323 		return -ENOMEM;
17324 	}
17325 
17326 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17327 	if (!mbox)
17328 		return -ENOMEM;
17329 
17330 	/* Allocate DMA memory and set up the non-embedded mailbox command */
17331 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17332 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
17333 			 LPFC_SLI4_MBX_NEMBED);
17334 
17335 	if (alloclen < reqlen) {
17336 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17337 				"0285 Allocated DMA memory size (%d) is "
17338 				"less than the requested DMA memory "
17339 				"size (%d)\n", alloclen, reqlen);
17340 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17341 		return -ENOMEM;
17342 	}
17343 	/* Set up the SGL pages in the non-embedded DMA pages */
17344 	viraddr = mbox->sge_array->addr[0];
17345 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
17346 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
17347 
17348 	pg_pairs = 0;
17349 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
17350 		/* Set up the sge entry */
17351 		sgl_pg_pairs->sgl_pg0_addr_lo =
17352 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
17353 		sgl_pg_pairs->sgl_pg0_addr_hi =
17354 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
17355 		sgl_pg_pairs->sgl_pg1_addr_lo =
17356 				cpu_to_le32(putPaddrLow(0));
17357 		sgl_pg_pairs->sgl_pg1_addr_hi =
17358 				cpu_to_le32(putPaddrHigh(0));
17359 
17360 		/* Keep the first xritag on the list */
17361 		if (pg_pairs == 0)
17362 			xritag_start = sglq_entry->sli4_xritag;
17363 		sgl_pg_pairs++;
17364 		pg_pairs++;
17365 	}
17366 
17367 	/* Complete initialization and perform endian conversion. */
17368 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
17369 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
17370 	sgl->word0 = cpu_to_le32(sgl->word0);
17371 
17372 	if (!phba->sli4_hba.intr_enable)
17373 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17374 	else {
17375 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17376 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17377 	}
17378 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
17379 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17380 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17381 	if (!phba->sli4_hba.intr_enable)
17382 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17383 	else if (rc != MBX_TIMEOUT)
17384 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17385 	if (shdr_status || shdr_add_status || rc) {
17386 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17387 				"2513 POST_SGL_BLOCK mailbox command failed "
17388 				"status x%x add_status x%x mbx status x%x\n",
17389 				shdr_status, shdr_add_status, rc);
17390 		rc = -ENXIO;
17391 	}
17392 	return rc;
17393 }
17394 
17395 /**
17396  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
17397  * @phba: pointer to lpfc hba data structure.
17398  * @nblist: pointer to nvme buffer list.
17399  * @count: number of scsi buffers on the list.
17400  *
17401  * This routine is invoked to post a block of @count scsi sgl pages from a
17402  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
17403  * No Lock is held.
17404  *
17405  **/
17406 static int
17407 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
17408 			    int count)
17409 {
17410 	struct lpfc_io_buf *lpfc_ncmd;
17411 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
17412 	struct sgl_page_pairs *sgl_pg_pairs;
17413 	void *viraddr;
17414 	LPFC_MBOXQ_t *mbox;
17415 	uint32_t reqlen, alloclen, pg_pairs;
17416 	uint32_t mbox_tmo;
17417 	uint16_t xritag_start = 0;
17418 	int rc = 0;
17419 	uint32_t shdr_status, shdr_add_status;
17420 	dma_addr_t pdma_phys_bpl1;
17421 	union lpfc_sli4_cfg_shdr *shdr;
17422 
17423 	/* Calculate the requested length of the dma memory */
17424 	reqlen = count * sizeof(struct sgl_page_pairs) +
17425 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
17426 	if (reqlen > SLI4_PAGE_SIZE) {
17427 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
17428 				"6118 Block sgl registration required DMA "
17429 				"size (%d) great than a page\n", reqlen);
17430 		return -ENOMEM;
17431 	}
17432 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17433 	if (!mbox) {
17434 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17435 				"6119 Failed to allocate mbox cmd memory\n");
17436 		return -ENOMEM;
17437 	}
17438 
17439 	/* Allocate DMA memory and set up the non-embedded mailbox command */
17440 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17441 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17442 				    reqlen, LPFC_SLI4_MBX_NEMBED);
17443 
17444 	if (alloclen < reqlen) {
17445 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17446 				"6120 Allocated DMA memory size (%d) is "
17447 				"less than the requested DMA memory "
17448 				"size (%d)\n", alloclen, reqlen);
17449 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17450 		return -ENOMEM;
17451 	}
17452 
17453 	/* Get the first SGE entry from the non-embedded DMA memory */
17454 	viraddr = mbox->sge_array->addr[0];
17455 
17456 	/* Set up the SGL pages in the non-embedded DMA pages */
17457 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
17458 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
17459 
17460 	pg_pairs = 0;
17461 	list_for_each_entry(lpfc_ncmd, nblist, list) {
17462 		/* Set up the sge entry */
17463 		sgl_pg_pairs->sgl_pg0_addr_lo =
17464 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
17465 		sgl_pg_pairs->sgl_pg0_addr_hi =
17466 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
17467 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
17468 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
17469 						SGL_PAGE_SIZE;
17470 		else
17471 			pdma_phys_bpl1 = 0;
17472 		sgl_pg_pairs->sgl_pg1_addr_lo =
17473 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
17474 		sgl_pg_pairs->sgl_pg1_addr_hi =
17475 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
17476 		/* Keep the first xritag on the list */
17477 		if (pg_pairs == 0)
17478 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
17479 		sgl_pg_pairs++;
17480 		pg_pairs++;
17481 	}
17482 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
17483 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
17484 	/* Perform endian conversion if necessary */
17485 	sgl->word0 = cpu_to_le32(sgl->word0);
17486 
17487 	if (!phba->sli4_hba.intr_enable) {
17488 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17489 	} else {
17490 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17491 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17492 	}
17493 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
17494 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17495 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17496 	if (!phba->sli4_hba.intr_enable)
17497 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17498 	else if (rc != MBX_TIMEOUT)
17499 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17500 	if (shdr_status || shdr_add_status || rc) {
17501 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17502 				"6125 POST_SGL_BLOCK mailbox command failed "
17503 				"status x%x add_status x%x mbx status x%x\n",
17504 				shdr_status, shdr_add_status, rc);
17505 		rc = -ENXIO;
17506 	}
17507 	return rc;
17508 }
17509 
17510 /**
17511  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
17512  * @phba: pointer to lpfc hba data structure.
17513  * @post_nblist: pointer to the nvme buffer list.
17514  * @sb_count: number of nvme buffers.
17515  *
17516  * This routine walks a list of nvme buffers that was passed in. It attempts
17517  * to construct blocks of nvme buffer sgls which contains contiguous xris and
17518  * uses the non-embedded SGL block post mailbox commands to post to the port.
17519  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
17520  * embedded SGL post mailbox command for posting. The @post_nblist passed in
17521  * must be local list, thus no lock is needed when manipulate the list.
17522  *
17523  * Returns: 0 = failure, non-zero number of successfully posted buffers.
17524  **/
17525 int
17526 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
17527 			   struct list_head *post_nblist, int sb_count)
17528 {
17529 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
17530 	int status, sgl_size;
17531 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
17532 	dma_addr_t pdma_phys_sgl1;
17533 	int last_xritag = NO_XRI;
17534 	int cur_xritag;
17535 	LIST_HEAD(prep_nblist);
17536 	LIST_HEAD(blck_nblist);
17537 	LIST_HEAD(nvme_nblist);
17538 
17539 	/* sanity check */
17540 	if (sb_count <= 0)
17541 		return -EINVAL;
17542 
17543 	sgl_size = phba->cfg_sg_dma_buf_size;
17544 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
17545 		list_del_init(&lpfc_ncmd->list);
17546 		block_cnt++;
17547 		if ((last_xritag != NO_XRI) &&
17548 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
17549 			/* a hole in xri block, form a sgl posting block */
17550 			list_splice_init(&prep_nblist, &blck_nblist);
17551 			post_cnt = block_cnt - 1;
17552 			/* prepare list for next posting block */
17553 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17554 			block_cnt = 1;
17555 		} else {
17556 			/* prepare list for next posting block */
17557 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17558 			/* enough sgls for non-embed sgl mbox command */
17559 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
17560 				list_splice_init(&prep_nblist, &blck_nblist);
17561 				post_cnt = block_cnt;
17562 				block_cnt = 0;
17563 			}
17564 		}
17565 		num_posting++;
17566 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17567 
17568 		/* end of repost sgl list condition for NVME buffers */
17569 		if (num_posting == sb_count) {
17570 			if (post_cnt == 0) {
17571 				/* last sgl posting block */
17572 				list_splice_init(&prep_nblist, &blck_nblist);
17573 				post_cnt = block_cnt;
17574 			} else if (block_cnt == 1) {
17575 				/* last single sgl with non-contiguous xri */
17576 				if (sgl_size > SGL_PAGE_SIZE)
17577 					pdma_phys_sgl1 =
17578 						lpfc_ncmd->dma_phys_sgl +
17579 						SGL_PAGE_SIZE;
17580 				else
17581 					pdma_phys_sgl1 = 0;
17582 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17583 				status = lpfc_sli4_post_sgl(
17584 						phba, lpfc_ncmd->dma_phys_sgl,
17585 						pdma_phys_sgl1, cur_xritag);
17586 				if (status) {
17587 					/* Post error.  Buffer unavailable. */
17588 					lpfc_ncmd->flags |=
17589 						LPFC_SBUF_NOT_POSTED;
17590 				} else {
17591 					/* Post success. Bffer available. */
17592 					lpfc_ncmd->flags &=
17593 						~LPFC_SBUF_NOT_POSTED;
17594 					lpfc_ncmd->status = IOSTAT_SUCCESS;
17595 					num_posted++;
17596 				}
17597 				/* success, put on NVME buffer sgl list */
17598 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17599 			}
17600 		}
17601 
17602 		/* continue until a nembed page worth of sgls */
17603 		if (post_cnt == 0)
17604 			continue;
17605 
17606 		/* post block of NVME buffer list sgls */
17607 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
17608 						     post_cnt);
17609 
17610 		/* don't reset xirtag due to hole in xri block */
17611 		if (block_cnt == 0)
17612 			last_xritag = NO_XRI;
17613 
17614 		/* reset NVME buffer post count for next round of posting */
17615 		post_cnt = 0;
17616 
17617 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
17618 		while (!list_empty(&blck_nblist)) {
17619 			list_remove_head(&blck_nblist, lpfc_ncmd,
17620 					 struct lpfc_io_buf, list);
17621 			if (status) {
17622 				/* Post error.  Mark buffer unavailable. */
17623 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
17624 			} else {
17625 				/* Post success, Mark buffer available. */
17626 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
17627 				lpfc_ncmd->status = IOSTAT_SUCCESS;
17628 				num_posted++;
17629 			}
17630 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17631 		}
17632 	}
17633 	/* Push NVME buffers with sgl posted to the available list */
17634 	lpfc_io_buf_replenish(phba, &nvme_nblist);
17635 
17636 	return num_posted;
17637 }
17638 
17639 /**
17640  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
17641  * @phba: pointer to lpfc_hba struct that the frame was received on
17642  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17643  *
17644  * This function checks the fields in the @fc_hdr to see if the FC frame is a
17645  * valid type of frame that the LPFC driver will handle. This function will
17646  * return a zero if the frame is a valid frame or a non zero value when the
17647  * frame does not pass the check.
17648  **/
17649 static int
17650 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
17651 {
17652 	/*  make rctl_names static to save stack space */
17653 	struct fc_vft_header *fc_vft_hdr;
17654 	uint32_t *header = (uint32_t *) fc_hdr;
17655 
17656 #define FC_RCTL_MDS_DIAGS	0xF4
17657 
17658 	switch (fc_hdr->fh_r_ctl) {
17659 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
17660 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
17661 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
17662 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
17663 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
17664 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
17665 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
17666 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
17667 	case FC_RCTL_ELS_REQ:	/* extended link services request */
17668 	case FC_RCTL_ELS_REP:	/* extended link services reply */
17669 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
17670 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
17671 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
17672 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
17673 	case FC_RCTL_BA_RMC: 	/* remove connection */
17674 	case FC_RCTL_BA_ACC:	/* basic accept */
17675 	case FC_RCTL_BA_RJT:	/* basic reject */
17676 	case FC_RCTL_BA_PRMT:
17677 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
17678 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
17679 	case FC_RCTL_P_RJT:	/* port reject */
17680 	case FC_RCTL_F_RJT:	/* fabric reject */
17681 	case FC_RCTL_P_BSY:	/* port busy */
17682 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
17683 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
17684 	case FC_RCTL_LCR:	/* link credit reset */
17685 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
17686 	case FC_RCTL_END:	/* end */
17687 		break;
17688 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
17689 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17690 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
17691 		return lpfc_fc_frame_check(phba, fc_hdr);
17692 	default:
17693 		goto drop;
17694 	}
17695 
17696 	switch (fc_hdr->fh_type) {
17697 	case FC_TYPE_BLS:
17698 	case FC_TYPE_ELS:
17699 	case FC_TYPE_FCP:
17700 	case FC_TYPE_CT:
17701 	case FC_TYPE_NVME:
17702 		break;
17703 	case FC_TYPE_IP:
17704 	case FC_TYPE_ILS:
17705 	default:
17706 		goto drop;
17707 	}
17708 
17709 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
17710 			"2538 Received frame rctl:x%x, type:x%x, "
17711 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
17712 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
17713 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
17714 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
17715 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
17716 			be32_to_cpu(header[6]));
17717 	return 0;
17718 drop:
17719 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
17720 			"2539 Dropped frame rctl:x%x type:x%x\n",
17721 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17722 	return 1;
17723 }
17724 
17725 /**
17726  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
17727  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17728  *
17729  * This function processes the FC header to retrieve the VFI from the VF
17730  * header, if one exists. This function will return the VFI if one exists
17731  * or 0 if no VSAN Header exists.
17732  **/
17733 static uint32_t
17734 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
17735 {
17736 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17737 
17738 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
17739 		return 0;
17740 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
17741 }
17742 
17743 /**
17744  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
17745  * @phba: Pointer to the HBA structure to search for the vport on
17746  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17747  * @fcfi: The FC Fabric ID that the frame came from
17748  * @did: Destination ID to match against
17749  *
17750  * This function searches the @phba for a vport that matches the content of the
17751  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
17752  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
17753  * returns the matching vport pointer or NULL if unable to match frame to a
17754  * vport.
17755  **/
17756 static struct lpfc_vport *
17757 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
17758 		       uint16_t fcfi, uint32_t did)
17759 {
17760 	struct lpfc_vport **vports;
17761 	struct lpfc_vport *vport = NULL;
17762 	int i;
17763 
17764 	if (did == Fabric_DID)
17765 		return phba->pport;
17766 	if ((phba->pport->fc_flag & FC_PT2PT) &&
17767 		!(phba->link_state == LPFC_HBA_READY))
17768 		return phba->pport;
17769 
17770 	vports = lpfc_create_vport_work_array(phba);
17771 	if (vports != NULL) {
17772 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
17773 			if (phba->fcf.fcfi == fcfi &&
17774 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
17775 			    vports[i]->fc_myDID == did) {
17776 				vport = vports[i];
17777 				break;
17778 			}
17779 		}
17780 	}
17781 	lpfc_destroy_vport_work_array(phba, vports);
17782 	return vport;
17783 }
17784 
17785 /**
17786  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
17787  * @vport: The vport to work on.
17788  *
17789  * This function updates the receive sequence time stamp for this vport. The
17790  * receive sequence time stamp indicates the time that the last frame of the
17791  * the sequence that has been idle for the longest amount of time was received.
17792  * the driver uses this time stamp to indicate if any received sequences have
17793  * timed out.
17794  **/
17795 static void
17796 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
17797 {
17798 	struct lpfc_dmabuf *h_buf;
17799 	struct hbq_dmabuf *dmabuf = NULL;
17800 
17801 	/* get the oldest sequence on the rcv list */
17802 	h_buf = list_get_first(&vport->rcv_buffer_list,
17803 			       struct lpfc_dmabuf, list);
17804 	if (!h_buf)
17805 		return;
17806 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17807 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
17808 }
17809 
17810 /**
17811  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
17812  * @vport: The vport that the received sequences were sent to.
17813  *
17814  * This function cleans up all outstanding received sequences. This is called
17815  * by the driver when a link event or user action invalidates all the received
17816  * sequences.
17817  **/
17818 void
17819 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
17820 {
17821 	struct lpfc_dmabuf *h_buf, *hnext;
17822 	struct lpfc_dmabuf *d_buf, *dnext;
17823 	struct hbq_dmabuf *dmabuf = NULL;
17824 
17825 	/* start with the oldest sequence on the rcv list */
17826 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17827 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17828 		list_del_init(&dmabuf->hbuf.list);
17829 		list_for_each_entry_safe(d_buf, dnext,
17830 					 &dmabuf->dbuf.list, list) {
17831 			list_del_init(&d_buf->list);
17832 			lpfc_in_buf_free(vport->phba, d_buf);
17833 		}
17834 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17835 	}
17836 }
17837 
17838 /**
17839  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
17840  * @vport: The vport that the received sequences were sent to.
17841  *
17842  * This function determines whether any received sequences have timed out by
17843  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
17844  * indicates that there is at least one timed out sequence this routine will
17845  * go through the received sequences one at a time from most inactive to most
17846  * active to determine which ones need to be cleaned up. Once it has determined
17847  * that a sequence needs to be cleaned up it will simply free up the resources
17848  * without sending an abort.
17849  **/
17850 void
17851 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
17852 {
17853 	struct lpfc_dmabuf *h_buf, *hnext;
17854 	struct lpfc_dmabuf *d_buf, *dnext;
17855 	struct hbq_dmabuf *dmabuf = NULL;
17856 	unsigned long timeout;
17857 	int abort_count = 0;
17858 
17859 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17860 		   vport->rcv_buffer_time_stamp);
17861 	if (list_empty(&vport->rcv_buffer_list) ||
17862 	    time_before(jiffies, timeout))
17863 		return;
17864 	/* start with the oldest sequence on the rcv list */
17865 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17866 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17867 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17868 			   dmabuf->time_stamp);
17869 		if (time_before(jiffies, timeout))
17870 			break;
17871 		abort_count++;
17872 		list_del_init(&dmabuf->hbuf.list);
17873 		list_for_each_entry_safe(d_buf, dnext,
17874 					 &dmabuf->dbuf.list, list) {
17875 			list_del_init(&d_buf->list);
17876 			lpfc_in_buf_free(vport->phba, d_buf);
17877 		}
17878 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17879 	}
17880 	if (abort_count)
17881 		lpfc_update_rcv_time_stamp(vport);
17882 }
17883 
17884 /**
17885  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
17886  * @vport: pointer to a vitural port
17887  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
17888  *
17889  * This function searches through the existing incomplete sequences that have
17890  * been sent to this @vport. If the frame matches one of the incomplete
17891  * sequences then the dbuf in the @dmabuf is added to the list of frames that
17892  * make up that sequence. If no sequence is found that matches this frame then
17893  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
17894  * This function returns a pointer to the first dmabuf in the sequence list that
17895  * the frame was linked to.
17896  **/
17897 static struct hbq_dmabuf *
17898 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
17899 {
17900 	struct fc_frame_header *new_hdr;
17901 	struct fc_frame_header *temp_hdr;
17902 	struct lpfc_dmabuf *d_buf;
17903 	struct lpfc_dmabuf *h_buf;
17904 	struct hbq_dmabuf *seq_dmabuf = NULL;
17905 	struct hbq_dmabuf *temp_dmabuf = NULL;
17906 	uint8_t	found = 0;
17907 
17908 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
17909 	dmabuf->time_stamp = jiffies;
17910 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17911 
17912 	/* Use the hdr_buf to find the sequence that this frame belongs to */
17913 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
17914 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
17915 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
17916 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
17917 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
17918 			continue;
17919 		/* found a pending sequence that matches this frame */
17920 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17921 		break;
17922 	}
17923 	if (!seq_dmabuf) {
17924 		/*
17925 		 * This indicates first frame received for this sequence.
17926 		 * Queue the buffer on the vport's rcv_buffer_list.
17927 		 */
17928 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17929 		lpfc_update_rcv_time_stamp(vport);
17930 		return dmabuf;
17931 	}
17932 	temp_hdr = seq_dmabuf->hbuf.virt;
17933 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
17934 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17935 		list_del_init(&seq_dmabuf->hbuf.list);
17936 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17937 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17938 		lpfc_update_rcv_time_stamp(vport);
17939 		return dmabuf;
17940 	}
17941 	/* move this sequence to the tail to indicate a young sequence */
17942 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
17943 	seq_dmabuf->time_stamp = jiffies;
17944 	lpfc_update_rcv_time_stamp(vport);
17945 	if (list_empty(&seq_dmabuf->dbuf.list)) {
17946 		temp_hdr = dmabuf->hbuf.virt;
17947 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17948 		return seq_dmabuf;
17949 	}
17950 	/* find the correct place in the sequence to insert this frame */
17951 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
17952 	while (!found) {
17953 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17954 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
17955 		/*
17956 		 * If the frame's sequence count is greater than the frame on
17957 		 * the list then insert the frame right after this frame
17958 		 */
17959 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
17960 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17961 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
17962 			found = 1;
17963 			break;
17964 		}
17965 
17966 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
17967 			break;
17968 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
17969 	}
17970 
17971 	if (found)
17972 		return seq_dmabuf;
17973 	return NULL;
17974 }
17975 
17976 /**
17977  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
17978  * @vport: pointer to a vitural port
17979  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17980  *
17981  * This function tries to abort from the partially assembed sequence, described
17982  * by the information from basic abbort @dmabuf. It checks to see whether such
17983  * partially assembled sequence held by the driver. If so, it shall free up all
17984  * the frames from the partially assembled sequence.
17985  *
17986  * Return
17987  * true  -- if there is matching partially assembled sequence present and all
17988  *          the frames freed with the sequence;
17989  * false -- if there is no matching partially assembled sequence present so
17990  *          nothing got aborted in the lower layer driver
17991  **/
17992 static bool
17993 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
17994 			    struct hbq_dmabuf *dmabuf)
17995 {
17996 	struct fc_frame_header *new_hdr;
17997 	struct fc_frame_header *temp_hdr;
17998 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
17999 	struct hbq_dmabuf *seq_dmabuf = NULL;
18000 
18001 	/* Use the hdr_buf to find the sequence that matches this frame */
18002 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18003 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
18004 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18005 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18006 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18007 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18008 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18009 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18010 			continue;
18011 		/* found a pending sequence that matches this frame */
18012 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18013 		break;
18014 	}
18015 
18016 	/* Free up all the frames from the partially assembled sequence */
18017 	if (seq_dmabuf) {
18018 		list_for_each_entry_safe(d_buf, n_buf,
18019 					 &seq_dmabuf->dbuf.list, list) {
18020 			list_del_init(&d_buf->list);
18021 			lpfc_in_buf_free(vport->phba, d_buf);
18022 		}
18023 		return true;
18024 	}
18025 	return false;
18026 }
18027 
18028 /**
18029  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18030  * @vport: pointer to a vitural port
18031  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18032  *
18033  * This function tries to abort from the assembed sequence from upper level
18034  * protocol, described by the information from basic abbort @dmabuf. It
18035  * checks to see whether such pending context exists at upper level protocol.
18036  * If so, it shall clean up the pending context.
18037  *
18038  * Return
18039  * true  -- if there is matching pending context of the sequence cleaned
18040  *          at ulp;
18041  * false -- if there is no matching pending context of the sequence present
18042  *          at ulp.
18043  **/
18044 static bool
18045 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18046 {
18047 	struct lpfc_hba *phba = vport->phba;
18048 	int handled;
18049 
18050 	/* Accepting abort at ulp with SLI4 only */
18051 	if (phba->sli_rev < LPFC_SLI_REV4)
18052 		return false;
18053 
18054 	/* Register all caring upper level protocols to attend abort */
18055 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18056 	if (handled)
18057 		return true;
18058 
18059 	return false;
18060 }
18061 
18062 /**
18063  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18064  * @phba: Pointer to HBA context object.
18065  * @cmd_iocbq: pointer to the command iocbq structure.
18066  * @rsp_iocbq: pointer to the response iocbq structure.
18067  *
18068  * This function handles the sequence abort response iocb command complete
18069  * event. It properly releases the memory allocated to the sequence abort
18070  * accept iocb.
18071  **/
18072 static void
18073 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18074 			     struct lpfc_iocbq *cmd_iocbq,
18075 			     struct lpfc_iocbq *rsp_iocbq)
18076 {
18077 	struct lpfc_nodelist *ndlp;
18078 
18079 	if (cmd_iocbq) {
18080 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
18081 		lpfc_nlp_put(ndlp);
18082 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
18083 	}
18084 
18085 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
18086 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18087 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18088 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
18089 			rsp_iocbq->iocb.ulpStatus,
18090 			rsp_iocbq->iocb.un.ulpWord[4]);
18091 }
18092 
18093 /**
18094  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
18095  * @phba: Pointer to HBA context object.
18096  * @xri: xri id in transaction.
18097  *
18098  * This function validates the xri maps to the known range of XRIs allocated an
18099  * used by the driver.
18100  **/
18101 uint16_t
18102 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
18103 		      uint16_t xri)
18104 {
18105 	uint16_t i;
18106 
18107 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
18108 		if (xri == phba->sli4_hba.xri_ids[i])
18109 			return i;
18110 	}
18111 	return NO_XRI;
18112 }
18113 
18114 /**
18115  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
18116  * @vport: pointer to a virtual port.
18117  * @fc_hdr: pointer to a FC frame header.
18118  * @aborted: was the partially assembled receive sequence successfully aborted
18119  *
18120  * This function sends a basic response to a previous unsol sequence abort
18121  * event after aborting the sequence handling.
18122  **/
18123 void
18124 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
18125 			struct fc_frame_header *fc_hdr, bool aborted)
18126 {
18127 	struct lpfc_hba *phba = vport->phba;
18128 	struct lpfc_iocbq *ctiocb = NULL;
18129 	struct lpfc_nodelist *ndlp;
18130 	uint16_t oxid, rxid, xri, lxri;
18131 	uint32_t sid, fctl;
18132 	IOCB_t *icmd;
18133 	int rc;
18134 
18135 	if (!lpfc_is_link_up(phba))
18136 		return;
18137 
18138 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18139 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
18140 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
18141 
18142 	ndlp = lpfc_findnode_did(vport, sid);
18143 	if (!ndlp) {
18144 		ndlp = lpfc_nlp_init(vport, sid);
18145 		if (!ndlp) {
18146 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
18147 					 "1268 Failed to allocate ndlp for "
18148 					 "oxid:x%x SID:x%x\n", oxid, sid);
18149 			return;
18150 		}
18151 		/* Put ndlp onto pport node list */
18152 		lpfc_enqueue_node(vport, ndlp);
18153 	}
18154 
18155 	/* Allocate buffer for rsp iocb */
18156 	ctiocb = lpfc_sli_get_iocbq(phba);
18157 	if (!ctiocb)
18158 		return;
18159 
18160 	/* Extract the F_CTL field from FC_HDR */
18161 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
18162 
18163 	icmd = &ctiocb->iocb;
18164 	icmd->un.xseq64.bdl.bdeSize = 0;
18165 	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
18166 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
18167 	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
18168 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
18169 
18170 	/* Fill in the rest of iocb fields */
18171 	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
18172 	icmd->ulpBdeCount = 0;
18173 	icmd->ulpLe = 1;
18174 	icmd->ulpClass = CLASS3;
18175 	icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
18176 	ctiocb->context1 = lpfc_nlp_get(ndlp);
18177 	if (!ctiocb->context1) {
18178 		lpfc_sli_release_iocbq(phba, ctiocb);
18179 		return;
18180 	}
18181 
18182 	ctiocb->vport = phba->pport;
18183 	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
18184 	ctiocb->sli4_lxritag = NO_XRI;
18185 	ctiocb->sli4_xritag = NO_XRI;
18186 
18187 	if (fctl & FC_FC_EX_CTX)
18188 		/* Exchange responder sent the abort so we
18189 		 * own the oxid.
18190 		 */
18191 		xri = oxid;
18192 	else
18193 		xri = rxid;
18194 	lxri = lpfc_sli4_xri_inrange(phba, xri);
18195 	if (lxri != NO_XRI)
18196 		lpfc_set_rrq_active(phba, ndlp, lxri,
18197 			(xri == oxid) ? rxid : oxid, 0);
18198 	/* For BA_ABTS from exchange responder, if the logical xri with
18199 	 * the oxid maps to the FCP XRI range, the port no longer has
18200 	 * that exchange context, send a BLS_RJT. Override the IOCB for
18201 	 * a BA_RJT.
18202 	 */
18203 	if ((fctl & FC_FC_EX_CTX) &&
18204 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
18205 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
18206 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
18207 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
18208 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
18209 	}
18210 
18211 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
18212 	 * the driver no longer has that exchange, send a BLS_RJT. Override
18213 	 * the IOCB for a BA_RJT.
18214 	 */
18215 	if (aborted == false) {
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 (fctl & FC_FC_EX_CTX) {
18223 		/* ABTS sent by responder to CT exchange, construction
18224 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
18225 		 * field and RX_ID from ABTS for RX_ID field.
18226 		 */
18227 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
18228 	} else {
18229 		/* ABTS sent by initiator to CT exchange, construction
18230 		 * of BA_ACC will need to allocate a new XRI as for the
18231 		 * XRI_TAG field.
18232 		 */
18233 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
18234 	}
18235 	bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
18236 	bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
18237 
18238 	/* Xmit CT abts response on exchange <xid> */
18239 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
18240 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
18241 			 icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
18242 
18243 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
18244 	if (rc == IOCB_ERROR) {
18245 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
18246 				 "2925 Failed to issue CT ABTS RSP x%x on "
18247 				 "xri x%x, Data x%x\n",
18248 				 icmd->un.xseq64.w5.hcsw.Rctl, oxid,
18249 				 phba->link_state);
18250 		lpfc_nlp_put(ndlp);
18251 		ctiocb->context1 = NULL;
18252 		lpfc_sli_release_iocbq(phba, ctiocb);
18253 	}
18254 }
18255 
18256 /**
18257  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
18258  * @vport: Pointer to the vport on which this sequence was received
18259  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18260  *
18261  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
18262  * receive sequence is only partially assembed by the driver, it shall abort
18263  * the partially assembled frames for the sequence. Otherwise, if the
18264  * unsolicited receive sequence has been completely assembled and passed to
18265  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
18266  * unsolicited sequence has been aborted. After that, it will issue a basic
18267  * accept to accept the abort.
18268  **/
18269 static void
18270 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
18271 			     struct hbq_dmabuf *dmabuf)
18272 {
18273 	struct lpfc_hba *phba = vport->phba;
18274 	struct fc_frame_header fc_hdr;
18275 	uint32_t fctl;
18276 	bool aborted;
18277 
18278 	/* Make a copy of fc_hdr before the dmabuf being released */
18279 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
18280 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
18281 
18282 	if (fctl & FC_FC_EX_CTX) {
18283 		/* ABTS by responder to exchange, no cleanup needed */
18284 		aborted = true;
18285 	} else {
18286 		/* ABTS by initiator to exchange, need to do cleanup */
18287 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
18288 		if (aborted == false)
18289 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
18290 	}
18291 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18292 
18293 	if (phba->nvmet_support) {
18294 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
18295 		return;
18296 	}
18297 
18298 	/* Respond with BA_ACC or BA_RJT accordingly */
18299 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
18300 }
18301 
18302 /**
18303  * lpfc_seq_complete - Indicates if a sequence is complete
18304  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18305  *
18306  * This function checks the sequence, starting with the frame described by
18307  * @dmabuf, to see if all the frames associated with this sequence are present.
18308  * the frames associated with this sequence are linked to the @dmabuf using the
18309  * dbuf list. This function looks for two major things. 1) That the first frame
18310  * has a sequence count of zero. 2) There is a frame with last frame of sequence
18311  * set. 3) That there are no holes in the sequence count. The function will
18312  * return 1 when the sequence is complete, otherwise it will return 0.
18313  **/
18314 static int
18315 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
18316 {
18317 	struct fc_frame_header *hdr;
18318 	struct lpfc_dmabuf *d_buf;
18319 	struct hbq_dmabuf *seq_dmabuf;
18320 	uint32_t fctl;
18321 	int seq_count = 0;
18322 
18323 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18324 	/* make sure first fame of sequence has a sequence count of zero */
18325 	if (hdr->fh_seq_cnt != seq_count)
18326 		return 0;
18327 	fctl = (hdr->fh_f_ctl[0] << 16 |
18328 		hdr->fh_f_ctl[1] << 8 |
18329 		hdr->fh_f_ctl[2]);
18330 	/* If last frame of sequence we can return success. */
18331 	if (fctl & FC_FC_END_SEQ)
18332 		return 1;
18333 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
18334 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18335 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18336 		/* If there is a hole in the sequence count then fail. */
18337 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
18338 			return 0;
18339 		fctl = (hdr->fh_f_ctl[0] << 16 |
18340 			hdr->fh_f_ctl[1] << 8 |
18341 			hdr->fh_f_ctl[2]);
18342 		/* If last frame of sequence we can return success. */
18343 		if (fctl & FC_FC_END_SEQ)
18344 			return 1;
18345 	}
18346 	return 0;
18347 }
18348 
18349 /**
18350  * lpfc_prep_seq - Prep sequence for ULP processing
18351  * @vport: Pointer to the vport on which this sequence was received
18352  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
18353  *
18354  * This function takes a sequence, described by a list of frames, and creates
18355  * a list of iocbq structures to describe the sequence. This iocbq list will be
18356  * used to issue to the generic unsolicited sequence handler. This routine
18357  * returns a pointer to the first iocbq in the list. If the function is unable
18358  * to allocate an iocbq then it throw out the received frames that were not
18359  * able to be described and return a pointer to the first iocbq. If unable to
18360  * allocate any iocbqs (including the first) this function will return NULL.
18361  **/
18362 static struct lpfc_iocbq *
18363 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
18364 {
18365 	struct hbq_dmabuf *hbq_buf;
18366 	struct lpfc_dmabuf *d_buf, *n_buf;
18367 	struct lpfc_iocbq *first_iocbq, *iocbq;
18368 	struct fc_frame_header *fc_hdr;
18369 	uint32_t sid;
18370 	uint32_t len, tot_len;
18371 	struct ulp_bde64 *pbde;
18372 
18373 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18374 	/* remove from receive buffer list */
18375 	list_del_init(&seq_dmabuf->hbuf.list);
18376 	lpfc_update_rcv_time_stamp(vport);
18377 	/* get the Remote Port's SID */
18378 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18379 	tot_len = 0;
18380 	/* Get an iocbq struct to fill in. */
18381 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
18382 	if (first_iocbq) {
18383 		/* Initialize the first IOCB. */
18384 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
18385 		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
18386 		first_iocbq->vport = vport;
18387 
18388 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
18389 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
18390 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
18391 			first_iocbq->iocb.un.rcvels.parmRo =
18392 				sli4_did_from_fc_hdr(fc_hdr);
18393 			first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
18394 		} else
18395 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
18396 		first_iocbq->iocb.ulpContext = NO_XRI;
18397 		first_iocbq->iocb.unsli3.rcvsli3.ox_id =
18398 			be16_to_cpu(fc_hdr->fh_ox_id);
18399 		/* iocbq is prepped for internal consumption.  Physical vpi. */
18400 		first_iocbq->iocb.unsli3.rcvsli3.vpi =
18401 			vport->phba->vpi_ids[vport->vpi];
18402 		/* put the first buffer into the first IOCBq */
18403 		tot_len = bf_get(lpfc_rcqe_length,
18404 				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
18405 
18406 		first_iocbq->context2 = &seq_dmabuf->dbuf;
18407 		first_iocbq->context3 = NULL;
18408 		first_iocbq->iocb.ulpBdeCount = 1;
18409 		if (tot_len > LPFC_DATA_BUF_SIZE)
18410 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
18411 							LPFC_DATA_BUF_SIZE;
18412 		else
18413 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
18414 
18415 		first_iocbq->iocb.un.rcvels.remoteID = sid;
18416 
18417 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
18418 	}
18419 	iocbq = first_iocbq;
18420 	/*
18421 	 * Each IOCBq can have two Buffers assigned, so go through the list
18422 	 * of buffers for this sequence and save two buffers in each IOCBq
18423 	 */
18424 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
18425 		if (!iocbq) {
18426 			lpfc_in_buf_free(vport->phba, d_buf);
18427 			continue;
18428 		}
18429 		if (!iocbq->context3) {
18430 			iocbq->context3 = d_buf;
18431 			iocbq->iocb.ulpBdeCount++;
18432 			/* We need to get the size out of the right CQE */
18433 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18434 			len = bf_get(lpfc_rcqe_length,
18435 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
18436 			pbde = (struct ulp_bde64 *)
18437 					&iocbq->iocb.unsli3.sli3Words[4];
18438 			if (len > LPFC_DATA_BUF_SIZE)
18439 				pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
18440 			else
18441 				pbde->tus.f.bdeSize = len;
18442 
18443 			iocbq->iocb.unsli3.rcvsli3.acc_len += len;
18444 			tot_len += len;
18445 		} else {
18446 			iocbq = lpfc_sli_get_iocbq(vport->phba);
18447 			if (!iocbq) {
18448 				if (first_iocbq) {
18449 					first_iocbq->iocb.ulpStatus =
18450 							IOSTAT_FCP_RSP_ERROR;
18451 					first_iocbq->iocb.un.ulpWord[4] =
18452 							IOERR_NO_RESOURCES;
18453 				}
18454 				lpfc_in_buf_free(vport->phba, d_buf);
18455 				continue;
18456 			}
18457 			/* We need to get the size out of the right CQE */
18458 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18459 			len = bf_get(lpfc_rcqe_length,
18460 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
18461 			iocbq->context2 = d_buf;
18462 			iocbq->context3 = NULL;
18463 			iocbq->iocb.ulpBdeCount = 1;
18464 			if (len > LPFC_DATA_BUF_SIZE)
18465 				iocbq->iocb.un.cont64[0].tus.f.bdeSize =
18466 							LPFC_DATA_BUF_SIZE;
18467 			else
18468 				iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
18469 
18470 			tot_len += len;
18471 			iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
18472 
18473 			iocbq->iocb.un.rcvels.remoteID = sid;
18474 			list_add_tail(&iocbq->list, &first_iocbq->list);
18475 		}
18476 	}
18477 	/* Free the sequence's header buffer */
18478 	if (!first_iocbq)
18479 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
18480 
18481 	return first_iocbq;
18482 }
18483 
18484 static void
18485 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
18486 			  struct hbq_dmabuf *seq_dmabuf)
18487 {
18488 	struct fc_frame_header *fc_hdr;
18489 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
18490 	struct lpfc_hba *phba = vport->phba;
18491 
18492 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18493 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
18494 	if (!iocbq) {
18495 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18496 				"2707 Ring %d handler: Failed to allocate "
18497 				"iocb Rctl x%x Type x%x received\n",
18498 				LPFC_ELS_RING,
18499 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18500 		return;
18501 	}
18502 	if (!lpfc_complete_unsol_iocb(phba,
18503 				      phba->sli4_hba.els_wq->pring,
18504 				      iocbq, fc_hdr->fh_r_ctl,
18505 				      fc_hdr->fh_type))
18506 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18507 				"2540 Ring %d handler: unexpected Rctl "
18508 				"x%x Type x%x received\n",
18509 				LPFC_ELS_RING,
18510 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18511 
18512 	/* Free iocb created in lpfc_prep_seq */
18513 	list_for_each_entry_safe(curr_iocb, next_iocb,
18514 		&iocbq->list, list) {
18515 		list_del_init(&curr_iocb->list);
18516 		lpfc_sli_release_iocbq(phba, curr_iocb);
18517 	}
18518 	lpfc_sli_release_iocbq(phba, iocbq);
18519 }
18520 
18521 static void
18522 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
18523 			    struct lpfc_iocbq *rspiocb)
18524 {
18525 	struct lpfc_dmabuf *pcmd = cmdiocb->context2;
18526 
18527 	if (pcmd && pcmd->virt)
18528 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18529 	kfree(pcmd);
18530 	lpfc_sli_release_iocbq(phba, cmdiocb);
18531 	lpfc_drain_txq(phba);
18532 }
18533 
18534 static void
18535 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
18536 			      struct hbq_dmabuf *dmabuf)
18537 {
18538 	struct fc_frame_header *fc_hdr;
18539 	struct lpfc_hba *phba = vport->phba;
18540 	struct lpfc_iocbq *iocbq = NULL;
18541 	union  lpfc_wqe *wqe;
18542 	struct lpfc_dmabuf *pcmd = NULL;
18543 	uint32_t frame_len;
18544 	int rc;
18545 	unsigned long iflags;
18546 
18547 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18548 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
18549 
18550 	/* Send the received frame back */
18551 	iocbq = lpfc_sli_get_iocbq(phba);
18552 	if (!iocbq) {
18553 		/* Queue cq event and wakeup worker thread to process it */
18554 		spin_lock_irqsave(&phba->hbalock, iflags);
18555 		list_add_tail(&dmabuf->cq_event.list,
18556 			      &phba->sli4_hba.sp_queue_event);
18557 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
18558 		spin_unlock_irqrestore(&phba->hbalock, iflags);
18559 		lpfc_worker_wake_up(phba);
18560 		return;
18561 	}
18562 
18563 	/* Allocate buffer for command payload */
18564 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
18565 	if (pcmd)
18566 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
18567 					    &pcmd->phys);
18568 	if (!pcmd || !pcmd->virt)
18569 		goto exit;
18570 
18571 	INIT_LIST_HEAD(&pcmd->list);
18572 
18573 	/* copyin the payload */
18574 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
18575 
18576 	/* fill in BDE's for command */
18577 	iocbq->iocb.un.xseq64.bdl.addrHigh = putPaddrHigh(pcmd->phys);
18578 	iocbq->iocb.un.xseq64.bdl.addrLow = putPaddrLow(pcmd->phys);
18579 	iocbq->iocb.un.xseq64.bdl.bdeFlags = BUFF_TYPE_BDE_64;
18580 	iocbq->iocb.un.xseq64.bdl.bdeSize = frame_len;
18581 
18582 	iocbq->context2 = pcmd;
18583 	iocbq->vport = vport;
18584 	iocbq->iocb_flag &= ~LPFC_FIP_ELS_ID_MASK;
18585 	iocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
18586 
18587 	/*
18588 	 * Setup rest of the iocb as though it were a WQE
18589 	 * Build the SEND_FRAME WQE
18590 	 */
18591 	wqe = (union lpfc_wqe *)&iocbq->iocb;
18592 
18593 	wqe->send_frame.frame_len = frame_len;
18594 	wqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((uint32_t *)fc_hdr));
18595 	wqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((uint32_t *)fc_hdr + 1));
18596 	wqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((uint32_t *)fc_hdr + 2));
18597 	wqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((uint32_t *)fc_hdr + 3));
18598 	wqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((uint32_t *)fc_hdr + 4));
18599 	wqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((uint32_t *)fc_hdr + 5));
18600 
18601 	iocbq->iocb.ulpCommand = CMD_SEND_FRAME;
18602 	iocbq->iocb.ulpLe = 1;
18603 	iocbq->iocb_cmpl = lpfc_sli4_mds_loopback_cmpl;
18604 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
18605 	if (rc == IOCB_ERROR)
18606 		goto exit;
18607 
18608 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18609 	return;
18610 
18611 exit:
18612 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18613 			"2023 Unable to process MDS loopback frame\n");
18614 	if (pcmd && pcmd->virt)
18615 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18616 	kfree(pcmd);
18617 	if (iocbq)
18618 		lpfc_sli_release_iocbq(phba, iocbq);
18619 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18620 }
18621 
18622 /**
18623  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
18624  * @phba: Pointer to HBA context object.
18625  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
18626  *
18627  * This function is called with no lock held. This function processes all
18628  * the received buffers and gives it to upper layers when a received buffer
18629  * indicates that it is the final frame in the sequence. The interrupt
18630  * service routine processes received buffers at interrupt contexts.
18631  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
18632  * appropriate receive function when the final frame in a sequence is received.
18633  **/
18634 void
18635 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
18636 				 struct hbq_dmabuf *dmabuf)
18637 {
18638 	struct hbq_dmabuf *seq_dmabuf;
18639 	struct fc_frame_header *fc_hdr;
18640 	struct lpfc_vport *vport;
18641 	uint32_t fcfi;
18642 	uint32_t did;
18643 
18644 	/* Process each received buffer */
18645 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18646 
18647 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
18648 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
18649 		vport = phba->pport;
18650 		/* Handle MDS Loopback frames */
18651 		if  (!(phba->pport->load_flag & FC_UNLOADING))
18652 			lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18653 		else
18654 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
18655 		return;
18656 	}
18657 
18658 	/* check to see if this a valid type of frame */
18659 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
18660 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18661 		return;
18662 	}
18663 
18664 	if ((bf_get(lpfc_cqe_code,
18665 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
18666 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
18667 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
18668 	else
18669 		fcfi = bf_get(lpfc_rcqe_fcf_id,
18670 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
18671 
18672 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
18673 		vport = phba->pport;
18674 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
18675 				"2023 MDS Loopback %d bytes\n",
18676 				bf_get(lpfc_rcqe_length,
18677 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
18678 		/* Handle MDS Loopback frames */
18679 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18680 		return;
18681 	}
18682 
18683 	/* d_id this frame is directed to */
18684 	did = sli4_did_from_fc_hdr(fc_hdr);
18685 
18686 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
18687 	if (!vport) {
18688 		/* throw out the frame */
18689 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18690 		return;
18691 	}
18692 
18693 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
18694 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
18695 		(did != Fabric_DID)) {
18696 		/*
18697 		 * Throw out the frame if we are not pt2pt.
18698 		 * The pt2pt protocol allows for discovery frames
18699 		 * to be received without a registered VPI.
18700 		 */
18701 		if (!(vport->fc_flag & FC_PT2PT) ||
18702 			(phba->link_state == LPFC_HBA_READY)) {
18703 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
18704 			return;
18705 		}
18706 	}
18707 
18708 	/* Handle the basic abort sequence (BA_ABTS) event */
18709 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
18710 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
18711 		return;
18712 	}
18713 
18714 	/* Link this frame */
18715 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
18716 	if (!seq_dmabuf) {
18717 		/* unable to add frame to vport - throw it out */
18718 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18719 		return;
18720 	}
18721 	/* If not last frame in sequence continue processing frames. */
18722 	if (!lpfc_seq_complete(seq_dmabuf))
18723 		return;
18724 
18725 	/* Send the complete sequence to the upper layer protocol */
18726 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
18727 }
18728 
18729 /**
18730  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
18731  * @phba: pointer to lpfc hba data structure.
18732  *
18733  * This routine is invoked to post rpi header templates to the
18734  * HBA consistent with the SLI-4 interface spec.  This routine
18735  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18736  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18737  *
18738  * This routine does not require any locks.  It's usage is expected
18739  * to be driver load or reset recovery when the driver is
18740  * sequential.
18741  *
18742  * Return codes
18743  * 	0 - successful
18744  *      -EIO - The mailbox failed to complete successfully.
18745  * 	When this error occurs, the driver is not guaranteed
18746  *	to have any rpi regions posted to the device and
18747  *	must either attempt to repost the regions or take a
18748  *	fatal error.
18749  **/
18750 int
18751 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
18752 {
18753 	struct lpfc_rpi_hdr *rpi_page;
18754 	uint32_t rc = 0;
18755 	uint16_t lrpi = 0;
18756 
18757 	/* SLI4 ports that support extents do not require RPI headers. */
18758 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18759 		goto exit;
18760 	if (phba->sli4_hba.extents_in_use)
18761 		return -EIO;
18762 
18763 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
18764 		/*
18765 		 * Assign the rpi headers a physical rpi only if the driver
18766 		 * has not initialized those resources.  A port reset only
18767 		 * needs the headers posted.
18768 		 */
18769 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
18770 		    LPFC_RPI_RSRC_RDY)
18771 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18772 
18773 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
18774 		if (rc != MBX_SUCCESS) {
18775 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18776 					"2008 Error %d posting all rpi "
18777 					"headers\n", rc);
18778 			rc = -EIO;
18779 			break;
18780 		}
18781 	}
18782 
18783  exit:
18784 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
18785 	       LPFC_RPI_RSRC_RDY);
18786 	return rc;
18787 }
18788 
18789 /**
18790  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
18791  * @phba: pointer to lpfc hba data structure.
18792  * @rpi_page:  pointer to the rpi memory region.
18793  *
18794  * This routine is invoked to post a single rpi header to the
18795  * HBA consistent with the SLI-4 interface spec.  This memory region
18796  * maps up to 64 rpi context regions.
18797  *
18798  * Return codes
18799  * 	0 - successful
18800  * 	-ENOMEM - No available memory
18801  *      -EIO - The mailbox failed to complete successfully.
18802  **/
18803 int
18804 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
18805 {
18806 	LPFC_MBOXQ_t *mboxq;
18807 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
18808 	uint32_t rc = 0;
18809 	uint32_t shdr_status, shdr_add_status;
18810 	union lpfc_sli4_cfg_shdr *shdr;
18811 
18812 	/* SLI4 ports that support extents do not require RPI headers. */
18813 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18814 		return rc;
18815 	if (phba->sli4_hba.extents_in_use)
18816 		return -EIO;
18817 
18818 	/* The port is notified of the header region via a mailbox command. */
18819 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18820 	if (!mboxq) {
18821 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18822 				"2001 Unable to allocate memory for issuing "
18823 				"SLI_CONFIG_SPECIAL mailbox command\n");
18824 		return -ENOMEM;
18825 	}
18826 
18827 	/* Post all rpi memory regions to the port. */
18828 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
18829 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
18830 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
18831 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
18832 			 sizeof(struct lpfc_sli4_cfg_mhdr),
18833 			 LPFC_SLI4_MBX_EMBED);
18834 
18835 
18836 	/* Post the physical rpi to the port for this rpi header. */
18837 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
18838 	       rpi_page->start_rpi);
18839 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
18840 	       hdr_tmpl, rpi_page->page_count);
18841 
18842 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
18843 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
18844 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
18845 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
18846 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18847 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18848 	mempool_free(mboxq, phba->mbox_mem_pool);
18849 	if (shdr_status || shdr_add_status || rc) {
18850 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18851 				"2514 POST_RPI_HDR mailbox failed with "
18852 				"status x%x add_status x%x, mbx status x%x\n",
18853 				shdr_status, shdr_add_status, rc);
18854 		rc = -ENXIO;
18855 	} else {
18856 		/*
18857 		 * The next_rpi stores the next logical module-64 rpi value used
18858 		 * to post physical rpis in subsequent rpi postings.
18859 		 */
18860 		spin_lock_irq(&phba->hbalock);
18861 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
18862 		spin_unlock_irq(&phba->hbalock);
18863 	}
18864 	return rc;
18865 }
18866 
18867 /**
18868  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
18869  * @phba: pointer to lpfc hba data structure.
18870  *
18871  * This routine is invoked to post rpi header templates to the
18872  * HBA consistent with the SLI-4 interface spec.  This routine
18873  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18874  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18875  *
18876  * Returns
18877  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
18878  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
18879  **/
18880 int
18881 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
18882 {
18883 	unsigned long rpi;
18884 	uint16_t max_rpi, rpi_limit;
18885 	uint16_t rpi_remaining, lrpi = 0;
18886 	struct lpfc_rpi_hdr *rpi_hdr;
18887 	unsigned long iflag;
18888 
18889 	/*
18890 	 * Fetch the next logical rpi.  Because this index is logical,
18891 	 * the  driver starts at 0 each time.
18892 	 */
18893 	spin_lock_irqsave(&phba->hbalock, iflag);
18894 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
18895 	rpi_limit = phba->sli4_hba.next_rpi;
18896 
18897 	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
18898 	if (rpi >= rpi_limit)
18899 		rpi = LPFC_RPI_ALLOC_ERROR;
18900 	else {
18901 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
18902 		phba->sli4_hba.max_cfg_param.rpi_used++;
18903 		phba->sli4_hba.rpi_count++;
18904 	}
18905 	lpfc_printf_log(phba, KERN_INFO,
18906 			LOG_NODE | LOG_DISCOVERY,
18907 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
18908 			(int) rpi, max_rpi, rpi_limit);
18909 
18910 	/*
18911 	 * Don't try to allocate more rpi header regions if the device limit
18912 	 * has been exhausted.
18913 	 */
18914 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
18915 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
18916 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18917 		return rpi;
18918 	}
18919 
18920 	/*
18921 	 * RPI header postings are not required for SLI4 ports capable of
18922 	 * extents.
18923 	 */
18924 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
18925 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18926 		return rpi;
18927 	}
18928 
18929 	/*
18930 	 * If the driver is running low on rpi resources, allocate another
18931 	 * page now.  Note that the next_rpi value is used because
18932 	 * it represents how many are actually in use whereas max_rpi notes
18933 	 * how many are supported max by the device.
18934 	 */
18935 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
18936 	spin_unlock_irqrestore(&phba->hbalock, iflag);
18937 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
18938 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
18939 		if (!rpi_hdr) {
18940 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18941 					"2002 Error Could not grow rpi "
18942 					"count\n");
18943 		} else {
18944 			lrpi = rpi_hdr->start_rpi;
18945 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18946 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
18947 		}
18948 	}
18949 
18950 	return rpi;
18951 }
18952 
18953 /**
18954  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
18955  * @phba: pointer to lpfc hba data structure.
18956  * @rpi: rpi to free
18957  *
18958  * This routine is invoked to release an rpi to the pool of
18959  * available rpis maintained by the driver.
18960  **/
18961 static void
18962 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
18963 {
18964 	/*
18965 	 * if the rpi value indicates a prior unreg has already
18966 	 * been done, skip the unreg.
18967 	 */
18968 	if (rpi == LPFC_RPI_ALLOC_ERROR)
18969 		return;
18970 
18971 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
18972 		phba->sli4_hba.rpi_count--;
18973 		phba->sli4_hba.max_cfg_param.rpi_used--;
18974 	} else {
18975 		lpfc_printf_log(phba, KERN_INFO,
18976 				LOG_NODE | LOG_DISCOVERY,
18977 				"2016 rpi %x not inuse\n",
18978 				rpi);
18979 	}
18980 }
18981 
18982 /**
18983  * lpfc_sli4_free_rpi - Release an rpi for reuse.
18984  * @phba: pointer to lpfc hba data structure.
18985  * @rpi: rpi to free
18986  *
18987  * This routine is invoked to release an rpi to the pool of
18988  * available rpis maintained by the driver.
18989  **/
18990 void
18991 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
18992 {
18993 	spin_lock_irq(&phba->hbalock);
18994 	__lpfc_sli4_free_rpi(phba, rpi);
18995 	spin_unlock_irq(&phba->hbalock);
18996 }
18997 
18998 /**
18999  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19000  * @phba: pointer to lpfc hba data structure.
19001  *
19002  * This routine is invoked to remove the memory region that
19003  * provided rpi via a bitmask.
19004  **/
19005 void
19006 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19007 {
19008 	kfree(phba->sli4_hba.rpi_bmask);
19009 	kfree(phba->sli4_hba.rpi_ids);
19010 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19011 }
19012 
19013 /**
19014  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
19015  * @ndlp: pointer to lpfc nodelist data structure.
19016  * @cmpl: completion call-back.
19017  * @arg: data to load as MBox 'caller buffer information'
19018  *
19019  * This routine is invoked to remove the memory region that
19020  * provided rpi via a bitmask.
19021  **/
19022 int
19023 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19024 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
19025 {
19026 	LPFC_MBOXQ_t *mboxq;
19027 	struct lpfc_hba *phba = ndlp->phba;
19028 	int rc;
19029 
19030 	/* The port is notified of the header region via a mailbox command. */
19031 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19032 	if (!mboxq)
19033 		return -ENOMEM;
19034 
19035 	/* Post all rpi memory regions to the port. */
19036 	lpfc_resume_rpi(mboxq, ndlp);
19037 	if (cmpl) {
19038 		mboxq->mbox_cmpl = cmpl;
19039 		mboxq->ctx_buf = arg;
19040 		mboxq->ctx_ndlp = ndlp;
19041 	} else
19042 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19043 	mboxq->vport = ndlp->vport;
19044 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19045 	if (rc == MBX_NOT_FINISHED) {
19046 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19047 				"2010 Resume RPI Mailbox failed "
19048 				"status %d, mbxStatus x%x\n", rc,
19049 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19050 		mempool_free(mboxq, phba->mbox_mem_pool);
19051 		return -EIO;
19052 	}
19053 	return 0;
19054 }
19055 
19056 /**
19057  * lpfc_sli4_init_vpi - Initialize a vpi with the port
19058  * @vport: Pointer to the vport for which the vpi is being initialized
19059  *
19060  * This routine is invoked to activate a vpi with the port.
19061  *
19062  * Returns:
19063  *    0 success
19064  *    -Evalue otherwise
19065  **/
19066 int
19067 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
19068 {
19069 	LPFC_MBOXQ_t *mboxq;
19070 	int rc = 0;
19071 	int retval = MBX_SUCCESS;
19072 	uint32_t mbox_tmo;
19073 	struct lpfc_hba *phba = vport->phba;
19074 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19075 	if (!mboxq)
19076 		return -ENOMEM;
19077 	lpfc_init_vpi(phba, mboxq, vport->vpi);
19078 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
19079 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
19080 	if (rc != MBX_SUCCESS) {
19081 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19082 				"2022 INIT VPI Mailbox failed "
19083 				"status %d, mbxStatus x%x\n", rc,
19084 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19085 		retval = -EIO;
19086 	}
19087 	if (rc != MBX_TIMEOUT)
19088 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
19089 
19090 	return retval;
19091 }
19092 
19093 /**
19094  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
19095  * @phba: pointer to lpfc hba data structure.
19096  * @mboxq: Pointer to mailbox object.
19097  *
19098  * This routine is invoked to manually add a single FCF record. The caller
19099  * must pass a completely initialized FCF_Record.  This routine takes
19100  * care of the nonembedded mailbox operations.
19101  **/
19102 static void
19103 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
19104 {
19105 	void *virt_addr;
19106 	union lpfc_sli4_cfg_shdr *shdr;
19107 	uint32_t shdr_status, shdr_add_status;
19108 
19109 	virt_addr = mboxq->sge_array->addr[0];
19110 	/* The IOCTL status is embedded in the mailbox subheader. */
19111 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
19112 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19113 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19114 
19115 	if ((shdr_status || shdr_add_status) &&
19116 		(shdr_status != STATUS_FCF_IN_USE))
19117 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19118 			"2558 ADD_FCF_RECORD mailbox failed with "
19119 			"status x%x add_status x%x\n",
19120 			shdr_status, shdr_add_status);
19121 
19122 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
19123 }
19124 
19125 /**
19126  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
19127  * @phba: pointer to lpfc hba data structure.
19128  * @fcf_record:  pointer to the initialized fcf record to add.
19129  *
19130  * This routine is invoked to manually add a single FCF record. The caller
19131  * must pass a completely initialized FCF_Record.  This routine takes
19132  * care of the nonembedded mailbox operations.
19133  **/
19134 int
19135 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
19136 {
19137 	int rc = 0;
19138 	LPFC_MBOXQ_t *mboxq;
19139 	uint8_t *bytep;
19140 	void *virt_addr;
19141 	struct lpfc_mbx_sge sge;
19142 	uint32_t alloc_len, req_len;
19143 	uint32_t fcfindex;
19144 
19145 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19146 	if (!mboxq) {
19147 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19148 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
19149 		return -ENOMEM;
19150 	}
19151 
19152 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
19153 		  sizeof(uint32_t);
19154 
19155 	/* Allocate DMA memory and set up the non-embedded mailbox command */
19156 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19157 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
19158 				     req_len, LPFC_SLI4_MBX_NEMBED);
19159 	if (alloc_len < req_len) {
19160 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19161 			"2523 Allocated DMA memory size (x%x) is "
19162 			"less than the requested DMA memory "
19163 			"size (x%x)\n", alloc_len, req_len);
19164 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19165 		return -ENOMEM;
19166 	}
19167 
19168 	/*
19169 	 * Get the first SGE entry from the non-embedded DMA memory.  This
19170 	 * routine only uses a single SGE.
19171 	 */
19172 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
19173 	virt_addr = mboxq->sge_array->addr[0];
19174 	/*
19175 	 * Configure the FCF record for FCFI 0.  This is the driver's
19176 	 * hardcoded default and gets used in nonFIP mode.
19177 	 */
19178 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
19179 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
19180 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
19181 
19182 	/*
19183 	 * Copy the fcf_index and the FCF Record Data. The data starts after
19184 	 * the FCoE header plus word10. The data copy needs to be endian
19185 	 * correct.
19186 	 */
19187 	bytep += sizeof(uint32_t);
19188 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
19189 	mboxq->vport = phba->pport;
19190 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
19191 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19192 	if (rc == MBX_NOT_FINISHED) {
19193 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19194 			"2515 ADD_FCF_RECORD mailbox failed with "
19195 			"status 0x%x\n", rc);
19196 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19197 		rc = -EIO;
19198 	} else
19199 		rc = 0;
19200 
19201 	return rc;
19202 }
19203 
19204 /**
19205  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
19206  * @phba: pointer to lpfc hba data structure.
19207  * @fcf_record:  pointer to the fcf record to write the default data.
19208  * @fcf_index: FCF table entry index.
19209  *
19210  * This routine is invoked to build the driver's default FCF record.  The
19211  * values used are hardcoded.  This routine handles memory initialization.
19212  *
19213  **/
19214 void
19215 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
19216 				struct fcf_record *fcf_record,
19217 				uint16_t fcf_index)
19218 {
19219 	memset(fcf_record, 0, sizeof(struct fcf_record));
19220 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
19221 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
19222 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
19223 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
19224 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
19225 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
19226 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
19227 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
19228 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
19229 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
19230 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
19231 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
19232 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
19233 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
19234 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
19235 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
19236 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
19237 	/* Set the VLAN bit map */
19238 	if (phba->valid_vlan) {
19239 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
19240 			= 1 << (phba->vlan_id % 8);
19241 	}
19242 }
19243 
19244 /**
19245  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
19246  * @phba: pointer to lpfc hba data structure.
19247  * @fcf_index: FCF table entry offset.
19248  *
19249  * This routine is invoked to scan the entire FCF table by reading FCF
19250  * record and processing it one at a time starting from the @fcf_index
19251  * for initial FCF discovery or fast FCF failover rediscovery.
19252  *
19253  * Return 0 if the mailbox command is submitted successfully, none 0
19254  * otherwise.
19255  **/
19256 int
19257 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19258 {
19259 	int rc = 0, error;
19260 	LPFC_MBOXQ_t *mboxq;
19261 
19262 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
19263 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
19264 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19265 	if (!mboxq) {
19266 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19267 				"2000 Failed to allocate mbox for "
19268 				"READ_FCF cmd\n");
19269 		error = -ENOMEM;
19270 		goto fail_fcf_scan;
19271 	}
19272 	/* Construct the read FCF record mailbox command */
19273 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19274 	if (rc) {
19275 		error = -EINVAL;
19276 		goto fail_fcf_scan;
19277 	}
19278 	/* Issue the mailbox command asynchronously */
19279 	mboxq->vport = phba->pport;
19280 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
19281 
19282 	spin_lock_irq(&phba->hbalock);
19283 	phba->hba_flag |= FCF_TS_INPROG;
19284 	spin_unlock_irq(&phba->hbalock);
19285 
19286 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19287 	if (rc == MBX_NOT_FINISHED)
19288 		error = -EIO;
19289 	else {
19290 		/* Reset eligible FCF count for new scan */
19291 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
19292 			phba->fcf.eligible_fcf_cnt = 0;
19293 		error = 0;
19294 	}
19295 fail_fcf_scan:
19296 	if (error) {
19297 		if (mboxq)
19298 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
19299 		/* FCF scan failed, clear FCF_TS_INPROG flag */
19300 		spin_lock_irq(&phba->hbalock);
19301 		phba->hba_flag &= ~FCF_TS_INPROG;
19302 		spin_unlock_irq(&phba->hbalock);
19303 	}
19304 	return error;
19305 }
19306 
19307 /**
19308  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
19309  * @phba: pointer to lpfc hba data structure.
19310  * @fcf_index: FCF table entry offset.
19311  *
19312  * This routine is invoked to read an FCF record indicated by @fcf_index
19313  * and to use it for FLOGI roundrobin FCF failover.
19314  *
19315  * Return 0 if the mailbox command is submitted successfully, none 0
19316  * otherwise.
19317  **/
19318 int
19319 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19320 {
19321 	int rc = 0, error;
19322 	LPFC_MBOXQ_t *mboxq;
19323 
19324 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19325 	if (!mboxq) {
19326 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
19327 				"2763 Failed to allocate mbox for "
19328 				"READ_FCF cmd\n");
19329 		error = -ENOMEM;
19330 		goto fail_fcf_read;
19331 	}
19332 	/* Construct the read FCF record mailbox command */
19333 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19334 	if (rc) {
19335 		error = -EINVAL;
19336 		goto fail_fcf_read;
19337 	}
19338 	/* Issue the mailbox command asynchronously */
19339 	mboxq->vport = phba->pport;
19340 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
19341 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19342 	if (rc == MBX_NOT_FINISHED)
19343 		error = -EIO;
19344 	else
19345 		error = 0;
19346 
19347 fail_fcf_read:
19348 	if (error && mboxq)
19349 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19350 	return error;
19351 }
19352 
19353 /**
19354  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
19355  * @phba: pointer to lpfc hba data structure.
19356  * @fcf_index: FCF table entry offset.
19357  *
19358  * This routine is invoked to read an FCF record indicated by @fcf_index to
19359  * determine whether it's eligible for FLOGI roundrobin failover list.
19360  *
19361  * Return 0 if the mailbox command is submitted successfully, none 0
19362  * otherwise.
19363  **/
19364 int
19365 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19366 {
19367 	int rc = 0, error;
19368 	LPFC_MBOXQ_t *mboxq;
19369 
19370 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19371 	if (!mboxq) {
19372 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
19373 				"2758 Failed to allocate mbox for "
19374 				"READ_FCF cmd\n");
19375 				error = -ENOMEM;
19376 				goto fail_fcf_read;
19377 	}
19378 	/* Construct the read FCF record mailbox command */
19379 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19380 	if (rc) {
19381 		error = -EINVAL;
19382 		goto fail_fcf_read;
19383 	}
19384 	/* Issue the mailbox command asynchronously */
19385 	mboxq->vport = phba->pport;
19386 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
19387 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19388 	if (rc == MBX_NOT_FINISHED)
19389 		error = -EIO;
19390 	else
19391 		error = 0;
19392 
19393 fail_fcf_read:
19394 	if (error && mboxq)
19395 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19396 	return error;
19397 }
19398 
19399 /**
19400  * lpfc_check_next_fcf_pri_level
19401  * @phba: pointer to the lpfc_hba struct for this port.
19402  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
19403  * routine when the rr_bmask is empty. The FCF indecies are put into the
19404  * rr_bmask based on their priority level. Starting from the highest priority
19405  * to the lowest. The most likely FCF candidate will be in the highest
19406  * priority group. When this routine is called it searches the fcf_pri list for
19407  * next lowest priority group and repopulates the rr_bmask with only those
19408  * fcf_indexes.
19409  * returns:
19410  * 1=success 0=failure
19411  **/
19412 static int
19413 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
19414 {
19415 	uint16_t next_fcf_pri;
19416 	uint16_t last_index;
19417 	struct lpfc_fcf_pri *fcf_pri;
19418 	int rc;
19419 	int ret = 0;
19420 
19421 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
19422 			LPFC_SLI4_FCF_TBL_INDX_MAX);
19423 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19424 			"3060 Last IDX %d\n", last_index);
19425 
19426 	/* Verify the priority list has 2 or more entries */
19427 	spin_lock_irq(&phba->hbalock);
19428 	if (list_empty(&phba->fcf.fcf_pri_list) ||
19429 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
19430 		spin_unlock_irq(&phba->hbalock);
19431 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19432 			"3061 Last IDX %d\n", last_index);
19433 		return 0; /* Empty rr list */
19434 	}
19435 	spin_unlock_irq(&phba->hbalock);
19436 
19437 	next_fcf_pri = 0;
19438 	/*
19439 	 * Clear the rr_bmask and set all of the bits that are at this
19440 	 * priority.
19441 	 */
19442 	memset(phba->fcf.fcf_rr_bmask, 0,
19443 			sizeof(*phba->fcf.fcf_rr_bmask));
19444 	spin_lock_irq(&phba->hbalock);
19445 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
19446 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
19447 			continue;
19448 		/*
19449 		 * the 1st priority that has not FLOGI failed
19450 		 * will be the highest.
19451 		 */
19452 		if (!next_fcf_pri)
19453 			next_fcf_pri = fcf_pri->fcf_rec.priority;
19454 		spin_unlock_irq(&phba->hbalock);
19455 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
19456 			rc = lpfc_sli4_fcf_rr_index_set(phba,
19457 						fcf_pri->fcf_rec.fcf_index);
19458 			if (rc)
19459 				return 0;
19460 		}
19461 		spin_lock_irq(&phba->hbalock);
19462 	}
19463 	/*
19464 	 * if next_fcf_pri was not set above and the list is not empty then
19465 	 * we have failed flogis on all of them. So reset flogi failed
19466 	 * and start at the beginning.
19467 	 */
19468 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
19469 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
19470 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
19471 			/*
19472 			 * the 1st priority that has not FLOGI failed
19473 			 * will be the highest.
19474 			 */
19475 			if (!next_fcf_pri)
19476 				next_fcf_pri = fcf_pri->fcf_rec.priority;
19477 			spin_unlock_irq(&phba->hbalock);
19478 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
19479 				rc = lpfc_sli4_fcf_rr_index_set(phba,
19480 						fcf_pri->fcf_rec.fcf_index);
19481 				if (rc)
19482 					return 0;
19483 			}
19484 			spin_lock_irq(&phba->hbalock);
19485 		}
19486 	} else
19487 		ret = 1;
19488 	spin_unlock_irq(&phba->hbalock);
19489 
19490 	return ret;
19491 }
19492 /**
19493  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
19494  * @phba: pointer to lpfc hba data structure.
19495  *
19496  * This routine is to get the next eligible FCF record index in a round
19497  * robin fashion. If the next eligible FCF record index equals to the
19498  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
19499  * shall be returned, otherwise, the next eligible FCF record's index
19500  * shall be returned.
19501  **/
19502 uint16_t
19503 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
19504 {
19505 	uint16_t next_fcf_index;
19506 
19507 initial_priority:
19508 	/* Search start from next bit of currently registered FCF index */
19509 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
19510 
19511 next_priority:
19512 	/* Determine the next fcf index to check */
19513 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
19514 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
19515 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
19516 				       next_fcf_index);
19517 
19518 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
19519 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19520 		/*
19521 		 * If we have wrapped then we need to clear the bits that
19522 		 * have been tested so that we can detect when we should
19523 		 * change the priority level.
19524 		 */
19525 		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
19526 					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
19527 	}
19528 
19529 
19530 	/* Check roundrobin failover list empty condition */
19531 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
19532 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
19533 		/*
19534 		 * If next fcf index is not found check if there are lower
19535 		 * Priority level fcf's in the fcf_priority list.
19536 		 * Set up the rr_bmask with all of the avaiable fcf bits
19537 		 * at that level and continue the selection process.
19538 		 */
19539 		if (lpfc_check_next_fcf_pri_level(phba))
19540 			goto initial_priority;
19541 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
19542 				"2844 No roundrobin failover FCF available\n");
19543 
19544 		return LPFC_FCOE_FCF_NEXT_NONE;
19545 	}
19546 
19547 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
19548 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
19549 		LPFC_FCF_FLOGI_FAILED) {
19550 		if (list_is_singular(&phba->fcf.fcf_pri_list))
19551 			return LPFC_FCOE_FCF_NEXT_NONE;
19552 
19553 		goto next_priority;
19554 	}
19555 
19556 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19557 			"2845 Get next roundrobin failover FCF (x%x)\n",
19558 			next_fcf_index);
19559 
19560 	return next_fcf_index;
19561 }
19562 
19563 /**
19564  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
19565  * @phba: pointer to lpfc hba data structure.
19566  * @fcf_index: index into the FCF table to 'set'
19567  *
19568  * This routine sets the FCF record index in to the eligible bmask for
19569  * roundrobin failover search. It checks to make sure that the index
19570  * does not go beyond the range of the driver allocated bmask dimension
19571  * before setting the bit.
19572  *
19573  * Returns 0 if the index bit successfully set, otherwise, it returns
19574  * -EINVAL.
19575  **/
19576 int
19577 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
19578 {
19579 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19580 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19581 				"2610 FCF (x%x) reached driver's book "
19582 				"keeping dimension:x%x\n",
19583 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19584 		return -EINVAL;
19585 	}
19586 	/* Set the eligible FCF record index bmask */
19587 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19588 
19589 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19590 			"2790 Set FCF (x%x) to roundrobin FCF failover "
19591 			"bmask\n", fcf_index);
19592 
19593 	return 0;
19594 }
19595 
19596 /**
19597  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
19598  * @phba: pointer to lpfc hba data structure.
19599  * @fcf_index: index into the FCF table to 'clear'
19600  *
19601  * This routine clears the FCF record index from the eligible bmask for
19602  * roundrobin failover search. It checks to make sure that the index
19603  * does not go beyond the range of the driver allocated bmask dimension
19604  * before clearing the bit.
19605  **/
19606 void
19607 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
19608 {
19609 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
19610 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19611 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19612 				"2762 FCF (x%x) reached driver's book "
19613 				"keeping dimension:x%x\n",
19614 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19615 		return;
19616 	}
19617 	/* Clear the eligible FCF record index bmask */
19618 	spin_lock_irq(&phba->hbalock);
19619 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
19620 				 list) {
19621 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
19622 			list_del_init(&fcf_pri->list);
19623 			break;
19624 		}
19625 	}
19626 	spin_unlock_irq(&phba->hbalock);
19627 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19628 
19629 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19630 			"2791 Clear FCF (x%x) from roundrobin failover "
19631 			"bmask\n", fcf_index);
19632 }
19633 
19634 /**
19635  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
19636  * @phba: pointer to lpfc hba data structure.
19637  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
19638  *
19639  * This routine is the completion routine for the rediscover FCF table mailbox
19640  * command. If the mailbox command returned failure, it will try to stop the
19641  * FCF rediscover wait timer.
19642  **/
19643 static void
19644 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
19645 {
19646 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19647 	uint32_t shdr_status, shdr_add_status;
19648 
19649 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19650 
19651 	shdr_status = bf_get(lpfc_mbox_hdr_status,
19652 			     &redisc_fcf->header.cfg_shdr.response);
19653 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
19654 			     &redisc_fcf->header.cfg_shdr.response);
19655 	if (shdr_status || shdr_add_status) {
19656 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19657 				"2746 Requesting for FCF rediscovery failed "
19658 				"status x%x add_status x%x\n",
19659 				shdr_status, shdr_add_status);
19660 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
19661 			spin_lock_irq(&phba->hbalock);
19662 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
19663 			spin_unlock_irq(&phba->hbalock);
19664 			/*
19665 			 * CVL event triggered FCF rediscover request failed,
19666 			 * last resort to re-try current registered FCF entry.
19667 			 */
19668 			lpfc_retry_pport_discovery(phba);
19669 		} else {
19670 			spin_lock_irq(&phba->hbalock);
19671 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
19672 			spin_unlock_irq(&phba->hbalock);
19673 			/*
19674 			 * DEAD FCF event triggered FCF rediscover request
19675 			 * failed, last resort to fail over as a link down
19676 			 * to FCF registration.
19677 			 */
19678 			lpfc_sli4_fcf_dead_failthrough(phba);
19679 		}
19680 	} else {
19681 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19682 				"2775 Start FCF rediscover quiescent timer\n");
19683 		/*
19684 		 * Start FCF rediscovery wait timer for pending FCF
19685 		 * before rescan FCF record table.
19686 		 */
19687 		lpfc_fcf_redisc_wait_start_timer(phba);
19688 	}
19689 
19690 	mempool_free(mbox, phba->mbox_mem_pool);
19691 }
19692 
19693 /**
19694  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
19695  * @phba: pointer to lpfc hba data structure.
19696  *
19697  * This routine is invoked to request for rediscovery of the entire FCF table
19698  * by the port.
19699  **/
19700 int
19701 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
19702 {
19703 	LPFC_MBOXQ_t *mbox;
19704 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19705 	int rc, length;
19706 
19707 	/* Cancel retry delay timers to all vports before FCF rediscover */
19708 	lpfc_cancel_all_vport_retry_delay_timer(phba);
19709 
19710 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19711 	if (!mbox) {
19712 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19713 				"2745 Failed to allocate mbox for "
19714 				"requesting FCF rediscover.\n");
19715 		return -ENOMEM;
19716 	}
19717 
19718 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
19719 		  sizeof(struct lpfc_sli4_cfg_mhdr));
19720 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
19721 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
19722 			 length, LPFC_SLI4_MBX_EMBED);
19723 
19724 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19725 	/* Set count to 0 for invalidating the entire FCF database */
19726 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
19727 
19728 	/* Issue the mailbox command asynchronously */
19729 	mbox->vport = phba->pport;
19730 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
19731 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
19732 
19733 	if (rc == MBX_NOT_FINISHED) {
19734 		mempool_free(mbox, phba->mbox_mem_pool);
19735 		return -EIO;
19736 	}
19737 	return 0;
19738 }
19739 
19740 /**
19741  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
19742  * @phba: pointer to lpfc hba data structure.
19743  *
19744  * This function is the failover routine as a last resort to the FCF DEAD
19745  * event when driver failed to perform fast FCF failover.
19746  **/
19747 void
19748 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
19749 {
19750 	uint32_t link_state;
19751 
19752 	/*
19753 	 * Last resort as FCF DEAD event failover will treat this as
19754 	 * a link down, but save the link state because we don't want
19755 	 * it to be changed to Link Down unless it is already down.
19756 	 */
19757 	link_state = phba->link_state;
19758 	lpfc_linkdown(phba);
19759 	phba->link_state = link_state;
19760 
19761 	/* Unregister FCF if no devices connected to it */
19762 	lpfc_unregister_unused_fcf(phba);
19763 }
19764 
19765 /**
19766  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
19767  * @phba: pointer to lpfc hba data structure.
19768  * @rgn23_data: pointer to configure region 23 data.
19769  *
19770  * This function gets SLI3 port configure region 23 data through memory dump
19771  * mailbox command. When it successfully retrieves data, the size of the data
19772  * will be returned, otherwise, 0 will be returned.
19773  **/
19774 static uint32_t
19775 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19776 {
19777 	LPFC_MBOXQ_t *pmb = NULL;
19778 	MAILBOX_t *mb;
19779 	uint32_t offset = 0;
19780 	int rc;
19781 
19782 	if (!rgn23_data)
19783 		return 0;
19784 
19785 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19786 	if (!pmb) {
19787 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19788 				"2600 failed to allocate mailbox memory\n");
19789 		return 0;
19790 	}
19791 	mb = &pmb->u.mb;
19792 
19793 	do {
19794 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
19795 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
19796 
19797 		if (rc != MBX_SUCCESS) {
19798 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19799 					"2601 failed to read config "
19800 					"region 23, rc 0x%x Status 0x%x\n",
19801 					rc, mb->mbxStatus);
19802 			mb->un.varDmp.word_cnt = 0;
19803 		}
19804 		/*
19805 		 * dump mem may return a zero when finished or we got a
19806 		 * mailbox error, either way we are done.
19807 		 */
19808 		if (mb->un.varDmp.word_cnt == 0)
19809 			break;
19810 
19811 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
19812 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
19813 
19814 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
19815 				       rgn23_data + offset,
19816 				       mb->un.varDmp.word_cnt);
19817 		offset += mb->un.varDmp.word_cnt;
19818 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
19819 
19820 	mempool_free(pmb, phba->mbox_mem_pool);
19821 	return offset;
19822 }
19823 
19824 /**
19825  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
19826  * @phba: pointer to lpfc hba data structure.
19827  * @rgn23_data: pointer to configure region 23 data.
19828  *
19829  * This function gets SLI4 port configure region 23 data through memory dump
19830  * mailbox command. When it successfully retrieves data, the size of the data
19831  * will be returned, otherwise, 0 will be returned.
19832  **/
19833 static uint32_t
19834 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19835 {
19836 	LPFC_MBOXQ_t *mboxq = NULL;
19837 	struct lpfc_dmabuf *mp = NULL;
19838 	struct lpfc_mqe *mqe;
19839 	uint32_t data_length = 0;
19840 	int rc;
19841 
19842 	if (!rgn23_data)
19843 		return 0;
19844 
19845 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19846 	if (!mboxq) {
19847 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19848 				"3105 failed to allocate mailbox memory\n");
19849 		return 0;
19850 	}
19851 
19852 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
19853 		goto out;
19854 	mqe = &mboxq->u.mqe;
19855 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
19856 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19857 	if (rc)
19858 		goto out;
19859 	data_length = mqe->un.mb_words[5];
19860 	if (data_length == 0)
19861 		goto out;
19862 	if (data_length > DMP_RGN23_SIZE) {
19863 		data_length = 0;
19864 		goto out;
19865 	}
19866 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
19867 out:
19868 	mempool_free(mboxq, phba->mbox_mem_pool);
19869 	if (mp) {
19870 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
19871 		kfree(mp);
19872 	}
19873 	return data_length;
19874 }
19875 
19876 /**
19877  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
19878  * @phba: pointer to lpfc hba data structure.
19879  *
19880  * This function read region 23 and parse TLV for port status to
19881  * decide if the user disaled the port. If the TLV indicates the
19882  * port is disabled, the hba_flag is set accordingly.
19883  **/
19884 void
19885 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
19886 {
19887 	uint8_t *rgn23_data = NULL;
19888 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
19889 	uint32_t offset = 0;
19890 
19891 	/* Get adapter Region 23 data */
19892 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
19893 	if (!rgn23_data)
19894 		goto out;
19895 
19896 	if (phba->sli_rev < LPFC_SLI_REV4)
19897 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
19898 	else {
19899 		if_type = bf_get(lpfc_sli_intf_if_type,
19900 				 &phba->sli4_hba.sli_intf);
19901 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
19902 			goto out;
19903 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
19904 	}
19905 
19906 	if (!data_size)
19907 		goto out;
19908 
19909 	/* Check the region signature first */
19910 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
19911 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19912 			"2619 Config region 23 has bad signature\n");
19913 			goto out;
19914 	}
19915 	offset += 4;
19916 
19917 	/* Check the data structure version */
19918 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
19919 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19920 			"2620 Config region 23 has bad version\n");
19921 		goto out;
19922 	}
19923 	offset += 4;
19924 
19925 	/* Parse TLV entries in the region */
19926 	while (offset < data_size) {
19927 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
19928 			break;
19929 		/*
19930 		 * If the TLV is not driver specific TLV or driver id is
19931 		 * not linux driver id, skip the record.
19932 		 */
19933 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
19934 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
19935 		    (rgn23_data[offset + 3] != 0)) {
19936 			offset += rgn23_data[offset + 1] * 4 + 4;
19937 			continue;
19938 		}
19939 
19940 		/* Driver found a driver specific TLV in the config region */
19941 		sub_tlv_len = rgn23_data[offset + 1] * 4;
19942 		offset += 4;
19943 		tlv_offset = 0;
19944 
19945 		/*
19946 		 * Search for configured port state sub-TLV.
19947 		 */
19948 		while ((offset < data_size) &&
19949 			(tlv_offset < sub_tlv_len)) {
19950 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
19951 				offset += 4;
19952 				tlv_offset += 4;
19953 				break;
19954 			}
19955 			if (rgn23_data[offset] != PORT_STE_TYPE) {
19956 				offset += rgn23_data[offset + 1] * 4 + 4;
19957 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
19958 				continue;
19959 			}
19960 
19961 			/* This HBA contains PORT_STE configured */
19962 			if (!rgn23_data[offset + 2])
19963 				phba->hba_flag |= LINK_DISABLED;
19964 
19965 			goto out;
19966 		}
19967 	}
19968 
19969 out:
19970 	kfree(rgn23_data);
19971 	return;
19972 }
19973 
19974 /**
19975  * lpfc_wr_object - write an object to the firmware
19976  * @phba: HBA structure that indicates port to create a queue on.
19977  * @dmabuf_list: list of dmabufs to write to the port.
19978  * @size: the total byte value of the objects to write to the port.
19979  * @offset: the current offset to be used to start the transfer.
19980  *
19981  * This routine will create a wr_object mailbox command to send to the port.
19982  * the mailbox command will be constructed using the dma buffers described in
19983  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
19984  * BDEs that the imbedded mailbox can support. The @offset variable will be
19985  * used to indicate the starting offset of the transfer and will also return
19986  * the offset after the write object mailbox has completed. @size is used to
19987  * determine the end of the object and whether the eof bit should be set.
19988  *
19989  * Return 0 is successful and offset will contain the the new offset to use
19990  * for the next write.
19991  * Return negative value for error cases.
19992  **/
19993 int
19994 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
19995 	       uint32_t size, uint32_t *offset)
19996 {
19997 	struct lpfc_mbx_wr_object *wr_object;
19998 	LPFC_MBOXQ_t *mbox;
19999 	int rc = 0, i = 0;
20000 	uint32_t shdr_status, shdr_add_status, shdr_change_status, shdr_csf;
20001 	uint32_t mbox_tmo;
20002 	struct lpfc_dmabuf *dmabuf;
20003 	uint32_t written = 0;
20004 	bool check_change_status = false;
20005 
20006 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20007 	if (!mbox)
20008 		return -ENOMEM;
20009 
20010 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
20011 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
20012 			sizeof(struct lpfc_mbx_wr_object) -
20013 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
20014 
20015 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
20016 	wr_object->u.request.write_offset = *offset;
20017 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
20018 	wr_object->u.request.object_name[0] =
20019 		cpu_to_le32(wr_object->u.request.object_name[0]);
20020 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
20021 	list_for_each_entry(dmabuf, dmabuf_list, list) {
20022 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
20023 			break;
20024 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
20025 		wr_object->u.request.bde[i].addrHigh =
20026 			putPaddrHigh(dmabuf->phys);
20027 		if (written + SLI4_PAGE_SIZE >= size) {
20028 			wr_object->u.request.bde[i].tus.f.bdeSize =
20029 				(size - written);
20030 			written += (size - written);
20031 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
20032 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
20033 			check_change_status = true;
20034 		} else {
20035 			wr_object->u.request.bde[i].tus.f.bdeSize =
20036 				SLI4_PAGE_SIZE;
20037 			written += SLI4_PAGE_SIZE;
20038 		}
20039 		i++;
20040 	}
20041 	wr_object->u.request.bde_count = i;
20042 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
20043 	if (!phba->sli4_hba.intr_enable)
20044 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
20045 	else {
20046 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
20047 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
20048 	}
20049 	/* The IOCTL status is embedded in the mailbox subheader. */
20050 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20051 			     &wr_object->header.cfg_shdr.response);
20052 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20053 				 &wr_object->header.cfg_shdr.response);
20054 	if (check_change_status) {
20055 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
20056 					    &wr_object->u.response);
20057 
20058 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20059 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20060 			shdr_csf = bf_get(lpfc_wr_object_csf,
20061 					  &wr_object->u.response);
20062 			if (shdr_csf)
20063 				shdr_change_status =
20064 						   LPFC_CHANGE_STATUS_PCI_RESET;
20065 		}
20066 
20067 		switch (shdr_change_status) {
20068 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20069 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20070 					"3198 Firmware write complete: System "
20071 					"reboot required to instantiate\n");
20072 			break;
20073 		case (LPFC_CHANGE_STATUS_FW_RESET):
20074 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20075 					"3199 Firmware write complete: Firmware"
20076 					" reset required to instantiate\n");
20077 			break;
20078 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20079 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20080 					"3200 Firmware write complete: Port "
20081 					"Migration or PCI Reset required to "
20082 					"instantiate\n");
20083 			break;
20084 		case (LPFC_CHANGE_STATUS_PCI_RESET):
20085 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20086 					"3201 Firmware write complete: PCI "
20087 					"Reset required to instantiate\n");
20088 			break;
20089 		default:
20090 			break;
20091 		}
20092 	}
20093 	if (!phba->sli4_hba.intr_enable)
20094 		mempool_free(mbox, phba->mbox_mem_pool);
20095 	else if (rc != MBX_TIMEOUT)
20096 		mempool_free(mbox, phba->mbox_mem_pool);
20097 	if (shdr_status || shdr_add_status || rc) {
20098 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20099 				"3025 Write Object mailbox failed with "
20100 				"status x%x add_status x%x, mbx status x%x\n",
20101 				shdr_status, shdr_add_status, rc);
20102 		rc = -ENXIO;
20103 		*offset = shdr_add_status;
20104 	} else
20105 		*offset += wr_object->u.response.actual_write_length;
20106 	return rc;
20107 }
20108 
20109 /**
20110  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
20111  * @vport: pointer to vport data structure.
20112  *
20113  * This function iterate through the mailboxq and clean up all REG_LOGIN
20114  * and REG_VPI mailbox commands associated with the vport. This function
20115  * is called when driver want to restart discovery of the vport due to
20116  * a Clear Virtual Link event.
20117  **/
20118 void
20119 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
20120 {
20121 	struct lpfc_hba *phba = vport->phba;
20122 	LPFC_MBOXQ_t *mb, *nextmb;
20123 	struct lpfc_dmabuf *mp;
20124 	struct lpfc_nodelist *ndlp;
20125 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
20126 	LIST_HEAD(mbox_cmd_list);
20127 	uint8_t restart_loop;
20128 
20129 	/* Clean up internally queued mailbox commands with the vport */
20130 	spin_lock_irq(&phba->hbalock);
20131 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
20132 		if (mb->vport != vport)
20133 			continue;
20134 
20135 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
20136 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
20137 			continue;
20138 
20139 		list_del(&mb->list);
20140 		list_add_tail(&mb->list, &mbox_cmd_list);
20141 	}
20142 	/* Clean up active mailbox command with the vport */
20143 	mb = phba->sli.mbox_active;
20144 	if (mb && (mb->vport == vport)) {
20145 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
20146 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
20147 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
20148 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20149 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20150 			/* Put reference count for delayed processing */
20151 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
20152 			/* Unregister the RPI when mailbox complete */
20153 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
20154 		}
20155 	}
20156 	/* Cleanup any mailbox completions which are not yet processed */
20157 	do {
20158 		restart_loop = 0;
20159 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
20160 			/*
20161 			 * If this mailox is already processed or it is
20162 			 * for another vport ignore it.
20163 			 */
20164 			if ((mb->vport != vport) ||
20165 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
20166 				continue;
20167 
20168 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
20169 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
20170 				continue;
20171 
20172 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
20173 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20174 				ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20175 				/* Unregister the RPI when mailbox complete */
20176 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
20177 				restart_loop = 1;
20178 				spin_unlock_irq(&phba->hbalock);
20179 				spin_lock(&ndlp->lock);
20180 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20181 				spin_unlock(&ndlp->lock);
20182 				spin_lock_irq(&phba->hbalock);
20183 				break;
20184 			}
20185 		}
20186 	} while (restart_loop);
20187 
20188 	spin_unlock_irq(&phba->hbalock);
20189 
20190 	/* Release the cleaned-up mailbox commands */
20191 	while (!list_empty(&mbox_cmd_list)) {
20192 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
20193 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20194 			mp = (struct lpfc_dmabuf *)(mb->ctx_buf);
20195 			if (mp) {
20196 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
20197 				kfree(mp);
20198 			}
20199 			mb->ctx_buf = NULL;
20200 			ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20201 			mb->ctx_ndlp = NULL;
20202 			if (ndlp) {
20203 				spin_lock(&ndlp->lock);
20204 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20205 				spin_unlock(&ndlp->lock);
20206 				lpfc_nlp_put(ndlp);
20207 			}
20208 		}
20209 		mempool_free(mb, phba->mbox_mem_pool);
20210 	}
20211 
20212 	/* Release the ndlp with the cleaned-up active mailbox command */
20213 	if (act_mbx_ndlp) {
20214 		spin_lock(&act_mbx_ndlp->lock);
20215 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20216 		spin_unlock(&act_mbx_ndlp->lock);
20217 		lpfc_nlp_put(act_mbx_ndlp);
20218 	}
20219 }
20220 
20221 /**
20222  * lpfc_drain_txq - Drain the txq
20223  * @phba: Pointer to HBA context object.
20224  *
20225  * This function attempt to submit IOCBs on the txq
20226  * to the adapter.  For SLI4 adapters, the txq contains
20227  * ELS IOCBs that have been deferred because the there
20228  * are no SGLs.  This congestion can occur with large
20229  * vport counts during node discovery.
20230  **/
20231 
20232 uint32_t
20233 lpfc_drain_txq(struct lpfc_hba *phba)
20234 {
20235 	LIST_HEAD(completions);
20236 	struct lpfc_sli_ring *pring;
20237 	struct lpfc_iocbq *piocbq = NULL;
20238 	unsigned long iflags = 0;
20239 	char *fail_msg = NULL;
20240 	struct lpfc_sglq *sglq;
20241 	union lpfc_wqe128 wqe;
20242 	uint32_t txq_cnt = 0;
20243 	struct lpfc_queue *wq;
20244 
20245 	if (phba->link_flag & LS_MDS_LOOPBACK) {
20246 		/* MDS WQE are posted only to first WQ*/
20247 		wq = phba->sli4_hba.hdwq[0].io_wq;
20248 		if (unlikely(!wq))
20249 			return 0;
20250 		pring = wq->pring;
20251 	} else {
20252 		wq = phba->sli4_hba.els_wq;
20253 		if (unlikely(!wq))
20254 			return 0;
20255 		pring = lpfc_phba_elsring(phba);
20256 	}
20257 
20258 	if (unlikely(!pring) || list_empty(&pring->txq))
20259 		return 0;
20260 
20261 	spin_lock_irqsave(&pring->ring_lock, iflags);
20262 	list_for_each_entry(piocbq, &pring->txq, list) {
20263 		txq_cnt++;
20264 	}
20265 
20266 	if (txq_cnt > pring->txq_max)
20267 		pring->txq_max = txq_cnt;
20268 
20269 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
20270 
20271 	while (!list_empty(&pring->txq)) {
20272 		spin_lock_irqsave(&pring->ring_lock, iflags);
20273 
20274 		piocbq = lpfc_sli_ringtx_get(phba, pring);
20275 		if (!piocbq) {
20276 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20277 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20278 				"2823 txq empty and txq_cnt is %d\n ",
20279 				txq_cnt);
20280 			break;
20281 		}
20282 		sglq = __lpfc_sli_get_els_sglq(phba, piocbq);
20283 		if (!sglq) {
20284 			__lpfc_sli_ringtx_put(phba, pring, piocbq);
20285 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20286 			break;
20287 		}
20288 		txq_cnt--;
20289 
20290 		/* The xri and iocb resources secured,
20291 		 * attempt to issue request
20292 		 */
20293 		piocbq->sli4_lxritag = sglq->sli4_lxritag;
20294 		piocbq->sli4_xritag = sglq->sli4_xritag;
20295 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
20296 			fail_msg = "to convert bpl to sgl";
20297 		else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
20298 			fail_msg = "to convert iocb to wqe";
20299 		else if (lpfc_sli4_wq_put(wq, &wqe))
20300 			fail_msg = " - Wq is full";
20301 		else
20302 			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
20303 
20304 		if (fail_msg) {
20305 			/* Failed means we can't issue and need to cancel */
20306 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20307 					"2822 IOCB failed %s iotag 0x%x "
20308 					"xri 0x%x\n",
20309 					fail_msg,
20310 					piocbq->iotag, piocbq->sli4_xritag);
20311 			list_add_tail(&piocbq->list, &completions);
20312 		}
20313 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20314 	}
20315 
20316 	/* Cancel all the IOCBs that cannot be issued */
20317 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
20318 				IOERR_SLI_ABORTED);
20319 
20320 	return txq_cnt;
20321 }
20322 
20323 /**
20324  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
20325  * @phba: Pointer to HBA context object.
20326  * @pwqeq: Pointer to command WQE.
20327  * @sglq: Pointer to the scatter gather queue object.
20328  *
20329  * This routine converts the bpl or bde that is in the WQE
20330  * to a sgl list for the sli4 hardware. The physical address
20331  * of the bpl/bde is converted back to a virtual address.
20332  * If the WQE contains a BPL then the list of BDE's is
20333  * converted to sli4_sge's. If the WQE contains a single
20334  * BDE then it is converted to a single sli_sge.
20335  * The WQE is still in cpu endianness so the contents of
20336  * the bpl can be used without byte swapping.
20337  *
20338  * Returns valid XRI = Success, NO_XRI = Failure.
20339  */
20340 static uint16_t
20341 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
20342 		 struct lpfc_sglq *sglq)
20343 {
20344 	uint16_t xritag = NO_XRI;
20345 	struct ulp_bde64 *bpl = NULL;
20346 	struct ulp_bde64 bde;
20347 	struct sli4_sge *sgl  = NULL;
20348 	struct lpfc_dmabuf *dmabuf;
20349 	union lpfc_wqe128 *wqe;
20350 	int numBdes = 0;
20351 	int i = 0;
20352 	uint32_t offset = 0; /* accumulated offset in the sg request list */
20353 	int inbound = 0; /* number of sg reply entries inbound from firmware */
20354 	uint32_t cmd;
20355 
20356 	if (!pwqeq || !sglq)
20357 		return xritag;
20358 
20359 	sgl  = (struct sli4_sge *)sglq->sgl;
20360 	wqe = &pwqeq->wqe;
20361 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
20362 
20363 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
20364 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
20365 		return sglq->sli4_xritag;
20366 	numBdes = pwqeq->rsvd2;
20367 	if (numBdes) {
20368 		/* The addrHigh and addrLow fields within the WQE
20369 		 * have not been byteswapped yet so there is no
20370 		 * need to swap them back.
20371 		 */
20372 		if (pwqeq->context3)
20373 			dmabuf = (struct lpfc_dmabuf *)pwqeq->context3;
20374 		else
20375 			return xritag;
20376 
20377 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
20378 		if (!bpl)
20379 			return xritag;
20380 
20381 		for (i = 0; i < numBdes; i++) {
20382 			/* Should already be byte swapped. */
20383 			sgl->addr_hi = bpl->addrHigh;
20384 			sgl->addr_lo = bpl->addrLow;
20385 
20386 			sgl->word2 = le32_to_cpu(sgl->word2);
20387 			if ((i+1) == numBdes)
20388 				bf_set(lpfc_sli4_sge_last, sgl, 1);
20389 			else
20390 				bf_set(lpfc_sli4_sge_last, sgl, 0);
20391 			/* swap the size field back to the cpu so we
20392 			 * can assign it to the sgl.
20393 			 */
20394 			bde.tus.w = le32_to_cpu(bpl->tus.w);
20395 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
20396 			/* The offsets in the sgl need to be accumulated
20397 			 * separately for the request and reply lists.
20398 			 * The request is always first, the reply follows.
20399 			 */
20400 			switch (cmd) {
20401 			case CMD_GEN_REQUEST64_WQE:
20402 				/* add up the reply sg entries */
20403 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
20404 					inbound++;
20405 				/* first inbound? reset the offset */
20406 				if (inbound == 1)
20407 					offset = 0;
20408 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
20409 				bf_set(lpfc_sli4_sge_type, sgl,
20410 					LPFC_SGE_TYPE_DATA);
20411 				offset += bde.tus.f.bdeSize;
20412 				break;
20413 			case CMD_FCP_TRSP64_WQE:
20414 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
20415 				bf_set(lpfc_sli4_sge_type, sgl,
20416 					LPFC_SGE_TYPE_DATA);
20417 				break;
20418 			case CMD_FCP_TSEND64_WQE:
20419 			case CMD_FCP_TRECEIVE64_WQE:
20420 				bf_set(lpfc_sli4_sge_type, sgl,
20421 					bpl->tus.f.bdeFlags);
20422 				if (i < 3)
20423 					offset = 0;
20424 				else
20425 					offset += bde.tus.f.bdeSize;
20426 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
20427 				break;
20428 			}
20429 			sgl->word2 = cpu_to_le32(sgl->word2);
20430 			bpl++;
20431 			sgl++;
20432 		}
20433 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
20434 		/* The addrHigh and addrLow fields of the BDE have not
20435 		 * been byteswapped yet so they need to be swapped
20436 		 * before putting them in the sgl.
20437 		 */
20438 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
20439 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
20440 		sgl->word2 = le32_to_cpu(sgl->word2);
20441 		bf_set(lpfc_sli4_sge_last, sgl, 1);
20442 		sgl->word2 = cpu_to_le32(sgl->word2);
20443 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
20444 	}
20445 	return sglq->sli4_xritag;
20446 }
20447 
20448 /**
20449  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
20450  * @phba: Pointer to HBA context object.
20451  * @qp: Pointer to HDW queue.
20452  * @pwqe: Pointer to command WQE.
20453  **/
20454 int
20455 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
20456 		    struct lpfc_iocbq *pwqe)
20457 {
20458 	union lpfc_wqe128 *wqe = &pwqe->wqe;
20459 	struct lpfc_async_xchg_ctx *ctxp;
20460 	struct lpfc_queue *wq;
20461 	struct lpfc_sglq *sglq;
20462 	struct lpfc_sli_ring *pring;
20463 	unsigned long iflags;
20464 	uint32_t ret = 0;
20465 
20466 	/* NVME_LS and NVME_LS ABTS requests. */
20467 	if (pwqe->iocb_flag & LPFC_IO_NVME_LS) {
20468 		pring =  phba->sli4_hba.nvmels_wq->pring;
20469 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20470 					  qp, wq_access);
20471 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
20472 		if (!sglq) {
20473 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20474 			return WQE_BUSY;
20475 		}
20476 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
20477 		pwqe->sli4_xritag = sglq->sli4_xritag;
20478 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
20479 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20480 			return WQE_ERROR;
20481 		}
20482 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
20483 		       pwqe->sli4_xritag);
20484 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
20485 		if (ret) {
20486 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20487 			return ret;
20488 		}
20489 
20490 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20491 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20492 
20493 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20494 		return 0;
20495 	}
20496 
20497 	/* NVME_FCREQ and NVME_ABTS requests */
20498 	if (pwqe->iocb_flag & LPFC_IO_NVME ||
20499 	    pwqe->iocb_flag & LPFC_IO_FCP) {
20500 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
20501 		wq = qp->io_wq;
20502 		pring = wq->pring;
20503 
20504 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
20505 
20506 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20507 					  qp, wq_access);
20508 		ret = lpfc_sli4_wq_put(wq, wqe);
20509 		if (ret) {
20510 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20511 			return ret;
20512 		}
20513 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20514 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20515 
20516 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20517 		return 0;
20518 	}
20519 
20520 	/* NVMET requests */
20521 	if (pwqe->iocb_flag & LPFC_IO_NVMET) {
20522 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
20523 		wq = qp->io_wq;
20524 		pring = wq->pring;
20525 
20526 		ctxp = pwqe->context2;
20527 		sglq = ctxp->ctxbuf->sglq;
20528 		if (pwqe->sli4_xritag ==  NO_XRI) {
20529 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
20530 			pwqe->sli4_xritag = sglq->sli4_xritag;
20531 		}
20532 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
20533 		       pwqe->sli4_xritag);
20534 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
20535 
20536 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20537 					  qp, wq_access);
20538 		ret = lpfc_sli4_wq_put(wq, wqe);
20539 		if (ret) {
20540 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20541 			return ret;
20542 		}
20543 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20544 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20545 
20546 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20547 		return 0;
20548 	}
20549 	return WQE_ERROR;
20550 }
20551 
20552 /**
20553  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
20554  * @phba: Pointer to HBA context object.
20555  * @cmdiocb: Pointer to driver command iocb object.
20556  * @cmpl: completion function.
20557  *
20558  * Fill the appropriate fields for the abort WQE and call
20559  * internal routine lpfc_sli4_issue_wqe to send the WQE
20560  * This function is called with hbalock held and no ring_lock held.
20561  *
20562  * RETURNS 0 - SUCCESS
20563  **/
20564 
20565 int
20566 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
20567 			    void *cmpl)
20568 {
20569 	struct lpfc_vport *vport = cmdiocb->vport;
20570 	struct lpfc_iocbq *abtsiocb = NULL;
20571 	union lpfc_wqe128 *abtswqe;
20572 	struct lpfc_io_buf *lpfc_cmd;
20573 	int retval = IOCB_ERROR;
20574 	u16 xritag = cmdiocb->sli4_xritag;
20575 
20576 	/*
20577 	 * The scsi command can not be in txq and it is in flight because the
20578 	 * pCmd is still pointing at the SCSI command we have to abort. There
20579 	 * is no need to search the txcmplq. Just send an abort to the FW.
20580 	 */
20581 
20582 	abtsiocb = __lpfc_sli_get_iocbq(phba);
20583 	if (!abtsiocb)
20584 		return WQE_NORESOURCE;
20585 
20586 	/* Indicate the IO is being aborted by the driver. */
20587 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
20588 
20589 	abtswqe = &abtsiocb->wqe;
20590 	memset(abtswqe, 0, sizeof(*abtswqe));
20591 
20592 	if (lpfc_is_link_up(phba))
20593 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
20594 	else
20595 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 0);
20596 	bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
20597 	abtswqe->abort_cmd.rsrvd5 = 0;
20598 	abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
20599 	bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
20600 	bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
20601 	bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
20602 	bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
20603 	bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
20604 	bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
20605 
20606 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
20607 	abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
20608 	abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
20609 	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
20610 		abtsiocb->iocb_flag |= LPFC_IO_FCP;
20611 	if (cmdiocb->iocb_flag & LPFC_IO_NVME)
20612 		abtsiocb->iocb_flag |= LPFC_IO_NVME;
20613 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
20614 		abtsiocb->iocb_flag |= LPFC_IO_FOF;
20615 	abtsiocb->vport = vport;
20616 	abtsiocb->wqe_cmpl = cmpl;
20617 
20618 	lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
20619 	retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
20620 
20621 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
20622 			 "0359 Abort xri x%x, original iotag x%x, "
20623 			 "abort cmd iotag x%x retval x%x\n",
20624 			 xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
20625 
20626 	if (retval) {
20627 		cmdiocb->iocb_flag &= ~LPFC_DRIVER_ABORTED;
20628 		__lpfc_sli_release_iocbq(phba, abtsiocb);
20629 	}
20630 
20631 	return retval;
20632 }
20633 
20634 #ifdef LPFC_MXP_STAT
20635 /**
20636  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
20637  * @phba: pointer to lpfc hba data structure.
20638  * @hwqid: belong to which HWQ.
20639  *
20640  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
20641  * 15 seconds after a test case is running.
20642  *
20643  * The user should call lpfc_debugfs_multixripools_write before running a test
20644  * case to clear stat_snapshot_taken. Then the user starts a test case. During
20645  * test case is running, stat_snapshot_taken is incremented by 1 every time when
20646  * this routine is called from heartbeat timer. When stat_snapshot_taken is
20647  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
20648  **/
20649 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
20650 {
20651 	struct lpfc_sli4_hdw_queue *qp;
20652 	struct lpfc_multixri_pool *multixri_pool;
20653 	struct lpfc_pvt_pool *pvt_pool;
20654 	struct lpfc_pbl_pool *pbl_pool;
20655 	u32 txcmplq_cnt;
20656 
20657 	qp = &phba->sli4_hba.hdwq[hwqid];
20658 	multixri_pool = qp->p_multixri_pool;
20659 	if (!multixri_pool)
20660 		return;
20661 
20662 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
20663 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
20664 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
20665 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20666 
20667 		multixri_pool->stat_pbl_count = pbl_pool->count;
20668 		multixri_pool->stat_pvt_count = pvt_pool->count;
20669 		multixri_pool->stat_busy_count = txcmplq_cnt;
20670 	}
20671 
20672 	multixri_pool->stat_snapshot_taken++;
20673 }
20674 #endif
20675 
20676 /**
20677  * lpfc_adjust_pvt_pool_count - Adjust private pool count
20678  * @phba: pointer to lpfc hba data structure.
20679  * @hwqid: belong to which HWQ.
20680  *
20681  * This routine moves some XRIs from private to public pool when private pool
20682  * is not busy.
20683  **/
20684 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
20685 {
20686 	struct lpfc_multixri_pool *multixri_pool;
20687 	u32 io_req_count;
20688 	u32 prev_io_req_count;
20689 
20690 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
20691 	if (!multixri_pool)
20692 		return;
20693 	io_req_count = multixri_pool->io_req_count;
20694 	prev_io_req_count = multixri_pool->prev_io_req_count;
20695 
20696 	if (prev_io_req_count != io_req_count) {
20697 		/* Private pool is busy */
20698 		multixri_pool->prev_io_req_count = io_req_count;
20699 	} else {
20700 		/* Private pool is not busy.
20701 		 * Move XRIs from private to public pool.
20702 		 */
20703 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
20704 	}
20705 }
20706 
20707 /**
20708  * lpfc_adjust_high_watermark - Adjust high watermark
20709  * @phba: pointer to lpfc hba data structure.
20710  * @hwqid: belong to which HWQ.
20711  *
20712  * This routine sets high watermark as number of outstanding XRIs,
20713  * but make sure the new value is between xri_limit/2 and xri_limit.
20714  **/
20715 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
20716 {
20717 	u32 new_watermark;
20718 	u32 watermark_max;
20719 	u32 watermark_min;
20720 	u32 xri_limit;
20721 	u32 txcmplq_cnt;
20722 	u32 abts_io_bufs;
20723 	struct lpfc_multixri_pool *multixri_pool;
20724 	struct lpfc_sli4_hdw_queue *qp;
20725 
20726 	qp = &phba->sli4_hba.hdwq[hwqid];
20727 	multixri_pool = qp->p_multixri_pool;
20728 	if (!multixri_pool)
20729 		return;
20730 	xri_limit = multixri_pool->xri_limit;
20731 
20732 	watermark_max = xri_limit;
20733 	watermark_min = xri_limit / 2;
20734 
20735 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20736 	abts_io_bufs = qp->abts_scsi_io_bufs;
20737 	abts_io_bufs += qp->abts_nvme_io_bufs;
20738 
20739 	new_watermark = txcmplq_cnt + abts_io_bufs;
20740 	new_watermark = min(watermark_max, new_watermark);
20741 	new_watermark = max(watermark_min, new_watermark);
20742 	multixri_pool->pvt_pool.high_watermark = new_watermark;
20743 
20744 #ifdef LPFC_MXP_STAT
20745 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
20746 					  new_watermark);
20747 #endif
20748 }
20749 
20750 /**
20751  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
20752  * @phba: pointer to lpfc hba data structure.
20753  * @hwqid: belong to which HWQ.
20754  *
20755  * This routine is called from hearbeat timer when pvt_pool is idle.
20756  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
20757  * The first step moves (all - low_watermark) amount of XRIs.
20758  * The second step moves the rest of XRIs.
20759  **/
20760 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
20761 {
20762 	struct lpfc_pbl_pool *pbl_pool;
20763 	struct lpfc_pvt_pool *pvt_pool;
20764 	struct lpfc_sli4_hdw_queue *qp;
20765 	struct lpfc_io_buf *lpfc_ncmd;
20766 	struct lpfc_io_buf *lpfc_ncmd_next;
20767 	unsigned long iflag;
20768 	struct list_head tmp_list;
20769 	u32 tmp_count;
20770 
20771 	qp = &phba->sli4_hba.hdwq[hwqid];
20772 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
20773 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
20774 	tmp_count = 0;
20775 
20776 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
20777 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
20778 
20779 	if (pvt_pool->count > pvt_pool->low_watermark) {
20780 		/* Step 1: move (all - low_watermark) from pvt_pool
20781 		 * to pbl_pool
20782 		 */
20783 
20784 		/* Move low watermark of bufs from pvt_pool to tmp_list */
20785 		INIT_LIST_HEAD(&tmp_list);
20786 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20787 					 &pvt_pool->list, list) {
20788 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
20789 			tmp_count++;
20790 			if (tmp_count >= pvt_pool->low_watermark)
20791 				break;
20792 		}
20793 
20794 		/* Move all bufs from pvt_pool to pbl_pool */
20795 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
20796 
20797 		/* Move all bufs from tmp_list to pvt_pool */
20798 		list_splice(&tmp_list, &pvt_pool->list);
20799 
20800 		pbl_pool->count += (pvt_pool->count - tmp_count);
20801 		pvt_pool->count = tmp_count;
20802 	} else {
20803 		/* Step 2: move the rest from pvt_pool to pbl_pool */
20804 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
20805 		pbl_pool->count += pvt_pool->count;
20806 		pvt_pool->count = 0;
20807 	}
20808 
20809 	spin_unlock(&pvt_pool->lock);
20810 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20811 }
20812 
20813 /**
20814  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
20815  * @phba: pointer to lpfc hba data structure
20816  * @qp: pointer to HDW queue
20817  * @pbl_pool: specified public free XRI pool
20818  * @pvt_pool: specified private free XRI pool
20819  * @count: number of XRIs to move
20820  *
20821  * This routine tries to move some free common bufs from the specified pbl_pool
20822  * to the specified pvt_pool. It might move less than count XRIs if there's not
20823  * enough in public pool.
20824  *
20825  * Return:
20826  *   true - if XRIs are successfully moved from the specified pbl_pool to the
20827  *          specified pvt_pool
20828  *   false - if the specified pbl_pool is empty or locked by someone else
20829  **/
20830 static bool
20831 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
20832 			  struct lpfc_pbl_pool *pbl_pool,
20833 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
20834 {
20835 	struct lpfc_io_buf *lpfc_ncmd;
20836 	struct lpfc_io_buf *lpfc_ncmd_next;
20837 	unsigned long iflag;
20838 	int ret;
20839 
20840 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
20841 	if (ret) {
20842 		if (pbl_pool->count) {
20843 			/* Move a batch of XRIs from public to private pool */
20844 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
20845 			list_for_each_entry_safe(lpfc_ncmd,
20846 						 lpfc_ncmd_next,
20847 						 &pbl_pool->list,
20848 						 list) {
20849 				list_move_tail(&lpfc_ncmd->list,
20850 					       &pvt_pool->list);
20851 				pvt_pool->count++;
20852 				pbl_pool->count--;
20853 				count--;
20854 				if (count == 0)
20855 					break;
20856 			}
20857 
20858 			spin_unlock(&pvt_pool->lock);
20859 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20860 			return true;
20861 		}
20862 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20863 	}
20864 
20865 	return false;
20866 }
20867 
20868 /**
20869  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
20870  * @phba: pointer to lpfc hba data structure.
20871  * @hwqid: belong to which HWQ.
20872  * @count: number of XRIs to move
20873  *
20874  * This routine tries to find some free common bufs in one of public pools with
20875  * Round Robin method. The search always starts from local hwqid, then the next
20876  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
20877  * a batch of free common bufs are moved to private pool on hwqid.
20878  * It might move less than count XRIs if there's not enough in public pool.
20879  **/
20880 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
20881 {
20882 	struct lpfc_multixri_pool *multixri_pool;
20883 	struct lpfc_multixri_pool *next_multixri_pool;
20884 	struct lpfc_pvt_pool *pvt_pool;
20885 	struct lpfc_pbl_pool *pbl_pool;
20886 	struct lpfc_sli4_hdw_queue *qp;
20887 	u32 next_hwqid;
20888 	u32 hwq_count;
20889 	int ret;
20890 
20891 	qp = &phba->sli4_hba.hdwq[hwqid];
20892 	multixri_pool = qp->p_multixri_pool;
20893 	pvt_pool = &multixri_pool->pvt_pool;
20894 	pbl_pool = &multixri_pool->pbl_pool;
20895 
20896 	/* Check if local pbl_pool is available */
20897 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
20898 	if (ret) {
20899 #ifdef LPFC_MXP_STAT
20900 		multixri_pool->local_pbl_hit_count++;
20901 #endif
20902 		return;
20903 	}
20904 
20905 	hwq_count = phba->cfg_hdw_queue;
20906 
20907 	/* Get the next hwqid which was found last time */
20908 	next_hwqid = multixri_pool->rrb_next_hwqid;
20909 
20910 	do {
20911 		/* Go to next hwq */
20912 		next_hwqid = (next_hwqid + 1) % hwq_count;
20913 
20914 		next_multixri_pool =
20915 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
20916 		pbl_pool = &next_multixri_pool->pbl_pool;
20917 
20918 		/* Check if the public free xri pool is available */
20919 		ret = _lpfc_move_xri_pbl_to_pvt(
20920 			phba, qp, pbl_pool, pvt_pool, count);
20921 
20922 		/* Exit while-loop if success or all hwqid are checked */
20923 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
20924 
20925 	/* Starting point for the next time */
20926 	multixri_pool->rrb_next_hwqid = next_hwqid;
20927 
20928 	if (!ret) {
20929 		/* stats: all public pools are empty*/
20930 		multixri_pool->pbl_empty_count++;
20931 	}
20932 
20933 #ifdef LPFC_MXP_STAT
20934 	if (ret) {
20935 		if (next_hwqid == hwqid)
20936 			multixri_pool->local_pbl_hit_count++;
20937 		else
20938 			multixri_pool->other_pbl_hit_count++;
20939 	}
20940 #endif
20941 }
20942 
20943 /**
20944  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
20945  * @phba: pointer to lpfc hba data structure.
20946  * @hwqid: belong to which HWQ.
20947  *
20948  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
20949  * low watermark.
20950  **/
20951 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
20952 {
20953 	struct lpfc_multixri_pool *multixri_pool;
20954 	struct lpfc_pvt_pool *pvt_pool;
20955 
20956 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
20957 	pvt_pool = &multixri_pool->pvt_pool;
20958 
20959 	if (pvt_pool->count < pvt_pool->low_watermark)
20960 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
20961 }
20962 
20963 /**
20964  * lpfc_release_io_buf - Return one IO buf back to free pool
20965  * @phba: pointer to lpfc hba data structure.
20966  * @lpfc_ncmd: IO buf to be returned.
20967  * @qp: belong to which HWQ.
20968  *
20969  * This routine returns one IO buf back to free pool. If this is an urgent IO,
20970  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
20971  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
20972  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
20973  * lpfc_io_buf_list_put.
20974  **/
20975 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
20976 			 struct lpfc_sli4_hdw_queue *qp)
20977 {
20978 	unsigned long iflag;
20979 	struct lpfc_pbl_pool *pbl_pool;
20980 	struct lpfc_pvt_pool *pvt_pool;
20981 	struct lpfc_epd_pool *epd_pool;
20982 	u32 txcmplq_cnt;
20983 	u32 xri_owned;
20984 	u32 xri_limit;
20985 	u32 abts_io_bufs;
20986 
20987 	/* MUST zero fields if buffer is reused by another protocol */
20988 	lpfc_ncmd->nvmeCmd = NULL;
20989 	lpfc_ncmd->cur_iocbq.wqe_cmpl = NULL;
20990 	lpfc_ncmd->cur_iocbq.iocb_cmpl = NULL;
20991 
20992 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
20993 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
20994 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
20995 
20996 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
20997 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
20998 
20999 	if (phba->cfg_xri_rebalancing) {
21000 		if (lpfc_ncmd->expedite) {
21001 			/* Return to expedite pool */
21002 			epd_pool = &phba->epd_pool;
21003 			spin_lock_irqsave(&epd_pool->lock, iflag);
21004 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21005 			epd_pool->count++;
21006 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
21007 			return;
21008 		}
21009 
21010 		/* Avoid invalid access if an IO sneaks in and is being rejected
21011 		 * just _after_ xri pools are destroyed in lpfc_offline.
21012 		 * Nothing much can be done at this point.
21013 		 */
21014 		if (!qp->p_multixri_pool)
21015 			return;
21016 
21017 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21018 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21019 
21020 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21021 		abts_io_bufs = qp->abts_scsi_io_bufs;
21022 		abts_io_bufs += qp->abts_nvme_io_bufs;
21023 
21024 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21025 		xri_limit = qp->p_multixri_pool->xri_limit;
21026 
21027 #ifdef LPFC_MXP_STAT
21028 		if (xri_owned <= xri_limit)
21029 			qp->p_multixri_pool->below_limit_count++;
21030 		else
21031 			qp->p_multixri_pool->above_limit_count++;
21032 #endif
21033 
21034 		/* XRI goes to either public or private free xri pool
21035 		 *     based on watermark and xri_limit
21036 		 */
21037 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
21038 		    (xri_owned < xri_limit &&
21039 		     pvt_pool->count < pvt_pool->high_watermark)) {
21040 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
21041 						  qp, free_pvt_pool);
21042 			list_add_tail(&lpfc_ncmd->list,
21043 				      &pvt_pool->list);
21044 			pvt_pool->count++;
21045 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21046 		} else {
21047 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
21048 						  qp, free_pub_pool);
21049 			list_add_tail(&lpfc_ncmd->list,
21050 				      &pbl_pool->list);
21051 			pbl_pool->count++;
21052 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21053 		}
21054 	} else {
21055 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
21056 					  qp, free_xri);
21057 		list_add_tail(&lpfc_ncmd->list,
21058 			      &qp->lpfc_io_buf_list_put);
21059 		qp->put_io_bufs++;
21060 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
21061 				       iflag);
21062 	}
21063 }
21064 
21065 /**
21066  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
21067  * @phba: pointer to lpfc hba data structure.
21068  * @qp: pointer to HDW queue
21069  * @pvt_pool: pointer to private pool data structure.
21070  * @ndlp: pointer to lpfc nodelist data structure.
21071  *
21072  * This routine tries to get one free IO buf from private pool.
21073  *
21074  * Return:
21075  *   pointer to one free IO buf - if private pool is not empty
21076  *   NULL - if private pool is empty
21077  **/
21078 static struct lpfc_io_buf *
21079 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
21080 				  struct lpfc_sli4_hdw_queue *qp,
21081 				  struct lpfc_pvt_pool *pvt_pool,
21082 				  struct lpfc_nodelist *ndlp)
21083 {
21084 	struct lpfc_io_buf *lpfc_ncmd;
21085 	struct lpfc_io_buf *lpfc_ncmd_next;
21086 	unsigned long iflag;
21087 
21088 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
21089 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21090 				 &pvt_pool->list, list) {
21091 		if (lpfc_test_rrq_active(
21092 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
21093 			continue;
21094 		list_del(&lpfc_ncmd->list);
21095 		pvt_pool->count--;
21096 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21097 		return lpfc_ncmd;
21098 	}
21099 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21100 
21101 	return NULL;
21102 }
21103 
21104 /**
21105  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
21106  * @phba: pointer to lpfc hba data structure.
21107  *
21108  * This routine tries to get one free IO buf from expedite pool.
21109  *
21110  * Return:
21111  *   pointer to one free IO buf - if expedite pool is not empty
21112  *   NULL - if expedite pool is empty
21113  **/
21114 static struct lpfc_io_buf *
21115 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
21116 {
21117 	struct lpfc_io_buf *lpfc_ncmd;
21118 	struct lpfc_io_buf *lpfc_ncmd_next;
21119 	unsigned long iflag;
21120 	struct lpfc_epd_pool *epd_pool;
21121 
21122 	epd_pool = &phba->epd_pool;
21123 	lpfc_ncmd = NULL;
21124 
21125 	spin_lock_irqsave(&epd_pool->lock, iflag);
21126 	if (epd_pool->count > 0) {
21127 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21128 					 &epd_pool->list, list) {
21129 			list_del(&lpfc_ncmd->list);
21130 			epd_pool->count--;
21131 			break;
21132 		}
21133 	}
21134 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
21135 
21136 	return lpfc_ncmd;
21137 }
21138 
21139 /**
21140  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
21141  * @phba: pointer to lpfc hba data structure.
21142  * @ndlp: pointer to lpfc nodelist data structure.
21143  * @hwqid: belong to which HWQ
21144  * @expedite: 1 means this request is urgent.
21145  *
21146  * This routine will do the following actions and then return a pointer to
21147  * one free IO buf.
21148  *
21149  * 1. If private free xri count is empty, move some XRIs from public to
21150  *    private pool.
21151  * 2. Get one XRI from private free xri pool.
21152  * 3. If we fail to get one from pvt_pool and this is an expedite request,
21153  *    get one free xri from expedite pool.
21154  *
21155  * Note: ndlp is only used on SCSI side for RRQ testing.
21156  *       The caller should pass NULL for ndlp on NVME side.
21157  *
21158  * Return:
21159  *   pointer to one free IO buf - if private pool is not empty
21160  *   NULL - if private pool is empty
21161  **/
21162 static struct lpfc_io_buf *
21163 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
21164 				    struct lpfc_nodelist *ndlp,
21165 				    int hwqid, int expedite)
21166 {
21167 	struct lpfc_sli4_hdw_queue *qp;
21168 	struct lpfc_multixri_pool *multixri_pool;
21169 	struct lpfc_pvt_pool *pvt_pool;
21170 	struct lpfc_io_buf *lpfc_ncmd;
21171 
21172 	qp = &phba->sli4_hba.hdwq[hwqid];
21173 	lpfc_ncmd = NULL;
21174 	multixri_pool = qp->p_multixri_pool;
21175 	pvt_pool = &multixri_pool->pvt_pool;
21176 	multixri_pool->io_req_count++;
21177 
21178 	/* If pvt_pool is empty, move some XRIs from public to private pool */
21179 	if (pvt_pool->count == 0)
21180 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21181 
21182 	/* Get one XRI from private free xri pool */
21183 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
21184 
21185 	if (lpfc_ncmd) {
21186 		lpfc_ncmd->hdwq = qp;
21187 		lpfc_ncmd->hdwq_no = hwqid;
21188 	} else if (expedite) {
21189 		/* If we fail to get one from pvt_pool and this is an expedite
21190 		 * request, get one free xri from expedite pool.
21191 		 */
21192 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
21193 	}
21194 
21195 	return lpfc_ncmd;
21196 }
21197 
21198 static inline struct lpfc_io_buf *
21199 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
21200 {
21201 	struct lpfc_sli4_hdw_queue *qp;
21202 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
21203 
21204 	qp = &phba->sli4_hba.hdwq[idx];
21205 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
21206 				 &qp->lpfc_io_buf_list_get, list) {
21207 		if (lpfc_test_rrq_active(phba, ndlp,
21208 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
21209 			continue;
21210 
21211 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
21212 			continue;
21213 
21214 		list_del_init(&lpfc_cmd->list);
21215 		qp->get_io_bufs--;
21216 		lpfc_cmd->hdwq = qp;
21217 		lpfc_cmd->hdwq_no = idx;
21218 		return lpfc_cmd;
21219 	}
21220 	return NULL;
21221 }
21222 
21223 /**
21224  * lpfc_get_io_buf - Get one IO buffer from free pool
21225  * @phba: The HBA for which this call is being executed.
21226  * @ndlp: pointer to lpfc nodelist data structure.
21227  * @hwqid: belong to which HWQ
21228  * @expedite: 1 means this request is urgent.
21229  *
21230  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
21231  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
21232  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
21233  *
21234  * Note: ndlp is only used on SCSI side for RRQ testing.
21235  *       The caller should pass NULL for ndlp on NVME side.
21236  *
21237  * Return codes:
21238  *   NULL - Error
21239  *   Pointer to lpfc_io_buf - Success
21240  **/
21241 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
21242 				    struct lpfc_nodelist *ndlp,
21243 				    u32 hwqid, int expedite)
21244 {
21245 	struct lpfc_sli4_hdw_queue *qp;
21246 	unsigned long iflag;
21247 	struct lpfc_io_buf *lpfc_cmd;
21248 
21249 	qp = &phba->sli4_hba.hdwq[hwqid];
21250 	lpfc_cmd = NULL;
21251 
21252 	if (phba->cfg_xri_rebalancing)
21253 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
21254 			phba, ndlp, hwqid, expedite);
21255 	else {
21256 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
21257 					  qp, alloc_xri_get);
21258 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
21259 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
21260 		if (!lpfc_cmd) {
21261 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
21262 					  qp, alloc_xri_put);
21263 			list_splice(&qp->lpfc_io_buf_list_put,
21264 				    &qp->lpfc_io_buf_list_get);
21265 			qp->get_io_bufs += qp->put_io_bufs;
21266 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
21267 			qp->put_io_bufs = 0;
21268 			spin_unlock(&qp->io_buf_list_put_lock);
21269 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
21270 			    expedite)
21271 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
21272 		}
21273 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
21274 	}
21275 
21276 	return lpfc_cmd;
21277 }
21278 
21279 /**
21280  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
21281  * @phba: The HBA for which this call is being executed.
21282  * @lpfc_buf: IO buf structure to append the SGL chunk
21283  *
21284  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
21285  * and will allocate an SGL chunk if the pool is empty.
21286  *
21287  * Return codes:
21288  *   NULL - Error
21289  *   Pointer to sli4_hybrid_sgl - Success
21290  **/
21291 struct sli4_hybrid_sgl *
21292 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
21293 {
21294 	struct sli4_hybrid_sgl *list_entry = NULL;
21295 	struct sli4_hybrid_sgl *tmp = NULL;
21296 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
21297 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21298 	struct list_head *buf_list = &hdwq->sgl_list;
21299 	unsigned long iflags;
21300 
21301 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21302 
21303 	if (likely(!list_empty(buf_list))) {
21304 		/* break off 1 chunk from the sgl_list */
21305 		list_for_each_entry_safe(list_entry, tmp,
21306 					 buf_list, list_node) {
21307 			list_move_tail(&list_entry->list_node,
21308 				       &lpfc_buf->dma_sgl_xtra_list);
21309 			break;
21310 		}
21311 	} else {
21312 		/* allocate more */
21313 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21314 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
21315 				   cpu_to_node(hdwq->io_wq->chann));
21316 		if (!tmp) {
21317 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21318 					"8353 error kmalloc memory for HDWQ "
21319 					"%d %s\n",
21320 					lpfc_buf->hdwq_no, __func__);
21321 			return NULL;
21322 		}
21323 
21324 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
21325 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
21326 		if (!tmp->dma_sgl) {
21327 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21328 					"8354 error pool_alloc memory for HDWQ "
21329 					"%d %s\n",
21330 					lpfc_buf->hdwq_no, __func__);
21331 			kfree(tmp);
21332 			return NULL;
21333 		}
21334 
21335 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21336 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
21337 	}
21338 
21339 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
21340 					struct sli4_hybrid_sgl,
21341 					list_node);
21342 
21343 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21344 
21345 	return allocated_sgl;
21346 }
21347 
21348 /**
21349  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
21350  * @phba: The HBA for which this call is being executed.
21351  * @lpfc_buf: IO buf structure with the SGL chunk
21352  *
21353  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
21354  *
21355  * Return codes:
21356  *   0 - Success
21357  *   -EINVAL - Error
21358  **/
21359 int
21360 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
21361 {
21362 	int rc = 0;
21363 	struct sli4_hybrid_sgl *list_entry = NULL;
21364 	struct sli4_hybrid_sgl *tmp = NULL;
21365 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21366 	struct list_head *buf_list = &hdwq->sgl_list;
21367 	unsigned long iflags;
21368 
21369 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21370 
21371 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
21372 		list_for_each_entry_safe(list_entry, tmp,
21373 					 &lpfc_buf->dma_sgl_xtra_list,
21374 					 list_node) {
21375 			list_move_tail(&list_entry->list_node,
21376 				       buf_list);
21377 		}
21378 	} else {
21379 		rc = -EINVAL;
21380 	}
21381 
21382 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21383 	return rc;
21384 }
21385 
21386 /**
21387  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
21388  * @phba: phba object
21389  * @hdwq: hdwq to cleanup sgl buff resources on
21390  *
21391  * This routine frees all SGL chunks of hdwq SGL chunk pool.
21392  *
21393  * Return codes:
21394  *   None
21395  **/
21396 void
21397 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
21398 		       struct lpfc_sli4_hdw_queue *hdwq)
21399 {
21400 	struct list_head *buf_list = &hdwq->sgl_list;
21401 	struct sli4_hybrid_sgl *list_entry = NULL;
21402 	struct sli4_hybrid_sgl *tmp = NULL;
21403 	unsigned long iflags;
21404 
21405 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21406 
21407 	/* Free sgl pool */
21408 	list_for_each_entry_safe(list_entry, tmp,
21409 				 buf_list, list_node) {
21410 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
21411 			      list_entry->dma_sgl,
21412 			      list_entry->dma_phys_sgl);
21413 		list_del(&list_entry->list_node);
21414 		kfree(list_entry);
21415 	}
21416 
21417 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21418 }
21419 
21420 /**
21421  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
21422  * @phba: The HBA for which this call is being executed.
21423  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
21424  *
21425  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
21426  * and will allocate an CMD/RSP buffer if the pool is empty.
21427  *
21428  * Return codes:
21429  *   NULL - Error
21430  *   Pointer to fcp_cmd_rsp_buf - Success
21431  **/
21432 struct fcp_cmd_rsp_buf *
21433 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
21434 			      struct lpfc_io_buf *lpfc_buf)
21435 {
21436 	struct fcp_cmd_rsp_buf *list_entry = NULL;
21437 	struct fcp_cmd_rsp_buf *tmp = NULL;
21438 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
21439 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21440 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
21441 	unsigned long iflags;
21442 
21443 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21444 
21445 	if (likely(!list_empty(buf_list))) {
21446 		/* break off 1 chunk from the list */
21447 		list_for_each_entry_safe(list_entry, tmp,
21448 					 buf_list,
21449 					 list_node) {
21450 			list_move_tail(&list_entry->list_node,
21451 				       &lpfc_buf->dma_cmd_rsp_list);
21452 			break;
21453 		}
21454 	} else {
21455 		/* allocate more */
21456 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21457 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
21458 				   cpu_to_node(hdwq->io_wq->chann));
21459 		if (!tmp) {
21460 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21461 					"8355 error kmalloc memory for HDWQ "
21462 					"%d %s\n",
21463 					lpfc_buf->hdwq_no, __func__);
21464 			return NULL;
21465 		}
21466 
21467 		tmp->fcp_cmnd = dma_pool_alloc(phba->lpfc_cmd_rsp_buf_pool,
21468 						GFP_ATOMIC,
21469 						&tmp->fcp_cmd_rsp_dma_handle);
21470 
21471 		if (!tmp->fcp_cmnd) {
21472 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21473 					"8356 error pool_alloc memory for HDWQ "
21474 					"%d %s\n",
21475 					lpfc_buf->hdwq_no, __func__);
21476 			kfree(tmp);
21477 			return NULL;
21478 		}
21479 
21480 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
21481 				sizeof(struct fcp_cmnd));
21482 
21483 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21484 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
21485 	}
21486 
21487 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
21488 					struct fcp_cmd_rsp_buf,
21489 					list_node);
21490 
21491 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21492 
21493 	return allocated_buf;
21494 }
21495 
21496 /**
21497  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
21498  * @phba: The HBA for which this call is being executed.
21499  * @lpfc_buf: IO buf structure with the CMD/RSP buf
21500  *
21501  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
21502  *
21503  * Return codes:
21504  *   0 - Success
21505  *   -EINVAL - Error
21506  **/
21507 int
21508 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
21509 			      struct lpfc_io_buf *lpfc_buf)
21510 {
21511 	int rc = 0;
21512 	struct fcp_cmd_rsp_buf *list_entry = NULL;
21513 	struct fcp_cmd_rsp_buf *tmp = NULL;
21514 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21515 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
21516 	unsigned long iflags;
21517 
21518 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21519 
21520 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
21521 		list_for_each_entry_safe(list_entry, tmp,
21522 					 &lpfc_buf->dma_cmd_rsp_list,
21523 					 list_node) {
21524 			list_move_tail(&list_entry->list_node,
21525 				       buf_list);
21526 		}
21527 	} else {
21528 		rc = -EINVAL;
21529 	}
21530 
21531 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21532 	return rc;
21533 }
21534 
21535 /**
21536  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
21537  * @phba: phba object
21538  * @hdwq: hdwq to cleanup cmd rsp buff resources on
21539  *
21540  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
21541  *
21542  * Return codes:
21543  *   None
21544  **/
21545 void
21546 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
21547 			       struct lpfc_sli4_hdw_queue *hdwq)
21548 {
21549 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
21550 	struct fcp_cmd_rsp_buf *list_entry = NULL;
21551 	struct fcp_cmd_rsp_buf *tmp = NULL;
21552 	unsigned long iflags;
21553 
21554 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21555 
21556 	/* Free cmd_rsp buf pool */
21557 	list_for_each_entry_safe(list_entry, tmp,
21558 				 buf_list,
21559 				 list_node) {
21560 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
21561 			      list_entry->fcp_cmnd,
21562 			      list_entry->fcp_cmd_rsp_dma_handle);
21563 		list_del(&list_entry->list_node);
21564 		kfree(list_entry);
21565 	}
21566 
21567 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21568 }
21569