xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision 76a4f7cc)
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 		    (!(unlikely(pci_channel_offline(phba->pcidev)))) &&
1408 		    sglq->state != SGL_XRI_ABORTED) {
1409 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1410 					  iflag);
1411 
1412 			/* Check if we can get a reference on ndlp */
1413 			if (sglq->ndlp && !lpfc_nlp_get(sglq->ndlp))
1414 				sglq->ndlp = NULL;
1415 
1416 			list_add(&sglq->list,
1417 				 &phba->sli4_hba.lpfc_abts_els_sgl_list);
1418 			spin_unlock_irqrestore(
1419 				&phba->sli4_hba.sgl_list_lock, iflag);
1420 		} else {
1421 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1422 					  iflag);
1423 			sglq->state = SGL_FREED;
1424 			sglq->ndlp = NULL;
1425 			list_add_tail(&sglq->list,
1426 				      &phba->sli4_hba.lpfc_els_sgl_list);
1427 			spin_unlock_irqrestore(
1428 				&phba->sli4_hba.sgl_list_lock, iflag);
1429 			pring = lpfc_phba_elsring(phba);
1430 			/* Check if TXQ queue needs to be serviced */
1431 			if (pring && (!list_empty(&pring->txq)))
1432 				lpfc_worker_wake_up(phba);
1433 		}
1434 	}
1435 
1436 out:
1437 	/*
1438 	 * Clean all volatile data fields, preserve iotag and node struct.
1439 	 */
1440 	memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1441 	iocbq->sli4_lxritag = NO_XRI;
1442 	iocbq->sli4_xritag = NO_XRI;
1443 	iocbq->iocb_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET | LPFC_IO_CMF |
1444 			      LPFC_IO_NVME_LS);
1445 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1446 }
1447 
1448 
1449 /**
1450  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1451  * @phba: Pointer to HBA context object.
1452  * @iocbq: Pointer to driver iocb object.
1453  *
1454  * This function is called to release the driver iocb object to the
1455  * iocb pool. The iotag in the iocb object does not change for each
1456  * use of the iocb object. This function clears all other fields of
1457  * the iocb object when it is freed. The hbalock is asserted held in
1458  * the code path calling this routine.
1459  **/
1460 static void
1461 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1462 {
1463 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1464 
1465 	/*
1466 	 * Clean all volatile data fields, preserve iotag and node struct.
1467 	 */
1468 	memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1469 	iocbq->sli4_xritag = NO_XRI;
1470 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1471 }
1472 
1473 /**
1474  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1475  * @phba: Pointer to HBA context object.
1476  * @iocbq: Pointer to driver iocb object.
1477  *
1478  * This function is called with hbalock held to release driver
1479  * iocb object to the iocb pool. The iotag in the iocb object
1480  * does not change for each use of the iocb object. This function
1481  * clears all other fields of the iocb object when it is freed.
1482  **/
1483 static void
1484 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1485 {
1486 	lockdep_assert_held(&phba->hbalock);
1487 
1488 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1489 	phba->iocb_cnt--;
1490 }
1491 
1492 /**
1493  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1494  * @phba: Pointer to HBA context object.
1495  * @iocbq: Pointer to driver iocb object.
1496  *
1497  * This function is called with no lock held to release the iocb to
1498  * iocb pool.
1499  **/
1500 void
1501 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1502 {
1503 	unsigned long iflags;
1504 
1505 	/*
1506 	 * Clean all volatile data fields, preserve iotag and node struct.
1507 	 */
1508 	spin_lock_irqsave(&phba->hbalock, iflags);
1509 	__lpfc_sli_release_iocbq(phba, iocbq);
1510 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1511 }
1512 
1513 /**
1514  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1515  * @phba: Pointer to HBA context object.
1516  * @iocblist: List of IOCBs.
1517  * @ulpstatus: ULP status in IOCB command field.
1518  * @ulpWord4: ULP word-4 in IOCB command field.
1519  *
1520  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1521  * on the list by invoking the complete callback function associated with the
1522  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1523  * fields.
1524  **/
1525 void
1526 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1527 		      uint32_t ulpstatus, uint32_t ulpWord4)
1528 {
1529 	struct lpfc_iocbq *piocb;
1530 
1531 	while (!list_empty(iocblist)) {
1532 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1533 		if (piocb->wqe_cmpl) {
1534 			if (piocb->iocb_flag & LPFC_IO_NVME)
1535 				lpfc_nvme_cancel_iocb(phba, piocb,
1536 						      ulpstatus, ulpWord4);
1537 			else
1538 				lpfc_sli_release_iocbq(phba, piocb);
1539 
1540 		} else if (piocb->iocb_cmpl) {
1541 			piocb->iocb.ulpStatus = ulpstatus;
1542 			piocb->iocb.un.ulpWord[4] = ulpWord4;
1543 			(piocb->iocb_cmpl) (phba, piocb, piocb);
1544 		} else {
1545 			lpfc_sli_release_iocbq(phba, piocb);
1546 		}
1547 	}
1548 	return;
1549 }
1550 
1551 /**
1552  * lpfc_sli_iocb_cmd_type - Get the iocb type
1553  * @iocb_cmnd: iocb command code.
1554  *
1555  * This function is called by ring event handler function to get the iocb type.
1556  * This function translates the iocb command to an iocb command type used to
1557  * decide the final disposition of each completed IOCB.
1558  * The function returns
1559  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1560  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1561  * LPFC_ABORT_IOCB   if it is an abort iocb
1562  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1563  *
1564  * The caller is not required to hold any lock.
1565  **/
1566 static lpfc_iocb_type
1567 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1568 {
1569 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1570 
1571 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1572 		return 0;
1573 
1574 	switch (iocb_cmnd) {
1575 	case CMD_XMIT_SEQUENCE_CR:
1576 	case CMD_XMIT_SEQUENCE_CX:
1577 	case CMD_XMIT_BCAST_CN:
1578 	case CMD_XMIT_BCAST_CX:
1579 	case CMD_ELS_REQUEST_CR:
1580 	case CMD_ELS_REQUEST_CX:
1581 	case CMD_CREATE_XRI_CR:
1582 	case CMD_CREATE_XRI_CX:
1583 	case CMD_GET_RPI_CN:
1584 	case CMD_XMIT_ELS_RSP_CX:
1585 	case CMD_GET_RPI_CR:
1586 	case CMD_FCP_IWRITE_CR:
1587 	case CMD_FCP_IWRITE_CX:
1588 	case CMD_FCP_IREAD_CR:
1589 	case CMD_FCP_IREAD_CX:
1590 	case CMD_FCP_ICMND_CR:
1591 	case CMD_FCP_ICMND_CX:
1592 	case CMD_FCP_TSEND_CX:
1593 	case CMD_FCP_TRSP_CX:
1594 	case CMD_FCP_TRECEIVE_CX:
1595 	case CMD_FCP_AUTO_TRSP_CX:
1596 	case CMD_ADAPTER_MSG:
1597 	case CMD_ADAPTER_DUMP:
1598 	case CMD_XMIT_SEQUENCE64_CR:
1599 	case CMD_XMIT_SEQUENCE64_CX:
1600 	case CMD_XMIT_BCAST64_CN:
1601 	case CMD_XMIT_BCAST64_CX:
1602 	case CMD_ELS_REQUEST64_CR:
1603 	case CMD_ELS_REQUEST64_CX:
1604 	case CMD_FCP_IWRITE64_CR:
1605 	case CMD_FCP_IWRITE64_CX:
1606 	case CMD_FCP_IREAD64_CR:
1607 	case CMD_FCP_IREAD64_CX:
1608 	case CMD_FCP_ICMND64_CR:
1609 	case CMD_FCP_ICMND64_CX:
1610 	case CMD_FCP_TSEND64_CX:
1611 	case CMD_FCP_TRSP64_CX:
1612 	case CMD_FCP_TRECEIVE64_CX:
1613 	case CMD_GEN_REQUEST64_CR:
1614 	case CMD_GEN_REQUEST64_CX:
1615 	case CMD_XMIT_ELS_RSP64_CX:
1616 	case DSSCMD_IWRITE64_CR:
1617 	case DSSCMD_IWRITE64_CX:
1618 	case DSSCMD_IREAD64_CR:
1619 	case DSSCMD_IREAD64_CX:
1620 	case CMD_SEND_FRAME:
1621 		type = LPFC_SOL_IOCB;
1622 		break;
1623 	case CMD_ABORT_XRI_CN:
1624 	case CMD_ABORT_XRI_CX:
1625 	case CMD_CLOSE_XRI_CN:
1626 	case CMD_CLOSE_XRI_CX:
1627 	case CMD_XRI_ABORTED_CX:
1628 	case CMD_ABORT_MXRI64_CN:
1629 	case CMD_XMIT_BLS_RSP64_CX:
1630 		type = LPFC_ABORT_IOCB;
1631 		break;
1632 	case CMD_RCV_SEQUENCE_CX:
1633 	case CMD_RCV_ELS_REQ_CX:
1634 	case CMD_RCV_SEQUENCE64_CX:
1635 	case CMD_RCV_ELS_REQ64_CX:
1636 	case CMD_ASYNC_STATUS:
1637 	case CMD_IOCB_RCV_SEQ64_CX:
1638 	case CMD_IOCB_RCV_ELS64_CX:
1639 	case CMD_IOCB_RCV_CONT64_CX:
1640 	case CMD_IOCB_RET_XRI64_CX:
1641 		type = LPFC_UNSOL_IOCB;
1642 		break;
1643 	case CMD_IOCB_XMIT_MSEQ64_CR:
1644 	case CMD_IOCB_XMIT_MSEQ64_CX:
1645 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1646 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1647 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1648 	case CMD_IOCB_ABORT_EXTENDED_CN:
1649 	case CMD_IOCB_RET_HBQE64_CN:
1650 	case CMD_IOCB_FCP_IBIDIR64_CR:
1651 	case CMD_IOCB_FCP_IBIDIR64_CX:
1652 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1653 	case CMD_IOCB_LOGENTRY_CN:
1654 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1655 		printk("%s - Unhandled SLI-3 Command x%x\n",
1656 				__func__, iocb_cmnd);
1657 		type = LPFC_UNKNOWN_IOCB;
1658 		break;
1659 	default:
1660 		type = LPFC_UNKNOWN_IOCB;
1661 		break;
1662 	}
1663 
1664 	return type;
1665 }
1666 
1667 /**
1668  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1669  * @phba: Pointer to HBA context object.
1670  *
1671  * This function is called from SLI initialization code
1672  * to configure every ring of the HBA's SLI interface. The
1673  * caller is not required to hold any lock. This function issues
1674  * a config_ring mailbox command for each ring.
1675  * This function returns zero if successful else returns a negative
1676  * error code.
1677  **/
1678 static int
1679 lpfc_sli_ring_map(struct lpfc_hba *phba)
1680 {
1681 	struct lpfc_sli *psli = &phba->sli;
1682 	LPFC_MBOXQ_t *pmb;
1683 	MAILBOX_t *pmbox;
1684 	int i, rc, ret = 0;
1685 
1686 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1687 	if (!pmb)
1688 		return -ENOMEM;
1689 	pmbox = &pmb->u.mb;
1690 	phba->link_state = LPFC_INIT_MBX_CMDS;
1691 	for (i = 0; i < psli->num_rings; i++) {
1692 		lpfc_config_ring(phba, i, pmb);
1693 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1694 		if (rc != MBX_SUCCESS) {
1695 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1696 					"0446 Adapter failed to init (%d), "
1697 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1698 					"ring %d\n",
1699 					rc, pmbox->mbxCommand,
1700 					pmbox->mbxStatus, i);
1701 			phba->link_state = LPFC_HBA_ERROR;
1702 			ret = -ENXIO;
1703 			break;
1704 		}
1705 	}
1706 	mempool_free(pmb, phba->mbox_mem_pool);
1707 	return ret;
1708 }
1709 
1710 /**
1711  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1712  * @phba: Pointer to HBA context object.
1713  * @pring: Pointer to driver SLI ring object.
1714  * @piocb: Pointer to the driver iocb object.
1715  *
1716  * The driver calls this function with the hbalock held for SLI3 ports or
1717  * the ring lock held for SLI4 ports. The function adds the
1718  * new iocb to txcmplq of the given ring. This function always returns
1719  * 0. If this function is called for ELS ring, this function checks if
1720  * there is a vport associated with the ELS command. This function also
1721  * starts els_tmofunc timer if this is an ELS command.
1722  **/
1723 static int
1724 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1725 			struct lpfc_iocbq *piocb)
1726 {
1727 	if (phba->sli_rev == LPFC_SLI_REV4)
1728 		lockdep_assert_held(&pring->ring_lock);
1729 	else
1730 		lockdep_assert_held(&phba->hbalock);
1731 
1732 	BUG_ON(!piocb);
1733 
1734 	list_add_tail(&piocb->list, &pring->txcmplq);
1735 	piocb->iocb_flag |= LPFC_IO_ON_TXCMPLQ;
1736 	pring->txcmplq_cnt++;
1737 
1738 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1739 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
1740 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
1741 		BUG_ON(!piocb->vport);
1742 		if (!(piocb->vport->load_flag & FC_UNLOADING))
1743 			mod_timer(&piocb->vport->els_tmofunc,
1744 				  jiffies +
1745 				  msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1746 	}
1747 
1748 	return 0;
1749 }
1750 
1751 /**
1752  * lpfc_sli_ringtx_get - Get first element of the txq
1753  * @phba: Pointer to HBA context object.
1754  * @pring: Pointer to driver SLI ring object.
1755  *
1756  * This function is called with hbalock held to get next
1757  * iocb in txq of the given ring. If there is any iocb in
1758  * the txq, the function returns first iocb in the list after
1759  * removing the iocb from the list, else it returns NULL.
1760  **/
1761 struct lpfc_iocbq *
1762 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1763 {
1764 	struct lpfc_iocbq *cmd_iocb;
1765 
1766 	lockdep_assert_held(&phba->hbalock);
1767 
1768 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1769 	return cmd_iocb;
1770 }
1771 
1772 /**
1773  * lpfc_cmf_sync_cmpl - Process a CMF_SYNC_WQE cmpl
1774  * @phba: Pointer to HBA context object.
1775  * @cmdiocb: Pointer to driver command iocb object.
1776  * @cmf_cmpl: Pointer to completed WCQE.
1777  *
1778  * This routine will inform the driver of any BW adjustments we need
1779  * to make. These changes will be picked up during the next CMF
1780  * timer interrupt. In addition, any BW changes will be logged
1781  * with LOG_CGN_MGMT.
1782  **/
1783 static void
1784 lpfc_cmf_sync_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
1785 		   struct lpfc_wcqe_complete *cmf_cmpl)
1786 {
1787 	union lpfc_wqe128 *wqe;
1788 	uint32_t status, info;
1789 	uint64_t bw, bwdif, slop;
1790 	uint64_t pcent, bwpcent;
1791 	int asig, afpin, sigcnt, fpincnt;
1792 	int wsigmax, wfpinmax, cg, tdp;
1793 	char *s;
1794 
1795 	/* First check for error */
1796 	status = bf_get(lpfc_wcqe_c_status, cmf_cmpl);
1797 	if (status) {
1798 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1799 				"6211 CMF_SYNC_WQE Error "
1800 				"req_tag x%x status x%x hwstatus x%x "
1801 				"tdatap x%x parm x%x\n",
1802 				bf_get(lpfc_wcqe_c_request_tag, cmf_cmpl),
1803 				bf_get(lpfc_wcqe_c_status, cmf_cmpl),
1804 				bf_get(lpfc_wcqe_c_hw_status, cmf_cmpl),
1805 				cmf_cmpl->total_data_placed,
1806 				cmf_cmpl->parameter);
1807 		goto out;
1808 	}
1809 
1810 	/* Gather congestion information on a successful cmpl */
1811 	info = cmf_cmpl->parameter;
1812 	phba->cmf_active_info = info;
1813 
1814 	/* See if firmware info count is valid or has changed */
1815 	if (info > LPFC_MAX_CMF_INFO || phba->cmf_info_per_interval == info)
1816 		info = 0;
1817 	else
1818 		phba->cmf_info_per_interval = info;
1819 
1820 	tdp = bf_get(lpfc_wcqe_c_cmf_bw, cmf_cmpl);
1821 	cg = bf_get(lpfc_wcqe_c_cmf_cg, cmf_cmpl);
1822 
1823 	/* Get BW requirement from firmware */
1824 	bw = (uint64_t)tdp * LPFC_CMF_BLK_SIZE;
1825 	if (!bw) {
1826 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1827 				"6212 CMF_SYNC_WQE x%x: NULL bw\n",
1828 				bf_get(lpfc_wcqe_c_request_tag, cmf_cmpl));
1829 		goto out;
1830 	}
1831 
1832 	/* Gather information needed for logging if a BW change is required */
1833 	wqe = &cmdiocb->wqe;
1834 	asig = bf_get(cmf_sync_asig, &wqe->cmf_sync);
1835 	afpin = bf_get(cmf_sync_afpin, &wqe->cmf_sync);
1836 	fpincnt = bf_get(cmf_sync_wfpincnt, &wqe->cmf_sync);
1837 	sigcnt = bf_get(cmf_sync_wsigcnt, &wqe->cmf_sync);
1838 	if (phba->cmf_max_bytes_per_interval != bw ||
1839 	    (asig || afpin || sigcnt || fpincnt)) {
1840 		/* Are we increasing or decreasing BW */
1841 		if (phba->cmf_max_bytes_per_interval <  bw) {
1842 			bwdif = bw - phba->cmf_max_bytes_per_interval;
1843 			s = "Increase";
1844 		} else {
1845 			bwdif = phba->cmf_max_bytes_per_interval - bw;
1846 			s = "Decrease";
1847 		}
1848 
1849 		/* What is the change percentage */
1850 		slop = div_u64(phba->cmf_link_byte_count, 200); /*For rounding*/
1851 		pcent = div64_u64(bwdif * 100 + slop,
1852 				  phba->cmf_link_byte_count);
1853 		bwpcent = div64_u64(bw * 100 + slop,
1854 				    phba->cmf_link_byte_count);
1855 		if (asig) {
1856 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1857 					"6237 BW Threshold %lld%% (%lld): "
1858 					"%lld%% %s: Signal Alarm: cg:%d "
1859 					"Info:%u\n",
1860 					bwpcent, bw, pcent, s, cg,
1861 					phba->cmf_active_info);
1862 		} else if (afpin) {
1863 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1864 					"6238 BW Threshold %lld%% (%lld): "
1865 					"%lld%% %s: FPIN Alarm: cg:%d "
1866 					"Info:%u\n",
1867 					bwpcent, bw, pcent, s, cg,
1868 					phba->cmf_active_info);
1869 		} else if (sigcnt) {
1870 			wsigmax = bf_get(cmf_sync_wsigmax, &wqe->cmf_sync);
1871 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1872 					"6239 BW Threshold %lld%% (%lld): "
1873 					"%lld%% %s: Signal Warning: "
1874 					"Cnt %d Max %d: cg:%d Info:%u\n",
1875 					bwpcent, bw, pcent, s, sigcnt,
1876 					wsigmax, cg, phba->cmf_active_info);
1877 		} else if (fpincnt) {
1878 			wfpinmax = bf_get(cmf_sync_wfpinmax, &wqe->cmf_sync);
1879 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1880 					"6240 BW Threshold %lld%% (%lld): "
1881 					"%lld%% %s: FPIN Warning: "
1882 					"Cnt %d Max %d: cg:%d Info:%u\n",
1883 					bwpcent, bw, pcent, s, fpincnt,
1884 					wfpinmax, cg, phba->cmf_active_info);
1885 		} else {
1886 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1887 					"6241 BW Threshold %lld%% (%lld): "
1888 					"CMF %lld%% %s: cg:%d Info:%u\n",
1889 					bwpcent, bw, pcent, s, cg,
1890 					phba->cmf_active_info);
1891 		}
1892 	} else if (info) {
1893 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1894 				"6246 Info Threshold %u\n", info);
1895 	}
1896 
1897 	/* Save BW change to be picked up during next timer interrupt */
1898 	phba->cmf_last_sync_bw = bw;
1899 out:
1900 	lpfc_sli_release_iocbq(phba, cmdiocb);
1901 }
1902 
1903 /**
1904  * lpfc_issue_cmf_sync_wqe - Issue a CMF_SYNC_WQE
1905  * @phba: Pointer to HBA context object.
1906  * @ms:   ms to set in WQE interval, 0 means use init op
1907  * @total: Total rcv bytes for this interval
1908  *
1909  * This routine is called every CMF timer interrupt. Its purpose is
1910  * to issue a CMF_SYNC_WQE to the firmware to inform it of any events
1911  * that may indicate we have congestion (FPINs or Signals). Upon
1912  * completion, the firmware will indicate any BW restrictions the
1913  * driver may need to take.
1914  **/
1915 int
1916 lpfc_issue_cmf_sync_wqe(struct lpfc_hba *phba, u32 ms, u64 total)
1917 {
1918 	union lpfc_wqe128 *wqe;
1919 	struct lpfc_iocbq *sync_buf;
1920 	unsigned long iflags;
1921 	u32 ret_val;
1922 	u32 atot, wtot, max;
1923 
1924 	/* First address any alarm / warning activity */
1925 	atot = atomic_xchg(&phba->cgn_sync_alarm_cnt, 0);
1926 	wtot = atomic_xchg(&phba->cgn_sync_warn_cnt, 0);
1927 
1928 	/* ONLY Managed mode will send the CMF_SYNC_WQE to the HBA */
1929 	if (phba->cmf_active_mode != LPFC_CFG_MANAGED ||
1930 	    phba->link_state == LPFC_LINK_DOWN)
1931 		return 0;
1932 
1933 	spin_lock_irqsave(&phba->hbalock, iflags);
1934 	sync_buf = __lpfc_sli_get_iocbq(phba);
1935 	if (!sync_buf) {
1936 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
1937 				"6213 No available WQEs for CMF_SYNC_WQE\n");
1938 		ret_val = ENOMEM;
1939 		goto out_unlock;
1940 	}
1941 
1942 	wqe = &sync_buf->wqe;
1943 
1944 	/* WQEs are reused.  Clear stale data and set key fields to zero */
1945 	memset(wqe, 0, sizeof(*wqe));
1946 
1947 	/* If this is the very first CMF_SYNC_WQE, issue an init operation */
1948 	if (!ms) {
1949 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1950 				"6441 CMF Init %d - CMF_SYNC_WQE\n",
1951 				phba->fc_eventTag);
1952 		bf_set(cmf_sync_op, &wqe->cmf_sync, 1); /* 1=init */
1953 		bf_set(cmf_sync_interval, &wqe->cmf_sync, LPFC_CMF_INTERVAL);
1954 		goto initpath;
1955 	}
1956 
1957 	bf_set(cmf_sync_op, &wqe->cmf_sync, 0); /* 0=recalc */
1958 	bf_set(cmf_sync_interval, &wqe->cmf_sync, ms);
1959 
1960 	/* Check for alarms / warnings */
1961 	if (atot) {
1962 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1963 			/* We hit an Signal alarm condition */
1964 			bf_set(cmf_sync_asig, &wqe->cmf_sync, 1);
1965 		} else {
1966 			/* We hit a FPIN alarm condition */
1967 			bf_set(cmf_sync_afpin, &wqe->cmf_sync, 1);
1968 		}
1969 	} else if (wtot) {
1970 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
1971 		    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1972 			/* We hit an Signal warning condition */
1973 			max = LPFC_SEC_TO_MSEC / lpfc_fabric_cgn_frequency *
1974 				lpfc_acqe_cgn_frequency;
1975 			bf_set(cmf_sync_wsigmax, &wqe->cmf_sync, max);
1976 			bf_set(cmf_sync_wsigcnt, &wqe->cmf_sync, wtot);
1977 		} else {
1978 			/* We hit a FPIN warning condition */
1979 			bf_set(cmf_sync_wfpinmax, &wqe->cmf_sync, 1);
1980 			bf_set(cmf_sync_wfpincnt, &wqe->cmf_sync, 1);
1981 		}
1982 	}
1983 
1984 	/* Update total read blocks during previous timer interval */
1985 	wqe->cmf_sync.read_bytes = (u32)(total / LPFC_CMF_BLK_SIZE);
1986 
1987 initpath:
1988 	bf_set(cmf_sync_ver, &wqe->cmf_sync, LPFC_CMF_SYNC_VER);
1989 	wqe->cmf_sync.event_tag = phba->fc_eventTag;
1990 	bf_set(cmf_sync_cmnd, &wqe->cmf_sync, CMD_CMF_SYNC_WQE);
1991 
1992 	/* Setup reqtag to match the wqe completion. */
1993 	bf_set(cmf_sync_reqtag, &wqe->cmf_sync, sync_buf->iotag);
1994 
1995 	bf_set(cmf_sync_qosd, &wqe->cmf_sync, 1);
1996 
1997 	bf_set(cmf_sync_cmd_type, &wqe->cmf_sync, CMF_SYNC_COMMAND);
1998 	bf_set(cmf_sync_wqec, &wqe->cmf_sync, 1);
1999 	bf_set(cmf_sync_cqid, &wqe->cmf_sync, LPFC_WQE_CQ_ID_DEFAULT);
2000 
2001 	sync_buf->vport = phba->pport;
2002 	sync_buf->wqe_cmpl = lpfc_cmf_sync_cmpl;
2003 	sync_buf->iocb_cmpl = NULL;
2004 	sync_buf->context1 = NULL;
2005 	sync_buf->context2 = NULL;
2006 	sync_buf->context3 = NULL;
2007 	sync_buf->sli4_xritag = NO_XRI;
2008 
2009 	sync_buf->iocb_flag |= LPFC_IO_CMF;
2010 	ret_val = lpfc_sli4_issue_wqe(phba, &phba->sli4_hba.hdwq[0], sync_buf);
2011 	if (ret_val)
2012 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
2013 				"6214 Cannot issue CMF_SYNC_WQE: x%x\n",
2014 				ret_val);
2015 out_unlock:
2016 	spin_unlock_irqrestore(&phba->hbalock, iflags);
2017 	return ret_val;
2018 }
2019 
2020 /**
2021  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
2022  * @phba: Pointer to HBA context object.
2023  * @pring: Pointer to driver SLI ring object.
2024  *
2025  * This function is called with hbalock held and the caller must post the
2026  * iocb without releasing the lock. If the caller releases the lock,
2027  * iocb slot returned by the function is not guaranteed to be available.
2028  * The function returns pointer to the next available iocb slot if there
2029  * is available slot in the ring, else it returns NULL.
2030  * If the get index of the ring is ahead of the put index, the function
2031  * will post an error attention event to the worker thread to take the
2032  * HBA to offline state.
2033  **/
2034 static IOCB_t *
2035 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2036 {
2037 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2038 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
2039 
2040 	lockdep_assert_held(&phba->hbalock);
2041 
2042 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
2043 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
2044 		pring->sli.sli3.next_cmdidx = 0;
2045 
2046 	if (unlikely(pring->sli.sli3.local_getidx ==
2047 		pring->sli.sli3.next_cmdidx)) {
2048 
2049 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
2050 
2051 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
2052 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2053 					"0315 Ring %d issue: portCmdGet %d "
2054 					"is bigger than cmd ring %d\n",
2055 					pring->ringno,
2056 					pring->sli.sli3.local_getidx,
2057 					max_cmd_idx);
2058 
2059 			phba->link_state = LPFC_HBA_ERROR;
2060 			/*
2061 			 * All error attention handlers are posted to
2062 			 * worker thread
2063 			 */
2064 			phba->work_ha |= HA_ERATT;
2065 			phba->work_hs = HS_FFER3;
2066 
2067 			lpfc_worker_wake_up(phba);
2068 
2069 			return NULL;
2070 		}
2071 
2072 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
2073 			return NULL;
2074 	}
2075 
2076 	return lpfc_cmd_iocb(phba, pring);
2077 }
2078 
2079 /**
2080  * lpfc_sli_next_iotag - Get an iotag for the iocb
2081  * @phba: Pointer to HBA context object.
2082  * @iocbq: Pointer to driver iocb object.
2083  *
2084  * This function gets an iotag for the iocb. If there is no unused iotag and
2085  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
2086  * array and assigns a new iotag.
2087  * The function returns the allocated iotag if successful, else returns zero.
2088  * Zero is not a valid iotag.
2089  * The caller is not required to hold any lock.
2090  **/
2091 uint16_t
2092 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
2093 {
2094 	struct lpfc_iocbq **new_arr;
2095 	struct lpfc_iocbq **old_arr;
2096 	size_t new_len;
2097 	struct lpfc_sli *psli = &phba->sli;
2098 	uint16_t iotag;
2099 
2100 	spin_lock_irq(&phba->hbalock);
2101 	iotag = psli->last_iotag;
2102 	if(++iotag < psli->iocbq_lookup_len) {
2103 		psli->last_iotag = iotag;
2104 		psli->iocbq_lookup[iotag] = iocbq;
2105 		spin_unlock_irq(&phba->hbalock);
2106 		iocbq->iotag = iotag;
2107 		return iotag;
2108 	} else if (psli->iocbq_lookup_len < (0xffff
2109 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
2110 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
2111 		spin_unlock_irq(&phba->hbalock);
2112 		new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
2113 				  GFP_KERNEL);
2114 		if (new_arr) {
2115 			spin_lock_irq(&phba->hbalock);
2116 			old_arr = psli->iocbq_lookup;
2117 			if (new_len <= psli->iocbq_lookup_len) {
2118 				/* highly unprobable case */
2119 				kfree(new_arr);
2120 				iotag = psli->last_iotag;
2121 				if(++iotag < psli->iocbq_lookup_len) {
2122 					psli->last_iotag = iotag;
2123 					psli->iocbq_lookup[iotag] = iocbq;
2124 					spin_unlock_irq(&phba->hbalock);
2125 					iocbq->iotag = iotag;
2126 					return iotag;
2127 				}
2128 				spin_unlock_irq(&phba->hbalock);
2129 				return 0;
2130 			}
2131 			if (psli->iocbq_lookup)
2132 				memcpy(new_arr, old_arr,
2133 				       ((psli->last_iotag  + 1) *
2134 					sizeof (struct lpfc_iocbq *)));
2135 			psli->iocbq_lookup = new_arr;
2136 			psli->iocbq_lookup_len = new_len;
2137 			psli->last_iotag = iotag;
2138 			psli->iocbq_lookup[iotag] = iocbq;
2139 			spin_unlock_irq(&phba->hbalock);
2140 			iocbq->iotag = iotag;
2141 			kfree(old_arr);
2142 			return iotag;
2143 		}
2144 	} else
2145 		spin_unlock_irq(&phba->hbalock);
2146 
2147 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2148 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
2149 			psli->last_iotag);
2150 
2151 	return 0;
2152 }
2153 
2154 /**
2155  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
2156  * @phba: Pointer to HBA context object.
2157  * @pring: Pointer to driver SLI ring object.
2158  * @iocb: Pointer to iocb slot in the ring.
2159  * @nextiocb: Pointer to driver iocb object which need to be
2160  *            posted to firmware.
2161  *
2162  * This function is called to post a new iocb to the firmware. This
2163  * function copies the new iocb to ring iocb slot and updates the
2164  * ring pointers. It adds the new iocb to txcmplq if there is
2165  * a completion call back for this iocb else the function will free the
2166  * iocb object.  The hbalock is asserted held in the code path calling
2167  * this routine.
2168  **/
2169 static void
2170 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2171 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
2172 {
2173 	/*
2174 	 * Set up an iotag
2175 	 */
2176 	nextiocb->iocb.ulpIoTag = (nextiocb->iocb_cmpl) ? nextiocb->iotag : 0;
2177 
2178 
2179 	if (pring->ringno == LPFC_ELS_RING) {
2180 		lpfc_debugfs_slow_ring_trc(phba,
2181 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
2182 			*(((uint32_t *) &nextiocb->iocb) + 4),
2183 			*(((uint32_t *) &nextiocb->iocb) + 6),
2184 			*(((uint32_t *) &nextiocb->iocb) + 7));
2185 	}
2186 
2187 	/*
2188 	 * Issue iocb command to adapter
2189 	 */
2190 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
2191 	wmb();
2192 	pring->stats.iocb_cmd++;
2193 
2194 	/*
2195 	 * If there is no completion routine to call, we can release the
2196 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
2197 	 * that have no rsp ring completion, iocb_cmpl MUST be NULL.
2198 	 */
2199 	if (nextiocb->iocb_cmpl)
2200 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
2201 	else
2202 		__lpfc_sli_release_iocbq(phba, nextiocb);
2203 
2204 	/*
2205 	 * Let the HBA know what IOCB slot will be the next one the
2206 	 * driver will put a command into.
2207 	 */
2208 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
2209 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
2210 }
2211 
2212 /**
2213  * lpfc_sli_update_full_ring - Update the chip attention register
2214  * @phba: Pointer to HBA context object.
2215  * @pring: Pointer to driver SLI ring object.
2216  *
2217  * The caller is not required to hold any lock for calling this function.
2218  * This function updates the chip attention bits for the ring to inform firmware
2219  * that there are pending work to be done for this ring and requests an
2220  * interrupt when there is space available in the ring. This function is
2221  * called when the driver is unable to post more iocbs to the ring due
2222  * to unavailability of space in the ring.
2223  **/
2224 static void
2225 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2226 {
2227 	int ringno = pring->ringno;
2228 
2229 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
2230 
2231 	wmb();
2232 
2233 	/*
2234 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
2235 	 * The HBA will tell us when an IOCB entry is available.
2236 	 */
2237 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
2238 	readl(phba->CAregaddr); /* flush */
2239 
2240 	pring->stats.iocb_cmd_full++;
2241 }
2242 
2243 /**
2244  * lpfc_sli_update_ring - Update chip attention register
2245  * @phba: Pointer to HBA context object.
2246  * @pring: Pointer to driver SLI ring object.
2247  *
2248  * This function updates the chip attention register bit for the
2249  * given ring to inform HBA that there is more work to be done
2250  * in this ring. The caller is not required to hold any lock.
2251  **/
2252 static void
2253 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2254 {
2255 	int ringno = pring->ringno;
2256 
2257 	/*
2258 	 * Tell the HBA that there is work to do in this ring.
2259 	 */
2260 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
2261 		wmb();
2262 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
2263 		readl(phba->CAregaddr); /* flush */
2264 	}
2265 }
2266 
2267 /**
2268  * lpfc_sli_resume_iocb - Process iocbs in the txq
2269  * @phba: Pointer to HBA context object.
2270  * @pring: Pointer to driver SLI ring object.
2271  *
2272  * This function is called with hbalock held to post pending iocbs
2273  * in the txq to the firmware. This function is called when driver
2274  * detects space available in the ring.
2275  **/
2276 static void
2277 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2278 {
2279 	IOCB_t *iocb;
2280 	struct lpfc_iocbq *nextiocb;
2281 
2282 	lockdep_assert_held(&phba->hbalock);
2283 
2284 	/*
2285 	 * Check to see if:
2286 	 *  (a) there is anything on the txq to send
2287 	 *  (b) link is up
2288 	 *  (c) link attention events can be processed (fcp ring only)
2289 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
2290 	 */
2291 
2292 	if (lpfc_is_link_up(phba) &&
2293 	    (!list_empty(&pring->txq)) &&
2294 	    (pring->ringno != LPFC_FCP_RING ||
2295 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
2296 
2297 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
2298 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
2299 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
2300 
2301 		if (iocb)
2302 			lpfc_sli_update_ring(phba, pring);
2303 		else
2304 			lpfc_sli_update_full_ring(phba, pring);
2305 	}
2306 
2307 	return;
2308 }
2309 
2310 /**
2311  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
2312  * @phba: Pointer to HBA context object.
2313  * @hbqno: HBQ number.
2314  *
2315  * This function is called with hbalock held to get the next
2316  * available slot for the given HBQ. If there is free slot
2317  * available for the HBQ it will return pointer to the next available
2318  * HBQ entry else it will return NULL.
2319  **/
2320 static struct lpfc_hbq_entry *
2321 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
2322 {
2323 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
2324 
2325 	lockdep_assert_held(&phba->hbalock);
2326 
2327 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
2328 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
2329 		hbqp->next_hbqPutIdx = 0;
2330 
2331 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
2332 		uint32_t raw_index = phba->hbq_get[hbqno];
2333 		uint32_t getidx = le32_to_cpu(raw_index);
2334 
2335 		hbqp->local_hbqGetIdx = getidx;
2336 
2337 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
2338 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2339 					"1802 HBQ %d: local_hbqGetIdx "
2340 					"%u is > than hbqp->entry_count %u\n",
2341 					hbqno, hbqp->local_hbqGetIdx,
2342 					hbqp->entry_count);
2343 
2344 			phba->link_state = LPFC_HBA_ERROR;
2345 			return NULL;
2346 		}
2347 
2348 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
2349 			return NULL;
2350 	}
2351 
2352 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
2353 			hbqp->hbqPutIdx;
2354 }
2355 
2356 /**
2357  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
2358  * @phba: Pointer to HBA context object.
2359  *
2360  * This function is called with no lock held to free all the
2361  * hbq buffers while uninitializing the SLI interface. It also
2362  * frees the HBQ buffers returned by the firmware but not yet
2363  * processed by the upper layers.
2364  **/
2365 void
2366 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
2367 {
2368 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
2369 	struct hbq_dmabuf *hbq_buf;
2370 	unsigned long flags;
2371 	int i, hbq_count;
2372 
2373 	hbq_count = lpfc_sli_hbq_count();
2374 	/* Return all memory used by all HBQs */
2375 	spin_lock_irqsave(&phba->hbalock, flags);
2376 	for (i = 0; i < hbq_count; ++i) {
2377 		list_for_each_entry_safe(dmabuf, next_dmabuf,
2378 				&phba->hbqs[i].hbq_buffer_list, list) {
2379 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2380 			list_del(&hbq_buf->dbuf.list);
2381 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2382 		}
2383 		phba->hbqs[i].buffer_count = 0;
2384 	}
2385 
2386 	/* Mark the HBQs not in use */
2387 	phba->hbq_in_use = 0;
2388 	spin_unlock_irqrestore(&phba->hbalock, flags);
2389 }
2390 
2391 /**
2392  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2393  * @phba: Pointer to HBA context object.
2394  * @hbqno: HBQ number.
2395  * @hbq_buf: Pointer to HBQ buffer.
2396  *
2397  * This function is called with the hbalock held to post a
2398  * hbq buffer to the firmware. If the function finds an empty
2399  * slot in the HBQ, it will post the buffer. The function will return
2400  * pointer to the hbq entry if it successfully post the buffer
2401  * else it will return NULL.
2402  **/
2403 static int
2404 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2405 			 struct hbq_dmabuf *hbq_buf)
2406 {
2407 	lockdep_assert_held(&phba->hbalock);
2408 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2409 }
2410 
2411 /**
2412  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2413  * @phba: Pointer to HBA context object.
2414  * @hbqno: HBQ number.
2415  * @hbq_buf: Pointer to HBQ buffer.
2416  *
2417  * This function is called with the hbalock held to post a hbq buffer to the
2418  * firmware. If the function finds an empty slot in the HBQ, it will post the
2419  * buffer and place it on the hbq_buffer_list. The function will return zero if
2420  * it successfully post the buffer else it will return an error.
2421  **/
2422 static int
2423 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2424 			    struct hbq_dmabuf *hbq_buf)
2425 {
2426 	struct lpfc_hbq_entry *hbqe;
2427 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
2428 
2429 	lockdep_assert_held(&phba->hbalock);
2430 	/* Get next HBQ entry slot to use */
2431 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2432 	if (hbqe) {
2433 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
2434 
2435 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2436 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2437 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2438 		hbqe->bde.tus.f.bdeFlags = 0;
2439 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2440 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2441 				/* Sync SLIM */
2442 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2443 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2444 				/* flush */
2445 		readl(phba->hbq_put + hbqno);
2446 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2447 		return 0;
2448 	} else
2449 		return -ENOMEM;
2450 }
2451 
2452 /**
2453  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2454  * @phba: Pointer to HBA context object.
2455  * @hbqno: HBQ number.
2456  * @hbq_buf: Pointer to HBQ buffer.
2457  *
2458  * This function is called with the hbalock held to post an RQE to the SLI4
2459  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2460  * the hbq_buffer_list and return zero, otherwise it will return an error.
2461  **/
2462 static int
2463 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2464 			    struct hbq_dmabuf *hbq_buf)
2465 {
2466 	int rc;
2467 	struct lpfc_rqe hrqe;
2468 	struct lpfc_rqe drqe;
2469 	struct lpfc_queue *hrq;
2470 	struct lpfc_queue *drq;
2471 
2472 	if (hbqno != LPFC_ELS_HBQ)
2473 		return 1;
2474 	hrq = phba->sli4_hba.hdr_rq;
2475 	drq = phba->sli4_hba.dat_rq;
2476 
2477 	lockdep_assert_held(&phba->hbalock);
2478 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2479 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2480 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2481 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2482 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2483 	if (rc < 0)
2484 		return rc;
2485 	hbq_buf->tag = (rc | (hbqno << 16));
2486 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2487 	return 0;
2488 }
2489 
2490 /* HBQ for ELS and CT traffic. */
2491 static struct lpfc_hbq_init lpfc_els_hbq = {
2492 	.rn = 1,
2493 	.entry_count = 256,
2494 	.mask_count = 0,
2495 	.profile = 0,
2496 	.ring_mask = (1 << LPFC_ELS_RING),
2497 	.buffer_count = 0,
2498 	.init_count = 40,
2499 	.add_count = 40,
2500 };
2501 
2502 /* Array of HBQs */
2503 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2504 	&lpfc_els_hbq,
2505 };
2506 
2507 /**
2508  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2509  * @phba: Pointer to HBA context object.
2510  * @hbqno: HBQ number.
2511  * @count: Number of HBQ buffers to be posted.
2512  *
2513  * This function is called with no lock held to post more hbq buffers to the
2514  * given HBQ. The function returns the number of HBQ buffers successfully
2515  * posted.
2516  **/
2517 static int
2518 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2519 {
2520 	uint32_t i, posted = 0;
2521 	unsigned long flags;
2522 	struct hbq_dmabuf *hbq_buffer;
2523 	LIST_HEAD(hbq_buf_list);
2524 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2525 		return 0;
2526 
2527 	if ((phba->hbqs[hbqno].buffer_count + count) >
2528 	    lpfc_hbq_defs[hbqno]->entry_count)
2529 		count = lpfc_hbq_defs[hbqno]->entry_count -
2530 					phba->hbqs[hbqno].buffer_count;
2531 	if (!count)
2532 		return 0;
2533 	/* Allocate HBQ entries */
2534 	for (i = 0; i < count; i++) {
2535 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2536 		if (!hbq_buffer)
2537 			break;
2538 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2539 	}
2540 	/* Check whether HBQ is still in use */
2541 	spin_lock_irqsave(&phba->hbalock, flags);
2542 	if (!phba->hbq_in_use)
2543 		goto err;
2544 	while (!list_empty(&hbq_buf_list)) {
2545 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2546 				 dbuf.list);
2547 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2548 				      (hbqno << 16));
2549 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2550 			phba->hbqs[hbqno].buffer_count++;
2551 			posted++;
2552 		} else
2553 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2554 	}
2555 	spin_unlock_irqrestore(&phba->hbalock, flags);
2556 	return posted;
2557 err:
2558 	spin_unlock_irqrestore(&phba->hbalock, flags);
2559 	while (!list_empty(&hbq_buf_list)) {
2560 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2561 				 dbuf.list);
2562 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2563 	}
2564 	return 0;
2565 }
2566 
2567 /**
2568  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2569  * @phba: Pointer to HBA context object.
2570  * @qno: HBQ number.
2571  *
2572  * This function posts more buffers to the HBQ. This function
2573  * is called with no lock held. The function returns the number of HBQ entries
2574  * successfully allocated.
2575  **/
2576 int
2577 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2578 {
2579 	if (phba->sli_rev == LPFC_SLI_REV4)
2580 		return 0;
2581 	else
2582 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2583 					 lpfc_hbq_defs[qno]->add_count);
2584 }
2585 
2586 /**
2587  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2588  * @phba: Pointer to HBA context object.
2589  * @qno:  HBQ queue number.
2590  *
2591  * This function is called from SLI initialization code path with
2592  * no lock held to post initial HBQ buffers to firmware. The
2593  * function returns the number of HBQ entries successfully allocated.
2594  **/
2595 static int
2596 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2597 {
2598 	if (phba->sli_rev == LPFC_SLI_REV4)
2599 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2600 					lpfc_hbq_defs[qno]->entry_count);
2601 	else
2602 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2603 					 lpfc_hbq_defs[qno]->init_count);
2604 }
2605 
2606 /*
2607  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2608  *
2609  * This function removes the first hbq buffer on an hbq list and returns a
2610  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2611  **/
2612 static struct hbq_dmabuf *
2613 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2614 {
2615 	struct lpfc_dmabuf *d_buf;
2616 
2617 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2618 	if (!d_buf)
2619 		return NULL;
2620 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2621 }
2622 
2623 /**
2624  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2625  * @phba: Pointer to HBA context object.
2626  * @hrq: HBQ number.
2627  *
2628  * This function removes the first RQ buffer on an RQ buffer list and returns a
2629  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2630  **/
2631 static struct rqb_dmabuf *
2632 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2633 {
2634 	struct lpfc_dmabuf *h_buf;
2635 	struct lpfc_rqb *rqbp;
2636 
2637 	rqbp = hrq->rqbp;
2638 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2639 			 struct lpfc_dmabuf, list);
2640 	if (!h_buf)
2641 		return NULL;
2642 	rqbp->buffer_count--;
2643 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2644 }
2645 
2646 /**
2647  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2648  * @phba: Pointer to HBA context object.
2649  * @tag: Tag of the hbq buffer.
2650  *
2651  * This function searches for the hbq buffer associated with the given tag in
2652  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2653  * otherwise it returns NULL.
2654  **/
2655 static struct hbq_dmabuf *
2656 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2657 {
2658 	struct lpfc_dmabuf *d_buf;
2659 	struct hbq_dmabuf *hbq_buf;
2660 	uint32_t hbqno;
2661 
2662 	hbqno = tag >> 16;
2663 	if (hbqno >= LPFC_MAX_HBQS)
2664 		return NULL;
2665 
2666 	spin_lock_irq(&phba->hbalock);
2667 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2668 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2669 		if (hbq_buf->tag == tag) {
2670 			spin_unlock_irq(&phba->hbalock);
2671 			return hbq_buf;
2672 		}
2673 	}
2674 	spin_unlock_irq(&phba->hbalock);
2675 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2676 			"1803 Bad hbq tag. Data: x%x x%x\n",
2677 			tag, phba->hbqs[tag >> 16].buffer_count);
2678 	return NULL;
2679 }
2680 
2681 /**
2682  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2683  * @phba: Pointer to HBA context object.
2684  * @hbq_buffer: Pointer to HBQ buffer.
2685  *
2686  * This function is called with hbalock. This function gives back
2687  * the hbq buffer to firmware. If the HBQ does not have space to
2688  * post the buffer, it will free the buffer.
2689  **/
2690 void
2691 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2692 {
2693 	uint32_t hbqno;
2694 
2695 	if (hbq_buffer) {
2696 		hbqno = hbq_buffer->tag >> 16;
2697 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2698 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2699 	}
2700 }
2701 
2702 /**
2703  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2704  * @mbxCommand: mailbox command code.
2705  *
2706  * This function is called by the mailbox event handler function to verify
2707  * that the completed mailbox command is a legitimate mailbox command. If the
2708  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2709  * and the mailbox event handler will take the HBA offline.
2710  **/
2711 static int
2712 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2713 {
2714 	uint8_t ret;
2715 
2716 	switch (mbxCommand) {
2717 	case MBX_LOAD_SM:
2718 	case MBX_READ_NV:
2719 	case MBX_WRITE_NV:
2720 	case MBX_WRITE_VPARMS:
2721 	case MBX_RUN_BIU_DIAG:
2722 	case MBX_INIT_LINK:
2723 	case MBX_DOWN_LINK:
2724 	case MBX_CONFIG_LINK:
2725 	case MBX_CONFIG_RING:
2726 	case MBX_RESET_RING:
2727 	case MBX_READ_CONFIG:
2728 	case MBX_READ_RCONFIG:
2729 	case MBX_READ_SPARM:
2730 	case MBX_READ_STATUS:
2731 	case MBX_READ_RPI:
2732 	case MBX_READ_XRI:
2733 	case MBX_READ_REV:
2734 	case MBX_READ_LNK_STAT:
2735 	case MBX_REG_LOGIN:
2736 	case MBX_UNREG_LOGIN:
2737 	case MBX_CLEAR_LA:
2738 	case MBX_DUMP_MEMORY:
2739 	case MBX_DUMP_CONTEXT:
2740 	case MBX_RUN_DIAGS:
2741 	case MBX_RESTART:
2742 	case MBX_UPDATE_CFG:
2743 	case MBX_DOWN_LOAD:
2744 	case MBX_DEL_LD_ENTRY:
2745 	case MBX_RUN_PROGRAM:
2746 	case MBX_SET_MASK:
2747 	case MBX_SET_VARIABLE:
2748 	case MBX_UNREG_D_ID:
2749 	case MBX_KILL_BOARD:
2750 	case MBX_CONFIG_FARP:
2751 	case MBX_BEACON:
2752 	case MBX_LOAD_AREA:
2753 	case MBX_RUN_BIU_DIAG64:
2754 	case MBX_CONFIG_PORT:
2755 	case MBX_READ_SPARM64:
2756 	case MBX_READ_RPI64:
2757 	case MBX_REG_LOGIN64:
2758 	case MBX_READ_TOPOLOGY:
2759 	case MBX_WRITE_WWN:
2760 	case MBX_SET_DEBUG:
2761 	case MBX_LOAD_EXP_ROM:
2762 	case MBX_ASYNCEVT_ENABLE:
2763 	case MBX_REG_VPI:
2764 	case MBX_UNREG_VPI:
2765 	case MBX_HEARTBEAT:
2766 	case MBX_PORT_CAPABILITIES:
2767 	case MBX_PORT_IOV_CONTROL:
2768 	case MBX_SLI4_CONFIG:
2769 	case MBX_SLI4_REQ_FTRS:
2770 	case MBX_REG_FCFI:
2771 	case MBX_UNREG_FCFI:
2772 	case MBX_REG_VFI:
2773 	case MBX_UNREG_VFI:
2774 	case MBX_INIT_VPI:
2775 	case MBX_INIT_VFI:
2776 	case MBX_RESUME_RPI:
2777 	case MBX_READ_EVENT_LOG_STATUS:
2778 	case MBX_READ_EVENT_LOG:
2779 	case MBX_SECURITY_MGMT:
2780 	case MBX_AUTH_PORT:
2781 	case MBX_ACCESS_VDATA:
2782 		ret = mbxCommand;
2783 		break;
2784 	default:
2785 		ret = MBX_SHUTDOWN;
2786 		break;
2787 	}
2788 	return ret;
2789 }
2790 
2791 /**
2792  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2793  * @phba: Pointer to HBA context object.
2794  * @pmboxq: Pointer to mailbox command.
2795  *
2796  * This is completion handler function for mailbox commands issued from
2797  * lpfc_sli_issue_mbox_wait function. This function is called by the
2798  * mailbox event handler function with no lock held. This function
2799  * will wake up thread waiting on the wait queue pointed by context1
2800  * of the mailbox.
2801  **/
2802 void
2803 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2804 {
2805 	unsigned long drvr_flag;
2806 	struct completion *pmbox_done;
2807 
2808 	/*
2809 	 * If pmbox_done is empty, the driver thread gave up waiting and
2810 	 * continued running.
2811 	 */
2812 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2813 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2814 	pmbox_done = (struct completion *)pmboxq->context3;
2815 	if (pmbox_done)
2816 		complete(pmbox_done);
2817 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2818 	return;
2819 }
2820 
2821 static void
2822 __lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2823 {
2824 	unsigned long iflags;
2825 
2826 	if (ndlp->nlp_flag & NLP_RELEASE_RPI) {
2827 		lpfc_sli4_free_rpi(vport->phba, ndlp->nlp_rpi);
2828 		spin_lock_irqsave(&ndlp->lock, iflags);
2829 		ndlp->nlp_flag &= ~NLP_RELEASE_RPI;
2830 		ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
2831 		spin_unlock_irqrestore(&ndlp->lock, iflags);
2832 	}
2833 	ndlp->nlp_flag &= ~NLP_UNREG_INP;
2834 }
2835 
2836 /**
2837  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2838  * @phba: Pointer to HBA context object.
2839  * @pmb: Pointer to mailbox object.
2840  *
2841  * This function is the default mailbox completion handler. It
2842  * frees the memory resources associated with the completed mailbox
2843  * command. If the completed command is a REG_LOGIN mailbox command,
2844  * this function will issue a UREG_LOGIN to re-claim the RPI.
2845  **/
2846 void
2847 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2848 {
2849 	struct lpfc_vport  *vport = pmb->vport;
2850 	struct lpfc_dmabuf *mp;
2851 	struct lpfc_nodelist *ndlp;
2852 	struct Scsi_Host *shost;
2853 	uint16_t rpi, vpi;
2854 	int rc;
2855 
2856 	mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
2857 
2858 	if (mp) {
2859 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
2860 		kfree(mp);
2861 	}
2862 
2863 	/*
2864 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2865 	 * is in re-discovery driver need to cleanup the RPI.
2866 	 */
2867 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2868 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2869 	    !pmb->u.mb.mbxStatus) {
2870 		rpi = pmb->u.mb.un.varWords[0];
2871 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2872 		if (phba->sli_rev == LPFC_SLI_REV4)
2873 			vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2874 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2875 		pmb->vport = vport;
2876 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2877 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2878 		if (rc != MBX_NOT_FINISHED)
2879 			return;
2880 	}
2881 
2882 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2883 		!(phba->pport->load_flag & FC_UNLOADING) &&
2884 		!pmb->u.mb.mbxStatus) {
2885 		shost = lpfc_shost_from_vport(vport);
2886 		spin_lock_irq(shost->host_lock);
2887 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2888 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2889 		spin_unlock_irq(shost->host_lock);
2890 	}
2891 
2892 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2893 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2894 		lpfc_nlp_put(ndlp);
2895 		pmb->ctx_buf = NULL;
2896 		pmb->ctx_ndlp = NULL;
2897 	}
2898 
2899 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2900 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2901 
2902 		/* Check to see if there are any deferred events to process */
2903 		if (ndlp) {
2904 			lpfc_printf_vlog(
2905 				vport,
2906 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2907 				"1438 UNREG cmpl deferred mbox x%x "
2908 				"on NPort x%x Data: x%x x%x x%px x%x x%x\n",
2909 				ndlp->nlp_rpi, ndlp->nlp_DID,
2910 				ndlp->nlp_flag, ndlp->nlp_defer_did,
2911 				ndlp, vport->load_flag, kref_read(&ndlp->kref));
2912 
2913 			if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2914 			    (ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING)) {
2915 				ndlp->nlp_flag &= ~NLP_UNREG_INP;
2916 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2917 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2918 			} else {
2919 				__lpfc_sli_rpi_release(vport, ndlp);
2920 			}
2921 
2922 			/* The unreg_login mailbox is complete and had a
2923 			 * reference that has to be released.  The PLOGI
2924 			 * got its own ref.
2925 			 */
2926 			lpfc_nlp_put(ndlp);
2927 			pmb->ctx_ndlp = NULL;
2928 		}
2929 	}
2930 
2931 	/* This nlp_put pairs with lpfc_sli4_resume_rpi */
2932 	if (pmb->u.mb.mbxCommand == MBX_RESUME_RPI) {
2933 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2934 		lpfc_nlp_put(ndlp);
2935 	}
2936 
2937 	/* Check security permission status on INIT_LINK mailbox command */
2938 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2939 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2940 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2941 				"2860 SLI authentication is required "
2942 				"for INIT_LINK but has not done yet\n");
2943 
2944 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2945 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2946 	else
2947 		mempool_free(pmb, phba->mbox_mem_pool);
2948 }
2949  /**
2950  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2951  * @phba: Pointer to HBA context object.
2952  * @pmb: Pointer to mailbox object.
2953  *
2954  * This function is the unreg rpi mailbox completion handler. It
2955  * frees the memory resources associated with the completed mailbox
2956  * command. An additional reference is put on the ndlp to prevent
2957  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2958  * the unreg mailbox command completes, this routine puts the
2959  * reference back.
2960  *
2961  **/
2962 void
2963 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2964 {
2965 	struct lpfc_vport  *vport = pmb->vport;
2966 	struct lpfc_nodelist *ndlp;
2967 
2968 	ndlp = pmb->ctx_ndlp;
2969 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2970 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2971 		    (bf_get(lpfc_sli_intf_if_type,
2972 		     &phba->sli4_hba.sli_intf) >=
2973 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2974 			if (ndlp) {
2975 				lpfc_printf_vlog(
2976 					 vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2977 					 "0010 UNREG_LOGIN vpi:%x "
2978 					 "rpi:%x DID:%x defer x%x flg x%x "
2979 					 "x%px\n",
2980 					 vport->vpi, ndlp->nlp_rpi,
2981 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
2982 					 ndlp->nlp_flag,
2983 					 ndlp);
2984 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2985 
2986 				/* Check to see if there are any deferred
2987 				 * events to process
2988 				 */
2989 				if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2990 				    (ndlp->nlp_defer_did !=
2991 				    NLP_EVT_NOTHING_PENDING)) {
2992 					lpfc_printf_vlog(
2993 						vport, KERN_INFO, LOG_DISCOVERY,
2994 						"4111 UNREG cmpl deferred "
2995 						"clr x%x on "
2996 						"NPort x%x Data: x%x x%px\n",
2997 						ndlp->nlp_rpi, ndlp->nlp_DID,
2998 						ndlp->nlp_defer_did, ndlp);
2999 					ndlp->nlp_flag &= ~NLP_UNREG_INP;
3000 					ndlp->nlp_defer_did =
3001 						NLP_EVT_NOTHING_PENDING;
3002 					lpfc_issue_els_plogi(
3003 						vport, ndlp->nlp_DID, 0);
3004 				} else {
3005 					__lpfc_sli_rpi_release(vport, ndlp);
3006 				}
3007 				lpfc_nlp_put(ndlp);
3008 			}
3009 		}
3010 	}
3011 
3012 	mempool_free(pmb, phba->mbox_mem_pool);
3013 }
3014 
3015 /**
3016  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
3017  * @phba: Pointer to HBA context object.
3018  *
3019  * This function is called with no lock held. This function processes all
3020  * the completed mailbox commands and gives it to upper layers. The interrupt
3021  * service routine processes mailbox completion interrupt and adds completed
3022  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
3023  * Worker thread call lpfc_sli_handle_mb_event, which will return the
3024  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
3025  * function returns the mailbox commands to the upper layer by calling the
3026  * completion handler function of each mailbox.
3027  **/
3028 int
3029 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
3030 {
3031 	MAILBOX_t *pmbox;
3032 	LPFC_MBOXQ_t *pmb;
3033 	int rc;
3034 	LIST_HEAD(cmplq);
3035 
3036 	phba->sli.slistat.mbox_event++;
3037 
3038 	/* Get all completed mailboxe buffers into the cmplq */
3039 	spin_lock_irq(&phba->hbalock);
3040 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
3041 	spin_unlock_irq(&phba->hbalock);
3042 
3043 	/* Get a Mailbox buffer to setup mailbox commands for callback */
3044 	do {
3045 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
3046 		if (pmb == NULL)
3047 			break;
3048 
3049 		pmbox = &pmb->u.mb;
3050 
3051 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
3052 			if (pmb->vport) {
3053 				lpfc_debugfs_disc_trc(pmb->vport,
3054 					LPFC_DISC_TRC_MBOX_VPORT,
3055 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
3056 					(uint32_t)pmbox->mbxCommand,
3057 					pmbox->un.varWords[0],
3058 					pmbox->un.varWords[1]);
3059 			}
3060 			else {
3061 				lpfc_debugfs_disc_trc(phba->pport,
3062 					LPFC_DISC_TRC_MBOX,
3063 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
3064 					(uint32_t)pmbox->mbxCommand,
3065 					pmbox->un.varWords[0],
3066 					pmbox->un.varWords[1]);
3067 			}
3068 		}
3069 
3070 		/*
3071 		 * It is a fatal error if unknown mbox command completion.
3072 		 */
3073 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
3074 		    MBX_SHUTDOWN) {
3075 			/* Unknown mailbox command compl */
3076 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3077 					"(%d):0323 Unknown Mailbox command "
3078 					"x%x (x%x/x%x) Cmpl\n",
3079 					pmb->vport ? pmb->vport->vpi :
3080 					LPFC_VPORT_UNKNOWN,
3081 					pmbox->mbxCommand,
3082 					lpfc_sli_config_mbox_subsys_get(phba,
3083 									pmb),
3084 					lpfc_sli_config_mbox_opcode_get(phba,
3085 									pmb));
3086 			phba->link_state = LPFC_HBA_ERROR;
3087 			phba->work_hs = HS_FFER3;
3088 			lpfc_handle_eratt(phba);
3089 			continue;
3090 		}
3091 
3092 		if (pmbox->mbxStatus) {
3093 			phba->sli.slistat.mbox_stat_err++;
3094 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
3095 				/* Mbox cmd cmpl error - RETRYing */
3096 				lpfc_printf_log(phba, KERN_INFO,
3097 					LOG_MBOX | LOG_SLI,
3098 					"(%d):0305 Mbox cmd cmpl "
3099 					"error - RETRYing Data: x%x "
3100 					"(x%x/x%x) x%x x%x x%x\n",
3101 					pmb->vport ? pmb->vport->vpi :
3102 					LPFC_VPORT_UNKNOWN,
3103 					pmbox->mbxCommand,
3104 					lpfc_sli_config_mbox_subsys_get(phba,
3105 									pmb),
3106 					lpfc_sli_config_mbox_opcode_get(phba,
3107 									pmb),
3108 					pmbox->mbxStatus,
3109 					pmbox->un.varWords[0],
3110 					pmb->vport ? pmb->vport->port_state :
3111 					LPFC_VPORT_UNKNOWN);
3112 				pmbox->mbxStatus = 0;
3113 				pmbox->mbxOwner = OWN_HOST;
3114 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3115 				if (rc != MBX_NOT_FINISHED)
3116 					continue;
3117 			}
3118 		}
3119 
3120 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
3121 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
3122 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
3123 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
3124 				"x%x x%x x%x\n",
3125 				pmb->vport ? pmb->vport->vpi : 0,
3126 				pmbox->mbxCommand,
3127 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
3128 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
3129 				pmb->mbox_cmpl,
3130 				*((uint32_t *) pmbox),
3131 				pmbox->un.varWords[0],
3132 				pmbox->un.varWords[1],
3133 				pmbox->un.varWords[2],
3134 				pmbox->un.varWords[3],
3135 				pmbox->un.varWords[4],
3136 				pmbox->un.varWords[5],
3137 				pmbox->un.varWords[6],
3138 				pmbox->un.varWords[7],
3139 				pmbox->un.varWords[8],
3140 				pmbox->un.varWords[9],
3141 				pmbox->un.varWords[10]);
3142 
3143 		if (pmb->mbox_cmpl)
3144 			pmb->mbox_cmpl(phba,pmb);
3145 	} while (1);
3146 	return 0;
3147 }
3148 
3149 /**
3150  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
3151  * @phba: Pointer to HBA context object.
3152  * @pring: Pointer to driver SLI ring object.
3153  * @tag: buffer tag.
3154  *
3155  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
3156  * is set in the tag the buffer is posted for a particular exchange,
3157  * the function will return the buffer without replacing the buffer.
3158  * If the buffer is for unsolicited ELS or CT traffic, this function
3159  * returns the buffer and also posts another buffer to the firmware.
3160  **/
3161 static struct lpfc_dmabuf *
3162 lpfc_sli_get_buff(struct lpfc_hba *phba,
3163 		  struct lpfc_sli_ring *pring,
3164 		  uint32_t tag)
3165 {
3166 	struct hbq_dmabuf *hbq_entry;
3167 
3168 	if (tag & QUE_BUFTAG_BIT)
3169 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
3170 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
3171 	if (!hbq_entry)
3172 		return NULL;
3173 	return &hbq_entry->dbuf;
3174 }
3175 
3176 /**
3177  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
3178  *                              containing a NVME LS request.
3179  * @phba: pointer to lpfc hba data structure.
3180  * @piocb: pointer to the iocbq struct representing the sequence starting
3181  *        frame.
3182  *
3183  * This routine initially validates the NVME LS, validates there is a login
3184  * with the port that sent the LS, and then calls the appropriate nvme host
3185  * or target LS request handler.
3186  **/
3187 static void
3188 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
3189 {
3190 	struct lpfc_nodelist *ndlp;
3191 	struct lpfc_dmabuf *d_buf;
3192 	struct hbq_dmabuf *nvmebuf;
3193 	struct fc_frame_header *fc_hdr;
3194 	struct lpfc_async_xchg_ctx *axchg = NULL;
3195 	char *failwhy = NULL;
3196 	uint32_t oxid, sid, did, fctl, size;
3197 	int ret = 1;
3198 
3199 	d_buf = piocb->context2;
3200 
3201 	nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
3202 	fc_hdr = nvmebuf->hbuf.virt;
3203 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
3204 	sid = sli4_sid_from_fc_hdr(fc_hdr);
3205 	did = sli4_did_from_fc_hdr(fc_hdr);
3206 	fctl = (fc_hdr->fh_f_ctl[0] << 16 |
3207 		fc_hdr->fh_f_ctl[1] << 8 |
3208 		fc_hdr->fh_f_ctl[2]);
3209 	size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
3210 
3211 	lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
3212 			 oxid, size, sid);
3213 
3214 	if (phba->pport->load_flag & FC_UNLOADING) {
3215 		failwhy = "Driver Unloading";
3216 	} else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
3217 		failwhy = "NVME FC4 Disabled";
3218 	} else if (!phba->nvmet_support && !phba->pport->localport) {
3219 		failwhy = "No Localport";
3220 	} else if (phba->nvmet_support && !phba->targetport) {
3221 		failwhy = "No Targetport";
3222 	} else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
3223 		failwhy = "Bad NVME LS R_CTL";
3224 	} else if (unlikely((fctl & 0x00FF0000) !=
3225 			(FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
3226 		failwhy = "Bad NVME LS F_CTL";
3227 	} else {
3228 		axchg = kzalloc(sizeof(*axchg), GFP_ATOMIC);
3229 		if (!axchg)
3230 			failwhy = "No CTX memory";
3231 	}
3232 
3233 	if (unlikely(failwhy)) {
3234 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3235 				"6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
3236 				sid, oxid, failwhy);
3237 		goto out_fail;
3238 	}
3239 
3240 	/* validate the source of the LS is logged in */
3241 	ndlp = lpfc_findnode_did(phba->pport, sid);
3242 	if (!ndlp ||
3243 	    ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
3244 	     (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
3245 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
3246 				"6216 NVME Unsol rcv: No ndlp: "
3247 				"NPort_ID x%x oxid x%x\n",
3248 				sid, oxid);
3249 		goto out_fail;
3250 	}
3251 
3252 	axchg->phba = phba;
3253 	axchg->ndlp = ndlp;
3254 	axchg->size = size;
3255 	axchg->oxid = oxid;
3256 	axchg->sid = sid;
3257 	axchg->wqeq = NULL;
3258 	axchg->state = LPFC_NVME_STE_LS_RCV;
3259 	axchg->entry_cnt = 1;
3260 	axchg->rqb_buffer = (void *)nvmebuf;
3261 	axchg->hdwq = &phba->sli4_hba.hdwq[0];
3262 	axchg->payload = nvmebuf->dbuf.virt;
3263 	INIT_LIST_HEAD(&axchg->list);
3264 
3265 	if (phba->nvmet_support) {
3266 		ret = lpfc_nvmet_handle_lsreq(phba, axchg);
3267 		spin_lock_irq(&ndlp->lock);
3268 		if (!ret && !(ndlp->fc4_xpt_flags & NLP_XPT_HAS_HH)) {
3269 			ndlp->fc4_xpt_flags |= NLP_XPT_HAS_HH;
3270 			spin_unlock_irq(&ndlp->lock);
3271 
3272 			/* This reference is a single occurrence to hold the
3273 			 * node valid until the nvmet transport calls
3274 			 * host_release.
3275 			 */
3276 			if (!lpfc_nlp_get(ndlp))
3277 				goto out_fail;
3278 
3279 			lpfc_printf_log(phba, KERN_ERR, LOG_NODE,
3280 					"6206 NVMET unsol ls_req ndlp x%px "
3281 					"DID x%x xflags x%x refcnt %d\n",
3282 					ndlp, ndlp->nlp_DID,
3283 					ndlp->fc4_xpt_flags,
3284 					kref_read(&ndlp->kref));
3285 		} else {
3286 			spin_unlock_irq(&ndlp->lock);
3287 		}
3288 	} else {
3289 		ret = lpfc_nvme_handle_lsreq(phba, axchg);
3290 	}
3291 
3292 	/* if zero, LS was successfully handled. If non-zero, LS not handled */
3293 	if (!ret)
3294 		return;
3295 
3296 out_fail:
3297 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3298 			"6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
3299 			"NVMe%s handler failed %d\n",
3300 			did, sid, oxid,
3301 			(phba->nvmet_support) ? "T" : "I", ret);
3302 
3303 	/* recycle receive buffer */
3304 	lpfc_in_buf_free(phba, &nvmebuf->dbuf);
3305 
3306 	/* If start of new exchange, abort it */
3307 	if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
3308 		ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
3309 
3310 	if (ret)
3311 		kfree(axchg);
3312 }
3313 
3314 /**
3315  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
3316  * @phba: Pointer to HBA context object.
3317  * @pring: Pointer to driver SLI ring object.
3318  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
3319  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
3320  * @fch_type: the type for the first frame of the sequence.
3321  *
3322  * This function is called with no lock held. This function uses the r_ctl and
3323  * type of the received sequence to find the correct callback function to call
3324  * to process the sequence.
3325  **/
3326 static int
3327 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3328 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
3329 			 uint32_t fch_type)
3330 {
3331 	int i;
3332 
3333 	switch (fch_type) {
3334 	case FC_TYPE_NVME:
3335 		lpfc_nvme_unsol_ls_handler(phba, saveq);
3336 		return 1;
3337 	default:
3338 		break;
3339 	}
3340 
3341 	/* unSolicited Responses */
3342 	if (pring->prt[0].profile) {
3343 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
3344 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
3345 									saveq);
3346 		return 1;
3347 	}
3348 	/* We must search, based on rctl / type
3349 	   for the right routine */
3350 	for (i = 0; i < pring->num_mask; i++) {
3351 		if ((pring->prt[i].rctl == fch_r_ctl) &&
3352 		    (pring->prt[i].type == fch_type)) {
3353 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
3354 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
3355 						(phba, pring, saveq);
3356 			return 1;
3357 		}
3358 	}
3359 	return 0;
3360 }
3361 
3362 /**
3363  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
3364  * @phba: Pointer to HBA context object.
3365  * @pring: Pointer to driver SLI ring object.
3366  * @saveq: Pointer to the unsolicited iocb.
3367  *
3368  * This function is called with no lock held by the ring event handler
3369  * when there is an unsolicited iocb posted to the response ring by the
3370  * firmware. This function gets the buffer associated with the iocbs
3371  * and calls the event handler for the ring. This function handles both
3372  * qring buffers and hbq buffers.
3373  * When the function returns 1 the caller can free the iocb object otherwise
3374  * upper layer functions will free the iocb objects.
3375  **/
3376 static int
3377 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3378 			    struct lpfc_iocbq *saveq)
3379 {
3380 	IOCB_t           * irsp;
3381 	WORD5            * w5p;
3382 	uint32_t           Rctl, Type;
3383 	struct lpfc_iocbq *iocbq;
3384 	struct lpfc_dmabuf *dmzbuf;
3385 
3386 	irsp = &(saveq->iocb);
3387 
3388 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
3389 		if (pring->lpfc_sli_rcv_async_status)
3390 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
3391 		else
3392 			lpfc_printf_log(phba,
3393 					KERN_WARNING,
3394 					LOG_SLI,
3395 					"0316 Ring %d handler: unexpected "
3396 					"ASYNC_STATUS iocb received evt_code "
3397 					"0x%x\n",
3398 					pring->ringno,
3399 					irsp->un.asyncstat.evt_code);
3400 		return 1;
3401 	}
3402 
3403 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3404 		(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3405 		if (irsp->ulpBdeCount > 0) {
3406 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3407 					irsp->un.ulpWord[3]);
3408 			lpfc_in_buf_free(phba, dmzbuf);
3409 		}
3410 
3411 		if (irsp->ulpBdeCount > 1) {
3412 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3413 					irsp->unsli3.sli3Words[3]);
3414 			lpfc_in_buf_free(phba, dmzbuf);
3415 		}
3416 
3417 		if (irsp->ulpBdeCount > 2) {
3418 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3419 				irsp->unsli3.sli3Words[7]);
3420 			lpfc_in_buf_free(phba, dmzbuf);
3421 		}
3422 
3423 		return 1;
3424 	}
3425 
3426 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3427 		if (irsp->ulpBdeCount != 0) {
3428 			saveq->context2 = lpfc_sli_get_buff(phba, pring,
3429 						irsp->un.ulpWord[3]);
3430 			if (!saveq->context2)
3431 				lpfc_printf_log(phba,
3432 					KERN_ERR,
3433 					LOG_SLI,
3434 					"0341 Ring %d Cannot find buffer for "
3435 					"an unsolicited iocb. tag 0x%x\n",
3436 					pring->ringno,
3437 					irsp->un.ulpWord[3]);
3438 		}
3439 		if (irsp->ulpBdeCount == 2) {
3440 			saveq->context3 = lpfc_sli_get_buff(phba, pring,
3441 						irsp->unsli3.sli3Words[7]);
3442 			if (!saveq->context3)
3443 				lpfc_printf_log(phba,
3444 					KERN_ERR,
3445 					LOG_SLI,
3446 					"0342 Ring %d Cannot find buffer for an"
3447 					" unsolicited iocb. tag 0x%x\n",
3448 					pring->ringno,
3449 					irsp->unsli3.sli3Words[7]);
3450 		}
3451 		list_for_each_entry(iocbq, &saveq->list, list) {
3452 			irsp = &(iocbq->iocb);
3453 			if (irsp->ulpBdeCount != 0) {
3454 				iocbq->context2 = lpfc_sli_get_buff(phba, pring,
3455 							irsp->un.ulpWord[3]);
3456 				if (!iocbq->context2)
3457 					lpfc_printf_log(phba,
3458 						KERN_ERR,
3459 						LOG_SLI,
3460 						"0343 Ring %d Cannot find "
3461 						"buffer for an unsolicited iocb"
3462 						". tag 0x%x\n", pring->ringno,
3463 						irsp->un.ulpWord[3]);
3464 			}
3465 			if (irsp->ulpBdeCount == 2) {
3466 				iocbq->context3 = lpfc_sli_get_buff(phba, pring,
3467 						irsp->unsli3.sli3Words[7]);
3468 				if (!iocbq->context3)
3469 					lpfc_printf_log(phba,
3470 						KERN_ERR,
3471 						LOG_SLI,
3472 						"0344 Ring %d Cannot find "
3473 						"buffer for an unsolicited "
3474 						"iocb. tag 0x%x\n",
3475 						pring->ringno,
3476 						irsp->unsli3.sli3Words[7]);
3477 			}
3478 		}
3479 	}
3480 	if (irsp->ulpBdeCount != 0 &&
3481 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3482 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3483 		int found = 0;
3484 
3485 		/* search continue save q for same XRI */
3486 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3487 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3488 				saveq->iocb.unsli3.rcvsli3.ox_id) {
3489 				list_add_tail(&saveq->list, &iocbq->list);
3490 				found = 1;
3491 				break;
3492 			}
3493 		}
3494 		if (!found)
3495 			list_add_tail(&saveq->clist,
3496 				      &pring->iocb_continue_saveq);
3497 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3498 			list_del_init(&iocbq->clist);
3499 			saveq = iocbq;
3500 			irsp = &(saveq->iocb);
3501 		} else
3502 			return 0;
3503 	}
3504 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3505 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3506 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3507 		Rctl = FC_RCTL_ELS_REQ;
3508 		Type = FC_TYPE_ELS;
3509 	} else {
3510 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3511 		Rctl = w5p->hcsw.Rctl;
3512 		Type = w5p->hcsw.Type;
3513 
3514 		/* Firmware Workaround */
3515 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3516 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3517 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3518 			Rctl = FC_RCTL_ELS_REQ;
3519 			Type = FC_TYPE_ELS;
3520 			w5p->hcsw.Rctl = Rctl;
3521 			w5p->hcsw.Type = Type;
3522 		}
3523 	}
3524 
3525 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3526 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3527 				"0313 Ring %d handler: unexpected Rctl x%x "
3528 				"Type x%x received\n",
3529 				pring->ringno, Rctl, Type);
3530 
3531 	return 1;
3532 }
3533 
3534 /**
3535  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3536  * @phba: Pointer to HBA context object.
3537  * @pring: Pointer to driver SLI ring object.
3538  * @prspiocb: Pointer to response iocb object.
3539  *
3540  * This function looks up the iocb_lookup table to get the command iocb
3541  * corresponding to the given response iocb using the iotag of the
3542  * response iocb. The driver calls this function with the hbalock held
3543  * for SLI3 ports or the ring lock held for SLI4 ports.
3544  * This function returns the command iocb object if it finds the command
3545  * iocb else returns NULL.
3546  **/
3547 static struct lpfc_iocbq *
3548 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3549 		      struct lpfc_sli_ring *pring,
3550 		      struct lpfc_iocbq *prspiocb)
3551 {
3552 	struct lpfc_iocbq *cmd_iocb = NULL;
3553 	uint16_t iotag;
3554 	spinlock_t *temp_lock = NULL;
3555 	unsigned long iflag = 0;
3556 
3557 	if (phba->sli_rev == LPFC_SLI_REV4)
3558 		temp_lock = &pring->ring_lock;
3559 	else
3560 		temp_lock = &phba->hbalock;
3561 
3562 	spin_lock_irqsave(temp_lock, iflag);
3563 	iotag = prspiocb->iocb.ulpIoTag;
3564 
3565 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3566 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3567 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3568 			/* remove from txcmpl queue list */
3569 			list_del_init(&cmd_iocb->list);
3570 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3571 			pring->txcmplq_cnt--;
3572 			spin_unlock_irqrestore(temp_lock, iflag);
3573 			return cmd_iocb;
3574 		}
3575 	}
3576 
3577 	spin_unlock_irqrestore(temp_lock, iflag);
3578 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3579 			"0317 iotag x%x is out of "
3580 			"range: max iotag x%x wd0 x%x\n",
3581 			iotag, phba->sli.last_iotag,
3582 			*(((uint32_t *) &prspiocb->iocb) + 7));
3583 	return NULL;
3584 }
3585 
3586 /**
3587  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3588  * @phba: Pointer to HBA context object.
3589  * @pring: Pointer to driver SLI ring object.
3590  * @iotag: IOCB tag.
3591  *
3592  * This function looks up the iocb_lookup table to get the command iocb
3593  * corresponding to the given iotag. The driver calls this function with
3594  * the ring lock held because this function is an SLI4 port only helper.
3595  * This function returns the command iocb object if it finds the command
3596  * iocb else returns NULL.
3597  **/
3598 static struct lpfc_iocbq *
3599 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3600 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3601 {
3602 	struct lpfc_iocbq *cmd_iocb = NULL;
3603 	spinlock_t *temp_lock = NULL;
3604 	unsigned long iflag = 0;
3605 
3606 	if (phba->sli_rev == LPFC_SLI_REV4)
3607 		temp_lock = &pring->ring_lock;
3608 	else
3609 		temp_lock = &phba->hbalock;
3610 
3611 	spin_lock_irqsave(temp_lock, iflag);
3612 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3613 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3614 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3615 			/* remove from txcmpl queue list */
3616 			list_del_init(&cmd_iocb->list);
3617 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3618 			pring->txcmplq_cnt--;
3619 			spin_unlock_irqrestore(temp_lock, iflag);
3620 			return cmd_iocb;
3621 		}
3622 	}
3623 
3624 	spin_unlock_irqrestore(temp_lock, iflag);
3625 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3626 			"0372 iotag x%x lookup error: max iotag (x%x) "
3627 			"iocb_flag x%x\n",
3628 			iotag, phba->sli.last_iotag,
3629 			cmd_iocb ? cmd_iocb->iocb_flag : 0xffff);
3630 	return NULL;
3631 }
3632 
3633 /**
3634  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3635  * @phba: Pointer to HBA context object.
3636  * @pring: Pointer to driver SLI ring object.
3637  * @saveq: Pointer to the response iocb to be processed.
3638  *
3639  * This function is called by the ring event handler for non-fcp
3640  * rings when there is a new response iocb in the response ring.
3641  * The caller is not required to hold any locks. This function
3642  * gets the command iocb associated with the response iocb and
3643  * calls the completion handler for the command iocb. If there
3644  * is no completion handler, the function will free the resources
3645  * associated with command iocb. If the response iocb is for
3646  * an already aborted command iocb, the status of the completion
3647  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3648  * This function always returns 1.
3649  **/
3650 static int
3651 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3652 			  struct lpfc_iocbq *saveq)
3653 {
3654 	struct lpfc_iocbq *cmdiocbp;
3655 	int rc = 1;
3656 	unsigned long iflag;
3657 
3658 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3659 	if (cmdiocbp) {
3660 		if (cmdiocbp->iocb_cmpl) {
3661 			/*
3662 			 * If an ELS command failed send an event to mgmt
3663 			 * application.
3664 			 */
3665 			if (saveq->iocb.ulpStatus &&
3666 			     (pring->ringno == LPFC_ELS_RING) &&
3667 			     (cmdiocbp->iocb.ulpCommand ==
3668 				CMD_ELS_REQUEST64_CR))
3669 				lpfc_send_els_failure_event(phba,
3670 					cmdiocbp, saveq);
3671 
3672 			/*
3673 			 * Post all ELS completions to the worker thread.
3674 			 * All other are passed to the completion callback.
3675 			 */
3676 			if (pring->ringno == LPFC_ELS_RING) {
3677 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3678 				    (cmdiocbp->iocb_flag &
3679 							LPFC_DRIVER_ABORTED)) {
3680 					spin_lock_irqsave(&phba->hbalock,
3681 							  iflag);
3682 					cmdiocbp->iocb_flag &=
3683 						~LPFC_DRIVER_ABORTED;
3684 					spin_unlock_irqrestore(&phba->hbalock,
3685 							       iflag);
3686 					saveq->iocb.ulpStatus =
3687 						IOSTAT_LOCAL_REJECT;
3688 					saveq->iocb.un.ulpWord[4] =
3689 						IOERR_SLI_ABORTED;
3690 
3691 					/* Firmware could still be in progress
3692 					 * of DMAing payload, so don't free data
3693 					 * buffer till after a hbeat.
3694 					 */
3695 					spin_lock_irqsave(&phba->hbalock,
3696 							  iflag);
3697 					saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
3698 					spin_unlock_irqrestore(&phba->hbalock,
3699 							       iflag);
3700 				}
3701 				if (phba->sli_rev == LPFC_SLI_REV4) {
3702 					if (saveq->iocb_flag &
3703 					    LPFC_EXCHANGE_BUSY) {
3704 						/* Set cmdiocb flag for the
3705 						 * exchange busy so sgl (xri)
3706 						 * will not be released until
3707 						 * the abort xri is received
3708 						 * from hba.
3709 						 */
3710 						spin_lock_irqsave(
3711 							&phba->hbalock, iflag);
3712 						cmdiocbp->iocb_flag |=
3713 							LPFC_EXCHANGE_BUSY;
3714 						spin_unlock_irqrestore(
3715 							&phba->hbalock, iflag);
3716 					}
3717 					if (cmdiocbp->iocb_flag &
3718 					    LPFC_DRIVER_ABORTED) {
3719 						/*
3720 						 * Clear LPFC_DRIVER_ABORTED
3721 						 * bit in case it was driver
3722 						 * initiated abort.
3723 						 */
3724 						spin_lock_irqsave(
3725 							&phba->hbalock, iflag);
3726 						cmdiocbp->iocb_flag &=
3727 							~LPFC_DRIVER_ABORTED;
3728 						spin_unlock_irqrestore(
3729 							&phba->hbalock, iflag);
3730 						cmdiocbp->iocb.ulpStatus =
3731 							IOSTAT_LOCAL_REJECT;
3732 						cmdiocbp->iocb.un.ulpWord[4] =
3733 							IOERR_ABORT_REQUESTED;
3734 						/*
3735 						 * For SLI4, irsiocb contains
3736 						 * NO_XRI in sli_xritag, it
3737 						 * shall not affect releasing
3738 						 * sgl (xri) process.
3739 						 */
3740 						saveq->iocb.ulpStatus =
3741 							IOSTAT_LOCAL_REJECT;
3742 						saveq->iocb.un.ulpWord[4] =
3743 							IOERR_SLI_ABORTED;
3744 						spin_lock_irqsave(
3745 							&phba->hbalock, iflag);
3746 						saveq->iocb_flag |=
3747 							LPFC_DELAY_MEM_FREE;
3748 						spin_unlock_irqrestore(
3749 							&phba->hbalock, iflag);
3750 					}
3751 				}
3752 			}
3753 			(cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
3754 		} else
3755 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3756 	} else {
3757 		/*
3758 		 * Unknown initiating command based on the response iotag.
3759 		 * This could be the case on the ELS ring because of
3760 		 * lpfc_els_abort().
3761 		 */
3762 		if (pring->ringno != LPFC_ELS_RING) {
3763 			/*
3764 			 * Ring <ringno> handler: unexpected completion IoTag
3765 			 * <IoTag>
3766 			 */
3767 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3768 					 "0322 Ring %d handler: "
3769 					 "unexpected completion IoTag x%x "
3770 					 "Data: x%x x%x x%x x%x\n",
3771 					 pring->ringno,
3772 					 saveq->iocb.ulpIoTag,
3773 					 saveq->iocb.ulpStatus,
3774 					 saveq->iocb.un.ulpWord[4],
3775 					 saveq->iocb.ulpCommand,
3776 					 saveq->iocb.ulpContext);
3777 		}
3778 	}
3779 
3780 	return rc;
3781 }
3782 
3783 /**
3784  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3785  * @phba: Pointer to HBA context object.
3786  * @pring: Pointer to driver SLI ring object.
3787  *
3788  * This function is called from the iocb ring event handlers when
3789  * put pointer is ahead of the get pointer for a ring. This function signal
3790  * an error attention condition to the worker thread and the worker
3791  * thread will transition the HBA to offline state.
3792  **/
3793 static void
3794 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3795 {
3796 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3797 	/*
3798 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3799 	 * rsp ring <portRspMax>
3800 	 */
3801 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3802 			"0312 Ring %d handler: portRspPut %d "
3803 			"is bigger than rsp ring %d\n",
3804 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3805 			pring->sli.sli3.numRiocb);
3806 
3807 	phba->link_state = LPFC_HBA_ERROR;
3808 
3809 	/*
3810 	 * All error attention handlers are posted to
3811 	 * worker thread
3812 	 */
3813 	phba->work_ha |= HA_ERATT;
3814 	phba->work_hs = HS_FFER3;
3815 
3816 	lpfc_worker_wake_up(phba);
3817 
3818 	return;
3819 }
3820 
3821 /**
3822  * lpfc_poll_eratt - Error attention polling timer timeout handler
3823  * @t: Context to fetch pointer to address of HBA context object from.
3824  *
3825  * This function is invoked by the Error Attention polling timer when the
3826  * timer times out. It will check the SLI Error Attention register for
3827  * possible attention events. If so, it will post an Error Attention event
3828  * and wake up worker thread to process it. Otherwise, it will set up the
3829  * Error Attention polling timer for the next poll.
3830  **/
3831 void lpfc_poll_eratt(struct timer_list *t)
3832 {
3833 	struct lpfc_hba *phba;
3834 	uint32_t eratt = 0;
3835 	uint64_t sli_intr, cnt;
3836 
3837 	phba = from_timer(phba, t, eratt_poll);
3838 
3839 	/* Here we will also keep track of interrupts per sec of the hba */
3840 	sli_intr = phba->sli.slistat.sli_intr;
3841 
3842 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3843 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3844 			sli_intr);
3845 	else
3846 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3847 
3848 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3849 	do_div(cnt, phba->eratt_poll_interval);
3850 	phba->sli.slistat.sli_ips = cnt;
3851 
3852 	phba->sli.slistat.sli_prev_intr = sli_intr;
3853 
3854 	/* Check chip HA register for error event */
3855 	eratt = lpfc_sli_check_eratt(phba);
3856 
3857 	if (eratt)
3858 		/* Tell the worker thread there is work to do */
3859 		lpfc_worker_wake_up(phba);
3860 	else
3861 		/* Restart the timer for next eratt poll */
3862 		mod_timer(&phba->eratt_poll,
3863 			  jiffies +
3864 			  msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3865 	return;
3866 }
3867 
3868 
3869 /**
3870  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3871  * @phba: Pointer to HBA context object.
3872  * @pring: Pointer to driver SLI ring object.
3873  * @mask: Host attention register mask for this ring.
3874  *
3875  * This function is called from the interrupt context when there is a ring
3876  * event for the fcp ring. The caller does not hold any lock.
3877  * The function processes each response iocb in the response ring until it
3878  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3879  * LE bit set. The function will call the completion handler of the command iocb
3880  * if the response iocb indicates a completion for a command iocb or it is
3881  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3882  * function if this is an unsolicited iocb.
3883  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3884  * to check it explicitly.
3885  */
3886 int
3887 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3888 				struct lpfc_sli_ring *pring, uint32_t mask)
3889 {
3890 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3891 	IOCB_t *irsp = NULL;
3892 	IOCB_t *entry = NULL;
3893 	struct lpfc_iocbq *cmdiocbq = NULL;
3894 	struct lpfc_iocbq rspiocbq;
3895 	uint32_t status;
3896 	uint32_t portRspPut, portRspMax;
3897 	int rc = 1;
3898 	lpfc_iocb_type type;
3899 	unsigned long iflag;
3900 	uint32_t rsp_cmpl = 0;
3901 
3902 	spin_lock_irqsave(&phba->hbalock, iflag);
3903 	pring->stats.iocb_event++;
3904 
3905 	/*
3906 	 * The next available response entry should never exceed the maximum
3907 	 * entries.  If it does, treat it as an adapter hardware error.
3908 	 */
3909 	portRspMax = pring->sli.sli3.numRiocb;
3910 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3911 	if (unlikely(portRspPut >= portRspMax)) {
3912 		lpfc_sli_rsp_pointers_error(phba, pring);
3913 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3914 		return 1;
3915 	}
3916 	if (phba->fcp_ring_in_use) {
3917 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3918 		return 1;
3919 	} else
3920 		phba->fcp_ring_in_use = 1;
3921 
3922 	rmb();
3923 	while (pring->sli.sli3.rspidx != portRspPut) {
3924 		/*
3925 		 * Fetch an entry off the ring and copy it into a local data
3926 		 * structure.  The copy involves a byte-swap since the
3927 		 * network byte order and pci byte orders are different.
3928 		 */
3929 		entry = lpfc_resp_iocb(phba, pring);
3930 		phba->last_completion_time = jiffies;
3931 
3932 		if (++pring->sli.sli3.rspidx >= portRspMax)
3933 			pring->sli.sli3.rspidx = 0;
3934 
3935 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3936 				      (uint32_t *) &rspiocbq.iocb,
3937 				      phba->iocb_rsp_size);
3938 		INIT_LIST_HEAD(&(rspiocbq.list));
3939 		irsp = &rspiocbq.iocb;
3940 
3941 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3942 		pring->stats.iocb_rsp++;
3943 		rsp_cmpl++;
3944 
3945 		if (unlikely(irsp->ulpStatus)) {
3946 			/*
3947 			 * If resource errors reported from HBA, reduce
3948 			 * queuedepths of the SCSI device.
3949 			 */
3950 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3951 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3952 			     IOERR_NO_RESOURCES)) {
3953 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3954 				phba->lpfc_rampdown_queue_depth(phba);
3955 				spin_lock_irqsave(&phba->hbalock, iflag);
3956 			}
3957 
3958 			/* Rsp ring <ringno> error: IOCB */
3959 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3960 					"0336 Rsp Ring %d error: IOCB Data: "
3961 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
3962 					pring->ringno,
3963 					irsp->un.ulpWord[0],
3964 					irsp->un.ulpWord[1],
3965 					irsp->un.ulpWord[2],
3966 					irsp->un.ulpWord[3],
3967 					irsp->un.ulpWord[4],
3968 					irsp->un.ulpWord[5],
3969 					*(uint32_t *)&irsp->un1,
3970 					*((uint32_t *)&irsp->un1 + 1));
3971 		}
3972 
3973 		switch (type) {
3974 		case LPFC_ABORT_IOCB:
3975 		case LPFC_SOL_IOCB:
3976 			/*
3977 			 * Idle exchange closed via ABTS from port.  No iocb
3978 			 * resources need to be recovered.
3979 			 */
3980 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3981 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3982 						"0333 IOCB cmd 0x%x"
3983 						" processed. Skipping"
3984 						" completion\n",
3985 						irsp->ulpCommand);
3986 				break;
3987 			}
3988 
3989 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3990 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3991 							 &rspiocbq);
3992 			spin_lock_irqsave(&phba->hbalock, iflag);
3993 			if (unlikely(!cmdiocbq))
3994 				break;
3995 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3996 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3997 			if (cmdiocbq->iocb_cmpl) {
3998 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3999 				(cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
4000 						      &rspiocbq);
4001 				spin_lock_irqsave(&phba->hbalock, iflag);
4002 			}
4003 			break;
4004 		case LPFC_UNSOL_IOCB:
4005 			spin_unlock_irqrestore(&phba->hbalock, iflag);
4006 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
4007 			spin_lock_irqsave(&phba->hbalock, iflag);
4008 			break;
4009 		default:
4010 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
4011 				char adaptermsg[LPFC_MAX_ADPTMSG];
4012 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4013 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
4014 				       MAX_MSG_DATA);
4015 				dev_warn(&((phba->pcidev)->dev),
4016 					 "lpfc%d: %s\n",
4017 					 phba->brd_no, adaptermsg);
4018 			} else {
4019 				/* Unknown IOCB command */
4020 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4021 						"0334 Unknown IOCB command "
4022 						"Data: x%x, x%x x%x x%x x%x\n",
4023 						type, irsp->ulpCommand,
4024 						irsp->ulpStatus,
4025 						irsp->ulpIoTag,
4026 						irsp->ulpContext);
4027 			}
4028 			break;
4029 		}
4030 
4031 		/*
4032 		 * The response IOCB has been processed.  Update the ring
4033 		 * pointer in SLIM.  If the port response put pointer has not
4034 		 * been updated, sync the pgp->rspPutInx and fetch the new port
4035 		 * response put pointer.
4036 		 */
4037 		writel(pring->sli.sli3.rspidx,
4038 			&phba->host_gp[pring->ringno].rspGetInx);
4039 
4040 		if (pring->sli.sli3.rspidx == portRspPut)
4041 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4042 	}
4043 
4044 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
4045 		pring->stats.iocb_rsp_full++;
4046 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4047 		writel(status, phba->CAregaddr);
4048 		readl(phba->CAregaddr);
4049 	}
4050 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4051 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4052 		pring->stats.iocb_cmd_empty++;
4053 
4054 		/* Force update of the local copy of cmdGetInx */
4055 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4056 		lpfc_sli_resume_iocb(phba, pring);
4057 
4058 		if ((pring->lpfc_sli_cmd_available))
4059 			(pring->lpfc_sli_cmd_available) (phba, pring);
4060 
4061 	}
4062 
4063 	phba->fcp_ring_in_use = 0;
4064 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4065 	return rc;
4066 }
4067 
4068 /**
4069  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
4070  * @phba: Pointer to HBA context object.
4071  * @pring: Pointer to driver SLI ring object.
4072  * @rspiocbp: Pointer to driver response IOCB object.
4073  *
4074  * This function is called from the worker thread when there is a slow-path
4075  * response IOCB to process. This function chains all the response iocbs until
4076  * seeing the iocb with the LE bit set. The function will call
4077  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
4078  * completion of a command iocb. The function will call the
4079  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
4080  * The function frees the resources or calls the completion handler if this
4081  * iocb is an abort completion. The function returns NULL when the response
4082  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
4083  * this function shall chain the iocb on to the iocb_continueq and return the
4084  * response iocb passed in.
4085  **/
4086 static struct lpfc_iocbq *
4087 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
4088 			struct lpfc_iocbq *rspiocbp)
4089 {
4090 	struct lpfc_iocbq *saveq;
4091 	struct lpfc_iocbq *cmdiocbp;
4092 	struct lpfc_iocbq *next_iocb;
4093 	IOCB_t *irsp = NULL;
4094 	uint32_t free_saveq;
4095 	uint8_t iocb_cmd_type;
4096 	lpfc_iocb_type type;
4097 	unsigned long iflag;
4098 	int rc;
4099 
4100 	spin_lock_irqsave(&phba->hbalock, iflag);
4101 	/* First add the response iocb to the countinueq list */
4102 	list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
4103 	pring->iocb_continueq_cnt++;
4104 
4105 	/* Now, determine whether the list is completed for processing */
4106 	irsp = &rspiocbp->iocb;
4107 	if (irsp->ulpLe) {
4108 		/*
4109 		 * By default, the driver expects to free all resources
4110 		 * associated with this iocb completion.
4111 		 */
4112 		free_saveq = 1;
4113 		saveq = list_get_first(&pring->iocb_continueq,
4114 				       struct lpfc_iocbq, list);
4115 		irsp = &(saveq->iocb);
4116 		list_del_init(&pring->iocb_continueq);
4117 		pring->iocb_continueq_cnt = 0;
4118 
4119 		pring->stats.iocb_rsp++;
4120 
4121 		/*
4122 		 * If resource errors reported from HBA, reduce
4123 		 * queuedepths of the SCSI device.
4124 		 */
4125 		if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
4126 		    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
4127 		     IOERR_NO_RESOURCES)) {
4128 			spin_unlock_irqrestore(&phba->hbalock, iflag);
4129 			phba->lpfc_rampdown_queue_depth(phba);
4130 			spin_lock_irqsave(&phba->hbalock, iflag);
4131 		}
4132 
4133 		if (irsp->ulpStatus) {
4134 			/* Rsp ring <ringno> error: IOCB */
4135 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4136 					"0328 Rsp Ring %d error: "
4137 					"IOCB Data: "
4138 					"x%x x%x x%x x%x "
4139 					"x%x x%x x%x x%x "
4140 					"x%x x%x x%x x%x "
4141 					"x%x x%x x%x x%x\n",
4142 					pring->ringno,
4143 					irsp->un.ulpWord[0],
4144 					irsp->un.ulpWord[1],
4145 					irsp->un.ulpWord[2],
4146 					irsp->un.ulpWord[3],
4147 					irsp->un.ulpWord[4],
4148 					irsp->un.ulpWord[5],
4149 					*(((uint32_t *) irsp) + 6),
4150 					*(((uint32_t *) irsp) + 7),
4151 					*(((uint32_t *) irsp) + 8),
4152 					*(((uint32_t *) irsp) + 9),
4153 					*(((uint32_t *) irsp) + 10),
4154 					*(((uint32_t *) irsp) + 11),
4155 					*(((uint32_t *) irsp) + 12),
4156 					*(((uint32_t *) irsp) + 13),
4157 					*(((uint32_t *) irsp) + 14),
4158 					*(((uint32_t *) irsp) + 15));
4159 		}
4160 
4161 		/*
4162 		 * Fetch the IOCB command type and call the correct completion
4163 		 * routine. Solicited and Unsolicited IOCBs on the ELS ring
4164 		 * get freed back to the lpfc_iocb_list by the discovery
4165 		 * kernel thread.
4166 		 */
4167 		iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
4168 		type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
4169 		switch (type) {
4170 		case LPFC_SOL_IOCB:
4171 			spin_unlock_irqrestore(&phba->hbalock, iflag);
4172 			rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
4173 			spin_lock_irqsave(&phba->hbalock, iflag);
4174 			break;
4175 
4176 		case LPFC_UNSOL_IOCB:
4177 			spin_unlock_irqrestore(&phba->hbalock, iflag);
4178 			rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
4179 			spin_lock_irqsave(&phba->hbalock, iflag);
4180 			if (!rc)
4181 				free_saveq = 0;
4182 			break;
4183 
4184 		case LPFC_ABORT_IOCB:
4185 			cmdiocbp = NULL;
4186 			if (irsp->ulpCommand != CMD_XRI_ABORTED_CX) {
4187 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4188 				cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
4189 								 saveq);
4190 				spin_lock_irqsave(&phba->hbalock, iflag);
4191 			}
4192 			if (cmdiocbp) {
4193 				/* Call the specified completion routine */
4194 				if (cmdiocbp->iocb_cmpl) {
4195 					spin_unlock_irqrestore(&phba->hbalock,
4196 							       iflag);
4197 					(cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
4198 							      saveq);
4199 					spin_lock_irqsave(&phba->hbalock,
4200 							  iflag);
4201 				} else
4202 					__lpfc_sli_release_iocbq(phba,
4203 								 cmdiocbp);
4204 			}
4205 			break;
4206 
4207 		case LPFC_UNKNOWN_IOCB:
4208 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
4209 				char adaptermsg[LPFC_MAX_ADPTMSG];
4210 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4211 				memcpy(&adaptermsg[0], (uint8_t *)irsp,
4212 				       MAX_MSG_DATA);
4213 				dev_warn(&((phba->pcidev)->dev),
4214 					 "lpfc%d: %s\n",
4215 					 phba->brd_no, adaptermsg);
4216 			} else {
4217 				/* Unknown IOCB command */
4218 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4219 						"0335 Unknown IOCB "
4220 						"command Data: x%x "
4221 						"x%x x%x x%x\n",
4222 						irsp->ulpCommand,
4223 						irsp->ulpStatus,
4224 						irsp->ulpIoTag,
4225 						irsp->ulpContext);
4226 			}
4227 			break;
4228 		}
4229 
4230 		if (free_saveq) {
4231 			list_for_each_entry_safe(rspiocbp, next_iocb,
4232 						 &saveq->list, list) {
4233 				list_del_init(&rspiocbp->list);
4234 				__lpfc_sli_release_iocbq(phba, rspiocbp);
4235 			}
4236 			__lpfc_sli_release_iocbq(phba, saveq);
4237 		}
4238 		rspiocbp = NULL;
4239 	}
4240 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4241 	return rspiocbp;
4242 }
4243 
4244 /**
4245  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
4246  * @phba: Pointer to HBA context object.
4247  * @pring: Pointer to driver SLI ring object.
4248  * @mask: Host attention register mask for this ring.
4249  *
4250  * This routine wraps the actual slow_ring event process routine from the
4251  * API jump table function pointer from the lpfc_hba struct.
4252  **/
4253 void
4254 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
4255 				struct lpfc_sli_ring *pring, uint32_t mask)
4256 {
4257 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
4258 }
4259 
4260 /**
4261  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
4262  * @phba: Pointer to HBA context object.
4263  * @pring: Pointer to driver SLI ring object.
4264  * @mask: Host attention register mask for this ring.
4265  *
4266  * This function is called from the worker thread when there is a ring event
4267  * for non-fcp rings. The caller does not hold any lock. The function will
4268  * remove each response iocb in the response ring and calls the handle
4269  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4270  **/
4271 static void
4272 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
4273 				   struct lpfc_sli_ring *pring, uint32_t mask)
4274 {
4275 	struct lpfc_pgp *pgp;
4276 	IOCB_t *entry;
4277 	IOCB_t *irsp = NULL;
4278 	struct lpfc_iocbq *rspiocbp = NULL;
4279 	uint32_t portRspPut, portRspMax;
4280 	unsigned long iflag;
4281 	uint32_t status;
4282 
4283 	pgp = &phba->port_gp[pring->ringno];
4284 	spin_lock_irqsave(&phba->hbalock, iflag);
4285 	pring->stats.iocb_event++;
4286 
4287 	/*
4288 	 * The next available response entry should never exceed the maximum
4289 	 * entries.  If it does, treat it as an adapter hardware error.
4290 	 */
4291 	portRspMax = pring->sli.sli3.numRiocb;
4292 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4293 	if (portRspPut >= portRspMax) {
4294 		/*
4295 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
4296 		 * rsp ring <portRspMax>
4297 		 */
4298 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4299 				"0303 Ring %d handler: portRspPut %d "
4300 				"is bigger than rsp ring %d\n",
4301 				pring->ringno, portRspPut, portRspMax);
4302 
4303 		phba->link_state = LPFC_HBA_ERROR;
4304 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4305 
4306 		phba->work_hs = HS_FFER3;
4307 		lpfc_handle_eratt(phba);
4308 
4309 		return;
4310 	}
4311 
4312 	rmb();
4313 	while (pring->sli.sli3.rspidx != portRspPut) {
4314 		/*
4315 		 * Build a completion list and call the appropriate handler.
4316 		 * The process is to get the next available response iocb, get
4317 		 * a free iocb from the list, copy the response data into the
4318 		 * free iocb, insert to the continuation list, and update the
4319 		 * next response index to slim.  This process makes response
4320 		 * iocb's in the ring available to DMA as fast as possible but
4321 		 * pays a penalty for a copy operation.  Since the iocb is
4322 		 * only 32 bytes, this penalty is considered small relative to
4323 		 * the PCI reads for register values and a slim write.  When
4324 		 * the ulpLe field is set, the entire Command has been
4325 		 * received.
4326 		 */
4327 		entry = lpfc_resp_iocb(phba, pring);
4328 
4329 		phba->last_completion_time = jiffies;
4330 		rspiocbp = __lpfc_sli_get_iocbq(phba);
4331 		if (rspiocbp == NULL) {
4332 			printk(KERN_ERR "%s: out of buffers! Failing "
4333 			       "completion.\n", __func__);
4334 			break;
4335 		}
4336 
4337 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
4338 				      phba->iocb_rsp_size);
4339 		irsp = &rspiocbp->iocb;
4340 
4341 		if (++pring->sli.sli3.rspidx >= portRspMax)
4342 			pring->sli.sli3.rspidx = 0;
4343 
4344 		if (pring->ringno == LPFC_ELS_RING) {
4345 			lpfc_debugfs_slow_ring_trc(phba,
4346 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
4347 				*(((uint32_t *) irsp) + 4),
4348 				*(((uint32_t *) irsp) + 6),
4349 				*(((uint32_t *) irsp) + 7));
4350 		}
4351 
4352 		writel(pring->sli.sli3.rspidx,
4353 			&phba->host_gp[pring->ringno].rspGetInx);
4354 
4355 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4356 		/* Handle the response IOCB */
4357 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
4358 		spin_lock_irqsave(&phba->hbalock, iflag);
4359 
4360 		/*
4361 		 * If the port response put pointer has not been updated, sync
4362 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
4363 		 * response put pointer.
4364 		 */
4365 		if (pring->sli.sli3.rspidx == portRspPut) {
4366 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4367 		}
4368 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
4369 
4370 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
4371 		/* At least one response entry has been freed */
4372 		pring->stats.iocb_rsp_full++;
4373 		/* SET RxRE_RSP in Chip Att register */
4374 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4375 		writel(status, phba->CAregaddr);
4376 		readl(phba->CAregaddr); /* flush */
4377 	}
4378 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4379 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4380 		pring->stats.iocb_cmd_empty++;
4381 
4382 		/* Force update of the local copy of cmdGetInx */
4383 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4384 		lpfc_sli_resume_iocb(phba, pring);
4385 
4386 		if ((pring->lpfc_sli_cmd_available))
4387 			(pring->lpfc_sli_cmd_available) (phba, pring);
4388 
4389 	}
4390 
4391 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4392 	return;
4393 }
4394 
4395 /**
4396  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
4397  * @phba: Pointer to HBA context object.
4398  * @pring: Pointer to driver SLI ring object.
4399  * @mask: Host attention register mask for this ring.
4400  *
4401  * This function is called from the worker thread when there is a pending
4402  * ELS response iocb on the driver internal slow-path response iocb worker
4403  * queue. The caller does not hold any lock. The function will remove each
4404  * response iocb from the response worker queue and calls the handle
4405  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4406  **/
4407 static void
4408 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4409 				   struct lpfc_sli_ring *pring, uint32_t mask)
4410 {
4411 	struct lpfc_iocbq *irspiocbq;
4412 	struct hbq_dmabuf *dmabuf;
4413 	struct lpfc_cq_event *cq_event;
4414 	unsigned long iflag;
4415 	int count = 0;
4416 
4417 	spin_lock_irqsave(&phba->hbalock, iflag);
4418 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
4419 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4420 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4421 		/* Get the response iocb from the head of work queue */
4422 		spin_lock_irqsave(&phba->hbalock, iflag);
4423 		list_remove_head(&phba->sli4_hba.sp_queue_event,
4424 				 cq_event, struct lpfc_cq_event, list);
4425 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4426 
4427 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4428 		case CQE_CODE_COMPL_WQE:
4429 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4430 						 cq_event);
4431 			/* Translate ELS WCQE to response IOCBQ */
4432 			irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
4433 								   irspiocbq);
4434 			if (irspiocbq)
4435 				lpfc_sli_sp_handle_rspiocb(phba, pring,
4436 							   irspiocbq);
4437 			count++;
4438 			break;
4439 		case CQE_CODE_RECEIVE:
4440 		case CQE_CODE_RECEIVE_V1:
4441 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
4442 					      cq_event);
4443 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
4444 			count++;
4445 			break;
4446 		default:
4447 			break;
4448 		}
4449 
4450 		/* Limit the number of events to 64 to avoid soft lockups */
4451 		if (count == 64)
4452 			break;
4453 	}
4454 }
4455 
4456 /**
4457  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4458  * @phba: Pointer to HBA context object.
4459  * @pring: Pointer to driver SLI ring object.
4460  *
4461  * This function aborts all iocbs in the given ring and frees all the iocb
4462  * objects in txq. This function issues an abort iocb for all the iocb commands
4463  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4464  * the return of this function. The caller is not required to hold any locks.
4465  **/
4466 void
4467 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4468 {
4469 	LIST_HEAD(completions);
4470 	struct lpfc_iocbq *iocb, *next_iocb;
4471 
4472 	if (pring->ringno == LPFC_ELS_RING) {
4473 		lpfc_fabric_abort_hba(phba);
4474 	}
4475 
4476 	/* Error everything on txq and txcmplq
4477 	 * First do the txq.
4478 	 */
4479 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4480 		spin_lock_irq(&pring->ring_lock);
4481 		list_splice_init(&pring->txq, &completions);
4482 		pring->txq_cnt = 0;
4483 		spin_unlock_irq(&pring->ring_lock);
4484 
4485 		spin_lock_irq(&phba->hbalock);
4486 		/* Next issue ABTS for everything on the txcmplq */
4487 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4488 			lpfc_sli_issue_abort_iotag(phba, pring, iocb, NULL);
4489 		spin_unlock_irq(&phba->hbalock);
4490 	} else {
4491 		spin_lock_irq(&phba->hbalock);
4492 		list_splice_init(&pring->txq, &completions);
4493 		pring->txq_cnt = 0;
4494 
4495 		/* Next issue ABTS for everything on the txcmplq */
4496 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4497 			lpfc_sli_issue_abort_iotag(phba, pring, iocb, NULL);
4498 		spin_unlock_irq(&phba->hbalock);
4499 	}
4500 	/* Make sure HBA is alive */
4501 	lpfc_issue_hb_tmo(phba);
4502 
4503 	/* Cancel all the IOCBs from the completions list */
4504 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
4505 			      IOERR_SLI_ABORTED);
4506 }
4507 
4508 /**
4509  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4510  * @phba: Pointer to HBA context object.
4511  *
4512  * This function aborts all iocbs in FCP rings and frees all the iocb
4513  * objects in txq. This function issues an abort iocb for all the iocb commands
4514  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4515  * the return of this function. The caller is not required to hold any locks.
4516  **/
4517 void
4518 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4519 {
4520 	struct lpfc_sli *psli = &phba->sli;
4521 	struct lpfc_sli_ring  *pring;
4522 	uint32_t i;
4523 
4524 	/* Look on all the FCP Rings for the iotag */
4525 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4526 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4527 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4528 			lpfc_sli_abort_iocb_ring(phba, pring);
4529 		}
4530 	} else {
4531 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4532 		lpfc_sli_abort_iocb_ring(phba, pring);
4533 	}
4534 }
4535 
4536 /**
4537  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4538  * @phba: Pointer to HBA context object.
4539  *
4540  * This function flushes all iocbs in the IO ring and frees all the iocb
4541  * objects in txq and txcmplq. This function will not issue abort iocbs
4542  * for all the iocb commands in txcmplq, they will just be returned with
4543  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4544  * slot has been permanently disabled.
4545  **/
4546 void
4547 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4548 {
4549 	LIST_HEAD(txq);
4550 	LIST_HEAD(txcmplq);
4551 	struct lpfc_sli *psli = &phba->sli;
4552 	struct lpfc_sli_ring  *pring;
4553 	uint32_t i;
4554 	struct lpfc_iocbq *piocb, *next_iocb;
4555 
4556 	spin_lock_irq(&phba->hbalock);
4557 	if (phba->hba_flag & HBA_IOQ_FLUSH ||
4558 	    !phba->sli4_hba.hdwq) {
4559 		spin_unlock_irq(&phba->hbalock);
4560 		return;
4561 	}
4562 	/* Indicate the I/O queues are flushed */
4563 	phba->hba_flag |= HBA_IOQ_FLUSH;
4564 	spin_unlock_irq(&phba->hbalock);
4565 
4566 	/* Look on all the FCP Rings for the iotag */
4567 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4568 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4569 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4570 
4571 			spin_lock_irq(&pring->ring_lock);
4572 			/* Retrieve everything on txq */
4573 			list_splice_init(&pring->txq, &txq);
4574 			list_for_each_entry_safe(piocb, next_iocb,
4575 						 &pring->txcmplq, list)
4576 				piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4577 			/* Retrieve everything on the txcmplq */
4578 			list_splice_init(&pring->txcmplq, &txcmplq);
4579 			pring->txq_cnt = 0;
4580 			pring->txcmplq_cnt = 0;
4581 			spin_unlock_irq(&pring->ring_lock);
4582 
4583 			/* Flush the txq */
4584 			lpfc_sli_cancel_iocbs(phba, &txq,
4585 					      IOSTAT_LOCAL_REJECT,
4586 					      IOERR_SLI_DOWN);
4587 			/* Flush the txcmplq */
4588 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4589 					      IOSTAT_LOCAL_REJECT,
4590 					      IOERR_SLI_DOWN);
4591 			if (unlikely(pci_channel_offline(phba->pcidev)))
4592 				lpfc_sli4_io_xri_aborted(phba, NULL, 0);
4593 		}
4594 	} else {
4595 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4596 
4597 		spin_lock_irq(&phba->hbalock);
4598 		/* Retrieve everything on txq */
4599 		list_splice_init(&pring->txq, &txq);
4600 		list_for_each_entry_safe(piocb, next_iocb,
4601 					 &pring->txcmplq, list)
4602 			piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4603 		/* Retrieve everything on the txcmplq */
4604 		list_splice_init(&pring->txcmplq, &txcmplq);
4605 		pring->txq_cnt = 0;
4606 		pring->txcmplq_cnt = 0;
4607 		spin_unlock_irq(&phba->hbalock);
4608 
4609 		/* Flush the txq */
4610 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4611 				      IOERR_SLI_DOWN);
4612 		/* Flush the txcmpq */
4613 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4614 				      IOERR_SLI_DOWN);
4615 	}
4616 }
4617 
4618 /**
4619  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4620  * @phba: Pointer to HBA context object.
4621  * @mask: Bit mask to be checked.
4622  *
4623  * This function reads the host status register and compares
4624  * with the provided bit mask to check if HBA completed
4625  * the restart. This function will wait in a loop for the
4626  * HBA to complete restart. If the HBA does not restart within
4627  * 15 iterations, the function will reset the HBA again. The
4628  * function returns 1 when HBA fail to restart otherwise returns
4629  * zero.
4630  **/
4631 static int
4632 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4633 {
4634 	uint32_t status;
4635 	int i = 0;
4636 	int retval = 0;
4637 
4638 	/* Read the HBA Host Status Register */
4639 	if (lpfc_readl(phba->HSregaddr, &status))
4640 		return 1;
4641 
4642 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4643 
4644 	/*
4645 	 * Check status register every 100ms for 5 retries, then every
4646 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4647 	 * every 2.5 sec for 4.
4648 	 * Break our of the loop if errors occurred during init.
4649 	 */
4650 	while (((status & mask) != mask) &&
4651 	       !(status & HS_FFERM) &&
4652 	       i++ < 20) {
4653 
4654 		if (i <= 5)
4655 			msleep(10);
4656 		else if (i <= 10)
4657 			msleep(500);
4658 		else
4659 			msleep(2500);
4660 
4661 		if (i == 15) {
4662 				/* Do post */
4663 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4664 			lpfc_sli_brdrestart(phba);
4665 		}
4666 		/* Read the HBA Host Status Register */
4667 		if (lpfc_readl(phba->HSregaddr, &status)) {
4668 			retval = 1;
4669 			break;
4670 		}
4671 	}
4672 
4673 	/* Check to see if any errors occurred during init */
4674 	if ((status & HS_FFERM) || (i >= 20)) {
4675 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4676 				"2751 Adapter failed to restart, "
4677 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4678 				status,
4679 				readl(phba->MBslimaddr + 0xa8),
4680 				readl(phba->MBslimaddr + 0xac));
4681 		phba->link_state = LPFC_HBA_ERROR;
4682 		retval = 1;
4683 	}
4684 
4685 	return retval;
4686 }
4687 
4688 /**
4689  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4690  * @phba: Pointer to HBA context object.
4691  * @mask: Bit mask to be checked.
4692  *
4693  * This function checks the host status register to check if HBA is
4694  * ready. This function will wait in a loop for the HBA to be ready
4695  * If the HBA is not ready , the function will will reset the HBA PCI
4696  * function again. The function returns 1 when HBA fail to be ready
4697  * otherwise returns zero.
4698  **/
4699 static int
4700 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4701 {
4702 	uint32_t status;
4703 	int retval = 0;
4704 
4705 	/* Read the HBA Host Status Register */
4706 	status = lpfc_sli4_post_status_check(phba);
4707 
4708 	if (status) {
4709 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4710 		lpfc_sli_brdrestart(phba);
4711 		status = lpfc_sli4_post_status_check(phba);
4712 	}
4713 
4714 	/* Check to see if any errors occurred during init */
4715 	if (status) {
4716 		phba->link_state = LPFC_HBA_ERROR;
4717 		retval = 1;
4718 	} else
4719 		phba->sli4_hba.intr_enable = 0;
4720 
4721 	phba->hba_flag &= ~HBA_SETUP;
4722 	return retval;
4723 }
4724 
4725 /**
4726  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4727  * @phba: Pointer to HBA context object.
4728  * @mask: Bit mask to be checked.
4729  *
4730  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4731  * from the API jump table function pointer from the lpfc_hba struct.
4732  **/
4733 int
4734 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4735 {
4736 	return phba->lpfc_sli_brdready(phba, mask);
4737 }
4738 
4739 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4740 
4741 /**
4742  * lpfc_reset_barrier - Make HBA ready for HBA reset
4743  * @phba: Pointer to HBA context object.
4744  *
4745  * This function is called before resetting an HBA. This function is called
4746  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4747  **/
4748 void lpfc_reset_barrier(struct lpfc_hba *phba)
4749 {
4750 	uint32_t __iomem *resp_buf;
4751 	uint32_t __iomem *mbox_buf;
4752 	volatile uint32_t mbox;
4753 	uint32_t hc_copy, ha_copy, resp_data;
4754 	int  i;
4755 	uint8_t hdrtype;
4756 
4757 	lockdep_assert_held(&phba->hbalock);
4758 
4759 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4760 	if (hdrtype != 0x80 ||
4761 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4762 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4763 		return;
4764 
4765 	/*
4766 	 * Tell the other part of the chip to suspend temporarily all
4767 	 * its DMA activity.
4768 	 */
4769 	resp_buf = phba->MBslimaddr;
4770 
4771 	/* Disable the error attention */
4772 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4773 		return;
4774 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4775 	readl(phba->HCregaddr); /* flush */
4776 	phba->link_flag |= LS_IGNORE_ERATT;
4777 
4778 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4779 		return;
4780 	if (ha_copy & HA_ERATT) {
4781 		/* Clear Chip error bit */
4782 		writel(HA_ERATT, phba->HAregaddr);
4783 		phba->pport->stopped = 1;
4784 	}
4785 
4786 	mbox = 0;
4787 	((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
4788 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
4789 
4790 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4791 	mbox_buf = phba->MBslimaddr;
4792 	writel(mbox, mbox_buf);
4793 
4794 	for (i = 0; i < 50; i++) {
4795 		if (lpfc_readl((resp_buf + 1), &resp_data))
4796 			return;
4797 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4798 			mdelay(1);
4799 		else
4800 			break;
4801 	}
4802 	resp_data = 0;
4803 	if (lpfc_readl((resp_buf + 1), &resp_data))
4804 		return;
4805 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4806 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4807 		    phba->pport->stopped)
4808 			goto restore_hc;
4809 		else
4810 			goto clear_errat;
4811 	}
4812 
4813 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
4814 	resp_data = 0;
4815 	for (i = 0; i < 500; i++) {
4816 		if (lpfc_readl(resp_buf, &resp_data))
4817 			return;
4818 		if (resp_data != mbox)
4819 			mdelay(1);
4820 		else
4821 			break;
4822 	}
4823 
4824 clear_errat:
4825 
4826 	while (++i < 500) {
4827 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4828 			return;
4829 		if (!(ha_copy & HA_ERATT))
4830 			mdelay(1);
4831 		else
4832 			break;
4833 	}
4834 
4835 	if (readl(phba->HAregaddr) & HA_ERATT) {
4836 		writel(HA_ERATT, phba->HAregaddr);
4837 		phba->pport->stopped = 1;
4838 	}
4839 
4840 restore_hc:
4841 	phba->link_flag &= ~LS_IGNORE_ERATT;
4842 	writel(hc_copy, phba->HCregaddr);
4843 	readl(phba->HCregaddr); /* flush */
4844 }
4845 
4846 /**
4847  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4848  * @phba: Pointer to HBA context object.
4849  *
4850  * This function issues a kill_board mailbox command and waits for
4851  * the error attention interrupt. This function is called for stopping
4852  * the firmware processing. The caller is not required to hold any
4853  * locks. This function calls lpfc_hba_down_post function to free
4854  * any pending commands after the kill. The function will return 1 when it
4855  * fails to kill the board else will return 0.
4856  **/
4857 int
4858 lpfc_sli_brdkill(struct lpfc_hba *phba)
4859 {
4860 	struct lpfc_sli *psli;
4861 	LPFC_MBOXQ_t *pmb;
4862 	uint32_t status;
4863 	uint32_t ha_copy;
4864 	int retval;
4865 	int i = 0;
4866 
4867 	psli = &phba->sli;
4868 
4869 	/* Kill HBA */
4870 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4871 			"0329 Kill HBA Data: x%x x%x\n",
4872 			phba->pport->port_state, psli->sli_flag);
4873 
4874 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4875 	if (!pmb)
4876 		return 1;
4877 
4878 	/* Disable the error attention */
4879 	spin_lock_irq(&phba->hbalock);
4880 	if (lpfc_readl(phba->HCregaddr, &status)) {
4881 		spin_unlock_irq(&phba->hbalock);
4882 		mempool_free(pmb, phba->mbox_mem_pool);
4883 		return 1;
4884 	}
4885 	status &= ~HC_ERINT_ENA;
4886 	writel(status, phba->HCregaddr);
4887 	readl(phba->HCregaddr); /* flush */
4888 	phba->link_flag |= LS_IGNORE_ERATT;
4889 	spin_unlock_irq(&phba->hbalock);
4890 
4891 	lpfc_kill_board(phba, pmb);
4892 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4893 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4894 
4895 	if (retval != MBX_SUCCESS) {
4896 		if (retval != MBX_BUSY)
4897 			mempool_free(pmb, phba->mbox_mem_pool);
4898 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4899 				"2752 KILL_BOARD command failed retval %d\n",
4900 				retval);
4901 		spin_lock_irq(&phba->hbalock);
4902 		phba->link_flag &= ~LS_IGNORE_ERATT;
4903 		spin_unlock_irq(&phba->hbalock);
4904 		return 1;
4905 	}
4906 
4907 	spin_lock_irq(&phba->hbalock);
4908 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
4909 	spin_unlock_irq(&phba->hbalock);
4910 
4911 	mempool_free(pmb, phba->mbox_mem_pool);
4912 
4913 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
4914 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
4915 	 * 3 seconds we still set HBA_ERROR state because the status of the
4916 	 * board is now undefined.
4917 	 */
4918 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4919 		return 1;
4920 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
4921 		mdelay(100);
4922 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4923 			return 1;
4924 	}
4925 
4926 	del_timer_sync(&psli->mbox_tmo);
4927 	if (ha_copy & HA_ERATT) {
4928 		writel(HA_ERATT, phba->HAregaddr);
4929 		phba->pport->stopped = 1;
4930 	}
4931 	spin_lock_irq(&phba->hbalock);
4932 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4933 	psli->mbox_active = NULL;
4934 	phba->link_flag &= ~LS_IGNORE_ERATT;
4935 	spin_unlock_irq(&phba->hbalock);
4936 
4937 	lpfc_hba_down_post(phba);
4938 	phba->link_state = LPFC_HBA_ERROR;
4939 
4940 	return ha_copy & HA_ERATT ? 0 : 1;
4941 }
4942 
4943 /**
4944  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
4945  * @phba: Pointer to HBA context object.
4946  *
4947  * This function resets the HBA by writing HC_INITFF to the control
4948  * register. After the HBA resets, this function resets all the iocb ring
4949  * indices. This function disables PCI layer parity checking during
4950  * the reset.
4951  * This function returns 0 always.
4952  * The caller is not required to hold any locks.
4953  **/
4954 int
4955 lpfc_sli_brdreset(struct lpfc_hba *phba)
4956 {
4957 	struct lpfc_sli *psli;
4958 	struct lpfc_sli_ring *pring;
4959 	uint16_t cfg_value;
4960 	int i;
4961 
4962 	psli = &phba->sli;
4963 
4964 	/* Reset HBA */
4965 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4966 			"0325 Reset HBA Data: x%x x%x\n",
4967 			(phba->pport) ? phba->pport->port_state : 0,
4968 			psli->sli_flag);
4969 
4970 	/* perform board reset */
4971 	phba->fc_eventTag = 0;
4972 	phba->link_events = 0;
4973 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4974 	if (phba->pport) {
4975 		phba->pport->fc_myDID = 0;
4976 		phba->pport->fc_prevDID = 0;
4977 	}
4978 
4979 	/* Turn off parity checking and serr during the physical reset */
4980 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
4981 		return -EIO;
4982 
4983 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
4984 			      (cfg_value &
4985 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4986 
4987 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4988 
4989 	/* Now toggle INITFF bit in the Host Control Register */
4990 	writel(HC_INITFF, phba->HCregaddr);
4991 	mdelay(1);
4992 	readl(phba->HCregaddr); /* flush */
4993 	writel(0, phba->HCregaddr);
4994 	readl(phba->HCregaddr); /* flush */
4995 
4996 	/* Restore PCI cmd register */
4997 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4998 
4999 	/* Initialize relevant SLI info */
5000 	for (i = 0; i < psli->num_rings; i++) {
5001 		pring = &psli->sli3_ring[i];
5002 		pring->flag = 0;
5003 		pring->sli.sli3.rspidx = 0;
5004 		pring->sli.sli3.next_cmdidx  = 0;
5005 		pring->sli.sli3.local_getidx = 0;
5006 		pring->sli.sli3.cmdidx = 0;
5007 		pring->missbufcnt = 0;
5008 	}
5009 
5010 	phba->link_state = LPFC_WARM_START;
5011 	return 0;
5012 }
5013 
5014 /**
5015  * lpfc_sli4_brdreset - Reset a sli-4 HBA
5016  * @phba: Pointer to HBA context object.
5017  *
5018  * This function resets a SLI4 HBA. This function disables PCI layer parity
5019  * checking during resets the device. The caller is not required to hold
5020  * any locks.
5021  *
5022  * This function returns 0 on success else returns negative error code.
5023  **/
5024 int
5025 lpfc_sli4_brdreset(struct lpfc_hba *phba)
5026 {
5027 	struct lpfc_sli *psli = &phba->sli;
5028 	uint16_t cfg_value;
5029 	int rc = 0;
5030 
5031 	/* Reset HBA */
5032 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5033 			"0295 Reset HBA Data: x%x x%x x%x\n",
5034 			phba->pport->port_state, psli->sli_flag,
5035 			phba->hba_flag);
5036 
5037 	/* perform board reset */
5038 	phba->fc_eventTag = 0;
5039 	phba->link_events = 0;
5040 	phba->pport->fc_myDID = 0;
5041 	phba->pport->fc_prevDID = 0;
5042 	phba->hba_flag &= ~HBA_SETUP;
5043 
5044 	spin_lock_irq(&phba->hbalock);
5045 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
5046 	phba->fcf.fcf_flag = 0;
5047 	spin_unlock_irq(&phba->hbalock);
5048 
5049 	/* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
5050 	if (phba->hba_flag & HBA_FW_DUMP_OP) {
5051 		phba->hba_flag &= ~HBA_FW_DUMP_OP;
5052 		return rc;
5053 	}
5054 
5055 	/* Now physically reset the device */
5056 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5057 			"0389 Performing PCI function reset!\n");
5058 
5059 	/* Turn off parity checking and serr during the physical reset */
5060 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
5061 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5062 				"3205 PCI read Config failed\n");
5063 		return -EIO;
5064 	}
5065 
5066 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
5067 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5068 
5069 	/* Perform FCoE PCI function reset before freeing queue memory */
5070 	rc = lpfc_pci_function_reset(phba);
5071 
5072 	/* Restore PCI cmd register */
5073 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5074 
5075 	return rc;
5076 }
5077 
5078 /**
5079  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
5080  * @phba: Pointer to HBA context object.
5081  *
5082  * This function is called in the SLI initialization code path to
5083  * restart the HBA. The caller is not required to hold any lock.
5084  * This function writes MBX_RESTART mailbox command to the SLIM and
5085  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
5086  * function to free any pending commands. The function enables
5087  * POST only during the first initialization. The function returns zero.
5088  * The function does not guarantee completion of MBX_RESTART mailbox
5089  * command before the return of this function.
5090  **/
5091 static int
5092 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
5093 {
5094 	MAILBOX_t *mb;
5095 	struct lpfc_sli *psli;
5096 	volatile uint32_t word0;
5097 	void __iomem *to_slim;
5098 	uint32_t hba_aer_enabled;
5099 
5100 	spin_lock_irq(&phba->hbalock);
5101 
5102 	/* Take PCIe device Advanced Error Reporting (AER) state */
5103 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
5104 
5105 	psli = &phba->sli;
5106 
5107 	/* Restart HBA */
5108 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5109 			"0337 Restart HBA Data: x%x x%x\n",
5110 			(phba->pport) ? phba->pport->port_state : 0,
5111 			psli->sli_flag);
5112 
5113 	word0 = 0;
5114 	mb = (MAILBOX_t *) &word0;
5115 	mb->mbxCommand = MBX_RESTART;
5116 	mb->mbxHc = 1;
5117 
5118 	lpfc_reset_barrier(phba);
5119 
5120 	to_slim = phba->MBslimaddr;
5121 	writel(*(uint32_t *) mb, to_slim);
5122 	readl(to_slim); /* flush */
5123 
5124 	/* Only skip post after fc_ffinit is completed */
5125 	if (phba->pport && phba->pport->port_state)
5126 		word0 = 1;	/* This is really setting up word1 */
5127 	else
5128 		word0 = 0;	/* This is really setting up word1 */
5129 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
5130 	writel(*(uint32_t *) mb, to_slim);
5131 	readl(to_slim); /* flush */
5132 
5133 	lpfc_sli_brdreset(phba);
5134 	if (phba->pport)
5135 		phba->pport->stopped = 0;
5136 	phba->link_state = LPFC_INIT_START;
5137 	phba->hba_flag = 0;
5138 	spin_unlock_irq(&phba->hbalock);
5139 
5140 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5141 	psli->stats_start = ktime_get_seconds();
5142 
5143 	/* Give the INITFF and Post time to settle. */
5144 	mdelay(100);
5145 
5146 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
5147 	if (hba_aer_enabled)
5148 		pci_disable_pcie_error_reporting(phba->pcidev);
5149 
5150 	lpfc_hba_down_post(phba);
5151 
5152 	return 0;
5153 }
5154 
5155 /**
5156  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
5157  * @phba: Pointer to HBA context object.
5158  *
5159  * This function is called in the SLI initialization code path to restart
5160  * a SLI4 HBA. The caller is not required to hold any lock.
5161  * At the end of the function, it calls lpfc_hba_down_post function to
5162  * free any pending commands.
5163  **/
5164 static int
5165 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
5166 {
5167 	struct lpfc_sli *psli = &phba->sli;
5168 	uint32_t hba_aer_enabled;
5169 	int rc;
5170 
5171 	/* Restart HBA */
5172 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5173 			"0296 Restart HBA Data: x%x x%x\n",
5174 			phba->pport->port_state, psli->sli_flag);
5175 
5176 	/* Take PCIe device Advanced Error Reporting (AER) state */
5177 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
5178 
5179 	rc = lpfc_sli4_brdreset(phba);
5180 	if (rc) {
5181 		phba->link_state = LPFC_HBA_ERROR;
5182 		goto hba_down_queue;
5183 	}
5184 
5185 	spin_lock_irq(&phba->hbalock);
5186 	phba->pport->stopped = 0;
5187 	phba->link_state = LPFC_INIT_START;
5188 	phba->hba_flag = 0;
5189 	spin_unlock_irq(&phba->hbalock);
5190 
5191 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5192 	psli->stats_start = ktime_get_seconds();
5193 
5194 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
5195 	if (hba_aer_enabled)
5196 		pci_disable_pcie_error_reporting(phba->pcidev);
5197 
5198 hba_down_queue:
5199 	lpfc_hba_down_post(phba);
5200 	lpfc_sli4_queue_destroy(phba);
5201 
5202 	return rc;
5203 }
5204 
5205 /**
5206  * lpfc_sli_brdrestart - Wrapper func for restarting hba
5207  * @phba: Pointer to HBA context object.
5208  *
5209  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
5210  * API jump table function pointer from the lpfc_hba struct.
5211 **/
5212 int
5213 lpfc_sli_brdrestart(struct lpfc_hba *phba)
5214 {
5215 	return phba->lpfc_sli_brdrestart(phba);
5216 }
5217 
5218 /**
5219  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
5220  * @phba: Pointer to HBA context object.
5221  *
5222  * This function is called after a HBA restart to wait for successful
5223  * restart of the HBA. Successful restart of the HBA is indicated by
5224  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
5225  * iteration, the function will restart the HBA again. The function returns
5226  * zero if HBA successfully restarted else returns negative error code.
5227  **/
5228 int
5229 lpfc_sli_chipset_init(struct lpfc_hba *phba)
5230 {
5231 	uint32_t status, i = 0;
5232 
5233 	/* Read the HBA Host Status Register */
5234 	if (lpfc_readl(phba->HSregaddr, &status))
5235 		return -EIO;
5236 
5237 	/* Check status register to see what current state is */
5238 	i = 0;
5239 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
5240 
5241 		/* Check every 10ms for 10 retries, then every 100ms for 90
5242 		 * retries, then every 1 sec for 50 retires for a total of
5243 		 * ~60 seconds before reset the board again and check every
5244 		 * 1 sec for 50 retries. The up to 60 seconds before the
5245 		 * board ready is required by the Falcon FIPS zeroization
5246 		 * complete, and any reset the board in between shall cause
5247 		 * restart of zeroization, further delay the board ready.
5248 		 */
5249 		if (i++ >= 200) {
5250 			/* Adapter failed to init, timeout, status reg
5251 			   <status> */
5252 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5253 					"0436 Adapter failed to init, "
5254 					"timeout, status reg x%x, "
5255 					"FW Data: A8 x%x AC x%x\n", status,
5256 					readl(phba->MBslimaddr + 0xa8),
5257 					readl(phba->MBslimaddr + 0xac));
5258 			phba->link_state = LPFC_HBA_ERROR;
5259 			return -ETIMEDOUT;
5260 		}
5261 
5262 		/* Check to see if any errors occurred during init */
5263 		if (status & HS_FFERM) {
5264 			/* ERROR: During chipset initialization */
5265 			/* Adapter failed to init, chipset, status reg
5266 			   <status> */
5267 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5268 					"0437 Adapter failed to init, "
5269 					"chipset, status reg x%x, "
5270 					"FW Data: A8 x%x AC x%x\n", status,
5271 					readl(phba->MBslimaddr + 0xa8),
5272 					readl(phba->MBslimaddr + 0xac));
5273 			phba->link_state = LPFC_HBA_ERROR;
5274 			return -EIO;
5275 		}
5276 
5277 		if (i <= 10)
5278 			msleep(10);
5279 		else if (i <= 100)
5280 			msleep(100);
5281 		else
5282 			msleep(1000);
5283 
5284 		if (i == 150) {
5285 			/* Do post */
5286 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5287 			lpfc_sli_brdrestart(phba);
5288 		}
5289 		/* Read the HBA Host Status Register */
5290 		if (lpfc_readl(phba->HSregaddr, &status))
5291 			return -EIO;
5292 	}
5293 
5294 	/* Check to see if any errors occurred during init */
5295 	if (status & HS_FFERM) {
5296 		/* ERROR: During chipset initialization */
5297 		/* Adapter failed to init, chipset, status reg <status> */
5298 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5299 				"0438 Adapter failed to init, chipset, "
5300 				"status reg x%x, "
5301 				"FW Data: A8 x%x AC x%x\n", status,
5302 				readl(phba->MBslimaddr + 0xa8),
5303 				readl(phba->MBslimaddr + 0xac));
5304 		phba->link_state = LPFC_HBA_ERROR;
5305 		return -EIO;
5306 	}
5307 
5308 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5309 
5310 	/* Clear all interrupt enable conditions */
5311 	writel(0, phba->HCregaddr);
5312 	readl(phba->HCregaddr); /* flush */
5313 
5314 	/* setup host attn register */
5315 	writel(0xffffffff, phba->HAregaddr);
5316 	readl(phba->HAregaddr); /* flush */
5317 	return 0;
5318 }
5319 
5320 /**
5321  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5322  *
5323  * This function calculates and returns the number of HBQs required to be
5324  * configured.
5325  **/
5326 int
5327 lpfc_sli_hbq_count(void)
5328 {
5329 	return ARRAY_SIZE(lpfc_hbq_defs);
5330 }
5331 
5332 /**
5333  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5334  *
5335  * This function adds the number of hbq entries in every HBQ to get
5336  * the total number of hbq entries required for the HBA and returns
5337  * the total count.
5338  **/
5339 static int
5340 lpfc_sli_hbq_entry_count(void)
5341 {
5342 	int  hbq_count = lpfc_sli_hbq_count();
5343 	int  count = 0;
5344 	int  i;
5345 
5346 	for (i = 0; i < hbq_count; ++i)
5347 		count += lpfc_hbq_defs[i]->entry_count;
5348 	return count;
5349 }
5350 
5351 /**
5352  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5353  *
5354  * This function calculates amount of memory required for all hbq entries
5355  * to be configured and returns the total memory required.
5356  **/
5357 int
5358 lpfc_sli_hbq_size(void)
5359 {
5360 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5361 }
5362 
5363 /**
5364  * lpfc_sli_hbq_setup - configure and initialize HBQs
5365  * @phba: Pointer to HBA context object.
5366  *
5367  * This function is called during the SLI initialization to configure
5368  * all the HBQs and post buffers to the HBQ. The caller is not
5369  * required to hold any locks. This function will return zero if successful
5370  * else it will return negative error code.
5371  **/
5372 static int
5373 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5374 {
5375 	int  hbq_count = lpfc_sli_hbq_count();
5376 	LPFC_MBOXQ_t *pmb;
5377 	MAILBOX_t *pmbox;
5378 	uint32_t hbqno;
5379 	uint32_t hbq_entry_index;
5380 
5381 				/* Get a Mailbox buffer to setup mailbox
5382 				 * commands for HBA initialization
5383 				 */
5384 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5385 
5386 	if (!pmb)
5387 		return -ENOMEM;
5388 
5389 	pmbox = &pmb->u.mb;
5390 
5391 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
5392 	phba->link_state = LPFC_INIT_MBX_CMDS;
5393 	phba->hbq_in_use = 1;
5394 
5395 	hbq_entry_index = 0;
5396 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5397 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
5398 		phba->hbqs[hbqno].hbqPutIdx      = 0;
5399 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5400 		phba->hbqs[hbqno].entry_count =
5401 			lpfc_hbq_defs[hbqno]->entry_count;
5402 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5403 			hbq_entry_index, pmb);
5404 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
5405 
5406 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5407 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5408 			   mbxStatus <status>, ring <num> */
5409 
5410 			lpfc_printf_log(phba, KERN_ERR,
5411 					LOG_SLI | LOG_VPORT,
5412 					"1805 Adapter failed to init. "
5413 					"Data: x%x x%x x%x\n",
5414 					pmbox->mbxCommand,
5415 					pmbox->mbxStatus, hbqno);
5416 
5417 			phba->link_state = LPFC_HBA_ERROR;
5418 			mempool_free(pmb, phba->mbox_mem_pool);
5419 			return -ENXIO;
5420 		}
5421 	}
5422 	phba->hbq_count = hbq_count;
5423 
5424 	mempool_free(pmb, phba->mbox_mem_pool);
5425 
5426 	/* Initially populate or replenish the HBQs */
5427 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5428 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5429 	return 0;
5430 }
5431 
5432 /**
5433  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5434  * @phba: Pointer to HBA context object.
5435  *
5436  * This function is called during the SLI initialization to configure
5437  * all the HBQs and post buffers to the HBQ. The caller is not
5438  * required to hold any locks. This function will return zero if successful
5439  * else it will return negative error code.
5440  **/
5441 static int
5442 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5443 {
5444 	phba->hbq_in_use = 1;
5445 	/**
5446 	 * Specific case when the MDS diagnostics is enabled and supported.
5447 	 * The receive buffer count is truncated to manage the incoming
5448 	 * traffic.
5449 	 **/
5450 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5451 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5452 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5453 	else
5454 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5455 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5456 	phba->hbq_count = 1;
5457 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5458 	/* Initially populate or replenish the HBQs */
5459 	return 0;
5460 }
5461 
5462 /**
5463  * lpfc_sli_config_port - Issue config port mailbox command
5464  * @phba: Pointer to HBA context object.
5465  * @sli_mode: sli mode - 2/3
5466  *
5467  * This function is called by the sli initialization code path
5468  * to issue config_port mailbox command. This function restarts the
5469  * HBA firmware and issues a config_port mailbox command to configure
5470  * the SLI interface in the sli mode specified by sli_mode
5471  * variable. The caller is not required to hold any locks.
5472  * The function returns 0 if successful, else returns negative error
5473  * code.
5474  **/
5475 int
5476 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5477 {
5478 	LPFC_MBOXQ_t *pmb;
5479 	uint32_t resetcount = 0, rc = 0, done = 0;
5480 
5481 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5482 	if (!pmb) {
5483 		phba->link_state = LPFC_HBA_ERROR;
5484 		return -ENOMEM;
5485 	}
5486 
5487 	phba->sli_rev = sli_mode;
5488 	while (resetcount < 2 && !done) {
5489 		spin_lock_irq(&phba->hbalock);
5490 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5491 		spin_unlock_irq(&phba->hbalock);
5492 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5493 		lpfc_sli_brdrestart(phba);
5494 		rc = lpfc_sli_chipset_init(phba);
5495 		if (rc)
5496 			break;
5497 
5498 		spin_lock_irq(&phba->hbalock);
5499 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5500 		spin_unlock_irq(&phba->hbalock);
5501 		resetcount++;
5502 
5503 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5504 		 * value of 0 means the call was successful.  Any other
5505 		 * nonzero value is a failure, but if ERESTART is returned,
5506 		 * the driver may reset the HBA and try again.
5507 		 */
5508 		rc = lpfc_config_port_prep(phba);
5509 		if (rc == -ERESTART) {
5510 			phba->link_state = LPFC_LINK_UNKNOWN;
5511 			continue;
5512 		} else if (rc)
5513 			break;
5514 
5515 		phba->link_state = LPFC_INIT_MBX_CMDS;
5516 		lpfc_config_port(phba, pmb);
5517 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5518 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5519 					LPFC_SLI3_HBQ_ENABLED |
5520 					LPFC_SLI3_CRP_ENABLED |
5521 					LPFC_SLI3_DSS_ENABLED);
5522 		if (rc != MBX_SUCCESS) {
5523 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5524 				"0442 Adapter failed to init, mbxCmd x%x "
5525 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5526 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5527 			spin_lock_irq(&phba->hbalock);
5528 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5529 			spin_unlock_irq(&phba->hbalock);
5530 			rc = -ENXIO;
5531 		} else {
5532 			/* Allow asynchronous mailbox command to go through */
5533 			spin_lock_irq(&phba->hbalock);
5534 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5535 			spin_unlock_irq(&phba->hbalock);
5536 			done = 1;
5537 
5538 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5539 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5540 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5541 					"3110 Port did not grant ASABT\n");
5542 		}
5543 	}
5544 	if (!done) {
5545 		rc = -EINVAL;
5546 		goto do_prep_failed;
5547 	}
5548 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5549 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5550 			rc = -ENXIO;
5551 			goto do_prep_failed;
5552 		}
5553 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5554 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5555 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5556 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5557 				phba->max_vpi : phba->max_vports;
5558 
5559 		} else
5560 			phba->max_vpi = 0;
5561 		if (pmb->u.mb.un.varCfgPort.gerbm)
5562 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5563 		if (pmb->u.mb.un.varCfgPort.gcrp)
5564 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5565 
5566 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5567 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5568 
5569 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5570 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5571 				phba->cfg_enable_bg = 0;
5572 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5573 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5574 						"0443 Adapter did not grant "
5575 						"BlockGuard\n");
5576 			}
5577 		}
5578 	} else {
5579 		phba->hbq_get = NULL;
5580 		phba->port_gp = phba->mbox->us.s2.port;
5581 		phba->max_vpi = 0;
5582 	}
5583 do_prep_failed:
5584 	mempool_free(pmb, phba->mbox_mem_pool);
5585 	return rc;
5586 }
5587 
5588 
5589 /**
5590  * lpfc_sli_hba_setup - SLI initialization function
5591  * @phba: Pointer to HBA context object.
5592  *
5593  * This function is the main SLI initialization function. This function
5594  * is called by the HBA initialization code, HBA reset code and HBA
5595  * error attention handler code. Caller is not required to hold any
5596  * locks. This function issues config_port mailbox command to configure
5597  * the SLI, setup iocb rings and HBQ rings. In the end the function
5598  * calls the config_port_post function to issue init_link mailbox
5599  * command and to start the discovery. The function will return zero
5600  * if successful, else it will return negative error code.
5601  **/
5602 int
5603 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5604 {
5605 	uint32_t rc;
5606 	int  i;
5607 	int longs;
5608 
5609 	/* Enable ISR already does config_port because of config_msi mbx */
5610 	if (phba->hba_flag & HBA_NEEDS_CFG_PORT) {
5611 		rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5612 		if (rc)
5613 			return -EIO;
5614 		phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
5615 	}
5616 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5617 
5618 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
5619 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
5620 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
5621 		if (!rc) {
5622 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5623 					"2709 This device supports "
5624 					"Advanced Error Reporting (AER)\n");
5625 			spin_lock_irq(&phba->hbalock);
5626 			phba->hba_flag |= HBA_AER_ENABLED;
5627 			spin_unlock_irq(&phba->hbalock);
5628 		} else {
5629 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5630 					"2708 This device does not support "
5631 					"Advanced Error Reporting (AER): %d\n",
5632 					rc);
5633 			phba->cfg_aer_support = 0;
5634 		}
5635 	}
5636 
5637 	if (phba->sli_rev == 3) {
5638 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5639 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5640 	} else {
5641 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5642 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5643 		phba->sli3_options = 0;
5644 	}
5645 
5646 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5647 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5648 			phba->sli_rev, phba->max_vpi);
5649 	rc = lpfc_sli_ring_map(phba);
5650 
5651 	if (rc)
5652 		goto lpfc_sli_hba_setup_error;
5653 
5654 	/* Initialize VPIs. */
5655 	if (phba->sli_rev == LPFC_SLI_REV3) {
5656 		/*
5657 		 * The VPI bitmask and physical ID array are allocated
5658 		 * and initialized once only - at driver load.  A port
5659 		 * reset doesn't need to reinitialize this memory.
5660 		 */
5661 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5662 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5663 			phba->vpi_bmask = kcalloc(longs,
5664 						  sizeof(unsigned long),
5665 						  GFP_KERNEL);
5666 			if (!phba->vpi_bmask) {
5667 				rc = -ENOMEM;
5668 				goto lpfc_sli_hba_setup_error;
5669 			}
5670 
5671 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5672 						sizeof(uint16_t),
5673 						GFP_KERNEL);
5674 			if (!phba->vpi_ids) {
5675 				kfree(phba->vpi_bmask);
5676 				rc = -ENOMEM;
5677 				goto lpfc_sli_hba_setup_error;
5678 			}
5679 			for (i = 0; i < phba->max_vpi; i++)
5680 				phba->vpi_ids[i] = i;
5681 		}
5682 	}
5683 
5684 	/* Init HBQs */
5685 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5686 		rc = lpfc_sli_hbq_setup(phba);
5687 		if (rc)
5688 			goto lpfc_sli_hba_setup_error;
5689 	}
5690 	spin_lock_irq(&phba->hbalock);
5691 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5692 	spin_unlock_irq(&phba->hbalock);
5693 
5694 	rc = lpfc_config_port_post(phba);
5695 	if (rc)
5696 		goto lpfc_sli_hba_setup_error;
5697 
5698 	return rc;
5699 
5700 lpfc_sli_hba_setup_error:
5701 	phba->link_state = LPFC_HBA_ERROR;
5702 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5703 			"0445 Firmware initialization failed\n");
5704 	return rc;
5705 }
5706 
5707 /**
5708  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5709  * @phba: Pointer to HBA context object.
5710  *
5711  * This function issue a dump mailbox command to read config region
5712  * 23 and parse the records in the region and populate driver
5713  * data structure.
5714  **/
5715 static int
5716 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5717 {
5718 	LPFC_MBOXQ_t *mboxq;
5719 	struct lpfc_dmabuf *mp;
5720 	struct lpfc_mqe *mqe;
5721 	uint32_t data_length;
5722 	int rc;
5723 
5724 	/* Program the default value of vlan_id and fc_map */
5725 	phba->valid_vlan = 0;
5726 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5727 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5728 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5729 
5730 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5731 	if (!mboxq)
5732 		return -ENOMEM;
5733 
5734 	mqe = &mboxq->u.mqe;
5735 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5736 		rc = -ENOMEM;
5737 		goto out_free_mboxq;
5738 	}
5739 
5740 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5741 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5742 
5743 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5744 			"(%d):2571 Mailbox cmd x%x Status x%x "
5745 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5746 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5747 			"CQ: x%x x%x x%x x%x\n",
5748 			mboxq->vport ? mboxq->vport->vpi : 0,
5749 			bf_get(lpfc_mqe_command, mqe),
5750 			bf_get(lpfc_mqe_status, mqe),
5751 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5752 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5753 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5754 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5755 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5756 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5757 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5758 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5759 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5760 			mboxq->mcqe.word0,
5761 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5762 			mboxq->mcqe.trailer);
5763 
5764 	if (rc) {
5765 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5766 		kfree(mp);
5767 		rc = -EIO;
5768 		goto out_free_mboxq;
5769 	}
5770 	data_length = mqe->un.mb_words[5];
5771 	if (data_length > DMP_RGN23_SIZE) {
5772 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5773 		kfree(mp);
5774 		rc = -EIO;
5775 		goto out_free_mboxq;
5776 	}
5777 
5778 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5779 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
5780 	kfree(mp);
5781 	rc = 0;
5782 
5783 out_free_mboxq:
5784 	mempool_free(mboxq, phba->mbox_mem_pool);
5785 	return rc;
5786 }
5787 
5788 /**
5789  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5790  * @phba: pointer to lpfc hba data structure.
5791  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5792  * @vpd: pointer to the memory to hold resulting port vpd data.
5793  * @vpd_size: On input, the number of bytes allocated to @vpd.
5794  *	      On output, the number of data bytes in @vpd.
5795  *
5796  * This routine executes a READ_REV SLI4 mailbox command.  In
5797  * addition, this routine gets the port vpd data.
5798  *
5799  * Return codes
5800  * 	0 - successful
5801  * 	-ENOMEM - could not allocated memory.
5802  **/
5803 static int
5804 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5805 		    uint8_t *vpd, uint32_t *vpd_size)
5806 {
5807 	int rc = 0;
5808 	uint32_t dma_size;
5809 	struct lpfc_dmabuf *dmabuf;
5810 	struct lpfc_mqe *mqe;
5811 
5812 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5813 	if (!dmabuf)
5814 		return -ENOMEM;
5815 
5816 	/*
5817 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5818 	 * mailbox command.
5819 	 */
5820 	dma_size = *vpd_size;
5821 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5822 					  &dmabuf->phys, GFP_KERNEL);
5823 	if (!dmabuf->virt) {
5824 		kfree(dmabuf);
5825 		return -ENOMEM;
5826 	}
5827 
5828 	/*
5829 	 * The SLI4 implementation of READ_REV conflicts at word1,
5830 	 * bits 31:16 and SLI4 adds vpd functionality not present
5831 	 * in SLI3.  This code corrects the conflicts.
5832 	 */
5833 	lpfc_read_rev(phba, mboxq);
5834 	mqe = &mboxq->u.mqe;
5835 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5836 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5837 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5838 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5839 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5840 
5841 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5842 	if (rc) {
5843 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5844 				  dmabuf->virt, dmabuf->phys);
5845 		kfree(dmabuf);
5846 		return -EIO;
5847 	}
5848 
5849 	/*
5850 	 * The available vpd length cannot be bigger than the
5851 	 * DMA buffer passed to the port.  Catch the less than
5852 	 * case and update the caller's size.
5853 	 */
5854 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5855 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5856 
5857 	memcpy(vpd, dmabuf->virt, *vpd_size);
5858 
5859 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5860 			  dmabuf->virt, dmabuf->phys);
5861 	kfree(dmabuf);
5862 	return 0;
5863 }
5864 
5865 /**
5866  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5867  * @phba: pointer to lpfc hba data structure.
5868  *
5869  * This routine retrieves SLI4 device physical port name this PCI function
5870  * is attached to.
5871  *
5872  * Return codes
5873  *      0 - successful
5874  *      otherwise - failed to retrieve controller attributes
5875  **/
5876 static int
5877 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5878 {
5879 	LPFC_MBOXQ_t *mboxq;
5880 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5881 	struct lpfc_controller_attribute *cntl_attr;
5882 	void *virtaddr = NULL;
5883 	uint32_t alloclen, reqlen;
5884 	uint32_t shdr_status, shdr_add_status;
5885 	union lpfc_sli4_cfg_shdr *shdr;
5886 	int rc;
5887 
5888 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5889 	if (!mboxq)
5890 		return -ENOMEM;
5891 
5892 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5893 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5894 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5895 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5896 			LPFC_SLI4_MBX_NEMBED);
5897 
5898 	if (alloclen < reqlen) {
5899 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5900 				"3084 Allocated DMA memory size (%d) is "
5901 				"less than the requested DMA memory size "
5902 				"(%d)\n", alloclen, reqlen);
5903 		rc = -ENOMEM;
5904 		goto out_free_mboxq;
5905 	}
5906 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5907 	virtaddr = mboxq->sge_array->addr[0];
5908 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5909 	shdr = &mbx_cntl_attr->cfg_shdr;
5910 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5911 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5912 	if (shdr_status || shdr_add_status || rc) {
5913 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5914 				"3085 Mailbox x%x (x%x/x%x) failed, "
5915 				"rc:x%x, status:x%x, add_status:x%x\n",
5916 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5917 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5918 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5919 				rc, shdr_status, shdr_add_status);
5920 		rc = -ENXIO;
5921 		goto out_free_mboxq;
5922 	}
5923 
5924 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5925 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5926 	phba->sli4_hba.lnk_info.lnk_tp =
5927 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5928 	phba->sli4_hba.lnk_info.lnk_no =
5929 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5930 	phba->sli4_hba.flash_id = bf_get(lpfc_cntl_attr_flash_id, cntl_attr);
5931 	phba->sli4_hba.asic_rev = bf_get(lpfc_cntl_attr_asic_rev, cntl_attr);
5932 
5933 	memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
5934 	strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
5935 		sizeof(phba->BIOSVersion));
5936 
5937 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5938 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s, "
5939 			"flash_id: x%02x, asic_rev: x%02x\n",
5940 			phba->sli4_hba.lnk_info.lnk_tp,
5941 			phba->sli4_hba.lnk_info.lnk_no,
5942 			phba->BIOSVersion, phba->sli4_hba.flash_id,
5943 			phba->sli4_hba.asic_rev);
5944 out_free_mboxq:
5945 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5946 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
5947 	else
5948 		mempool_free(mboxq, phba->mbox_mem_pool);
5949 	return rc;
5950 }
5951 
5952 /**
5953  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
5954  * @phba: pointer to lpfc hba data structure.
5955  *
5956  * This routine retrieves SLI4 device physical port name this PCI function
5957  * is attached to.
5958  *
5959  * Return codes
5960  *      0 - successful
5961  *      otherwise - failed to retrieve physical port name
5962  **/
5963 static int
5964 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
5965 {
5966 	LPFC_MBOXQ_t *mboxq;
5967 	struct lpfc_mbx_get_port_name *get_port_name;
5968 	uint32_t shdr_status, shdr_add_status;
5969 	union lpfc_sli4_cfg_shdr *shdr;
5970 	char cport_name = 0;
5971 	int rc;
5972 
5973 	/* We assume nothing at this point */
5974 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5975 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
5976 
5977 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5978 	if (!mboxq)
5979 		return -ENOMEM;
5980 	/* obtain link type and link number via READ_CONFIG */
5981 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5982 	lpfc_sli4_read_config(phba);
5983 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
5984 		goto retrieve_ppname;
5985 
5986 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
5987 	rc = lpfc_sli4_get_ctl_attr(phba);
5988 	if (rc)
5989 		goto out_free_mboxq;
5990 
5991 retrieve_ppname:
5992 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5993 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
5994 		sizeof(struct lpfc_mbx_get_port_name) -
5995 		sizeof(struct lpfc_sli4_cfg_mhdr),
5996 		LPFC_SLI4_MBX_EMBED);
5997 	get_port_name = &mboxq->u.mqe.un.get_port_name;
5998 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5999 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
6000 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
6001 		phba->sli4_hba.lnk_info.lnk_tp);
6002 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6003 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6004 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6005 	if (shdr_status || shdr_add_status || rc) {
6006 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6007 				"3087 Mailbox x%x (x%x/x%x) failed: "
6008 				"rc:x%x, status:x%x, add_status:x%x\n",
6009 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6010 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6011 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6012 				rc, shdr_status, shdr_add_status);
6013 		rc = -ENXIO;
6014 		goto out_free_mboxq;
6015 	}
6016 	switch (phba->sli4_hba.lnk_info.lnk_no) {
6017 	case LPFC_LINK_NUMBER_0:
6018 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
6019 				&get_port_name->u.response);
6020 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6021 		break;
6022 	case LPFC_LINK_NUMBER_1:
6023 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
6024 				&get_port_name->u.response);
6025 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6026 		break;
6027 	case LPFC_LINK_NUMBER_2:
6028 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
6029 				&get_port_name->u.response);
6030 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6031 		break;
6032 	case LPFC_LINK_NUMBER_3:
6033 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
6034 				&get_port_name->u.response);
6035 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6036 		break;
6037 	default:
6038 		break;
6039 	}
6040 
6041 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
6042 		phba->Port[0] = cport_name;
6043 		phba->Port[1] = '\0';
6044 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6045 				"3091 SLI get port name: %s\n", phba->Port);
6046 	}
6047 
6048 out_free_mboxq:
6049 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6050 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6051 	else
6052 		mempool_free(mboxq, phba->mbox_mem_pool);
6053 	return rc;
6054 }
6055 
6056 /**
6057  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
6058  * @phba: pointer to lpfc hba data structure.
6059  *
6060  * This routine is called to explicitly arm the SLI4 device's completion and
6061  * event queues
6062  **/
6063 static void
6064 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
6065 {
6066 	int qidx;
6067 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
6068 	struct lpfc_sli4_hdw_queue *qp;
6069 	struct lpfc_queue *eq;
6070 
6071 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
6072 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
6073 	if (sli4_hba->nvmels_cq)
6074 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
6075 					   LPFC_QUEUE_REARM);
6076 
6077 	if (sli4_hba->hdwq) {
6078 		/* Loop thru all Hardware Queues */
6079 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
6080 			qp = &sli4_hba->hdwq[qidx];
6081 			/* ARM the corresponding CQ */
6082 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
6083 						LPFC_QUEUE_REARM);
6084 		}
6085 
6086 		/* Loop thru all IRQ vectors */
6087 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
6088 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
6089 			/* ARM the corresponding EQ */
6090 			sli4_hba->sli4_write_eq_db(phba, eq,
6091 						   0, LPFC_QUEUE_REARM);
6092 		}
6093 	}
6094 
6095 	if (phba->nvmet_support) {
6096 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
6097 			sli4_hba->sli4_write_cq_db(phba,
6098 				sli4_hba->nvmet_cqset[qidx], 0,
6099 				LPFC_QUEUE_REARM);
6100 		}
6101 	}
6102 }
6103 
6104 /**
6105  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
6106  * @phba: Pointer to HBA context object.
6107  * @type: The resource extent type.
6108  * @extnt_count: buffer to hold port available extent count.
6109  * @extnt_size: buffer to hold element count per extent.
6110  *
6111  * This function calls the port and retrievs the number of available
6112  * extents and their size for a particular extent type.
6113  *
6114  * Returns: 0 if successful.  Nonzero otherwise.
6115  **/
6116 int
6117 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
6118 			       uint16_t *extnt_count, uint16_t *extnt_size)
6119 {
6120 	int rc = 0;
6121 	uint32_t length;
6122 	uint32_t mbox_tmo;
6123 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
6124 	LPFC_MBOXQ_t *mbox;
6125 
6126 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6127 	if (!mbox)
6128 		return -ENOMEM;
6129 
6130 	/* Find out how many extents are available for this resource type */
6131 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
6132 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6133 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6134 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
6135 			 length, LPFC_SLI4_MBX_EMBED);
6136 
6137 	/* Send an extents count of 0 - the GET doesn't use it. */
6138 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6139 					LPFC_SLI4_MBX_EMBED);
6140 	if (unlikely(rc)) {
6141 		rc = -EIO;
6142 		goto err_exit;
6143 	}
6144 
6145 	if (!phba->sli4_hba.intr_enable)
6146 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6147 	else {
6148 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6149 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6150 	}
6151 	if (unlikely(rc)) {
6152 		rc = -EIO;
6153 		goto err_exit;
6154 	}
6155 
6156 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
6157 	if (bf_get(lpfc_mbox_hdr_status,
6158 		   &rsrc_info->header.cfg_shdr.response)) {
6159 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6160 				"2930 Failed to get resource extents "
6161 				"Status 0x%x Add'l Status 0x%x\n",
6162 				bf_get(lpfc_mbox_hdr_status,
6163 				       &rsrc_info->header.cfg_shdr.response),
6164 				bf_get(lpfc_mbox_hdr_add_status,
6165 				       &rsrc_info->header.cfg_shdr.response));
6166 		rc = -EIO;
6167 		goto err_exit;
6168 	}
6169 
6170 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
6171 			      &rsrc_info->u.rsp);
6172 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
6173 			     &rsrc_info->u.rsp);
6174 
6175 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6176 			"3162 Retrieved extents type-%d from port: count:%d, "
6177 			"size:%d\n", type, *extnt_count, *extnt_size);
6178 
6179 err_exit:
6180 	mempool_free(mbox, phba->mbox_mem_pool);
6181 	return rc;
6182 }
6183 
6184 /**
6185  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
6186  * @phba: Pointer to HBA context object.
6187  * @type: The extent type to check.
6188  *
6189  * This function reads the current available extents from the port and checks
6190  * if the extent count or extent size has changed since the last access.
6191  * Callers use this routine post port reset to understand if there is a
6192  * extent reprovisioning requirement.
6193  *
6194  * Returns:
6195  *   -Error: error indicates problem.
6196  *   1: Extent count or size has changed.
6197  *   0: No changes.
6198  **/
6199 static int
6200 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
6201 {
6202 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
6203 	uint16_t size_diff, rsrc_ext_size;
6204 	int rc = 0;
6205 	struct lpfc_rsrc_blks *rsrc_entry;
6206 	struct list_head *rsrc_blk_list = NULL;
6207 
6208 	size_diff = 0;
6209 	curr_ext_cnt = 0;
6210 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6211 					    &rsrc_ext_cnt,
6212 					    &rsrc_ext_size);
6213 	if (unlikely(rc))
6214 		return -EIO;
6215 
6216 	switch (type) {
6217 	case LPFC_RSC_TYPE_FCOE_RPI:
6218 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6219 		break;
6220 	case LPFC_RSC_TYPE_FCOE_VPI:
6221 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
6222 		break;
6223 	case LPFC_RSC_TYPE_FCOE_XRI:
6224 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6225 		break;
6226 	case LPFC_RSC_TYPE_FCOE_VFI:
6227 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6228 		break;
6229 	default:
6230 		break;
6231 	}
6232 
6233 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
6234 		curr_ext_cnt++;
6235 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
6236 			size_diff++;
6237 	}
6238 
6239 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
6240 		rc = 1;
6241 
6242 	return rc;
6243 }
6244 
6245 /**
6246  * lpfc_sli4_cfg_post_extnts -
6247  * @phba: Pointer to HBA context object.
6248  * @extnt_cnt: number of available extents.
6249  * @type: the extent type (rpi, xri, vfi, vpi).
6250  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
6251  * @mbox: pointer to the caller's allocated mailbox structure.
6252  *
6253  * This function executes the extents allocation request.  It also
6254  * takes care of the amount of memory needed to allocate or get the
6255  * allocated extents. It is the caller's responsibility to evaluate
6256  * the response.
6257  *
6258  * Returns:
6259  *   -Error:  Error value describes the condition found.
6260  *   0: if successful
6261  **/
6262 static int
6263 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6264 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6265 {
6266 	int rc = 0;
6267 	uint32_t req_len;
6268 	uint32_t emb_len;
6269 	uint32_t alloc_len, mbox_tmo;
6270 
6271 	/* Calculate the total requested length of the dma memory */
6272 	req_len = extnt_cnt * sizeof(uint16_t);
6273 
6274 	/*
6275 	 * Calculate the size of an embedded mailbox.  The uint32_t
6276 	 * accounts for extents-specific word.
6277 	 */
6278 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6279 		sizeof(uint32_t);
6280 
6281 	/*
6282 	 * Presume the allocation and response will fit into an embedded
6283 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6284 	 */
6285 	*emb = LPFC_SLI4_MBX_EMBED;
6286 	if (req_len > emb_len) {
6287 		req_len = extnt_cnt * sizeof(uint16_t) +
6288 			sizeof(union lpfc_sli4_cfg_shdr) +
6289 			sizeof(uint32_t);
6290 		*emb = LPFC_SLI4_MBX_NEMBED;
6291 	}
6292 
6293 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6294 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6295 				     req_len, *emb);
6296 	if (alloc_len < req_len) {
6297 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6298 			"2982 Allocated DMA memory size (x%x) is "
6299 			"less than the requested DMA memory "
6300 			"size (x%x)\n", alloc_len, req_len);
6301 		return -ENOMEM;
6302 	}
6303 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6304 	if (unlikely(rc))
6305 		return -EIO;
6306 
6307 	if (!phba->sli4_hba.intr_enable)
6308 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6309 	else {
6310 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6311 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6312 	}
6313 
6314 	if (unlikely(rc))
6315 		rc = -EIO;
6316 	return rc;
6317 }
6318 
6319 /**
6320  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6321  * @phba: Pointer to HBA context object.
6322  * @type:  The resource extent type to allocate.
6323  *
6324  * This function allocates the number of elements for the specified
6325  * resource type.
6326  **/
6327 static int
6328 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6329 {
6330 	bool emb = false;
6331 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6332 	uint16_t rsrc_id, rsrc_start, j, k;
6333 	uint16_t *ids;
6334 	int i, rc;
6335 	unsigned long longs;
6336 	unsigned long *bmask;
6337 	struct lpfc_rsrc_blks *rsrc_blks;
6338 	LPFC_MBOXQ_t *mbox;
6339 	uint32_t length;
6340 	struct lpfc_id_range *id_array = NULL;
6341 	void *virtaddr = NULL;
6342 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6343 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6344 	struct list_head *ext_blk_list;
6345 
6346 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6347 					    &rsrc_cnt,
6348 					    &rsrc_size);
6349 	if (unlikely(rc))
6350 		return -EIO;
6351 
6352 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6353 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6354 			"3009 No available Resource Extents "
6355 			"for resource type 0x%x: Count: 0x%x, "
6356 			"Size 0x%x\n", type, rsrc_cnt,
6357 			rsrc_size);
6358 		return -ENOMEM;
6359 	}
6360 
6361 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6362 			"2903 Post resource extents type-0x%x: "
6363 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6364 
6365 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6366 	if (!mbox)
6367 		return -ENOMEM;
6368 
6369 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6370 	if (unlikely(rc)) {
6371 		rc = -EIO;
6372 		goto err_exit;
6373 	}
6374 
6375 	/*
6376 	 * Figure out where the response is located.  Then get local pointers
6377 	 * to the response data.  The port does not guarantee to respond to
6378 	 * all extents counts request so update the local variable with the
6379 	 * allocated count from the port.
6380 	 */
6381 	if (emb == LPFC_SLI4_MBX_EMBED) {
6382 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6383 		id_array = &rsrc_ext->u.rsp.id[0];
6384 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6385 	} else {
6386 		virtaddr = mbox->sge_array->addr[0];
6387 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6388 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6389 		id_array = &n_rsrc->id;
6390 	}
6391 
6392 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6393 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6394 
6395 	/*
6396 	 * Based on the resource size and count, correct the base and max
6397 	 * resource values.
6398 	 */
6399 	length = sizeof(struct lpfc_rsrc_blks);
6400 	switch (type) {
6401 	case LPFC_RSC_TYPE_FCOE_RPI:
6402 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6403 						   sizeof(unsigned long),
6404 						   GFP_KERNEL);
6405 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6406 			rc = -ENOMEM;
6407 			goto err_exit;
6408 		}
6409 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6410 						 sizeof(uint16_t),
6411 						 GFP_KERNEL);
6412 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6413 			kfree(phba->sli4_hba.rpi_bmask);
6414 			rc = -ENOMEM;
6415 			goto err_exit;
6416 		}
6417 
6418 		/*
6419 		 * The next_rpi was initialized with the maximum available
6420 		 * count but the port may allocate a smaller number.  Catch
6421 		 * that case and update the next_rpi.
6422 		 */
6423 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6424 
6425 		/* Initialize local ptrs for common extent processing later. */
6426 		bmask = phba->sli4_hba.rpi_bmask;
6427 		ids = phba->sli4_hba.rpi_ids;
6428 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6429 		break;
6430 	case LPFC_RSC_TYPE_FCOE_VPI:
6431 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6432 					  GFP_KERNEL);
6433 		if (unlikely(!phba->vpi_bmask)) {
6434 			rc = -ENOMEM;
6435 			goto err_exit;
6436 		}
6437 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6438 					 GFP_KERNEL);
6439 		if (unlikely(!phba->vpi_ids)) {
6440 			kfree(phba->vpi_bmask);
6441 			rc = -ENOMEM;
6442 			goto err_exit;
6443 		}
6444 
6445 		/* Initialize local ptrs for common extent processing later. */
6446 		bmask = phba->vpi_bmask;
6447 		ids = phba->vpi_ids;
6448 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6449 		break;
6450 	case LPFC_RSC_TYPE_FCOE_XRI:
6451 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6452 						   sizeof(unsigned long),
6453 						   GFP_KERNEL);
6454 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6455 			rc = -ENOMEM;
6456 			goto err_exit;
6457 		}
6458 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6459 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6460 						 sizeof(uint16_t),
6461 						 GFP_KERNEL);
6462 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6463 			kfree(phba->sli4_hba.xri_bmask);
6464 			rc = -ENOMEM;
6465 			goto err_exit;
6466 		}
6467 
6468 		/* Initialize local ptrs for common extent processing later. */
6469 		bmask = phba->sli4_hba.xri_bmask;
6470 		ids = phba->sli4_hba.xri_ids;
6471 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6472 		break;
6473 	case LPFC_RSC_TYPE_FCOE_VFI:
6474 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6475 						   sizeof(unsigned long),
6476 						   GFP_KERNEL);
6477 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6478 			rc = -ENOMEM;
6479 			goto err_exit;
6480 		}
6481 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6482 						 sizeof(uint16_t),
6483 						 GFP_KERNEL);
6484 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6485 			kfree(phba->sli4_hba.vfi_bmask);
6486 			rc = -ENOMEM;
6487 			goto err_exit;
6488 		}
6489 
6490 		/* Initialize local ptrs for common extent processing later. */
6491 		bmask = phba->sli4_hba.vfi_bmask;
6492 		ids = phba->sli4_hba.vfi_ids;
6493 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6494 		break;
6495 	default:
6496 		/* Unsupported Opcode.  Fail call. */
6497 		id_array = NULL;
6498 		bmask = NULL;
6499 		ids = NULL;
6500 		ext_blk_list = NULL;
6501 		goto err_exit;
6502 	}
6503 
6504 	/*
6505 	 * Complete initializing the extent configuration with the
6506 	 * allocated ids assigned to this function.  The bitmask serves
6507 	 * as an index into the array and manages the available ids.  The
6508 	 * array just stores the ids communicated to the port via the wqes.
6509 	 */
6510 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6511 		if ((i % 2) == 0)
6512 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6513 					 &id_array[k]);
6514 		else
6515 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6516 					 &id_array[k]);
6517 
6518 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6519 		if (unlikely(!rsrc_blks)) {
6520 			rc = -ENOMEM;
6521 			kfree(bmask);
6522 			kfree(ids);
6523 			goto err_exit;
6524 		}
6525 		rsrc_blks->rsrc_start = rsrc_id;
6526 		rsrc_blks->rsrc_size = rsrc_size;
6527 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6528 		rsrc_start = rsrc_id;
6529 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6530 			phba->sli4_hba.io_xri_start = rsrc_start +
6531 				lpfc_sli4_get_iocb_cnt(phba);
6532 		}
6533 
6534 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6535 			ids[j] = rsrc_id;
6536 			rsrc_id++;
6537 			j++;
6538 		}
6539 		/* Entire word processed.  Get next word.*/
6540 		if ((i % 2) == 1)
6541 			k++;
6542 	}
6543  err_exit:
6544 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6545 	return rc;
6546 }
6547 
6548 
6549 
6550 /**
6551  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6552  * @phba: Pointer to HBA context object.
6553  * @type: the extent's type.
6554  *
6555  * This function deallocates all extents of a particular resource type.
6556  * SLI4 does not allow for deallocating a particular extent range.  It
6557  * is the caller's responsibility to release all kernel memory resources.
6558  **/
6559 static int
6560 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6561 {
6562 	int rc;
6563 	uint32_t length, mbox_tmo = 0;
6564 	LPFC_MBOXQ_t *mbox;
6565 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6566 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6567 
6568 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6569 	if (!mbox)
6570 		return -ENOMEM;
6571 
6572 	/*
6573 	 * This function sends an embedded mailbox because it only sends the
6574 	 * the resource type.  All extents of this type are released by the
6575 	 * port.
6576 	 */
6577 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6578 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6579 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6580 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6581 			 length, LPFC_SLI4_MBX_EMBED);
6582 
6583 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6584 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6585 					LPFC_SLI4_MBX_EMBED);
6586 	if (unlikely(rc)) {
6587 		rc = -EIO;
6588 		goto out_free_mbox;
6589 	}
6590 	if (!phba->sli4_hba.intr_enable)
6591 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6592 	else {
6593 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6594 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6595 	}
6596 	if (unlikely(rc)) {
6597 		rc = -EIO;
6598 		goto out_free_mbox;
6599 	}
6600 
6601 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6602 	if (bf_get(lpfc_mbox_hdr_status,
6603 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6604 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6605 				"2919 Failed to release resource extents "
6606 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6607 				"Resource memory not released.\n",
6608 				type,
6609 				bf_get(lpfc_mbox_hdr_status,
6610 				    &dealloc_rsrc->header.cfg_shdr.response),
6611 				bf_get(lpfc_mbox_hdr_add_status,
6612 				    &dealloc_rsrc->header.cfg_shdr.response));
6613 		rc = -EIO;
6614 		goto out_free_mbox;
6615 	}
6616 
6617 	/* Release kernel memory resources for the specific type. */
6618 	switch (type) {
6619 	case LPFC_RSC_TYPE_FCOE_VPI:
6620 		kfree(phba->vpi_bmask);
6621 		kfree(phba->vpi_ids);
6622 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6623 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6624 				    &phba->lpfc_vpi_blk_list, list) {
6625 			list_del_init(&rsrc_blk->list);
6626 			kfree(rsrc_blk);
6627 		}
6628 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6629 		break;
6630 	case LPFC_RSC_TYPE_FCOE_XRI:
6631 		kfree(phba->sli4_hba.xri_bmask);
6632 		kfree(phba->sli4_hba.xri_ids);
6633 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6634 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6635 			list_del_init(&rsrc_blk->list);
6636 			kfree(rsrc_blk);
6637 		}
6638 		break;
6639 	case LPFC_RSC_TYPE_FCOE_VFI:
6640 		kfree(phba->sli4_hba.vfi_bmask);
6641 		kfree(phba->sli4_hba.vfi_ids);
6642 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6643 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6644 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6645 			list_del_init(&rsrc_blk->list);
6646 			kfree(rsrc_blk);
6647 		}
6648 		break;
6649 	case LPFC_RSC_TYPE_FCOE_RPI:
6650 		/* RPI bitmask and physical id array are cleaned up earlier. */
6651 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6652 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6653 			list_del_init(&rsrc_blk->list);
6654 			kfree(rsrc_blk);
6655 		}
6656 		break;
6657 	default:
6658 		break;
6659 	}
6660 
6661 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6662 
6663  out_free_mbox:
6664 	mempool_free(mbox, phba->mbox_mem_pool);
6665 	return rc;
6666 }
6667 
6668 static void
6669 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6670 		  uint32_t feature)
6671 {
6672 	uint32_t len;
6673 	u32 sig_freq = 0;
6674 
6675 	len = sizeof(struct lpfc_mbx_set_feature) -
6676 		sizeof(struct lpfc_sli4_cfg_mhdr);
6677 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6678 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6679 			 LPFC_SLI4_MBX_EMBED);
6680 
6681 	switch (feature) {
6682 	case LPFC_SET_UE_RECOVERY:
6683 		bf_set(lpfc_mbx_set_feature_UER,
6684 		       &mbox->u.mqe.un.set_feature, 1);
6685 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6686 		mbox->u.mqe.un.set_feature.param_len = 8;
6687 		break;
6688 	case LPFC_SET_MDS_DIAGS:
6689 		bf_set(lpfc_mbx_set_feature_mds,
6690 		       &mbox->u.mqe.un.set_feature, 1);
6691 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6692 		       &mbox->u.mqe.un.set_feature, 1);
6693 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6694 		mbox->u.mqe.un.set_feature.param_len = 8;
6695 		break;
6696 	case LPFC_SET_CGN_SIGNAL:
6697 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6698 			sig_freq = 0;
6699 		else
6700 			sig_freq = phba->cgn_sig_freq;
6701 
6702 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6703 			bf_set(lpfc_mbx_set_feature_CGN_alarm_freq,
6704 			       &mbox->u.mqe.un.set_feature, sig_freq);
6705 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6706 			       &mbox->u.mqe.un.set_feature, sig_freq);
6707 		}
6708 
6709 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY)
6710 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6711 			       &mbox->u.mqe.un.set_feature, sig_freq);
6712 
6713 		if (phba->cmf_active_mode == LPFC_CFG_OFF ||
6714 		    phba->cgn_reg_signal == EDC_CG_SIG_NOTSUPPORTED)
6715 			sig_freq = 0;
6716 		else
6717 			sig_freq = lpfc_acqe_cgn_frequency;
6718 
6719 		bf_set(lpfc_mbx_set_feature_CGN_acqe_freq,
6720 		       &mbox->u.mqe.un.set_feature, sig_freq);
6721 
6722 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_CGN_SIGNAL;
6723 		mbox->u.mqe.un.set_feature.param_len = 12;
6724 		break;
6725 	case LPFC_SET_DUAL_DUMP:
6726 		bf_set(lpfc_mbx_set_feature_dd,
6727 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6728 		bf_set(lpfc_mbx_set_feature_ddquery,
6729 		       &mbox->u.mqe.un.set_feature, 0);
6730 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6731 		mbox->u.mqe.un.set_feature.param_len = 4;
6732 		break;
6733 	case LPFC_SET_ENABLE_MI:
6734 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_MI;
6735 		mbox->u.mqe.un.set_feature.param_len = 4;
6736 		bf_set(lpfc_mbx_set_feature_milunq, &mbox->u.mqe.un.set_feature,
6737 		       phba->pport->cfg_lun_queue_depth);
6738 		bf_set(lpfc_mbx_set_feature_mi, &mbox->u.mqe.un.set_feature,
6739 		       phba->sli4_hba.pc_sli4_params.mi_ver);
6740 		break;
6741 	case LPFC_SET_ENABLE_CMF:
6742 		bf_set(lpfc_mbx_set_feature_dd, &mbox->u.mqe.un.set_feature, 1);
6743 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_CMF;
6744 		mbox->u.mqe.un.set_feature.param_len = 4;
6745 		bf_set(lpfc_mbx_set_feature_cmf,
6746 		       &mbox->u.mqe.un.set_feature, 1);
6747 		break;
6748 	}
6749 	return;
6750 }
6751 
6752 /**
6753  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6754  * @phba: Pointer to HBA context object.
6755  *
6756  * Disable FW logging into host memory on the adapter. To
6757  * be done before reading logs from the host memory.
6758  **/
6759 void
6760 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6761 {
6762 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6763 
6764 	spin_lock_irq(&phba->hbalock);
6765 	ras_fwlog->state = INACTIVE;
6766 	spin_unlock_irq(&phba->hbalock);
6767 
6768 	/* Disable FW logging to host memory */
6769 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6770 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6771 
6772 	/* Wait 10ms for firmware to stop using DMA buffer */
6773 	usleep_range(10 * 1000, 20 * 1000);
6774 }
6775 
6776 /**
6777  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6778  * @phba: Pointer to HBA context object.
6779  *
6780  * This function is called to free memory allocated for RAS FW logging
6781  * support in the driver.
6782  **/
6783 void
6784 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6785 {
6786 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6787 	struct lpfc_dmabuf *dmabuf, *next;
6788 
6789 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6790 		list_for_each_entry_safe(dmabuf, next,
6791 				    &ras_fwlog->fwlog_buff_list,
6792 				    list) {
6793 			list_del(&dmabuf->list);
6794 			dma_free_coherent(&phba->pcidev->dev,
6795 					  LPFC_RAS_MAX_ENTRY_SIZE,
6796 					  dmabuf->virt, dmabuf->phys);
6797 			kfree(dmabuf);
6798 		}
6799 	}
6800 
6801 	if (ras_fwlog->lwpd.virt) {
6802 		dma_free_coherent(&phba->pcidev->dev,
6803 				  sizeof(uint32_t) * 2,
6804 				  ras_fwlog->lwpd.virt,
6805 				  ras_fwlog->lwpd.phys);
6806 		ras_fwlog->lwpd.virt = NULL;
6807 	}
6808 
6809 	spin_lock_irq(&phba->hbalock);
6810 	ras_fwlog->state = INACTIVE;
6811 	spin_unlock_irq(&phba->hbalock);
6812 }
6813 
6814 /**
6815  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6816  * @phba: Pointer to HBA context object.
6817  * @fwlog_buff_count: Count of buffers to be created.
6818  *
6819  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6820  * to update FW log is posted to the adapter.
6821  * Buffer count is calculated based on module param ras_fwlog_buffsize
6822  * Size of each buffer posted to FW is 64K.
6823  **/
6824 
6825 static int
6826 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6827 			uint32_t fwlog_buff_count)
6828 {
6829 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6830 	struct lpfc_dmabuf *dmabuf;
6831 	int rc = 0, i = 0;
6832 
6833 	/* Initialize List */
6834 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6835 
6836 	/* Allocate memory for the LWPD */
6837 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6838 					    sizeof(uint32_t) * 2,
6839 					    &ras_fwlog->lwpd.phys,
6840 					    GFP_KERNEL);
6841 	if (!ras_fwlog->lwpd.virt) {
6842 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6843 				"6185 LWPD Memory Alloc Failed\n");
6844 
6845 		return -ENOMEM;
6846 	}
6847 
6848 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6849 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6850 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6851 				 GFP_KERNEL);
6852 		if (!dmabuf) {
6853 			rc = -ENOMEM;
6854 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6855 					"6186 Memory Alloc failed FW logging");
6856 			goto free_mem;
6857 		}
6858 
6859 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6860 						  LPFC_RAS_MAX_ENTRY_SIZE,
6861 						  &dmabuf->phys, GFP_KERNEL);
6862 		if (!dmabuf->virt) {
6863 			kfree(dmabuf);
6864 			rc = -ENOMEM;
6865 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6866 					"6187 DMA Alloc Failed FW logging");
6867 			goto free_mem;
6868 		}
6869 		dmabuf->buffer_tag = i;
6870 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6871 	}
6872 
6873 free_mem:
6874 	if (rc)
6875 		lpfc_sli4_ras_dma_free(phba);
6876 
6877 	return rc;
6878 }
6879 
6880 /**
6881  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6882  * @phba: pointer to lpfc hba data structure.
6883  * @pmb: pointer to the driver internal queue element for mailbox command.
6884  *
6885  * Completion handler for driver's RAS MBX command to the device.
6886  **/
6887 static void
6888 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6889 {
6890 	MAILBOX_t *mb;
6891 	union lpfc_sli4_cfg_shdr *shdr;
6892 	uint32_t shdr_status, shdr_add_status;
6893 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6894 
6895 	mb = &pmb->u.mb;
6896 
6897 	shdr = (union lpfc_sli4_cfg_shdr *)
6898 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6899 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6900 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6901 
6902 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6903 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6904 				"6188 FW LOG mailbox "
6905 				"completed with status x%x add_status x%x,"
6906 				" mbx status x%x\n",
6907 				shdr_status, shdr_add_status, mb->mbxStatus);
6908 
6909 		ras_fwlog->ras_hwsupport = false;
6910 		goto disable_ras;
6911 	}
6912 
6913 	spin_lock_irq(&phba->hbalock);
6914 	ras_fwlog->state = ACTIVE;
6915 	spin_unlock_irq(&phba->hbalock);
6916 	mempool_free(pmb, phba->mbox_mem_pool);
6917 
6918 	return;
6919 
6920 disable_ras:
6921 	/* Free RAS DMA memory */
6922 	lpfc_sli4_ras_dma_free(phba);
6923 	mempool_free(pmb, phba->mbox_mem_pool);
6924 }
6925 
6926 /**
6927  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
6928  * @phba: pointer to lpfc hba data structure.
6929  * @fwlog_level: Logging verbosity level.
6930  * @fwlog_enable: Enable/Disable logging.
6931  *
6932  * Initialize memory and post mailbox command to enable FW logging in host
6933  * memory.
6934  **/
6935 int
6936 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
6937 			 uint32_t fwlog_level,
6938 			 uint32_t fwlog_enable)
6939 {
6940 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6941 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
6942 	struct lpfc_dmabuf *dmabuf;
6943 	LPFC_MBOXQ_t *mbox;
6944 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
6945 	int rc = 0;
6946 
6947 	spin_lock_irq(&phba->hbalock);
6948 	ras_fwlog->state = INACTIVE;
6949 	spin_unlock_irq(&phba->hbalock);
6950 
6951 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
6952 			  phba->cfg_ras_fwlog_buffsize);
6953 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
6954 
6955 	/*
6956 	 * If re-enabling FW logging support use earlier allocated
6957 	 * DMA buffers while posting MBX command.
6958 	 **/
6959 	if (!ras_fwlog->lwpd.virt) {
6960 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
6961 		if (rc) {
6962 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6963 					"6189 FW Log Memory Allocation Failed");
6964 			return rc;
6965 		}
6966 	}
6967 
6968 	/* Setup Mailbox command */
6969 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6970 	if (!mbox) {
6971 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6972 				"6190 RAS MBX Alloc Failed");
6973 		rc = -ENOMEM;
6974 		goto mem_free;
6975 	}
6976 
6977 	ras_fwlog->fw_loglevel = fwlog_level;
6978 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
6979 		sizeof(struct lpfc_sli4_cfg_mhdr));
6980 
6981 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
6982 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
6983 			 len, LPFC_SLI4_MBX_EMBED);
6984 
6985 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
6986 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
6987 	       fwlog_enable);
6988 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
6989 	       ras_fwlog->fw_loglevel);
6990 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
6991 	       ras_fwlog->fw_buffcount);
6992 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
6993 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
6994 
6995 	/* Update DMA buffer address */
6996 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
6997 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
6998 
6999 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
7000 			putPaddrLow(dmabuf->phys);
7001 
7002 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
7003 			putPaddrHigh(dmabuf->phys);
7004 	}
7005 
7006 	/* Update LPWD address */
7007 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
7008 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
7009 
7010 	spin_lock_irq(&phba->hbalock);
7011 	ras_fwlog->state = REG_INPROGRESS;
7012 	spin_unlock_irq(&phba->hbalock);
7013 	mbox->vport = phba->pport;
7014 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
7015 
7016 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
7017 
7018 	if (rc == MBX_NOT_FINISHED) {
7019 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7020 				"6191 FW-Log Mailbox failed. "
7021 				"status %d mbxStatus : x%x", rc,
7022 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
7023 		mempool_free(mbox, phba->mbox_mem_pool);
7024 		rc = -EIO;
7025 		goto mem_free;
7026 	} else
7027 		rc = 0;
7028 mem_free:
7029 	if (rc)
7030 		lpfc_sli4_ras_dma_free(phba);
7031 
7032 	return rc;
7033 }
7034 
7035 /**
7036  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
7037  * @phba: Pointer to HBA context object.
7038  *
7039  * Check if RAS is supported on the adapter and initialize it.
7040  **/
7041 void
7042 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
7043 {
7044 	/* Check RAS FW Log needs to be enabled or not */
7045 	if (lpfc_check_fwlog_support(phba))
7046 		return;
7047 
7048 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
7049 				 LPFC_RAS_ENABLE_LOGGING);
7050 }
7051 
7052 /**
7053  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
7054  * @phba: Pointer to HBA context object.
7055  *
7056  * This function allocates all SLI4 resource identifiers.
7057  **/
7058 int
7059 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
7060 {
7061 	int i, rc, error = 0;
7062 	uint16_t count, base;
7063 	unsigned long longs;
7064 
7065 	if (!phba->sli4_hba.rpi_hdrs_in_use)
7066 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
7067 	if (phba->sli4_hba.extents_in_use) {
7068 		/*
7069 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
7070 		 * resource extent count must be read and allocated before
7071 		 * provisioning the resource id arrays.
7072 		 */
7073 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7074 		    LPFC_IDX_RSRC_RDY) {
7075 			/*
7076 			 * Extent-based resources are set - the driver could
7077 			 * be in a port reset. Figure out if any corrective
7078 			 * actions need to be taken.
7079 			 */
7080 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7081 						 LPFC_RSC_TYPE_FCOE_VFI);
7082 			if (rc != 0)
7083 				error++;
7084 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7085 						 LPFC_RSC_TYPE_FCOE_VPI);
7086 			if (rc != 0)
7087 				error++;
7088 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7089 						 LPFC_RSC_TYPE_FCOE_XRI);
7090 			if (rc != 0)
7091 				error++;
7092 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7093 						 LPFC_RSC_TYPE_FCOE_RPI);
7094 			if (rc != 0)
7095 				error++;
7096 
7097 			/*
7098 			 * It's possible that the number of resources
7099 			 * provided to this port instance changed between
7100 			 * resets.  Detect this condition and reallocate
7101 			 * resources.  Otherwise, there is no action.
7102 			 */
7103 			if (error) {
7104 				lpfc_printf_log(phba, KERN_INFO,
7105 						LOG_MBOX | LOG_INIT,
7106 						"2931 Detected extent resource "
7107 						"change.  Reallocating all "
7108 						"extents.\n");
7109 				rc = lpfc_sli4_dealloc_extent(phba,
7110 						 LPFC_RSC_TYPE_FCOE_VFI);
7111 				rc = lpfc_sli4_dealloc_extent(phba,
7112 						 LPFC_RSC_TYPE_FCOE_VPI);
7113 				rc = lpfc_sli4_dealloc_extent(phba,
7114 						 LPFC_RSC_TYPE_FCOE_XRI);
7115 				rc = lpfc_sli4_dealloc_extent(phba,
7116 						 LPFC_RSC_TYPE_FCOE_RPI);
7117 			} else
7118 				return 0;
7119 		}
7120 
7121 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7122 		if (unlikely(rc))
7123 			goto err_exit;
7124 
7125 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7126 		if (unlikely(rc))
7127 			goto err_exit;
7128 
7129 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7130 		if (unlikely(rc))
7131 			goto err_exit;
7132 
7133 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7134 		if (unlikely(rc))
7135 			goto err_exit;
7136 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7137 		       LPFC_IDX_RSRC_RDY);
7138 		return rc;
7139 	} else {
7140 		/*
7141 		 * The port does not support resource extents.  The XRI, VPI,
7142 		 * VFI, RPI resource ids were determined from READ_CONFIG.
7143 		 * Just allocate the bitmasks and provision the resource id
7144 		 * arrays.  If a port reset is active, the resources don't
7145 		 * need any action - just exit.
7146 		 */
7147 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7148 		    LPFC_IDX_RSRC_RDY) {
7149 			lpfc_sli4_dealloc_resource_identifiers(phba);
7150 			lpfc_sli4_remove_rpis(phba);
7151 		}
7152 		/* RPIs. */
7153 		count = phba->sli4_hba.max_cfg_param.max_rpi;
7154 		if (count <= 0) {
7155 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7156 					"3279 Invalid provisioning of "
7157 					"rpi:%d\n", count);
7158 			rc = -EINVAL;
7159 			goto err_exit;
7160 		}
7161 		base = phba->sli4_hba.max_cfg_param.rpi_base;
7162 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7163 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
7164 						   sizeof(unsigned long),
7165 						   GFP_KERNEL);
7166 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
7167 			rc = -ENOMEM;
7168 			goto err_exit;
7169 		}
7170 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
7171 						 GFP_KERNEL);
7172 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
7173 			rc = -ENOMEM;
7174 			goto free_rpi_bmask;
7175 		}
7176 
7177 		for (i = 0; i < count; i++)
7178 			phba->sli4_hba.rpi_ids[i] = base + i;
7179 
7180 		/* VPIs. */
7181 		count = phba->sli4_hba.max_cfg_param.max_vpi;
7182 		if (count <= 0) {
7183 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7184 					"3280 Invalid provisioning of "
7185 					"vpi:%d\n", count);
7186 			rc = -EINVAL;
7187 			goto free_rpi_ids;
7188 		}
7189 		base = phba->sli4_hba.max_cfg_param.vpi_base;
7190 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7191 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
7192 					  GFP_KERNEL);
7193 		if (unlikely(!phba->vpi_bmask)) {
7194 			rc = -ENOMEM;
7195 			goto free_rpi_ids;
7196 		}
7197 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
7198 					GFP_KERNEL);
7199 		if (unlikely(!phba->vpi_ids)) {
7200 			rc = -ENOMEM;
7201 			goto free_vpi_bmask;
7202 		}
7203 
7204 		for (i = 0; i < count; i++)
7205 			phba->vpi_ids[i] = base + i;
7206 
7207 		/* XRIs. */
7208 		count = phba->sli4_hba.max_cfg_param.max_xri;
7209 		if (count <= 0) {
7210 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7211 					"3281 Invalid provisioning of "
7212 					"xri:%d\n", count);
7213 			rc = -EINVAL;
7214 			goto free_vpi_ids;
7215 		}
7216 		base = phba->sli4_hba.max_cfg_param.xri_base;
7217 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7218 		phba->sli4_hba.xri_bmask = kcalloc(longs,
7219 						   sizeof(unsigned long),
7220 						   GFP_KERNEL);
7221 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
7222 			rc = -ENOMEM;
7223 			goto free_vpi_ids;
7224 		}
7225 		phba->sli4_hba.max_cfg_param.xri_used = 0;
7226 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
7227 						 GFP_KERNEL);
7228 		if (unlikely(!phba->sli4_hba.xri_ids)) {
7229 			rc = -ENOMEM;
7230 			goto free_xri_bmask;
7231 		}
7232 
7233 		for (i = 0; i < count; i++)
7234 			phba->sli4_hba.xri_ids[i] = base + i;
7235 
7236 		/* VFIs. */
7237 		count = phba->sli4_hba.max_cfg_param.max_vfi;
7238 		if (count <= 0) {
7239 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7240 					"3282 Invalid provisioning of "
7241 					"vfi:%d\n", count);
7242 			rc = -EINVAL;
7243 			goto free_xri_ids;
7244 		}
7245 		base = phba->sli4_hba.max_cfg_param.vfi_base;
7246 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7247 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
7248 						   sizeof(unsigned long),
7249 						   GFP_KERNEL);
7250 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
7251 			rc = -ENOMEM;
7252 			goto free_xri_ids;
7253 		}
7254 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
7255 						 GFP_KERNEL);
7256 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
7257 			rc = -ENOMEM;
7258 			goto free_vfi_bmask;
7259 		}
7260 
7261 		for (i = 0; i < count; i++)
7262 			phba->sli4_hba.vfi_ids[i] = base + i;
7263 
7264 		/*
7265 		 * Mark all resources ready.  An HBA reset doesn't need
7266 		 * to reset the initialization.
7267 		 */
7268 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7269 		       LPFC_IDX_RSRC_RDY);
7270 		return 0;
7271 	}
7272 
7273  free_vfi_bmask:
7274 	kfree(phba->sli4_hba.vfi_bmask);
7275 	phba->sli4_hba.vfi_bmask = NULL;
7276  free_xri_ids:
7277 	kfree(phba->sli4_hba.xri_ids);
7278 	phba->sli4_hba.xri_ids = NULL;
7279  free_xri_bmask:
7280 	kfree(phba->sli4_hba.xri_bmask);
7281 	phba->sli4_hba.xri_bmask = NULL;
7282  free_vpi_ids:
7283 	kfree(phba->vpi_ids);
7284 	phba->vpi_ids = NULL;
7285  free_vpi_bmask:
7286 	kfree(phba->vpi_bmask);
7287 	phba->vpi_bmask = NULL;
7288  free_rpi_ids:
7289 	kfree(phba->sli4_hba.rpi_ids);
7290 	phba->sli4_hba.rpi_ids = NULL;
7291  free_rpi_bmask:
7292 	kfree(phba->sli4_hba.rpi_bmask);
7293 	phba->sli4_hba.rpi_bmask = NULL;
7294  err_exit:
7295 	return rc;
7296 }
7297 
7298 /**
7299  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
7300  * @phba: Pointer to HBA context object.
7301  *
7302  * This function allocates the number of elements for the specified
7303  * resource type.
7304  **/
7305 int
7306 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7307 {
7308 	if (phba->sli4_hba.extents_in_use) {
7309 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7310 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7311 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7312 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7313 	} else {
7314 		kfree(phba->vpi_bmask);
7315 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
7316 		kfree(phba->vpi_ids);
7317 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7318 		kfree(phba->sli4_hba.xri_bmask);
7319 		kfree(phba->sli4_hba.xri_ids);
7320 		kfree(phba->sli4_hba.vfi_bmask);
7321 		kfree(phba->sli4_hba.vfi_ids);
7322 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7323 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7324 	}
7325 
7326 	return 0;
7327 }
7328 
7329 /**
7330  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7331  * @phba: Pointer to HBA context object.
7332  * @type: The resource extent type.
7333  * @extnt_cnt: buffer to hold port extent count response
7334  * @extnt_size: buffer to hold port extent size response.
7335  *
7336  * This function calls the port to read the host allocated extents
7337  * for a particular type.
7338  **/
7339 int
7340 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7341 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
7342 {
7343 	bool emb;
7344 	int rc = 0;
7345 	uint16_t curr_blks = 0;
7346 	uint32_t req_len, emb_len;
7347 	uint32_t alloc_len, mbox_tmo;
7348 	struct list_head *blk_list_head;
7349 	struct lpfc_rsrc_blks *rsrc_blk;
7350 	LPFC_MBOXQ_t *mbox;
7351 	void *virtaddr = NULL;
7352 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7353 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7354 	union  lpfc_sli4_cfg_shdr *shdr;
7355 
7356 	switch (type) {
7357 	case LPFC_RSC_TYPE_FCOE_VPI:
7358 		blk_list_head = &phba->lpfc_vpi_blk_list;
7359 		break;
7360 	case LPFC_RSC_TYPE_FCOE_XRI:
7361 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7362 		break;
7363 	case LPFC_RSC_TYPE_FCOE_VFI:
7364 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7365 		break;
7366 	case LPFC_RSC_TYPE_FCOE_RPI:
7367 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7368 		break;
7369 	default:
7370 		return -EIO;
7371 	}
7372 
7373 	/* Count the number of extents currently allocatd for this type. */
7374 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
7375 		if (curr_blks == 0) {
7376 			/*
7377 			 * The GET_ALLOCATED mailbox does not return the size,
7378 			 * just the count.  The size should be just the size
7379 			 * stored in the current allocated block and all sizes
7380 			 * for an extent type are the same so set the return
7381 			 * value now.
7382 			 */
7383 			*extnt_size = rsrc_blk->rsrc_size;
7384 		}
7385 		curr_blks++;
7386 	}
7387 
7388 	/*
7389 	 * Calculate the size of an embedded mailbox.  The uint32_t
7390 	 * accounts for extents-specific word.
7391 	 */
7392 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7393 		sizeof(uint32_t);
7394 
7395 	/*
7396 	 * Presume the allocation and response will fit into an embedded
7397 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7398 	 */
7399 	emb = LPFC_SLI4_MBX_EMBED;
7400 	req_len = emb_len;
7401 	if (req_len > emb_len) {
7402 		req_len = curr_blks * sizeof(uint16_t) +
7403 			sizeof(union lpfc_sli4_cfg_shdr) +
7404 			sizeof(uint32_t);
7405 		emb = LPFC_SLI4_MBX_NEMBED;
7406 	}
7407 
7408 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7409 	if (!mbox)
7410 		return -ENOMEM;
7411 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7412 
7413 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7414 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7415 				     req_len, emb);
7416 	if (alloc_len < req_len) {
7417 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7418 			"2983 Allocated DMA memory size (x%x) is "
7419 			"less than the requested DMA memory "
7420 			"size (x%x)\n", alloc_len, req_len);
7421 		rc = -ENOMEM;
7422 		goto err_exit;
7423 	}
7424 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7425 	if (unlikely(rc)) {
7426 		rc = -EIO;
7427 		goto err_exit;
7428 	}
7429 
7430 	if (!phba->sli4_hba.intr_enable)
7431 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7432 	else {
7433 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7434 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7435 	}
7436 
7437 	if (unlikely(rc)) {
7438 		rc = -EIO;
7439 		goto err_exit;
7440 	}
7441 
7442 	/*
7443 	 * Figure out where the response is located.  Then get local pointers
7444 	 * to the response data.  The port does not guarantee to respond to
7445 	 * all extents counts request so update the local variable with the
7446 	 * allocated count from the port.
7447 	 */
7448 	if (emb == LPFC_SLI4_MBX_EMBED) {
7449 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7450 		shdr = &rsrc_ext->header.cfg_shdr;
7451 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7452 	} else {
7453 		virtaddr = mbox->sge_array->addr[0];
7454 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7455 		shdr = &n_rsrc->cfg_shdr;
7456 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7457 	}
7458 
7459 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7460 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7461 			"2984 Failed to read allocated resources "
7462 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7463 			type,
7464 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7465 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7466 		rc = -EIO;
7467 		goto err_exit;
7468 	}
7469  err_exit:
7470 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7471 	return rc;
7472 }
7473 
7474 /**
7475  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7476  * @phba: pointer to lpfc hba data structure.
7477  * @sgl_list: linked link of sgl buffers to post
7478  * @cnt: number of linked list buffers
7479  *
7480  * This routine walks the list of buffers that have been allocated and
7481  * repost them to the port by using SGL block post. This is needed after a
7482  * pci_function_reset/warm_start or start. It attempts to construct blocks
7483  * of buffer sgls which contains contiguous xris and uses the non-embedded
7484  * SGL block post mailbox commands to post them to the port. For single
7485  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7486  * mailbox command for posting.
7487  *
7488  * Returns: 0 = success, non-zero failure.
7489  **/
7490 static int
7491 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7492 			  struct list_head *sgl_list, int cnt)
7493 {
7494 	struct lpfc_sglq *sglq_entry = NULL;
7495 	struct lpfc_sglq *sglq_entry_next = NULL;
7496 	struct lpfc_sglq *sglq_entry_first = NULL;
7497 	int status, total_cnt;
7498 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7499 	int last_xritag = NO_XRI;
7500 	LIST_HEAD(prep_sgl_list);
7501 	LIST_HEAD(blck_sgl_list);
7502 	LIST_HEAD(allc_sgl_list);
7503 	LIST_HEAD(post_sgl_list);
7504 	LIST_HEAD(free_sgl_list);
7505 
7506 	spin_lock_irq(&phba->hbalock);
7507 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7508 	list_splice_init(sgl_list, &allc_sgl_list);
7509 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7510 	spin_unlock_irq(&phba->hbalock);
7511 
7512 	total_cnt = cnt;
7513 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7514 				 &allc_sgl_list, list) {
7515 		list_del_init(&sglq_entry->list);
7516 		block_cnt++;
7517 		if ((last_xritag != NO_XRI) &&
7518 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7519 			/* a hole in xri block, form a sgl posting block */
7520 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7521 			post_cnt = block_cnt - 1;
7522 			/* prepare list for next posting block */
7523 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7524 			block_cnt = 1;
7525 		} else {
7526 			/* prepare list for next posting block */
7527 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7528 			/* enough sgls for non-embed sgl mbox command */
7529 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7530 				list_splice_init(&prep_sgl_list,
7531 						 &blck_sgl_list);
7532 				post_cnt = block_cnt;
7533 				block_cnt = 0;
7534 			}
7535 		}
7536 		num_posted++;
7537 
7538 		/* keep track of last sgl's xritag */
7539 		last_xritag = sglq_entry->sli4_xritag;
7540 
7541 		/* end of repost sgl list condition for buffers */
7542 		if (num_posted == total_cnt) {
7543 			if (post_cnt == 0) {
7544 				list_splice_init(&prep_sgl_list,
7545 						 &blck_sgl_list);
7546 				post_cnt = block_cnt;
7547 			} else if (block_cnt == 1) {
7548 				status = lpfc_sli4_post_sgl(phba,
7549 						sglq_entry->phys, 0,
7550 						sglq_entry->sli4_xritag);
7551 				if (!status) {
7552 					/* successful, put sgl to posted list */
7553 					list_add_tail(&sglq_entry->list,
7554 						      &post_sgl_list);
7555 				} else {
7556 					/* Failure, put sgl to free list */
7557 					lpfc_printf_log(phba, KERN_WARNING,
7558 						LOG_SLI,
7559 						"3159 Failed to post "
7560 						"sgl, xritag:x%x\n",
7561 						sglq_entry->sli4_xritag);
7562 					list_add_tail(&sglq_entry->list,
7563 						      &free_sgl_list);
7564 					total_cnt--;
7565 				}
7566 			}
7567 		}
7568 
7569 		/* continue until a nembed page worth of sgls */
7570 		if (post_cnt == 0)
7571 			continue;
7572 
7573 		/* post the buffer list sgls as a block */
7574 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7575 						 post_cnt);
7576 
7577 		if (!status) {
7578 			/* success, put sgl list to posted sgl list */
7579 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7580 		} else {
7581 			/* Failure, put sgl list to free sgl list */
7582 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7583 							    struct lpfc_sglq,
7584 							    list);
7585 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7586 					"3160 Failed to post sgl-list, "
7587 					"xritag:x%x-x%x\n",
7588 					sglq_entry_first->sli4_xritag,
7589 					(sglq_entry_first->sli4_xritag +
7590 					 post_cnt - 1));
7591 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7592 			total_cnt -= post_cnt;
7593 		}
7594 
7595 		/* don't reset xirtag due to hole in xri block */
7596 		if (block_cnt == 0)
7597 			last_xritag = NO_XRI;
7598 
7599 		/* reset sgl post count for next round of posting */
7600 		post_cnt = 0;
7601 	}
7602 
7603 	/* free the sgls failed to post */
7604 	lpfc_free_sgl_list(phba, &free_sgl_list);
7605 
7606 	/* push sgls posted to the available list */
7607 	if (!list_empty(&post_sgl_list)) {
7608 		spin_lock_irq(&phba->hbalock);
7609 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7610 		list_splice_init(&post_sgl_list, sgl_list);
7611 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7612 		spin_unlock_irq(&phba->hbalock);
7613 	} else {
7614 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7615 				"3161 Failure to post sgl to port.\n");
7616 		return -EIO;
7617 	}
7618 
7619 	/* return the number of XRIs actually posted */
7620 	return total_cnt;
7621 }
7622 
7623 /**
7624  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7625  * @phba: pointer to lpfc hba data structure.
7626  *
7627  * This routine walks the list of nvme buffers that have been allocated and
7628  * repost them to the port by using SGL block post. This is needed after a
7629  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7630  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7631  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7632  *
7633  * Returns: 0 = success, non-zero failure.
7634  **/
7635 static int
7636 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7637 {
7638 	LIST_HEAD(post_nblist);
7639 	int num_posted, rc = 0;
7640 
7641 	/* get all NVME buffers need to repost to a local list */
7642 	lpfc_io_buf_flush(phba, &post_nblist);
7643 
7644 	/* post the list of nvme buffer sgls to port if available */
7645 	if (!list_empty(&post_nblist)) {
7646 		num_posted = lpfc_sli4_post_io_sgl_list(
7647 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7648 		/* failed to post any nvme buffer, return error */
7649 		if (num_posted == 0)
7650 			rc = -EIO;
7651 	}
7652 	return rc;
7653 }
7654 
7655 static void
7656 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7657 {
7658 	uint32_t len;
7659 
7660 	len = sizeof(struct lpfc_mbx_set_host_data) -
7661 		sizeof(struct lpfc_sli4_cfg_mhdr);
7662 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7663 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7664 			 LPFC_SLI4_MBX_EMBED);
7665 
7666 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7667 	mbox->u.mqe.un.set_host_data.param_len =
7668 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7669 	snprintf(mbox->u.mqe.un.set_host_data.un.data,
7670 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7671 		 "Linux %s v"LPFC_DRIVER_VERSION,
7672 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7673 }
7674 
7675 int
7676 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7677 		    struct lpfc_queue *drq, int count, int idx)
7678 {
7679 	int rc, i;
7680 	struct lpfc_rqe hrqe;
7681 	struct lpfc_rqe drqe;
7682 	struct lpfc_rqb *rqbp;
7683 	unsigned long flags;
7684 	struct rqb_dmabuf *rqb_buffer;
7685 	LIST_HEAD(rqb_buf_list);
7686 
7687 	rqbp = hrq->rqbp;
7688 	for (i = 0; i < count; i++) {
7689 		spin_lock_irqsave(&phba->hbalock, flags);
7690 		/* IF RQ is already full, don't bother */
7691 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7692 			spin_unlock_irqrestore(&phba->hbalock, flags);
7693 			break;
7694 		}
7695 		spin_unlock_irqrestore(&phba->hbalock, flags);
7696 
7697 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7698 		if (!rqb_buffer)
7699 			break;
7700 		rqb_buffer->hrq = hrq;
7701 		rqb_buffer->drq = drq;
7702 		rqb_buffer->idx = idx;
7703 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7704 	}
7705 
7706 	spin_lock_irqsave(&phba->hbalock, flags);
7707 	while (!list_empty(&rqb_buf_list)) {
7708 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7709 				 hbuf.list);
7710 
7711 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7712 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7713 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7714 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7715 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7716 		if (rc < 0) {
7717 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7718 					"6421 Cannot post to HRQ %d: %x %x %x "
7719 					"DRQ %x %x\n",
7720 					hrq->queue_id,
7721 					hrq->host_index,
7722 					hrq->hba_index,
7723 					hrq->entry_count,
7724 					drq->host_index,
7725 					drq->hba_index);
7726 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7727 		} else {
7728 			list_add_tail(&rqb_buffer->hbuf.list,
7729 				      &rqbp->rqb_buffer_list);
7730 			rqbp->buffer_count++;
7731 		}
7732 	}
7733 	spin_unlock_irqrestore(&phba->hbalock, flags);
7734 	return 1;
7735 }
7736 
7737 static void
7738 lpfc_mbx_cmpl_cgn_set_ftrs(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7739 {
7740 	struct lpfc_vport *vport = pmb->vport;
7741 	union lpfc_sli4_cfg_shdr *shdr;
7742 	u32 shdr_status, shdr_add_status;
7743 	u32 sig, acqe;
7744 
7745 	/* Two outcomes. (1) Set featurs was successul and EDC negotiation
7746 	 * is done. (2) Mailbox failed and send FPIN support only.
7747 	 */
7748 	shdr = (union lpfc_sli4_cfg_shdr *)
7749 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7750 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7751 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7752 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7753 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
7754 				"2516 CGN SET_FEATURE mbox failed with "
7755 				"status x%x add_status x%x, mbx status x%x "
7756 				"Reset Congestion to FPINs only\n",
7757 				shdr_status, shdr_add_status,
7758 				pmb->u.mb.mbxStatus);
7759 		/* If there is a mbox error, move on to RDF */
7760 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7761 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7762 		goto out;
7763 	}
7764 
7765 	/* Zero out Congestion Signal ACQE counter */
7766 	phba->cgn_acqe_cnt = 0;
7767 
7768 	acqe = bf_get(lpfc_mbx_set_feature_CGN_acqe_freq,
7769 		      &pmb->u.mqe.un.set_feature);
7770 	sig = bf_get(lpfc_mbx_set_feature_CGN_warn_freq,
7771 		     &pmb->u.mqe.un.set_feature);
7772 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7773 			"4620 SET_FEATURES Success: Freq: %ds %dms "
7774 			" Reg: x%x x%x\n", acqe, sig,
7775 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7776 out:
7777 	mempool_free(pmb, phba->mbox_mem_pool);
7778 
7779 	/* Register for FPIN events from the fabric now that the
7780 	 * EDC common_set_features has completed.
7781 	 */
7782 	lpfc_issue_els_rdf(vport, 0);
7783 }
7784 
7785 int
7786 lpfc_config_cgn_signal(struct lpfc_hba *phba)
7787 {
7788 	LPFC_MBOXQ_t *mboxq;
7789 	u32 rc;
7790 
7791 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7792 	if (!mboxq)
7793 		goto out_rdf;
7794 
7795 	lpfc_set_features(phba, mboxq, LPFC_SET_CGN_SIGNAL);
7796 	mboxq->vport = phba->pport;
7797 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_cgn_set_ftrs;
7798 
7799 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7800 			"4621 SET_FEATURES: FREQ sig x%x acqe x%x: "
7801 			"Reg: x%x x%x\n",
7802 			phba->cgn_sig_freq, lpfc_acqe_cgn_frequency,
7803 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7804 
7805 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7806 	if (rc == MBX_NOT_FINISHED)
7807 		goto out;
7808 	return 0;
7809 
7810 out:
7811 	mempool_free(mboxq, phba->mbox_mem_pool);
7812 out_rdf:
7813 	/* If there is a mbox error, move on to RDF */
7814 	phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7815 	phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7816 	lpfc_issue_els_rdf(phba->pport, 0);
7817 	return -EIO;
7818 }
7819 
7820 /**
7821  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7822  * @phba: pointer to lpfc hba data structure.
7823  *
7824  * This routine initializes the per-cq idle_stat to dynamically dictate
7825  * polling decisions.
7826  *
7827  * Return codes:
7828  *   None
7829  **/
7830 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
7831 {
7832 	int i;
7833 	struct lpfc_sli4_hdw_queue *hdwq;
7834 	struct lpfc_queue *cq;
7835 	struct lpfc_idle_stat *idle_stat;
7836 	u64 wall;
7837 
7838 	for_each_present_cpu(i) {
7839 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
7840 		cq = hdwq->io_cq;
7841 
7842 		/* Skip if we've already handled this cq's primary CPU */
7843 		if (cq->chann != i)
7844 			continue;
7845 
7846 		idle_stat = &phba->sli4_hba.idle_stat[i];
7847 
7848 		idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
7849 		idle_stat->prev_wall = wall;
7850 
7851 		if (phba->nvmet_support ||
7852 		    phba->cmf_active_mode != LPFC_CFG_OFF)
7853 			cq->poll_mode = LPFC_QUEUE_WORK;
7854 		else
7855 			cq->poll_mode = LPFC_IRQ_POLL;
7856 	}
7857 
7858 	if (!phba->nvmet_support)
7859 		schedule_delayed_work(&phba->idle_stat_delay_work,
7860 				      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
7861 }
7862 
7863 static void lpfc_sli4_dip(struct lpfc_hba *phba)
7864 {
7865 	uint32_t if_type;
7866 
7867 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
7868 	if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
7869 	    if_type == LPFC_SLI_INTF_IF_TYPE_6) {
7870 		struct lpfc_register reg_data;
7871 
7872 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
7873 			       &reg_data.word0))
7874 			return;
7875 
7876 		if (bf_get(lpfc_sliport_status_dip, &reg_data))
7877 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7878 					"2904 Firmware Dump Image Present"
7879 					" on Adapter");
7880 	}
7881 }
7882 
7883 /**
7884  * lpfc_cmf_setup - Initialize idle_stat tracking
7885  * @phba: Pointer to HBA context object.
7886  *
7887  * This is called from HBA setup during driver load or when the HBA
7888  * comes online. this does all the initialization to support CMF and MI.
7889  **/
7890 static int
7891 lpfc_cmf_setup(struct lpfc_hba *phba)
7892 {
7893 	LPFC_MBOXQ_t *mboxq;
7894 	struct lpfc_mqe *mqe;
7895 	struct lpfc_dmabuf *mp;
7896 	struct lpfc_pc_sli4_params *sli4_params;
7897 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
7898 	int length;
7899 	int rc, cmf, mi_ver;
7900 
7901 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7902 	if (!mboxq)
7903 		return -ENOMEM;
7904 	mqe = &mboxq->u.mqe;
7905 
7906 	/* Read the port's SLI4 Config Parameters */
7907 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
7908 		  sizeof(struct lpfc_sli4_cfg_mhdr));
7909 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
7910 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
7911 			 length, LPFC_SLI4_MBX_EMBED);
7912 
7913 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7914 	if (unlikely(rc)) {
7915 		mempool_free(mboxq, phba->mbox_mem_pool);
7916 		return rc;
7917 	}
7918 
7919 	/* Gather info on CMF and MI support */
7920 	sli4_params = &phba->sli4_hba.pc_sli4_params;
7921 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
7922 	sli4_params->mi_ver = bf_get(cfg_mi_ver, mbx_sli4_parameters);
7923 	sli4_params->cmf = bf_get(cfg_cmf, mbx_sli4_parameters);
7924 
7925 	/* Are we forcing MI off via module parameter? */
7926 	if (!phba->cfg_enable_mi)
7927 		sli4_params->mi_ver = 0;
7928 
7929 	/* Always try to enable MI feature if we can */
7930 	if (sli4_params->mi_ver) {
7931 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_MI);
7932 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7933 		mi_ver = bf_get(lpfc_mbx_set_feature_mi,
7934 				 &mboxq->u.mqe.un.set_feature);
7935 
7936 		if (rc == MBX_SUCCESS) {
7937 			if (mi_ver) {
7938 				lpfc_printf_log(phba,
7939 						KERN_WARNING, LOG_CGN_MGMT,
7940 						"6215 MI is enabled\n");
7941 				sli4_params->mi_ver = mi_ver;
7942 			} else {
7943 				lpfc_printf_log(phba,
7944 						KERN_WARNING, LOG_CGN_MGMT,
7945 						"6338 MI is disabled\n");
7946 				sli4_params->mi_ver = 0;
7947 			}
7948 		} else {
7949 			/* mi_ver is already set from GET_SLI4_PARAMETERS */
7950 			lpfc_printf_log(phba, KERN_INFO,
7951 					LOG_CGN_MGMT | LOG_INIT,
7952 					"6245 Enable MI Mailbox x%x (x%x/x%x) "
7953 					"failed, rc:x%x mi:x%x\n",
7954 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7955 					lpfc_sli_config_mbox_subsys_get
7956 						(phba, mboxq),
7957 					lpfc_sli_config_mbox_opcode_get
7958 						(phba, mboxq),
7959 					rc, sli4_params->mi_ver);
7960 		}
7961 	} else {
7962 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
7963 				"6217 MI is disabled\n");
7964 	}
7965 
7966 	/* Ensure FDMI is enabled for MI if enable_mi is set */
7967 	if (sli4_params->mi_ver)
7968 		phba->cfg_fdmi_on = LPFC_FDMI_SUPPORT;
7969 
7970 	/* Always try to enable CMF feature if we can */
7971 	if (sli4_params->cmf) {
7972 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_CMF);
7973 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7974 		cmf = bf_get(lpfc_mbx_set_feature_cmf,
7975 			     &mboxq->u.mqe.un.set_feature);
7976 		if (rc == MBX_SUCCESS && cmf) {
7977 			lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
7978 					"6218 CMF is enabled: mode %d\n",
7979 					phba->cmf_active_mode);
7980 		} else {
7981 			lpfc_printf_log(phba, KERN_WARNING,
7982 					LOG_CGN_MGMT | LOG_INIT,
7983 					"6219 Enable CMF Mailbox x%x (x%x/x%x) "
7984 					"failed, rc:x%x dd:x%x\n",
7985 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7986 					lpfc_sli_config_mbox_subsys_get
7987 						(phba, mboxq),
7988 					lpfc_sli_config_mbox_opcode_get
7989 						(phba, mboxq),
7990 					rc, cmf);
7991 			sli4_params->cmf = 0;
7992 			phba->cmf_active_mode = LPFC_CFG_OFF;
7993 			goto no_cmf;
7994 		}
7995 
7996 		/* Allocate Congestion Information Buffer */
7997 		if (!phba->cgn_i) {
7998 			mp = kmalloc(sizeof(*mp), GFP_KERNEL);
7999 			if (mp)
8000 				mp->virt = dma_alloc_coherent
8001 						(&phba->pcidev->dev,
8002 						sizeof(struct lpfc_cgn_info),
8003 						&mp->phys, GFP_KERNEL);
8004 			if (!mp || !mp->virt) {
8005 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8006 						"2640 Failed to alloc memory "
8007 						"for Congestion Info\n");
8008 				kfree(mp);
8009 				sli4_params->cmf = 0;
8010 				phba->cmf_active_mode = LPFC_CFG_OFF;
8011 				goto no_cmf;
8012 			}
8013 			phba->cgn_i = mp;
8014 
8015 			/* initialize congestion buffer info */
8016 			lpfc_init_congestion_buf(phba);
8017 			lpfc_init_congestion_stat(phba);
8018 
8019 			/* Zero out Congestion Signal counters */
8020 			atomic64_set(&phba->cgn_acqe_stat.alarm, 0);
8021 			atomic64_set(&phba->cgn_acqe_stat.warn, 0);
8022 		}
8023 
8024 		rc = lpfc_sli4_cgn_params_read(phba);
8025 		if (rc < 0) {
8026 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8027 					"6242 Error reading Cgn Params (%d)\n",
8028 					rc);
8029 			/* Ensure CGN Mode is off */
8030 			sli4_params->cmf = 0;
8031 		} else if (!rc) {
8032 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8033 					"6243 CGN Event empty object.\n");
8034 			/* Ensure CGN Mode is off */
8035 			sli4_params->cmf = 0;
8036 		}
8037 	} else {
8038 no_cmf:
8039 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8040 				"6220 CMF is disabled\n");
8041 	}
8042 
8043 	/* Only register congestion buffer with firmware if BOTH
8044 	 * CMF and E2E are enabled.
8045 	 */
8046 	if (sli4_params->cmf && sli4_params->mi_ver) {
8047 		rc = lpfc_reg_congestion_buf(phba);
8048 		if (rc) {
8049 			dma_free_coherent(&phba->pcidev->dev,
8050 					  sizeof(struct lpfc_cgn_info),
8051 					  phba->cgn_i->virt, phba->cgn_i->phys);
8052 			kfree(phba->cgn_i);
8053 			phba->cgn_i = NULL;
8054 			/* Ensure CGN Mode is off */
8055 			phba->cmf_active_mode = LPFC_CFG_OFF;
8056 			return 0;
8057 		}
8058 	}
8059 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8060 			"6470 Setup MI version %d CMF %d mode %d\n",
8061 			sli4_params->mi_ver, sli4_params->cmf,
8062 			phba->cmf_active_mode);
8063 
8064 	mempool_free(mboxq, phba->mbox_mem_pool);
8065 
8066 	/* Initialize atomic counters */
8067 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
8068 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
8069 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
8070 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
8071 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
8072 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
8073 	atomic64_set(&phba->cgn_latency_evt, 0);
8074 
8075 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
8076 
8077 	/* Allocate RX Monitor Buffer */
8078 	if (!phba->rxtable) {
8079 		phba->rxtable = kmalloc_array(LPFC_MAX_RXMONITOR_ENTRY,
8080 					      sizeof(struct rxtable_entry),
8081 					      GFP_KERNEL);
8082 		if (!phba->rxtable) {
8083 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8084 					"2644 Failed to alloc memory "
8085 					"for RX Monitor Buffer\n");
8086 			return -ENOMEM;
8087 		}
8088 	}
8089 	atomic_set(&phba->rxtable_idx_head, 0);
8090 	atomic_set(&phba->rxtable_idx_tail, 0);
8091 	return 0;
8092 }
8093 
8094 static int
8095 lpfc_set_host_tm(struct lpfc_hba *phba)
8096 {
8097 	LPFC_MBOXQ_t *mboxq;
8098 	uint32_t len, rc;
8099 	struct timespec64 cur_time;
8100 	struct tm broken;
8101 	uint32_t month, day, year;
8102 	uint32_t hour, minute, second;
8103 	struct lpfc_mbx_set_host_date_time *tm;
8104 
8105 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8106 	if (!mboxq)
8107 		return -ENOMEM;
8108 
8109 	len = sizeof(struct lpfc_mbx_set_host_data) -
8110 		sizeof(struct lpfc_sli4_cfg_mhdr);
8111 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
8112 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
8113 			 LPFC_SLI4_MBX_EMBED);
8114 
8115 	mboxq->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_DATE_TIME;
8116 	mboxq->u.mqe.un.set_host_data.param_len =
8117 			sizeof(struct lpfc_mbx_set_host_date_time);
8118 	tm = &mboxq->u.mqe.un.set_host_data.un.tm;
8119 	ktime_get_real_ts64(&cur_time);
8120 	time64_to_tm(cur_time.tv_sec, 0, &broken);
8121 	month = broken.tm_mon + 1;
8122 	day = broken.tm_mday;
8123 	year = broken.tm_year - 100;
8124 	hour = broken.tm_hour;
8125 	minute = broken.tm_min;
8126 	second = broken.tm_sec;
8127 	bf_set(lpfc_mbx_set_host_month, tm, month);
8128 	bf_set(lpfc_mbx_set_host_day, tm, day);
8129 	bf_set(lpfc_mbx_set_host_year, tm, year);
8130 	bf_set(lpfc_mbx_set_host_hour, tm, hour);
8131 	bf_set(lpfc_mbx_set_host_min, tm, minute);
8132 	bf_set(lpfc_mbx_set_host_sec, tm, second);
8133 
8134 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8135 	mempool_free(mboxq, phba->mbox_mem_pool);
8136 	return rc;
8137 }
8138 
8139 /**
8140  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
8141  * @phba: Pointer to HBA context object.
8142  *
8143  * This function is the main SLI4 device initialization PCI function. This
8144  * function is called by the HBA initialization code, HBA reset code and
8145  * HBA error attention handler code. Caller is not required to hold any
8146  * locks.
8147  **/
8148 int
8149 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
8150 {
8151 	int rc, i, cnt, len, dd;
8152 	LPFC_MBOXQ_t *mboxq;
8153 	struct lpfc_mqe *mqe;
8154 	uint8_t *vpd;
8155 	uint32_t vpd_size;
8156 	uint32_t ftr_rsp = 0;
8157 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
8158 	struct lpfc_vport *vport = phba->pport;
8159 	struct lpfc_dmabuf *mp;
8160 	struct lpfc_rqb *rqbp;
8161 	u32 flg;
8162 
8163 	/* Perform a PCI function reset to start from clean */
8164 	rc = lpfc_pci_function_reset(phba);
8165 	if (unlikely(rc))
8166 		return -ENODEV;
8167 
8168 	/* Check the HBA Host Status Register for readyness */
8169 	rc = lpfc_sli4_post_status_check(phba);
8170 	if (unlikely(rc))
8171 		return -ENODEV;
8172 	else {
8173 		spin_lock_irq(&phba->hbalock);
8174 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
8175 		flg = phba->sli.sli_flag;
8176 		spin_unlock_irq(&phba->hbalock);
8177 		/* Allow a little time after setting SLI_ACTIVE for any polled
8178 		 * MBX commands to complete via BSG.
8179 		 */
8180 		for (i = 0; i < 50 && (flg & LPFC_SLI_MBOX_ACTIVE); i++) {
8181 			msleep(20);
8182 			spin_lock_irq(&phba->hbalock);
8183 			flg = phba->sli.sli_flag;
8184 			spin_unlock_irq(&phba->hbalock);
8185 		}
8186 	}
8187 
8188 	lpfc_sli4_dip(phba);
8189 
8190 	/*
8191 	 * Allocate a single mailbox container for initializing the
8192 	 * port.
8193 	 */
8194 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8195 	if (!mboxq)
8196 		return -ENOMEM;
8197 
8198 	/* Issue READ_REV to collect vpd and FW information. */
8199 	vpd_size = SLI4_PAGE_SIZE;
8200 	vpd = kzalloc(vpd_size, GFP_KERNEL);
8201 	if (!vpd) {
8202 		rc = -ENOMEM;
8203 		goto out_free_mbox;
8204 	}
8205 
8206 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
8207 	if (unlikely(rc)) {
8208 		kfree(vpd);
8209 		goto out_free_mbox;
8210 	}
8211 
8212 	mqe = &mboxq->u.mqe;
8213 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
8214 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
8215 		phba->hba_flag |= HBA_FCOE_MODE;
8216 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
8217 	} else {
8218 		phba->hba_flag &= ~HBA_FCOE_MODE;
8219 	}
8220 
8221 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
8222 		LPFC_DCBX_CEE_MODE)
8223 		phba->hba_flag |= HBA_FIP_SUPPORT;
8224 	else
8225 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
8226 
8227 	phba->hba_flag &= ~HBA_IOQ_FLUSH;
8228 
8229 	if (phba->sli_rev != LPFC_SLI_REV4) {
8230 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8231 			"0376 READ_REV Error. SLI Level %d "
8232 			"FCoE enabled %d\n",
8233 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
8234 		rc = -EIO;
8235 		kfree(vpd);
8236 		goto out_free_mbox;
8237 	}
8238 
8239 	rc = lpfc_set_host_tm(phba);
8240 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
8241 			"6468 Set host date / time: Status x%x:\n", rc);
8242 
8243 	/*
8244 	 * Continue initialization with default values even if driver failed
8245 	 * to read FCoE param config regions, only read parameters if the
8246 	 * board is FCoE
8247 	 */
8248 	if (phba->hba_flag & HBA_FCOE_MODE &&
8249 	    lpfc_sli4_read_fcoe_params(phba))
8250 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
8251 			"2570 Failed to read FCoE parameters\n");
8252 
8253 	/*
8254 	 * Retrieve sli4 device physical port name, failure of doing it
8255 	 * is considered as non-fatal.
8256 	 */
8257 	rc = lpfc_sli4_retrieve_pport_name(phba);
8258 	if (!rc)
8259 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8260 				"3080 Successful retrieving SLI4 device "
8261 				"physical port name: %s.\n", phba->Port);
8262 
8263 	rc = lpfc_sli4_get_ctl_attr(phba);
8264 	if (!rc)
8265 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8266 				"8351 Successful retrieving SLI4 device "
8267 				"CTL ATTR\n");
8268 
8269 	/*
8270 	 * Evaluate the read rev and vpd data. Populate the driver
8271 	 * state with the results. If this routine fails, the failure
8272 	 * is not fatal as the driver will use generic values.
8273 	 */
8274 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
8275 	if (unlikely(!rc)) {
8276 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8277 				"0377 Error %d parsing vpd. "
8278 				"Using defaults.\n", rc);
8279 		rc = 0;
8280 	}
8281 	kfree(vpd);
8282 
8283 	/* Save information as VPD data */
8284 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
8285 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
8286 
8287 	/*
8288 	 * This is because first G7 ASIC doesn't support the standard
8289 	 * 0x5a NVME cmd descriptor type/subtype
8290 	 */
8291 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8292 			LPFC_SLI_INTF_IF_TYPE_6) &&
8293 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
8294 	    (phba->vpd.rev.smRev == 0) &&
8295 	    (phba->cfg_nvme_embed_cmd == 1))
8296 		phba->cfg_nvme_embed_cmd = 0;
8297 
8298 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
8299 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
8300 					 &mqe->un.read_rev);
8301 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
8302 				       &mqe->un.read_rev);
8303 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
8304 					    &mqe->un.read_rev);
8305 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
8306 					   &mqe->un.read_rev);
8307 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
8308 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
8309 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
8310 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
8311 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
8312 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
8313 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8314 			"(%d):0380 READ_REV Status x%x "
8315 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
8316 			mboxq->vport ? mboxq->vport->vpi : 0,
8317 			bf_get(lpfc_mqe_status, mqe),
8318 			phba->vpd.rev.opFwName,
8319 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
8320 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
8321 
8322 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8323 	    LPFC_SLI_INTF_IF_TYPE_0) {
8324 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
8325 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8326 		if (rc == MBX_SUCCESS) {
8327 			phba->hba_flag |= HBA_RECOVERABLE_UE;
8328 			/* Set 1Sec interval to detect UE */
8329 			phba->eratt_poll_interval = 1;
8330 			phba->sli4_hba.ue_to_sr = bf_get(
8331 					lpfc_mbx_set_feature_UESR,
8332 					&mboxq->u.mqe.un.set_feature);
8333 			phba->sli4_hba.ue_to_rp = bf_get(
8334 					lpfc_mbx_set_feature_UERP,
8335 					&mboxq->u.mqe.un.set_feature);
8336 		}
8337 	}
8338 
8339 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
8340 		/* Enable MDS Diagnostics only if the SLI Port supports it */
8341 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
8342 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8343 		if (rc != MBX_SUCCESS)
8344 			phba->mds_diags_support = 0;
8345 	}
8346 
8347 	/*
8348 	 * Discover the port's supported feature set and match it against the
8349 	 * hosts requests.
8350 	 */
8351 	lpfc_request_features(phba, mboxq);
8352 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8353 	if (unlikely(rc)) {
8354 		rc = -EIO;
8355 		goto out_free_mbox;
8356 	}
8357 
8358 	/* Disable VMID if app header is not supported */
8359 	if (phba->cfg_vmid_app_header && !(bf_get(lpfc_mbx_rq_ftr_rsp_ashdr,
8360 						  &mqe->un.req_ftrs))) {
8361 		bf_set(lpfc_ftr_ashdr, &phba->sli4_hba.sli4_flags, 0);
8362 		phba->cfg_vmid_app_header = 0;
8363 		lpfc_printf_log(phba, KERN_DEBUG, LOG_SLI,
8364 				"1242 vmid feature not supported\n");
8365 	}
8366 
8367 	/*
8368 	 * The port must support FCP initiator mode as this is the
8369 	 * only mode running in the host.
8370 	 */
8371 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
8372 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8373 				"0378 No support for fcpi mode.\n");
8374 		ftr_rsp++;
8375 	}
8376 
8377 	/* Performance Hints are ONLY for FCoE */
8378 	if (phba->hba_flag & HBA_FCOE_MODE) {
8379 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
8380 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
8381 		else
8382 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
8383 	}
8384 
8385 	/*
8386 	 * If the port cannot support the host's requested features
8387 	 * then turn off the global config parameters to disable the
8388 	 * feature in the driver.  This is not a fatal error.
8389 	 */
8390 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8391 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
8392 			phba->cfg_enable_bg = 0;
8393 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
8394 			ftr_rsp++;
8395 		}
8396 	}
8397 
8398 	if (phba->max_vpi && phba->cfg_enable_npiv &&
8399 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8400 		ftr_rsp++;
8401 
8402 	if (ftr_rsp) {
8403 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8404 				"0379 Feature Mismatch Data: x%08x %08x "
8405 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
8406 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
8407 				phba->cfg_enable_npiv, phba->max_vpi);
8408 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
8409 			phba->cfg_enable_bg = 0;
8410 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8411 			phba->cfg_enable_npiv = 0;
8412 	}
8413 
8414 	/* These SLI3 features are assumed in SLI4 */
8415 	spin_lock_irq(&phba->hbalock);
8416 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
8417 	spin_unlock_irq(&phba->hbalock);
8418 
8419 	/* Always try to enable dual dump feature if we can */
8420 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
8421 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8422 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
8423 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
8424 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8425 				"6448 Dual Dump is enabled\n");
8426 	else
8427 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
8428 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
8429 				"rc:x%x dd:x%x\n",
8430 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8431 				lpfc_sli_config_mbox_subsys_get(
8432 					phba, mboxq),
8433 				lpfc_sli_config_mbox_opcode_get(
8434 					phba, mboxq),
8435 				rc, dd);
8436 	/*
8437 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
8438 	 * calls depends on these resources to complete port setup.
8439 	 */
8440 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
8441 	if (rc) {
8442 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8443 				"2920 Failed to alloc Resource IDs "
8444 				"rc = x%x\n", rc);
8445 		goto out_free_mbox;
8446 	}
8447 
8448 	lpfc_set_host_data(phba, mboxq);
8449 
8450 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8451 	if (rc) {
8452 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8453 				"2134 Failed to set host os driver version %x",
8454 				rc);
8455 	}
8456 
8457 	/* Read the port's service parameters. */
8458 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
8459 	if (rc) {
8460 		phba->link_state = LPFC_HBA_ERROR;
8461 		rc = -ENOMEM;
8462 		goto out_free_mbox;
8463 	}
8464 
8465 	mboxq->vport = vport;
8466 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8467 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
8468 	if (rc == MBX_SUCCESS) {
8469 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
8470 		rc = 0;
8471 	}
8472 
8473 	/*
8474 	 * This memory was allocated by the lpfc_read_sparam routine. Release
8475 	 * it to the mbuf pool.
8476 	 */
8477 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
8478 	kfree(mp);
8479 	mboxq->ctx_buf = NULL;
8480 	if (unlikely(rc)) {
8481 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8482 				"0382 READ_SPARAM command failed "
8483 				"status %d, mbxStatus x%x\n",
8484 				rc, bf_get(lpfc_mqe_status, mqe));
8485 		phba->link_state = LPFC_HBA_ERROR;
8486 		rc = -EIO;
8487 		goto out_free_mbox;
8488 	}
8489 
8490 	lpfc_update_vport_wwn(vport);
8491 
8492 	/* Update the fc_host data structures with new wwn. */
8493 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
8494 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
8495 
8496 	/* Create all the SLI4 queues */
8497 	rc = lpfc_sli4_queue_create(phba);
8498 	if (rc) {
8499 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8500 				"3089 Failed to allocate queues\n");
8501 		rc = -ENODEV;
8502 		goto out_free_mbox;
8503 	}
8504 	/* Set up all the queues to the device */
8505 	rc = lpfc_sli4_queue_setup(phba);
8506 	if (unlikely(rc)) {
8507 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8508 				"0381 Error %d during queue setup.\n ", rc);
8509 		goto out_stop_timers;
8510 	}
8511 	/* Initialize the driver internal SLI layer lists. */
8512 	lpfc_sli4_setup(phba);
8513 	lpfc_sli4_queue_init(phba);
8514 
8515 	/* update host els xri-sgl sizes and mappings */
8516 	rc = lpfc_sli4_els_sgl_update(phba);
8517 	if (unlikely(rc)) {
8518 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8519 				"1400 Failed to update xri-sgl size and "
8520 				"mapping: %d\n", rc);
8521 		goto out_destroy_queue;
8522 	}
8523 
8524 	/* register the els sgl pool to the port */
8525 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
8526 				       phba->sli4_hba.els_xri_cnt);
8527 	if (unlikely(rc < 0)) {
8528 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8529 				"0582 Error %d during els sgl post "
8530 				"operation\n", rc);
8531 		rc = -ENODEV;
8532 		goto out_destroy_queue;
8533 	}
8534 	phba->sli4_hba.els_xri_cnt = rc;
8535 
8536 	if (phba->nvmet_support) {
8537 		/* update host nvmet xri-sgl sizes and mappings */
8538 		rc = lpfc_sli4_nvmet_sgl_update(phba);
8539 		if (unlikely(rc)) {
8540 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8541 					"6308 Failed to update nvmet-sgl size "
8542 					"and mapping: %d\n", rc);
8543 			goto out_destroy_queue;
8544 		}
8545 
8546 		/* register the nvmet sgl pool to the port */
8547 		rc = lpfc_sli4_repost_sgl_list(
8548 			phba,
8549 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
8550 			phba->sli4_hba.nvmet_xri_cnt);
8551 		if (unlikely(rc < 0)) {
8552 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8553 					"3117 Error %d during nvmet "
8554 					"sgl post\n", rc);
8555 			rc = -ENODEV;
8556 			goto out_destroy_queue;
8557 		}
8558 		phba->sli4_hba.nvmet_xri_cnt = rc;
8559 
8560 		/* We allocate an iocbq for every receive context SGL.
8561 		 * The additional allocation is for abort and ls handling.
8562 		 */
8563 		cnt = phba->sli4_hba.nvmet_xri_cnt +
8564 			phba->sli4_hba.max_cfg_param.max_xri;
8565 	} else {
8566 		/* update host common xri-sgl sizes and mappings */
8567 		rc = lpfc_sli4_io_sgl_update(phba);
8568 		if (unlikely(rc)) {
8569 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8570 					"6082 Failed to update nvme-sgl size "
8571 					"and mapping: %d\n", rc);
8572 			goto out_destroy_queue;
8573 		}
8574 
8575 		/* register the allocated common sgl pool to the port */
8576 		rc = lpfc_sli4_repost_io_sgl_list(phba);
8577 		if (unlikely(rc)) {
8578 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8579 					"6116 Error %d during nvme sgl post "
8580 					"operation\n", rc);
8581 			/* Some NVME buffers were moved to abort nvme list */
8582 			/* A pci function reset will repost them */
8583 			rc = -ENODEV;
8584 			goto out_destroy_queue;
8585 		}
8586 		/* Each lpfc_io_buf job structure has an iocbq element.
8587 		 * This cnt provides for abort, els, ct and ls requests.
8588 		 */
8589 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
8590 	}
8591 
8592 	if (!phba->sli.iocbq_lookup) {
8593 		/* Initialize and populate the iocb list per host */
8594 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8595 				"2821 initialize iocb list with %d entries\n",
8596 				cnt);
8597 		rc = lpfc_init_iocb_list(phba, cnt);
8598 		if (rc) {
8599 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8600 					"1413 Failed to init iocb list.\n");
8601 			goto out_destroy_queue;
8602 		}
8603 	}
8604 
8605 	if (phba->nvmet_support)
8606 		lpfc_nvmet_create_targetport(phba);
8607 
8608 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
8609 		/* Post initial buffers to all RQs created */
8610 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
8611 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
8612 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
8613 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
8614 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
8615 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
8616 			rqbp->buffer_count = 0;
8617 
8618 			lpfc_post_rq_buffer(
8619 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
8620 				phba->sli4_hba.nvmet_mrq_data[i],
8621 				phba->cfg_nvmet_mrq_post, i);
8622 		}
8623 	}
8624 
8625 	/* Post the rpi header region to the device. */
8626 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
8627 	if (unlikely(rc)) {
8628 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8629 				"0393 Error %d during rpi post operation\n",
8630 				rc);
8631 		rc = -ENODEV;
8632 		goto out_free_iocblist;
8633 	}
8634 	lpfc_sli4_node_prep(phba);
8635 
8636 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
8637 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
8638 			/*
8639 			 * The FC Port needs to register FCFI (index 0)
8640 			 */
8641 			lpfc_reg_fcfi(phba, mboxq);
8642 			mboxq->vport = phba->pport;
8643 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8644 			if (rc != MBX_SUCCESS)
8645 				goto out_unset_queue;
8646 			rc = 0;
8647 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
8648 						&mboxq->u.mqe.un.reg_fcfi);
8649 		} else {
8650 			/* We are a NVME Target mode with MRQ > 1 */
8651 
8652 			/* First register the FCFI */
8653 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
8654 			mboxq->vport = phba->pport;
8655 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8656 			if (rc != MBX_SUCCESS)
8657 				goto out_unset_queue;
8658 			rc = 0;
8659 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
8660 						&mboxq->u.mqe.un.reg_fcfi_mrq);
8661 
8662 			/* Next register the MRQs */
8663 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
8664 			mboxq->vport = phba->pport;
8665 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8666 			if (rc != MBX_SUCCESS)
8667 				goto out_unset_queue;
8668 			rc = 0;
8669 		}
8670 		/* Check if the port is configured to be disabled */
8671 		lpfc_sli_read_link_ste(phba);
8672 	}
8673 
8674 	/* Don't post more new bufs if repost already recovered
8675 	 * the nvme sgls.
8676 	 */
8677 	if (phba->nvmet_support == 0) {
8678 		if (phba->sli4_hba.io_xri_cnt == 0) {
8679 			len = lpfc_new_io_buf(
8680 					      phba, phba->sli4_hba.io_xri_max);
8681 			if (len == 0) {
8682 				rc = -ENOMEM;
8683 				goto out_unset_queue;
8684 			}
8685 
8686 			if (phba->cfg_xri_rebalancing)
8687 				lpfc_create_multixri_pools(phba);
8688 		}
8689 	} else {
8690 		phba->cfg_xri_rebalancing = 0;
8691 	}
8692 
8693 	/* Allow asynchronous mailbox command to go through */
8694 	spin_lock_irq(&phba->hbalock);
8695 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8696 	spin_unlock_irq(&phba->hbalock);
8697 
8698 	/* Post receive buffers to the device */
8699 	lpfc_sli4_rb_setup(phba);
8700 
8701 	/* Reset HBA FCF states after HBA reset */
8702 	phba->fcf.fcf_flag = 0;
8703 	phba->fcf.current_rec.flag = 0;
8704 
8705 	/* Start the ELS watchdog timer */
8706 	mod_timer(&vport->els_tmofunc,
8707 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
8708 
8709 	/* Start heart beat timer */
8710 	mod_timer(&phba->hb_tmofunc,
8711 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
8712 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
8713 	phba->last_completion_time = jiffies;
8714 
8715 	/* start eq_delay heartbeat */
8716 	if (phba->cfg_auto_imax)
8717 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
8718 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
8719 
8720 	/* start per phba idle_stat_delay heartbeat */
8721 	lpfc_init_idle_stat_hb(phba);
8722 
8723 	/* Start error attention (ERATT) polling timer */
8724 	mod_timer(&phba->eratt_poll,
8725 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
8726 
8727 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
8728 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
8729 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
8730 		if (!rc) {
8731 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8732 					"2829 This device supports "
8733 					"Advanced Error Reporting (AER)\n");
8734 			spin_lock_irq(&phba->hbalock);
8735 			phba->hba_flag |= HBA_AER_ENABLED;
8736 			spin_unlock_irq(&phba->hbalock);
8737 		} else {
8738 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8739 					"2830 This device does not support "
8740 					"Advanced Error Reporting (AER)\n");
8741 			phba->cfg_aer_support = 0;
8742 		}
8743 		rc = 0;
8744 	}
8745 
8746 	/*
8747 	 * The port is ready, set the host's link state to LINK_DOWN
8748 	 * in preparation for link interrupts.
8749 	 */
8750 	spin_lock_irq(&phba->hbalock);
8751 	phba->link_state = LPFC_LINK_DOWN;
8752 
8753 	/* Check if physical ports are trunked */
8754 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
8755 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
8756 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
8757 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
8758 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
8759 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
8760 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
8761 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
8762 	spin_unlock_irq(&phba->hbalock);
8763 
8764 	/* Arm the CQs and then EQs on device */
8765 	lpfc_sli4_arm_cqeq_intr(phba);
8766 
8767 	/* Indicate device interrupt mode */
8768 	phba->sli4_hba.intr_enable = 1;
8769 
8770 	/* Setup CMF after HBA is initialized */
8771 	lpfc_cmf_setup(phba);
8772 
8773 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
8774 	    (phba->hba_flag & LINK_DISABLED)) {
8775 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8776 				"3103 Adapter Link is disabled.\n");
8777 		lpfc_down_link(phba, mboxq);
8778 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8779 		if (rc != MBX_SUCCESS) {
8780 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8781 					"3104 Adapter failed to issue "
8782 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
8783 			goto out_io_buff_free;
8784 		}
8785 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
8786 		/* don't perform init_link on SLI4 FC port loopback test */
8787 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
8788 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
8789 			if (rc)
8790 				goto out_io_buff_free;
8791 		}
8792 	}
8793 	mempool_free(mboxq, phba->mbox_mem_pool);
8794 
8795 	phba->hba_flag |= HBA_SETUP;
8796 	return rc;
8797 
8798 out_io_buff_free:
8799 	/* Free allocated IO Buffers */
8800 	lpfc_io_free(phba);
8801 out_unset_queue:
8802 	/* Unset all the queues set up in this routine when error out */
8803 	lpfc_sli4_queue_unset(phba);
8804 out_free_iocblist:
8805 	lpfc_free_iocb_list(phba);
8806 out_destroy_queue:
8807 	lpfc_sli4_queue_destroy(phba);
8808 out_stop_timers:
8809 	lpfc_stop_hba_timers(phba);
8810 out_free_mbox:
8811 	mempool_free(mboxq, phba->mbox_mem_pool);
8812 	return rc;
8813 }
8814 
8815 /**
8816  * lpfc_mbox_timeout - Timeout call back function for mbox timer
8817  * @t: Context to fetch pointer to hba structure from.
8818  *
8819  * This is the callback function for mailbox timer. The mailbox
8820  * timer is armed when a new mailbox command is issued and the timer
8821  * is deleted when the mailbox complete. The function is called by
8822  * the kernel timer code when a mailbox does not complete within
8823  * expected time. This function wakes up the worker thread to
8824  * process the mailbox timeout and returns. All the processing is
8825  * done by the worker thread function lpfc_mbox_timeout_handler.
8826  **/
8827 void
8828 lpfc_mbox_timeout(struct timer_list *t)
8829 {
8830 	struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
8831 	unsigned long iflag;
8832 	uint32_t tmo_posted;
8833 
8834 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
8835 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
8836 	if (!tmo_posted)
8837 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
8838 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
8839 
8840 	if (!tmo_posted)
8841 		lpfc_worker_wake_up(phba);
8842 	return;
8843 }
8844 
8845 /**
8846  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
8847  *                                    are pending
8848  * @phba: Pointer to HBA context object.
8849  *
8850  * This function checks if any mailbox completions are present on the mailbox
8851  * completion queue.
8852  **/
8853 static bool
8854 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
8855 {
8856 
8857 	uint32_t idx;
8858 	struct lpfc_queue *mcq;
8859 	struct lpfc_mcqe *mcqe;
8860 	bool pending_completions = false;
8861 	uint8_t	qe_valid;
8862 
8863 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8864 		return false;
8865 
8866 	/* Check for completions on mailbox completion queue */
8867 
8868 	mcq = phba->sli4_hba.mbx_cq;
8869 	idx = mcq->hba_index;
8870 	qe_valid = mcq->qe_valid;
8871 	while (bf_get_le32(lpfc_cqe_valid,
8872 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
8873 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
8874 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
8875 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
8876 			pending_completions = true;
8877 			break;
8878 		}
8879 		idx = (idx + 1) % mcq->entry_count;
8880 		if (mcq->hba_index == idx)
8881 			break;
8882 
8883 		/* if the index wrapped around, toggle the valid bit */
8884 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
8885 			qe_valid = (qe_valid) ? 0 : 1;
8886 	}
8887 	return pending_completions;
8888 
8889 }
8890 
8891 /**
8892  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
8893  *					      that were missed.
8894  * @phba: Pointer to HBA context object.
8895  *
8896  * For sli4, it is possible to miss an interrupt. As such mbox completions
8897  * maybe missed causing erroneous mailbox timeouts to occur. This function
8898  * checks to see if mbox completions are on the mailbox completion queue
8899  * and will process all the completions associated with the eq for the
8900  * mailbox completion queue.
8901  **/
8902 static bool
8903 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
8904 {
8905 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
8906 	uint32_t eqidx;
8907 	struct lpfc_queue *fpeq = NULL;
8908 	struct lpfc_queue *eq;
8909 	bool mbox_pending;
8910 
8911 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8912 		return false;
8913 
8914 	/* Find the EQ associated with the mbox CQ */
8915 	if (sli4_hba->hdwq) {
8916 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
8917 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
8918 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
8919 				fpeq = eq;
8920 				break;
8921 			}
8922 		}
8923 	}
8924 	if (!fpeq)
8925 		return false;
8926 
8927 	/* Turn off interrupts from this EQ */
8928 
8929 	sli4_hba->sli4_eq_clr_intr(fpeq);
8930 
8931 	/* Check to see if a mbox completion is pending */
8932 
8933 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
8934 
8935 	/*
8936 	 * If a mbox completion is pending, process all the events on EQ
8937 	 * associated with the mbox completion queue (this could include
8938 	 * mailbox commands, async events, els commands, receive queue data
8939 	 * and fcp commands)
8940 	 */
8941 
8942 	if (mbox_pending)
8943 		/* process and rearm the EQ */
8944 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
8945 	else
8946 		/* Always clear and re-arm the EQ */
8947 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
8948 
8949 	return mbox_pending;
8950 
8951 }
8952 
8953 /**
8954  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
8955  * @phba: Pointer to HBA context object.
8956  *
8957  * This function is called from worker thread when a mailbox command times out.
8958  * The caller is not required to hold any locks. This function will reset the
8959  * HBA and recover all the pending commands.
8960  **/
8961 void
8962 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
8963 {
8964 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
8965 	MAILBOX_t *mb = NULL;
8966 
8967 	struct lpfc_sli *psli = &phba->sli;
8968 
8969 	/* If the mailbox completed, process the completion */
8970 	lpfc_sli4_process_missed_mbox_completions(phba);
8971 
8972 	if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
8973 		return;
8974 
8975 	if (pmbox != NULL)
8976 		mb = &pmbox->u.mb;
8977 	/* Check the pmbox pointer first.  There is a race condition
8978 	 * between the mbox timeout handler getting executed in the
8979 	 * worklist and the mailbox actually completing. When this
8980 	 * race condition occurs, the mbox_active will be NULL.
8981 	 */
8982 	spin_lock_irq(&phba->hbalock);
8983 	if (pmbox == NULL) {
8984 		lpfc_printf_log(phba, KERN_WARNING,
8985 				LOG_MBOX | LOG_SLI,
8986 				"0353 Active Mailbox cleared - mailbox timeout "
8987 				"exiting\n");
8988 		spin_unlock_irq(&phba->hbalock);
8989 		return;
8990 	}
8991 
8992 	/* Mbox cmd <mbxCommand> timeout */
8993 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8994 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
8995 			mb->mbxCommand,
8996 			phba->pport->port_state,
8997 			phba->sli.sli_flag,
8998 			phba->sli.mbox_active);
8999 	spin_unlock_irq(&phba->hbalock);
9000 
9001 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
9002 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
9003 	 * it to fail all outstanding SCSI IO.
9004 	 */
9005 	spin_lock_irq(&phba->pport->work_port_lock);
9006 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9007 	spin_unlock_irq(&phba->pport->work_port_lock);
9008 	spin_lock_irq(&phba->hbalock);
9009 	phba->link_state = LPFC_LINK_UNKNOWN;
9010 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
9011 	spin_unlock_irq(&phba->hbalock);
9012 
9013 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9014 			"0345 Resetting board due to mailbox timeout\n");
9015 
9016 	/* Reset the HBA device */
9017 	lpfc_reset_hba(phba);
9018 }
9019 
9020 /**
9021  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
9022  * @phba: Pointer to HBA context object.
9023  * @pmbox: Pointer to mailbox object.
9024  * @flag: Flag indicating how the mailbox need to be processed.
9025  *
9026  * This function is called by discovery code and HBA management code
9027  * to submit a mailbox command to firmware with SLI-3 interface spec. This
9028  * function gets the hbalock to protect the data structures.
9029  * The mailbox command can be submitted in polling mode, in which case
9030  * this function will wait in a polling loop for the completion of the
9031  * mailbox.
9032  * If the mailbox is submitted in no_wait mode (not polling) the
9033  * function will submit the command and returns immediately without waiting
9034  * for the mailbox completion. The no_wait is supported only when HBA
9035  * is in SLI2/SLI3 mode - interrupts are enabled.
9036  * The SLI interface allows only one mailbox pending at a time. If the
9037  * mailbox is issued in polling mode and there is already a mailbox
9038  * pending, then the function will return an error. If the mailbox is issued
9039  * in NO_WAIT mode and there is a mailbox pending already, the function
9040  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
9041  * The sli layer owns the mailbox object until the completion of mailbox
9042  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
9043  * return codes the caller owns the mailbox command after the return of
9044  * the function.
9045  **/
9046 static int
9047 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
9048 		       uint32_t flag)
9049 {
9050 	MAILBOX_t *mbx;
9051 	struct lpfc_sli *psli = &phba->sli;
9052 	uint32_t status, evtctr;
9053 	uint32_t ha_copy, hc_copy;
9054 	int i;
9055 	unsigned long timeout;
9056 	unsigned long drvr_flag = 0;
9057 	uint32_t word0, ldata;
9058 	void __iomem *to_slim;
9059 	int processing_queue = 0;
9060 
9061 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
9062 	if (!pmbox) {
9063 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9064 		/* processing mbox queue from intr_handler */
9065 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9066 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9067 			return MBX_SUCCESS;
9068 		}
9069 		processing_queue = 1;
9070 		pmbox = lpfc_mbox_get(phba);
9071 		if (!pmbox) {
9072 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9073 			return MBX_SUCCESS;
9074 		}
9075 	}
9076 
9077 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
9078 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
9079 		if(!pmbox->vport) {
9080 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9081 			lpfc_printf_log(phba, KERN_ERR,
9082 					LOG_MBOX | LOG_VPORT,
9083 					"1806 Mbox x%x failed. No vport\n",
9084 					pmbox->u.mb.mbxCommand);
9085 			dump_stack();
9086 			goto out_not_finished;
9087 		}
9088 	}
9089 
9090 	/* If the PCI channel is in offline state, do not post mbox. */
9091 	if (unlikely(pci_channel_offline(phba->pcidev))) {
9092 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9093 		goto out_not_finished;
9094 	}
9095 
9096 	/* If HBA has a deferred error attention, fail the iocb. */
9097 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
9098 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9099 		goto out_not_finished;
9100 	}
9101 
9102 	psli = &phba->sli;
9103 
9104 	mbx = &pmbox->u.mb;
9105 	status = MBX_SUCCESS;
9106 
9107 	if (phba->link_state == LPFC_HBA_ERROR) {
9108 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9109 
9110 		/* Mbox command <mbxCommand> cannot issue */
9111 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9112 				"(%d):0311 Mailbox command x%x cannot "
9113 				"issue Data: x%x x%x\n",
9114 				pmbox->vport ? pmbox->vport->vpi : 0,
9115 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9116 		goto out_not_finished;
9117 	}
9118 
9119 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
9120 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
9121 			!(hc_copy & HC_MBINT_ENA)) {
9122 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9123 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9124 				"(%d):2528 Mailbox command x%x cannot "
9125 				"issue Data: x%x x%x\n",
9126 				pmbox->vport ? pmbox->vport->vpi : 0,
9127 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9128 			goto out_not_finished;
9129 		}
9130 	}
9131 
9132 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9133 		/* Polling for a mbox command when another one is already active
9134 		 * is not allowed in SLI. Also, the driver must have established
9135 		 * SLI2 mode to queue and process multiple mbox commands.
9136 		 */
9137 
9138 		if (flag & MBX_POLL) {
9139 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9140 
9141 			/* Mbox command <mbxCommand> cannot issue */
9142 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9143 					"(%d):2529 Mailbox command x%x "
9144 					"cannot issue Data: x%x x%x\n",
9145 					pmbox->vport ? pmbox->vport->vpi : 0,
9146 					pmbox->u.mb.mbxCommand,
9147 					psli->sli_flag, flag);
9148 			goto out_not_finished;
9149 		}
9150 
9151 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
9152 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9153 			/* Mbox command <mbxCommand> cannot issue */
9154 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9155 					"(%d):2530 Mailbox command x%x "
9156 					"cannot issue Data: x%x x%x\n",
9157 					pmbox->vport ? pmbox->vport->vpi : 0,
9158 					pmbox->u.mb.mbxCommand,
9159 					psli->sli_flag, flag);
9160 			goto out_not_finished;
9161 		}
9162 
9163 		/* Another mailbox command is still being processed, queue this
9164 		 * command to be processed later.
9165 		 */
9166 		lpfc_mbox_put(phba, pmbox);
9167 
9168 		/* Mbox cmd issue - BUSY */
9169 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9170 				"(%d):0308 Mbox cmd issue - BUSY Data: "
9171 				"x%x x%x x%x x%x\n",
9172 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
9173 				mbx->mbxCommand,
9174 				phba->pport ? phba->pport->port_state : 0xff,
9175 				psli->sli_flag, flag);
9176 
9177 		psli->slistat.mbox_busy++;
9178 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9179 
9180 		if (pmbox->vport) {
9181 			lpfc_debugfs_disc_trc(pmbox->vport,
9182 				LPFC_DISC_TRC_MBOX_VPORT,
9183 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
9184 				(uint32_t)mbx->mbxCommand,
9185 				mbx->un.varWords[0], mbx->un.varWords[1]);
9186 		}
9187 		else {
9188 			lpfc_debugfs_disc_trc(phba->pport,
9189 				LPFC_DISC_TRC_MBOX,
9190 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
9191 				(uint32_t)mbx->mbxCommand,
9192 				mbx->un.varWords[0], mbx->un.varWords[1]);
9193 		}
9194 
9195 		return MBX_BUSY;
9196 	}
9197 
9198 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9199 
9200 	/* If we are not polling, we MUST be in SLI2 mode */
9201 	if (flag != MBX_POLL) {
9202 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
9203 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
9204 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9205 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9206 			/* Mbox command <mbxCommand> cannot issue */
9207 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9208 					"(%d):2531 Mailbox command x%x "
9209 					"cannot issue Data: x%x x%x\n",
9210 					pmbox->vport ? pmbox->vport->vpi : 0,
9211 					pmbox->u.mb.mbxCommand,
9212 					psli->sli_flag, flag);
9213 			goto out_not_finished;
9214 		}
9215 		/* timeout active mbox command */
9216 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9217 					   1000);
9218 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
9219 	}
9220 
9221 	/* Mailbox cmd <cmd> issue */
9222 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9223 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
9224 			"x%x\n",
9225 			pmbox->vport ? pmbox->vport->vpi : 0,
9226 			mbx->mbxCommand,
9227 			phba->pport ? phba->pport->port_state : 0xff,
9228 			psli->sli_flag, flag);
9229 
9230 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
9231 		if (pmbox->vport) {
9232 			lpfc_debugfs_disc_trc(pmbox->vport,
9233 				LPFC_DISC_TRC_MBOX_VPORT,
9234 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9235 				(uint32_t)mbx->mbxCommand,
9236 				mbx->un.varWords[0], mbx->un.varWords[1]);
9237 		}
9238 		else {
9239 			lpfc_debugfs_disc_trc(phba->pport,
9240 				LPFC_DISC_TRC_MBOX,
9241 				"MBOX Send:       cmd:x%x mb:x%x x%x",
9242 				(uint32_t)mbx->mbxCommand,
9243 				mbx->un.varWords[0], mbx->un.varWords[1]);
9244 		}
9245 	}
9246 
9247 	psli->slistat.mbox_cmd++;
9248 	evtctr = psli->slistat.mbox_event;
9249 
9250 	/* next set own bit for the adapter and copy over command word */
9251 	mbx->mbxOwner = OWN_CHIP;
9252 
9253 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9254 		/* Populate mbox extension offset word. */
9255 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
9256 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9257 				= (uint8_t *)phba->mbox_ext
9258 				  - (uint8_t *)phba->mbox;
9259 		}
9260 
9261 		/* Copy the mailbox extension data */
9262 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
9263 			lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
9264 					      (uint8_t *)phba->mbox_ext,
9265 					      pmbox->in_ext_byte_len);
9266 		}
9267 		/* Copy command data to host SLIM area */
9268 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
9269 	} else {
9270 		/* Populate mbox extension offset word. */
9271 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
9272 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9273 				= MAILBOX_HBA_EXT_OFFSET;
9274 
9275 		/* Copy the mailbox extension data */
9276 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
9277 			lpfc_memcpy_to_slim(phba->MBslimaddr +
9278 				MAILBOX_HBA_EXT_OFFSET,
9279 				pmbox->ctx_buf, pmbox->in_ext_byte_len);
9280 
9281 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9282 			/* copy command data into host mbox for cmpl */
9283 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
9284 					      MAILBOX_CMD_SIZE);
9285 
9286 		/* First copy mbox command data to HBA SLIM, skip past first
9287 		   word */
9288 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
9289 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
9290 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
9291 
9292 		/* Next copy over first word, with mbxOwner set */
9293 		ldata = *((uint32_t *)mbx);
9294 		to_slim = phba->MBslimaddr;
9295 		writel(ldata, to_slim);
9296 		readl(to_slim); /* flush */
9297 
9298 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9299 			/* switch over to host mailbox */
9300 			psli->sli_flag |= LPFC_SLI_ACTIVE;
9301 	}
9302 
9303 	wmb();
9304 
9305 	switch (flag) {
9306 	case MBX_NOWAIT:
9307 		/* Set up reference to mailbox command */
9308 		psli->mbox_active = pmbox;
9309 		/* Interrupt board to do it */
9310 		writel(CA_MBATT, phba->CAregaddr);
9311 		readl(phba->CAregaddr); /* flush */
9312 		/* Don't wait for it to finish, just return */
9313 		break;
9314 
9315 	case MBX_POLL:
9316 		/* Set up null reference to mailbox command */
9317 		psli->mbox_active = NULL;
9318 		/* Interrupt board to do it */
9319 		writel(CA_MBATT, phba->CAregaddr);
9320 		readl(phba->CAregaddr); /* flush */
9321 
9322 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9323 			/* First read mbox status word */
9324 			word0 = *((uint32_t *)phba->mbox);
9325 			word0 = le32_to_cpu(word0);
9326 		} else {
9327 			/* First read mbox status word */
9328 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
9329 				spin_unlock_irqrestore(&phba->hbalock,
9330 						       drvr_flag);
9331 				goto out_not_finished;
9332 			}
9333 		}
9334 
9335 		/* Read the HBA Host Attention Register */
9336 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9337 			spin_unlock_irqrestore(&phba->hbalock,
9338 						       drvr_flag);
9339 			goto out_not_finished;
9340 		}
9341 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9342 							1000) + jiffies;
9343 		i = 0;
9344 		/* Wait for command to complete */
9345 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
9346 		       (!(ha_copy & HA_MBATT) &&
9347 			(phba->link_state > LPFC_WARM_START))) {
9348 			if (time_after(jiffies, timeout)) {
9349 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9350 				spin_unlock_irqrestore(&phba->hbalock,
9351 						       drvr_flag);
9352 				goto out_not_finished;
9353 			}
9354 
9355 			/* Check if we took a mbox interrupt while we were
9356 			   polling */
9357 			if (((word0 & OWN_CHIP) != OWN_CHIP)
9358 			    && (evtctr != psli->slistat.mbox_event))
9359 				break;
9360 
9361 			if (i++ > 10) {
9362 				spin_unlock_irqrestore(&phba->hbalock,
9363 						       drvr_flag);
9364 				msleep(1);
9365 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
9366 			}
9367 
9368 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9369 				/* First copy command data */
9370 				word0 = *((uint32_t *)phba->mbox);
9371 				word0 = le32_to_cpu(word0);
9372 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
9373 					MAILBOX_t *slimmb;
9374 					uint32_t slimword0;
9375 					/* Check real SLIM for any errors */
9376 					slimword0 = readl(phba->MBslimaddr);
9377 					slimmb = (MAILBOX_t *) & slimword0;
9378 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
9379 					    && slimmb->mbxStatus) {
9380 						psli->sli_flag &=
9381 						    ~LPFC_SLI_ACTIVE;
9382 						word0 = slimword0;
9383 					}
9384 				}
9385 			} else {
9386 				/* First copy command data */
9387 				word0 = readl(phba->MBslimaddr);
9388 			}
9389 			/* Read the HBA Host Attention Register */
9390 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9391 				spin_unlock_irqrestore(&phba->hbalock,
9392 						       drvr_flag);
9393 				goto out_not_finished;
9394 			}
9395 		}
9396 
9397 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9398 			/* copy results back to user */
9399 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
9400 						MAILBOX_CMD_SIZE);
9401 			/* Copy the mailbox extension data */
9402 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9403 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
9404 						      pmbox->ctx_buf,
9405 						      pmbox->out_ext_byte_len);
9406 			}
9407 		} else {
9408 			/* First copy command data */
9409 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
9410 						MAILBOX_CMD_SIZE);
9411 			/* Copy the mailbox extension data */
9412 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9413 				lpfc_memcpy_from_slim(
9414 					pmbox->ctx_buf,
9415 					phba->MBslimaddr +
9416 					MAILBOX_HBA_EXT_OFFSET,
9417 					pmbox->out_ext_byte_len);
9418 			}
9419 		}
9420 
9421 		writel(HA_MBATT, phba->HAregaddr);
9422 		readl(phba->HAregaddr); /* flush */
9423 
9424 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9425 		status = mbx->mbxStatus;
9426 	}
9427 
9428 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9429 	return status;
9430 
9431 out_not_finished:
9432 	if (processing_queue) {
9433 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
9434 		lpfc_mbox_cmpl_put(phba, pmbox);
9435 	}
9436 	return MBX_NOT_FINISHED;
9437 }
9438 
9439 /**
9440  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
9441  * @phba: Pointer to HBA context object.
9442  *
9443  * The function blocks the posting of SLI4 asynchronous mailbox commands from
9444  * the driver internal pending mailbox queue. It will then try to wait out the
9445  * possible outstanding mailbox command before return.
9446  *
9447  * Returns:
9448  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
9449  * 	the outstanding mailbox command timed out.
9450  **/
9451 static int
9452 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
9453 {
9454 	struct lpfc_sli *psli = &phba->sli;
9455 	LPFC_MBOXQ_t *mboxq;
9456 	int rc = 0;
9457 	unsigned long timeout = 0;
9458 	u32 sli_flag;
9459 	u8 cmd, subsys, opcode;
9460 
9461 	/* Mark the asynchronous mailbox command posting as blocked */
9462 	spin_lock_irq(&phba->hbalock);
9463 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
9464 	/* Determine how long we might wait for the active mailbox
9465 	 * command to be gracefully completed by firmware.
9466 	 */
9467 	if (phba->sli.mbox_active)
9468 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
9469 						phba->sli.mbox_active) *
9470 						1000) + jiffies;
9471 	spin_unlock_irq(&phba->hbalock);
9472 
9473 	/* Make sure the mailbox is really active */
9474 	if (timeout)
9475 		lpfc_sli4_process_missed_mbox_completions(phba);
9476 
9477 	/* Wait for the outstanding mailbox command to complete */
9478 	while (phba->sli.mbox_active) {
9479 		/* Check active mailbox complete status every 2ms */
9480 		msleep(2);
9481 		if (time_after(jiffies, timeout)) {
9482 			/* Timeout, mark the outstanding cmd not complete */
9483 
9484 			/* Sanity check sli.mbox_active has not completed or
9485 			 * cancelled from another context during last 2ms sleep,
9486 			 * so take hbalock to be sure before logging.
9487 			 */
9488 			spin_lock_irq(&phba->hbalock);
9489 			if (phba->sli.mbox_active) {
9490 				mboxq = phba->sli.mbox_active;
9491 				cmd = mboxq->u.mb.mbxCommand;
9492 				subsys = lpfc_sli_config_mbox_subsys_get(phba,
9493 									 mboxq);
9494 				opcode = lpfc_sli_config_mbox_opcode_get(phba,
9495 									 mboxq);
9496 				sli_flag = psli->sli_flag;
9497 				spin_unlock_irq(&phba->hbalock);
9498 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9499 						"2352 Mailbox command x%x "
9500 						"(x%x/x%x) sli_flag x%x could "
9501 						"not complete\n",
9502 						cmd, subsys, opcode,
9503 						sli_flag);
9504 			} else {
9505 				spin_unlock_irq(&phba->hbalock);
9506 			}
9507 
9508 			rc = 1;
9509 			break;
9510 		}
9511 	}
9512 
9513 	/* Can not cleanly block async mailbox command, fails it */
9514 	if (rc) {
9515 		spin_lock_irq(&phba->hbalock);
9516 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9517 		spin_unlock_irq(&phba->hbalock);
9518 	}
9519 	return rc;
9520 }
9521 
9522 /**
9523  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
9524  * @phba: Pointer to HBA context object.
9525  *
9526  * The function unblocks and resume posting of SLI4 asynchronous mailbox
9527  * commands from the driver internal pending mailbox queue. It makes sure
9528  * that there is no outstanding mailbox command before resuming posting
9529  * asynchronous mailbox commands. If, for any reason, there is outstanding
9530  * mailbox command, it will try to wait it out before resuming asynchronous
9531  * mailbox command posting.
9532  **/
9533 static void
9534 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
9535 {
9536 	struct lpfc_sli *psli = &phba->sli;
9537 
9538 	spin_lock_irq(&phba->hbalock);
9539 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9540 		/* Asynchronous mailbox posting is not blocked, do nothing */
9541 		spin_unlock_irq(&phba->hbalock);
9542 		return;
9543 	}
9544 
9545 	/* Outstanding synchronous mailbox command is guaranteed to be done,
9546 	 * successful or timeout, after timing-out the outstanding mailbox
9547 	 * command shall always be removed, so just unblock posting async
9548 	 * mailbox command and resume
9549 	 */
9550 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9551 	spin_unlock_irq(&phba->hbalock);
9552 
9553 	/* wake up worker thread to post asynchronous mailbox command */
9554 	lpfc_worker_wake_up(phba);
9555 }
9556 
9557 /**
9558  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
9559  * @phba: Pointer to HBA context object.
9560  * @mboxq: Pointer to mailbox object.
9561  *
9562  * The function waits for the bootstrap mailbox register ready bit from
9563  * port for twice the regular mailbox command timeout value.
9564  *
9565  *      0 - no timeout on waiting for bootstrap mailbox register ready.
9566  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
9567  **/
9568 static int
9569 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9570 {
9571 	uint32_t db_ready;
9572 	unsigned long timeout;
9573 	struct lpfc_register bmbx_reg;
9574 
9575 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
9576 				   * 1000) + jiffies;
9577 
9578 	do {
9579 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
9580 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
9581 		if (!db_ready)
9582 			mdelay(2);
9583 
9584 		if (time_after(jiffies, timeout))
9585 			return MBXERR_ERROR;
9586 	} while (!db_ready);
9587 
9588 	return 0;
9589 }
9590 
9591 /**
9592  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
9593  * @phba: Pointer to HBA context object.
9594  * @mboxq: Pointer to mailbox object.
9595  *
9596  * The function posts a mailbox to the port.  The mailbox is expected
9597  * to be comletely filled in and ready for the port to operate on it.
9598  * This routine executes a synchronous completion operation on the
9599  * mailbox by polling for its completion.
9600  *
9601  * The caller must not be holding any locks when calling this routine.
9602  *
9603  * Returns:
9604  *	MBX_SUCCESS - mailbox posted successfully
9605  *	Any of the MBX error values.
9606  **/
9607 static int
9608 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9609 {
9610 	int rc = MBX_SUCCESS;
9611 	unsigned long iflag;
9612 	uint32_t mcqe_status;
9613 	uint32_t mbx_cmnd;
9614 	struct lpfc_sli *psli = &phba->sli;
9615 	struct lpfc_mqe *mb = &mboxq->u.mqe;
9616 	struct lpfc_bmbx_create *mbox_rgn;
9617 	struct dma_address *dma_address;
9618 
9619 	/*
9620 	 * Only one mailbox can be active to the bootstrap mailbox region
9621 	 * at a time and there is no queueing provided.
9622 	 */
9623 	spin_lock_irqsave(&phba->hbalock, iflag);
9624 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9625 		spin_unlock_irqrestore(&phba->hbalock, iflag);
9626 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9627 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
9628 				"cannot issue Data: x%x x%x\n",
9629 				mboxq->vport ? mboxq->vport->vpi : 0,
9630 				mboxq->u.mb.mbxCommand,
9631 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9632 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9633 				psli->sli_flag, MBX_POLL);
9634 		return MBXERR_ERROR;
9635 	}
9636 	/* The server grabs the token and owns it until release */
9637 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9638 	phba->sli.mbox_active = mboxq;
9639 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9640 
9641 	/* wait for bootstrap mbox register for readyness */
9642 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9643 	if (rc)
9644 		goto exit;
9645 	/*
9646 	 * Initialize the bootstrap memory region to avoid stale data areas
9647 	 * in the mailbox post.  Then copy the caller's mailbox contents to
9648 	 * the bmbx mailbox region.
9649 	 */
9650 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
9651 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
9652 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
9653 			       sizeof(struct lpfc_mqe));
9654 
9655 	/* Post the high mailbox dma address to the port and wait for ready. */
9656 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9657 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
9658 
9659 	/* wait for bootstrap mbox register for hi-address write done */
9660 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9661 	if (rc)
9662 		goto exit;
9663 
9664 	/* Post the low mailbox dma address to the port. */
9665 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
9666 
9667 	/* wait for bootstrap mbox register for low address write done */
9668 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9669 	if (rc)
9670 		goto exit;
9671 
9672 	/*
9673 	 * Read the CQ to ensure the mailbox has completed.
9674 	 * If so, update the mailbox status so that the upper layers
9675 	 * can complete the request normally.
9676 	 */
9677 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
9678 			       sizeof(struct lpfc_mqe));
9679 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
9680 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
9681 			       sizeof(struct lpfc_mcqe));
9682 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
9683 	/*
9684 	 * When the CQE status indicates a failure and the mailbox status
9685 	 * indicates success then copy the CQE status into the mailbox status
9686 	 * (and prefix it with x4000).
9687 	 */
9688 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
9689 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
9690 			bf_set(lpfc_mqe_status, mb,
9691 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
9692 		rc = MBXERR_ERROR;
9693 	} else
9694 		lpfc_sli4_swap_str(phba, mboxq);
9695 
9696 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9697 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
9698 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
9699 			" x%x x%x CQ: x%x x%x x%x x%x\n",
9700 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
9701 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9702 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9703 			bf_get(lpfc_mqe_status, mb),
9704 			mb->un.mb_words[0], mb->un.mb_words[1],
9705 			mb->un.mb_words[2], mb->un.mb_words[3],
9706 			mb->un.mb_words[4], mb->un.mb_words[5],
9707 			mb->un.mb_words[6], mb->un.mb_words[7],
9708 			mb->un.mb_words[8], mb->un.mb_words[9],
9709 			mb->un.mb_words[10], mb->un.mb_words[11],
9710 			mb->un.mb_words[12], mboxq->mcqe.word0,
9711 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
9712 			mboxq->mcqe.trailer);
9713 exit:
9714 	/* We are holding the token, no needed for lock when release */
9715 	spin_lock_irqsave(&phba->hbalock, iflag);
9716 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9717 	phba->sli.mbox_active = NULL;
9718 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9719 	return rc;
9720 }
9721 
9722 /**
9723  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
9724  * @phba: Pointer to HBA context object.
9725  * @mboxq: Pointer to mailbox object.
9726  * @flag: Flag indicating how the mailbox need to be processed.
9727  *
9728  * This function is called by discovery code and HBA management code to submit
9729  * a mailbox command to firmware with SLI-4 interface spec.
9730  *
9731  * Return codes the caller owns the mailbox command after the return of the
9732  * function.
9733  **/
9734 static int
9735 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
9736 		       uint32_t flag)
9737 {
9738 	struct lpfc_sli *psli = &phba->sli;
9739 	unsigned long iflags;
9740 	int rc;
9741 
9742 	/* dump from issue mailbox command if setup */
9743 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
9744 
9745 	rc = lpfc_mbox_dev_check(phba);
9746 	if (unlikely(rc)) {
9747 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9748 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
9749 				"cannot issue Data: x%x x%x\n",
9750 				mboxq->vport ? mboxq->vport->vpi : 0,
9751 				mboxq->u.mb.mbxCommand,
9752 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9753 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9754 				psli->sli_flag, flag);
9755 		goto out_not_finished;
9756 	}
9757 
9758 	/* Detect polling mode and jump to a handler */
9759 	if (!phba->sli4_hba.intr_enable) {
9760 		if (flag == MBX_POLL)
9761 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
9762 		else
9763 			rc = -EIO;
9764 		if (rc != MBX_SUCCESS)
9765 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
9766 					"(%d):2541 Mailbox command x%x "
9767 					"(x%x/x%x) failure: "
9768 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
9769 					"Data: x%x x%x\n",
9770 					mboxq->vport ? mboxq->vport->vpi : 0,
9771 					mboxq->u.mb.mbxCommand,
9772 					lpfc_sli_config_mbox_subsys_get(phba,
9773 									mboxq),
9774 					lpfc_sli_config_mbox_opcode_get(phba,
9775 									mboxq),
9776 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
9777 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
9778 					bf_get(lpfc_mcqe_ext_status,
9779 					       &mboxq->mcqe),
9780 					psli->sli_flag, flag);
9781 		return rc;
9782 	} else if (flag == MBX_POLL) {
9783 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
9784 				"(%d):2542 Try to issue mailbox command "
9785 				"x%x (x%x/x%x) synchronously ahead of async "
9786 				"mailbox command queue: x%x x%x\n",
9787 				mboxq->vport ? mboxq->vport->vpi : 0,
9788 				mboxq->u.mb.mbxCommand,
9789 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9790 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9791 				psli->sli_flag, flag);
9792 		/* Try to block the asynchronous mailbox posting */
9793 		rc = lpfc_sli4_async_mbox_block(phba);
9794 		if (!rc) {
9795 			/* Successfully blocked, now issue sync mbox cmd */
9796 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
9797 			if (rc != MBX_SUCCESS)
9798 				lpfc_printf_log(phba, KERN_WARNING,
9799 					LOG_MBOX | LOG_SLI,
9800 					"(%d):2597 Sync Mailbox command "
9801 					"x%x (x%x/x%x) failure: "
9802 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
9803 					"Data: x%x x%x\n",
9804 					mboxq->vport ? mboxq->vport->vpi : 0,
9805 					mboxq->u.mb.mbxCommand,
9806 					lpfc_sli_config_mbox_subsys_get(phba,
9807 									mboxq),
9808 					lpfc_sli_config_mbox_opcode_get(phba,
9809 									mboxq),
9810 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
9811 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
9812 					bf_get(lpfc_mcqe_ext_status,
9813 					       &mboxq->mcqe),
9814 					psli->sli_flag, flag);
9815 			/* Unblock the async mailbox posting afterward */
9816 			lpfc_sli4_async_mbox_unblock(phba);
9817 		}
9818 		return rc;
9819 	}
9820 
9821 	/* Now, interrupt mode asynchronous mailbox command */
9822 	rc = lpfc_mbox_cmd_check(phba, mboxq);
9823 	if (rc) {
9824 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9825 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
9826 				"cannot issue Data: x%x x%x\n",
9827 				mboxq->vport ? mboxq->vport->vpi : 0,
9828 				mboxq->u.mb.mbxCommand,
9829 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9830 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9831 				psli->sli_flag, flag);
9832 		goto out_not_finished;
9833 	}
9834 
9835 	/* Put the mailbox command to the driver internal FIFO */
9836 	psli->slistat.mbox_busy++;
9837 	spin_lock_irqsave(&phba->hbalock, iflags);
9838 	lpfc_mbox_put(phba, mboxq);
9839 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9840 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9841 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
9842 			"x%x (x%x/x%x) x%x x%x x%x\n",
9843 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
9844 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
9845 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9846 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9847 			phba->pport->port_state,
9848 			psli->sli_flag, MBX_NOWAIT);
9849 	/* Wake up worker thread to transport mailbox command from head */
9850 	lpfc_worker_wake_up(phba);
9851 
9852 	return MBX_BUSY;
9853 
9854 out_not_finished:
9855 	return MBX_NOT_FINISHED;
9856 }
9857 
9858 /**
9859  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
9860  * @phba: Pointer to HBA context object.
9861  *
9862  * This function is called by worker thread to send a mailbox command to
9863  * SLI4 HBA firmware.
9864  *
9865  **/
9866 int
9867 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
9868 {
9869 	struct lpfc_sli *psli = &phba->sli;
9870 	LPFC_MBOXQ_t *mboxq;
9871 	int rc = MBX_SUCCESS;
9872 	unsigned long iflags;
9873 	struct lpfc_mqe *mqe;
9874 	uint32_t mbx_cmnd;
9875 
9876 	/* Check interrupt mode before post async mailbox command */
9877 	if (unlikely(!phba->sli4_hba.intr_enable))
9878 		return MBX_NOT_FINISHED;
9879 
9880 	/* Check for mailbox command service token */
9881 	spin_lock_irqsave(&phba->hbalock, iflags);
9882 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9883 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9884 		return MBX_NOT_FINISHED;
9885 	}
9886 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9887 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9888 		return MBX_NOT_FINISHED;
9889 	}
9890 	if (unlikely(phba->sli.mbox_active)) {
9891 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9892 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9893 				"0384 There is pending active mailbox cmd\n");
9894 		return MBX_NOT_FINISHED;
9895 	}
9896 	/* Take the mailbox command service token */
9897 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9898 
9899 	/* Get the next mailbox command from head of queue */
9900 	mboxq = lpfc_mbox_get(phba);
9901 
9902 	/* If no more mailbox command waiting for post, we're done */
9903 	if (!mboxq) {
9904 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9905 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9906 		return MBX_SUCCESS;
9907 	}
9908 	phba->sli.mbox_active = mboxq;
9909 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9910 
9911 	/* Check device readiness for posting mailbox command */
9912 	rc = lpfc_mbox_dev_check(phba);
9913 	if (unlikely(rc))
9914 		/* Driver clean routine will clean up pending mailbox */
9915 		goto out_not_finished;
9916 
9917 	/* Prepare the mbox command to be posted */
9918 	mqe = &mboxq->u.mqe;
9919 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
9920 
9921 	/* Start timer for the mbox_tmo and log some mailbox post messages */
9922 	mod_timer(&psli->mbox_tmo, (jiffies +
9923 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
9924 
9925 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9926 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
9927 			"x%x x%x\n",
9928 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
9929 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9930 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9931 			phba->pport->port_state, psli->sli_flag);
9932 
9933 	if (mbx_cmnd != MBX_HEARTBEAT) {
9934 		if (mboxq->vport) {
9935 			lpfc_debugfs_disc_trc(mboxq->vport,
9936 				LPFC_DISC_TRC_MBOX_VPORT,
9937 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9938 				mbx_cmnd, mqe->un.mb_words[0],
9939 				mqe->un.mb_words[1]);
9940 		} else {
9941 			lpfc_debugfs_disc_trc(phba->pport,
9942 				LPFC_DISC_TRC_MBOX,
9943 				"MBOX Send: cmd:x%x mb:x%x x%x",
9944 				mbx_cmnd, mqe->un.mb_words[0],
9945 				mqe->un.mb_words[1]);
9946 		}
9947 	}
9948 	psli->slistat.mbox_cmd++;
9949 
9950 	/* Post the mailbox command to the port */
9951 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
9952 	if (rc != MBX_SUCCESS) {
9953 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9954 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
9955 				"cannot issue Data: x%x x%x\n",
9956 				mboxq->vport ? mboxq->vport->vpi : 0,
9957 				mboxq->u.mb.mbxCommand,
9958 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9959 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9960 				psli->sli_flag, MBX_NOWAIT);
9961 		goto out_not_finished;
9962 	}
9963 
9964 	return rc;
9965 
9966 out_not_finished:
9967 	spin_lock_irqsave(&phba->hbalock, iflags);
9968 	if (phba->sli.mbox_active) {
9969 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
9970 		__lpfc_mbox_cmpl_put(phba, mboxq);
9971 		/* Release the token */
9972 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9973 		phba->sli.mbox_active = NULL;
9974 	}
9975 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9976 
9977 	return MBX_NOT_FINISHED;
9978 }
9979 
9980 /**
9981  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
9982  * @phba: Pointer to HBA context object.
9983  * @pmbox: Pointer to mailbox object.
9984  * @flag: Flag indicating how the mailbox need to be processed.
9985  *
9986  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
9987  * the API jump table function pointer from the lpfc_hba struct.
9988  *
9989  * Return codes the caller owns the mailbox command after the return of the
9990  * function.
9991  **/
9992 int
9993 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
9994 {
9995 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
9996 }
9997 
9998 /**
9999  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
10000  * @phba: The hba struct for which this call is being executed.
10001  * @dev_grp: The HBA PCI-Device group number.
10002  *
10003  * This routine sets up the mbox interface API function jump table in @phba
10004  * struct.
10005  * Returns: 0 - success, -ENODEV - failure.
10006  **/
10007 int
10008 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10009 {
10010 
10011 	switch (dev_grp) {
10012 	case LPFC_PCI_DEV_LP:
10013 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
10014 		phba->lpfc_sli_handle_slow_ring_event =
10015 				lpfc_sli_handle_slow_ring_event_s3;
10016 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
10017 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
10018 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
10019 		break;
10020 	case LPFC_PCI_DEV_OC:
10021 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
10022 		phba->lpfc_sli_handle_slow_ring_event =
10023 				lpfc_sli_handle_slow_ring_event_s4;
10024 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
10025 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
10026 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
10027 		break;
10028 	default:
10029 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10030 				"1420 Invalid HBA PCI-device group: 0x%x\n",
10031 				dev_grp);
10032 		return -ENODEV;
10033 	}
10034 	return 0;
10035 }
10036 
10037 /**
10038  * __lpfc_sli_ringtx_put - Add an iocb to the txq
10039  * @phba: Pointer to HBA context object.
10040  * @pring: Pointer to driver SLI ring object.
10041  * @piocb: Pointer to address of newly added command iocb.
10042  *
10043  * This function is called with hbalock held for SLI3 ports or
10044  * the ring lock held for SLI4 ports to add a command
10045  * iocb to the txq when SLI layer cannot submit the command iocb
10046  * to the ring.
10047  **/
10048 void
10049 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10050 		    struct lpfc_iocbq *piocb)
10051 {
10052 	if (phba->sli_rev == LPFC_SLI_REV4)
10053 		lockdep_assert_held(&pring->ring_lock);
10054 	else
10055 		lockdep_assert_held(&phba->hbalock);
10056 	/* Insert the caller's iocb in the txq tail for later processing. */
10057 	list_add_tail(&piocb->list, &pring->txq);
10058 }
10059 
10060 /**
10061  * lpfc_sli_next_iocb - Get the next iocb in the txq
10062  * @phba: Pointer to HBA context object.
10063  * @pring: Pointer to driver SLI ring object.
10064  * @piocb: Pointer to address of newly added command iocb.
10065  *
10066  * This function is called with hbalock held before a new
10067  * iocb is submitted to the firmware. This function checks
10068  * txq to flush the iocbs in txq to Firmware before
10069  * submitting new iocbs to the Firmware.
10070  * If there are iocbs in the txq which need to be submitted
10071  * to firmware, lpfc_sli_next_iocb returns the first element
10072  * of the txq after dequeuing it from txq.
10073  * If there is no iocb in the txq then the function will return
10074  * *piocb and *piocb is set to NULL. Caller needs to check
10075  * *piocb to find if there are more commands in the txq.
10076  **/
10077 static struct lpfc_iocbq *
10078 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10079 		   struct lpfc_iocbq **piocb)
10080 {
10081 	struct lpfc_iocbq * nextiocb;
10082 
10083 	lockdep_assert_held(&phba->hbalock);
10084 
10085 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
10086 	if (!nextiocb) {
10087 		nextiocb = *piocb;
10088 		*piocb = NULL;
10089 	}
10090 
10091 	return nextiocb;
10092 }
10093 
10094 /**
10095  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
10096  * @phba: Pointer to HBA context object.
10097  * @ring_number: SLI ring number to issue iocb on.
10098  * @piocb: Pointer to command iocb.
10099  * @flag: Flag indicating if this command can be put into txq.
10100  *
10101  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
10102  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
10103  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
10104  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
10105  * this function allows only iocbs for posting buffers. This function finds
10106  * next available slot in the command ring and posts the command to the
10107  * available slot and writes the port attention register to request HBA start
10108  * processing new iocb. If there is no slot available in the ring and
10109  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
10110  * the function returns IOCB_BUSY.
10111  *
10112  * This function is called with hbalock held. The function will return success
10113  * after it successfully submit the iocb to firmware or after adding to the
10114  * txq.
10115  **/
10116 static int
10117 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
10118 		    struct lpfc_iocbq *piocb, uint32_t flag)
10119 {
10120 	struct lpfc_iocbq *nextiocb;
10121 	IOCB_t *iocb;
10122 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
10123 
10124 	lockdep_assert_held(&phba->hbalock);
10125 
10126 	if (piocb->iocb_cmpl && (!piocb->vport) &&
10127 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
10128 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
10129 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10130 				"1807 IOCB x%x failed. No vport\n",
10131 				piocb->iocb.ulpCommand);
10132 		dump_stack();
10133 		return IOCB_ERROR;
10134 	}
10135 
10136 
10137 	/* If the PCI channel is in offline state, do not post iocbs. */
10138 	if (unlikely(pci_channel_offline(phba->pcidev)))
10139 		return IOCB_ERROR;
10140 
10141 	/* If HBA has a deferred error attention, fail the iocb. */
10142 	if (unlikely(phba->hba_flag & DEFER_ERATT))
10143 		return IOCB_ERROR;
10144 
10145 	/*
10146 	 * We should never get an IOCB if we are in a < LINK_DOWN state
10147 	 */
10148 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
10149 		return IOCB_ERROR;
10150 
10151 	/*
10152 	 * Check to see if we are blocking IOCB processing because of a
10153 	 * outstanding event.
10154 	 */
10155 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
10156 		goto iocb_busy;
10157 
10158 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
10159 		/*
10160 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
10161 		 * can be issued if the link is not up.
10162 		 */
10163 		switch (piocb->iocb.ulpCommand) {
10164 		case CMD_GEN_REQUEST64_CR:
10165 		case CMD_GEN_REQUEST64_CX:
10166 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
10167 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
10168 					FC_RCTL_DD_UNSOL_CMD) ||
10169 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
10170 					MENLO_TRANSPORT_TYPE))
10171 
10172 				goto iocb_busy;
10173 			break;
10174 		case CMD_QUE_RING_BUF_CN:
10175 		case CMD_QUE_RING_BUF64_CN:
10176 			/*
10177 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
10178 			 * completion, iocb_cmpl MUST be 0.
10179 			 */
10180 			if (piocb->iocb_cmpl)
10181 				piocb->iocb_cmpl = NULL;
10182 			fallthrough;
10183 		case CMD_CREATE_XRI_CR:
10184 		case CMD_CLOSE_XRI_CN:
10185 		case CMD_CLOSE_XRI_CX:
10186 			break;
10187 		default:
10188 			goto iocb_busy;
10189 		}
10190 
10191 	/*
10192 	 * For FCP commands, we must be in a state where we can process link
10193 	 * attention events.
10194 	 */
10195 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
10196 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
10197 		goto iocb_busy;
10198 	}
10199 
10200 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
10201 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
10202 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
10203 
10204 	if (iocb)
10205 		lpfc_sli_update_ring(phba, pring);
10206 	else
10207 		lpfc_sli_update_full_ring(phba, pring);
10208 
10209 	if (!piocb)
10210 		return IOCB_SUCCESS;
10211 
10212 	goto out_busy;
10213 
10214  iocb_busy:
10215 	pring->stats.iocb_cmd_delay++;
10216 
10217  out_busy:
10218 
10219 	if (!(flag & SLI_IOCB_RET_IOCB)) {
10220 		__lpfc_sli_ringtx_put(phba, pring, piocb);
10221 		return IOCB_SUCCESS;
10222 	}
10223 
10224 	return IOCB_BUSY;
10225 }
10226 
10227 /**
10228  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
10229  * @phba: Pointer to HBA context object.
10230  * @piocbq: Pointer to command iocb.
10231  * @sglq: Pointer to the scatter gather queue object.
10232  *
10233  * This routine converts the bpl or bde that is in the IOCB
10234  * to a sgl list for the sli4 hardware. The physical address
10235  * of the bpl/bde is converted back to a virtual address.
10236  * If the IOCB contains a BPL then the list of BDE's is
10237  * converted to sli4_sge's. If the IOCB contains a single
10238  * BDE then it is converted to a single sli_sge.
10239  * The IOCB is still in cpu endianess so the contents of
10240  * the bpl can be used without byte swapping.
10241  *
10242  * Returns valid XRI = Success, NO_XRI = Failure.
10243 **/
10244 static uint16_t
10245 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
10246 		struct lpfc_sglq *sglq)
10247 {
10248 	uint16_t xritag = NO_XRI;
10249 	struct ulp_bde64 *bpl = NULL;
10250 	struct ulp_bde64 bde;
10251 	struct sli4_sge *sgl  = NULL;
10252 	struct lpfc_dmabuf *dmabuf;
10253 	IOCB_t *icmd;
10254 	int numBdes = 0;
10255 	int i = 0;
10256 	uint32_t offset = 0; /* accumulated offset in the sg request list */
10257 	int inbound = 0; /* number of sg reply entries inbound from firmware */
10258 
10259 	if (!piocbq || !sglq)
10260 		return xritag;
10261 
10262 	sgl  = (struct sli4_sge *)sglq->sgl;
10263 	icmd = &piocbq->iocb;
10264 	if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
10265 		return sglq->sli4_xritag;
10266 	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
10267 		numBdes = icmd->un.genreq64.bdl.bdeSize /
10268 				sizeof(struct ulp_bde64);
10269 		/* The addrHigh and addrLow fields within the IOCB
10270 		 * have not been byteswapped yet so there is no
10271 		 * need to swap them back.
10272 		 */
10273 		if (piocbq->context3)
10274 			dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
10275 		else
10276 			return xritag;
10277 
10278 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
10279 		if (!bpl)
10280 			return xritag;
10281 
10282 		for (i = 0; i < numBdes; i++) {
10283 			/* Should already be byte swapped. */
10284 			sgl->addr_hi = bpl->addrHigh;
10285 			sgl->addr_lo = bpl->addrLow;
10286 
10287 			sgl->word2 = le32_to_cpu(sgl->word2);
10288 			if ((i+1) == numBdes)
10289 				bf_set(lpfc_sli4_sge_last, sgl, 1);
10290 			else
10291 				bf_set(lpfc_sli4_sge_last, sgl, 0);
10292 			/* swap the size field back to the cpu so we
10293 			 * can assign it to the sgl.
10294 			 */
10295 			bde.tus.w = le32_to_cpu(bpl->tus.w);
10296 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
10297 			/* The offsets in the sgl need to be accumulated
10298 			 * separately for the request and reply lists.
10299 			 * The request is always first, the reply follows.
10300 			 */
10301 			if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
10302 				/* add up the reply sg entries */
10303 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
10304 					inbound++;
10305 				/* first inbound? reset the offset */
10306 				if (inbound == 1)
10307 					offset = 0;
10308 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
10309 				bf_set(lpfc_sli4_sge_type, sgl,
10310 					LPFC_SGE_TYPE_DATA);
10311 				offset += bde.tus.f.bdeSize;
10312 			}
10313 			sgl->word2 = cpu_to_le32(sgl->word2);
10314 			bpl++;
10315 			sgl++;
10316 		}
10317 	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
10318 			/* The addrHigh and addrLow fields of the BDE have not
10319 			 * been byteswapped yet so they need to be swapped
10320 			 * before putting them in the sgl.
10321 			 */
10322 			sgl->addr_hi =
10323 				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
10324 			sgl->addr_lo =
10325 				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
10326 			sgl->word2 = le32_to_cpu(sgl->word2);
10327 			bf_set(lpfc_sli4_sge_last, sgl, 1);
10328 			sgl->word2 = cpu_to_le32(sgl->word2);
10329 			sgl->sge_len =
10330 				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
10331 	}
10332 	return sglq->sli4_xritag;
10333 }
10334 
10335 /**
10336  * lpfc_sli4_iocb2wqe - Convert the IOCB to a work queue entry.
10337  * @phba: Pointer to HBA context object.
10338  * @iocbq: Pointer to command iocb.
10339  * @wqe: Pointer to the work queue entry.
10340  *
10341  * This routine converts the iocb command to its Work Queue Entry
10342  * equivalent. The wqe pointer should not have any fields set when
10343  * this routine is called because it will memcpy over them.
10344  * This routine does not set the CQ_ID or the WQEC bits in the
10345  * wqe.
10346  *
10347  * Returns: 0 = Success, IOCB_ERROR = Failure.
10348  **/
10349 static int
10350 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
10351 		union lpfc_wqe128 *wqe)
10352 {
10353 	uint32_t xmit_len = 0, total_len = 0;
10354 	uint8_t ct = 0;
10355 	uint32_t fip;
10356 	uint32_t abort_tag;
10357 	uint8_t command_type = ELS_COMMAND_NON_FIP;
10358 	uint8_t cmnd;
10359 	uint16_t xritag;
10360 	uint16_t abrt_iotag;
10361 	struct lpfc_iocbq *abrtiocbq;
10362 	struct ulp_bde64 *bpl = NULL;
10363 	uint32_t els_id = LPFC_ELS_ID_DEFAULT;
10364 	int numBdes, i;
10365 	struct ulp_bde64 bde;
10366 	struct lpfc_nodelist *ndlp;
10367 	uint32_t *pcmd;
10368 	uint32_t if_type;
10369 
10370 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
10371 	/* The fcp commands will set command type */
10372 	if (iocbq->iocb_flag &  LPFC_IO_FCP)
10373 		command_type = FCP_COMMAND;
10374 	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
10375 		command_type = ELS_COMMAND_FIP;
10376 	else
10377 		command_type = ELS_COMMAND_NON_FIP;
10378 
10379 	if (phba->fcp_embed_io)
10380 		memset(wqe, 0, sizeof(union lpfc_wqe128));
10381 	/* Some of the fields are in the right position already */
10382 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
10383 	/* The ct field has moved so reset */
10384 	wqe->generic.wqe_com.word7 = 0;
10385 	wqe->generic.wqe_com.word10 = 0;
10386 
10387 	abort_tag = (uint32_t) iocbq->iotag;
10388 	xritag = iocbq->sli4_xritag;
10389 	/* words0-2 bpl convert bde */
10390 	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
10391 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
10392 				sizeof(struct ulp_bde64);
10393 		bpl  = (struct ulp_bde64 *)
10394 			((struct lpfc_dmabuf *)iocbq->context3)->virt;
10395 		if (!bpl)
10396 			return IOCB_ERROR;
10397 
10398 		/* Should already be byte swapped. */
10399 		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
10400 		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
10401 		/* swap the size field back to the cpu so we
10402 		 * can assign it to the sgl.
10403 		 */
10404 		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
10405 		xmit_len = wqe->generic.bde.tus.f.bdeSize;
10406 		total_len = 0;
10407 		for (i = 0; i < numBdes; i++) {
10408 			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
10409 			total_len += bde.tus.f.bdeSize;
10410 		}
10411 	} else
10412 		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
10413 
10414 	iocbq->iocb.ulpIoTag = iocbq->iotag;
10415 	cmnd = iocbq->iocb.ulpCommand;
10416 
10417 	switch (iocbq->iocb.ulpCommand) {
10418 	case CMD_ELS_REQUEST64_CR:
10419 		if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
10420 			ndlp = iocbq->context_un.ndlp;
10421 		else
10422 			ndlp = (struct lpfc_nodelist *)iocbq->context1;
10423 		if (!iocbq->iocb.ulpLe) {
10424 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10425 				"2007 Only Limited Edition cmd Format"
10426 				" supported 0x%x\n",
10427 				iocbq->iocb.ulpCommand);
10428 			return IOCB_ERROR;
10429 		}
10430 
10431 		wqe->els_req.payload_len = xmit_len;
10432 		/* Els_reguest64 has a TMO */
10433 		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
10434 			iocbq->iocb.ulpTimeout);
10435 		/* Need a VF for word 4 set the vf bit*/
10436 		bf_set(els_req64_vf, &wqe->els_req, 0);
10437 		/* And a VFID for word 12 */
10438 		bf_set(els_req64_vfid, &wqe->els_req, 0);
10439 		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
10440 		bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10441 		       iocbq->iocb.ulpContext);
10442 		bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
10443 		bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
10444 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
10445 		if (command_type == ELS_COMMAND_FIP)
10446 			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
10447 					>> LPFC_FIP_ELS_ID_SHIFT);
10448 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
10449 					iocbq->context2)->virt);
10450 		if_type = bf_get(lpfc_sli_intf_if_type,
10451 					&phba->sli4_hba.sli_intf);
10452 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10453 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
10454 				*pcmd == ELS_CMD_SCR ||
10455 				*pcmd == ELS_CMD_RDF ||
10456 				*pcmd == ELS_CMD_EDC ||
10457 				*pcmd == ELS_CMD_RSCN_XMT ||
10458 				*pcmd == ELS_CMD_FDISC ||
10459 				*pcmd == ELS_CMD_LOGO ||
10460 				*pcmd == ELS_CMD_QFPA ||
10461 				*pcmd == ELS_CMD_UVEM ||
10462 				*pcmd == ELS_CMD_PLOGI)) {
10463 				bf_set(els_req64_sp, &wqe->els_req, 1);
10464 				bf_set(els_req64_sid, &wqe->els_req,
10465 					iocbq->vport->fc_myDID);
10466 				if ((*pcmd == ELS_CMD_FLOGI) &&
10467 					!(phba->fc_topology ==
10468 						LPFC_TOPOLOGY_LOOP))
10469 					bf_set(els_req64_sid, &wqe->els_req, 0);
10470 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
10471 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10472 					phba->vpi_ids[iocbq->vport->vpi]);
10473 			} else if (pcmd && iocbq->context1) {
10474 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
10475 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10476 					phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
10477 			}
10478 		}
10479 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
10480 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
10481 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
10482 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
10483 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
10484 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
10485 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
10486 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
10487 		wqe->els_req.max_response_payload_len = total_len - xmit_len;
10488 		break;
10489 	case CMD_XMIT_SEQUENCE64_CX:
10490 		bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
10491 		       iocbq->iocb.un.ulpWord[3]);
10492 		bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
10493 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
10494 		/* The entire sequence is transmitted for this IOCB */
10495 		xmit_len = total_len;
10496 		cmnd = CMD_XMIT_SEQUENCE64_CR;
10497 		if (phba->link_flag & LS_LOOPBACK_MODE)
10498 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
10499 		fallthrough;
10500 	case CMD_XMIT_SEQUENCE64_CR:
10501 		/* word3 iocb=io_tag32 wqe=reserved */
10502 		wqe->xmit_sequence.rsvd3 = 0;
10503 		/* word4 relative_offset memcpy */
10504 		/* word5 r_ctl/df_ctl memcpy */
10505 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
10506 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
10507 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
10508 		       LPFC_WQE_IOD_WRITE);
10509 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
10510 		       LPFC_WQE_LENLOC_WORD12);
10511 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
10512 		wqe->xmit_sequence.xmit_len = xmit_len;
10513 		command_type = OTHER_COMMAND;
10514 		break;
10515 	case CMD_XMIT_BCAST64_CN:
10516 		/* word3 iocb=iotag32 wqe=seq_payload_len */
10517 		wqe->xmit_bcast64.seq_payload_len = xmit_len;
10518 		/* word4 iocb=rsvd wqe=rsvd */
10519 		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
10520 		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
10521 		bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
10522 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
10523 		bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
10524 		bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
10525 		bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
10526 		       LPFC_WQE_LENLOC_WORD3);
10527 		bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
10528 		break;
10529 	case CMD_FCP_IWRITE64_CR:
10530 		command_type = FCP_COMMAND_DATA_OUT;
10531 		/* word3 iocb=iotag wqe=payload_offset_len */
10532 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
10533 		bf_set(payload_offset_len, &wqe->fcp_iwrite,
10534 		       xmit_len + sizeof(struct fcp_rsp));
10535 		bf_set(cmd_buff_len, &wqe->fcp_iwrite,
10536 		       0);
10537 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
10538 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
10539 		bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
10540 		       iocbq->iocb.ulpFCP2Rcvy);
10541 		bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
10542 		/* Always open the exchange */
10543 		bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
10544 		bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
10545 		       LPFC_WQE_LENLOC_WORD4);
10546 		bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
10547 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
10548 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
10549 			bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
10550 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
10551 			if (iocbq->priority) {
10552 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10553 				       (iocbq->priority << 1));
10554 			} else {
10555 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10556 				       (phba->cfg_XLanePriority << 1));
10557 			}
10558 		}
10559 		/* Note, word 10 is already initialized to 0 */
10560 
10561 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
10562 		if (phba->cfg_enable_pbde)
10563 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 1);
10564 		else
10565 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
10566 
10567 		if (phba->fcp_embed_io) {
10568 			struct lpfc_io_buf *lpfc_cmd;
10569 			struct sli4_sge *sgl;
10570 			struct fcp_cmnd *fcp_cmnd;
10571 			uint32_t *ptr;
10572 
10573 			/* 128 byte wqe support here */
10574 
10575 			lpfc_cmd = iocbq->context1;
10576 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10577 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
10578 
10579 			/* Word 0-2 - FCP_CMND */
10580 			wqe->generic.bde.tus.f.bdeFlags =
10581 				BUFF_TYPE_BDE_IMMED;
10582 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10583 			wqe->generic.bde.addrHigh = 0;
10584 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
10585 
10586 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10587 			bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10588 
10589 			/* Word 22-29  FCP CMND Payload */
10590 			ptr = &wqe->words[22];
10591 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10592 		}
10593 		break;
10594 	case CMD_FCP_IREAD64_CR:
10595 		/* word3 iocb=iotag wqe=payload_offset_len */
10596 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
10597 		bf_set(payload_offset_len, &wqe->fcp_iread,
10598 		       xmit_len + sizeof(struct fcp_rsp));
10599 		bf_set(cmd_buff_len, &wqe->fcp_iread,
10600 		       0);
10601 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
10602 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
10603 		bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
10604 		       iocbq->iocb.ulpFCP2Rcvy);
10605 		bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
10606 		/* Always open the exchange */
10607 		bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
10608 		bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
10609 		       LPFC_WQE_LENLOC_WORD4);
10610 		bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
10611 		bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
10612 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
10613 			bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
10614 			bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
10615 			if (iocbq->priority) {
10616 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
10617 				       (iocbq->priority << 1));
10618 			} else {
10619 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
10620 				       (phba->cfg_XLanePriority << 1));
10621 			}
10622 		}
10623 		/* Note, word 10 is already initialized to 0 */
10624 
10625 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
10626 		if (phba->cfg_enable_pbde)
10627 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 1);
10628 		else
10629 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
10630 
10631 		if (phba->fcp_embed_io) {
10632 			struct lpfc_io_buf *lpfc_cmd;
10633 			struct sli4_sge *sgl;
10634 			struct fcp_cmnd *fcp_cmnd;
10635 			uint32_t *ptr;
10636 
10637 			/* 128 byte wqe support here */
10638 
10639 			lpfc_cmd = iocbq->context1;
10640 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10641 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
10642 
10643 			/* Word 0-2 - FCP_CMND */
10644 			wqe->generic.bde.tus.f.bdeFlags =
10645 				BUFF_TYPE_BDE_IMMED;
10646 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10647 			wqe->generic.bde.addrHigh = 0;
10648 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
10649 
10650 			bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
10651 			bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
10652 
10653 			/* Word 22-29  FCP CMND Payload */
10654 			ptr = &wqe->words[22];
10655 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10656 		}
10657 		break;
10658 	case CMD_FCP_ICMND64_CR:
10659 		/* word3 iocb=iotag wqe=payload_offset_len */
10660 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
10661 		bf_set(payload_offset_len, &wqe->fcp_icmd,
10662 		       xmit_len + sizeof(struct fcp_rsp));
10663 		bf_set(cmd_buff_len, &wqe->fcp_icmd,
10664 		       0);
10665 		/* word3 iocb=IO_TAG wqe=reserved */
10666 		bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
10667 		/* Always open the exchange */
10668 		bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
10669 		bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
10670 		bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
10671 		bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
10672 		       LPFC_WQE_LENLOC_NONE);
10673 		bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
10674 		       iocbq->iocb.ulpFCP2Rcvy);
10675 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
10676 			bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
10677 			bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
10678 			if (iocbq->priority) {
10679 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
10680 				       (iocbq->priority << 1));
10681 			} else {
10682 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
10683 				       (phba->cfg_XLanePriority << 1));
10684 			}
10685 		}
10686 		/* Note, word 10 is already initialized to 0 */
10687 
10688 		if (phba->fcp_embed_io) {
10689 			struct lpfc_io_buf *lpfc_cmd;
10690 			struct sli4_sge *sgl;
10691 			struct fcp_cmnd *fcp_cmnd;
10692 			uint32_t *ptr;
10693 
10694 			/* 128 byte wqe support here */
10695 
10696 			lpfc_cmd = iocbq->context1;
10697 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10698 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
10699 
10700 			/* Word 0-2 - FCP_CMND */
10701 			wqe->generic.bde.tus.f.bdeFlags =
10702 				BUFF_TYPE_BDE_IMMED;
10703 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10704 			wqe->generic.bde.addrHigh = 0;
10705 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
10706 
10707 			bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
10708 			bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
10709 
10710 			/* Word 22-29  FCP CMND Payload */
10711 			ptr = &wqe->words[22];
10712 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10713 		}
10714 		break;
10715 	case CMD_GEN_REQUEST64_CR:
10716 		/* For this command calculate the xmit length of the
10717 		 * request bde.
10718 		 */
10719 		xmit_len = 0;
10720 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
10721 			sizeof(struct ulp_bde64);
10722 		for (i = 0; i < numBdes; i++) {
10723 			bde.tus.w = le32_to_cpu(bpl[i].tus.w);
10724 			if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
10725 				break;
10726 			xmit_len += bde.tus.f.bdeSize;
10727 		}
10728 		/* word3 iocb=IO_TAG wqe=request_payload_len */
10729 		wqe->gen_req.request_payload_len = xmit_len;
10730 		/* word4 iocb=parameter wqe=relative_offset memcpy */
10731 		/* word5 [rctl, type, df_ctl, la] copied in memcpy */
10732 		/* word6 context tag copied in memcpy */
10733 		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
10734 			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
10735 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10736 				"2015 Invalid CT %x command 0x%x\n",
10737 				ct, iocbq->iocb.ulpCommand);
10738 			return IOCB_ERROR;
10739 		}
10740 		bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
10741 		bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
10742 		bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
10743 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
10744 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
10745 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
10746 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
10747 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
10748 		wqe->gen_req.max_response_payload_len = total_len - xmit_len;
10749 		command_type = OTHER_COMMAND;
10750 		break;
10751 	case CMD_XMIT_ELS_RSP64_CX:
10752 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
10753 		/* words0-2 BDE memcpy */
10754 		/* word3 iocb=iotag32 wqe=response_payload_len */
10755 		wqe->xmit_els_rsp.response_payload_len = xmit_len;
10756 		/* word4 */
10757 		wqe->xmit_els_rsp.word4 = 0;
10758 		/* word5 iocb=rsvd wge=did */
10759 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
10760 			 iocbq->iocb.un.xseq64.xmit_els_remoteID);
10761 
10762 		if_type = bf_get(lpfc_sli_intf_if_type,
10763 					&phba->sli4_hba.sli_intf);
10764 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10765 			if (iocbq->vport->fc_flag & FC_PT2PT) {
10766 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
10767 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
10768 					iocbq->vport->fc_myDID);
10769 				if (iocbq->vport->fc_myDID == Fabric_DID) {
10770 					bf_set(wqe_els_did,
10771 						&wqe->xmit_els_rsp.wqe_dest, 0);
10772 				}
10773 			}
10774 		}
10775 		bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
10776 		       ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
10777 		bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
10778 		bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
10779 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
10780 		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
10781 			bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
10782 			       phba->vpi_ids[iocbq->vport->vpi]);
10783 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
10784 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
10785 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
10786 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
10787 		       LPFC_WQE_LENLOC_WORD3);
10788 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
10789 		bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
10790 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
10791 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
10792 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
10793 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
10794 					iocbq->vport->fc_myDID);
10795 				bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
10796 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
10797 					phba->vpi_ids[phba->pport->vpi]);
10798 		}
10799 		command_type = OTHER_COMMAND;
10800 		break;
10801 	case CMD_CLOSE_XRI_CN:
10802 	case CMD_ABORT_XRI_CN:
10803 	case CMD_ABORT_XRI_CX:
10804 		/* words 0-2 memcpy should be 0 rserved */
10805 		/* port will send abts */
10806 		abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
10807 		if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
10808 			abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
10809 			fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
10810 		} else
10811 			fip = 0;
10812 
10813 		if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
10814 			/*
10815 			 * The link is down, or the command was ELS_FIP
10816 			 * so the fw does not need to send abts
10817 			 * on the wire.
10818 			 */
10819 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
10820 		else
10821 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
10822 		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
10823 		/* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
10824 		wqe->abort_cmd.rsrvd5 = 0;
10825 		bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
10826 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
10827 		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
10828 		/*
10829 		 * The abort handler will send us CMD_ABORT_XRI_CN or
10830 		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
10831 		 */
10832 		bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
10833 		bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
10834 		bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
10835 		       LPFC_WQE_LENLOC_NONE);
10836 		cmnd = CMD_ABORT_XRI_CX;
10837 		command_type = OTHER_COMMAND;
10838 		xritag = 0;
10839 		break;
10840 	case CMD_XMIT_BLS_RSP64_CX:
10841 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
10842 		/* As BLS ABTS RSP WQE is very different from other WQEs,
10843 		 * we re-construct this WQE here based on information in
10844 		 * iocbq from scratch.
10845 		 */
10846 		memset(wqe, 0, sizeof(*wqe));
10847 		/* OX_ID is invariable to who sent ABTS to CT exchange */
10848 		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
10849 		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
10850 		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
10851 		    LPFC_ABTS_UNSOL_INT) {
10852 			/* ABTS sent by initiator to CT exchange, the
10853 			 * RX_ID field will be filled with the newly
10854 			 * allocated responder XRI.
10855 			 */
10856 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10857 			       iocbq->sli4_xritag);
10858 		} else {
10859 			/* ABTS sent by responder to CT exchange, the
10860 			 * RX_ID field will be filled with the responder
10861 			 * RX_ID from ABTS.
10862 			 */
10863 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10864 			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
10865 		}
10866 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
10867 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
10868 
10869 		/* Use CT=VPI */
10870 		bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
10871 			ndlp->nlp_DID);
10872 		bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
10873 			iocbq->iocb.ulpContext);
10874 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
10875 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
10876 			phba->vpi_ids[phba->pport->vpi]);
10877 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
10878 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
10879 		       LPFC_WQE_LENLOC_NONE);
10880 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
10881 		command_type = OTHER_COMMAND;
10882 		if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
10883 			bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
10884 			       bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
10885 			bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
10886 			       bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
10887 			bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
10888 			       bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
10889 		}
10890 
10891 		break;
10892 	case CMD_SEND_FRAME:
10893 		bf_set(wqe_cmnd, &wqe->generic.wqe_com, CMD_SEND_FRAME);
10894 		bf_set(wqe_sof, &wqe->generic.wqe_com, 0x2E); /* SOF byte */
10895 		bf_set(wqe_eof, &wqe->generic.wqe_com, 0x41); /* EOF byte */
10896 		bf_set(wqe_lenloc, &wqe->generic.wqe_com, 1);
10897 		bf_set(wqe_xbl, &wqe->generic.wqe_com, 1);
10898 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10899 		bf_set(wqe_xc, &wqe->generic.wqe_com, 1);
10900 		bf_set(wqe_cmd_type, &wqe->generic.wqe_com, 0xA);
10901 		bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10902 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10903 		bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10904 		return 0;
10905 	case CMD_XRI_ABORTED_CX:
10906 	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
10907 	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
10908 	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
10909 	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
10910 	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
10911 	default:
10912 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10913 				"2014 Invalid command 0x%x\n",
10914 				iocbq->iocb.ulpCommand);
10915 		return IOCB_ERROR;
10916 	}
10917 
10918 	if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
10919 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
10920 	else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
10921 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
10922 	else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
10923 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
10924 	iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
10925 			      LPFC_IO_DIF_INSERT);
10926 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10927 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10928 	wqe->generic.wqe_com.abort_tag = abort_tag;
10929 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
10930 	bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
10931 	bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
10932 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10933 	return 0;
10934 }
10935 
10936 /**
10937  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10938  * @phba: Pointer to HBA context object.
10939  * @ring_number: SLI ring number to issue wqe on.
10940  * @piocb: Pointer to command iocb.
10941  * @flag: Flag indicating if this command can be put into txq.
10942  *
10943  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10944  * send  an iocb command to an HBA with SLI-4 interface spec.
10945  *
10946  * This function takes the hbalock before invoking the lockless version.
10947  * The function will return success after it successfully submit the wqe to
10948  * firmware or after adding to the txq.
10949  **/
10950 static int
10951 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10952 			   struct lpfc_iocbq *piocb, uint32_t flag)
10953 {
10954 	unsigned long iflags;
10955 	int rc;
10956 
10957 	spin_lock_irqsave(&phba->hbalock, iflags);
10958 	rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10959 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10960 
10961 	return rc;
10962 }
10963 
10964 /**
10965  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10966  * @phba: Pointer to HBA context object.
10967  * @ring_number: SLI ring number to issue wqe on.
10968  * @piocb: Pointer to command iocb.
10969  * @flag: Flag indicating if this command can be put into txq.
10970  *
10971  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10972  * an wqe command to an HBA with SLI-4 interface spec.
10973  *
10974  * This function is a lockless version. The function will return success
10975  * after it successfully submit the wqe to firmware or after adding to the
10976  * txq.
10977  **/
10978 static int
10979 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10980 			   struct lpfc_iocbq *piocb, uint32_t flag)
10981 {
10982 	int rc;
10983 	struct lpfc_io_buf *lpfc_cmd =
10984 		(struct lpfc_io_buf *)piocb->context1;
10985 	union lpfc_wqe128 *wqe = &piocb->wqe;
10986 	struct sli4_sge *sgl;
10987 
10988 	/* 128 byte wqe support here */
10989 	sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10990 
10991 	if (phba->fcp_embed_io) {
10992 		struct fcp_cmnd *fcp_cmnd;
10993 		u32 *ptr;
10994 
10995 		fcp_cmnd = lpfc_cmd->fcp_cmnd;
10996 
10997 		/* Word 0-2 - FCP_CMND */
10998 		wqe->generic.bde.tus.f.bdeFlags =
10999 			BUFF_TYPE_BDE_IMMED;
11000 		wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
11001 		wqe->generic.bde.addrHigh = 0;
11002 		wqe->generic.bde.addrLow =  88;  /* Word 22 */
11003 
11004 		bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
11005 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
11006 
11007 		/* Word 22-29  FCP CMND Payload */
11008 		ptr = &wqe->words[22];
11009 		memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
11010 	} else {
11011 		/* Word 0-2 - Inline BDE */
11012 		wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
11013 		wqe->generic.bde.tus.f.bdeSize = sizeof(struct fcp_cmnd);
11014 		wqe->generic.bde.addrHigh = sgl->addr_hi;
11015 		wqe->generic.bde.addrLow =  sgl->addr_lo;
11016 
11017 		/* Word 10 */
11018 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
11019 		bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
11020 	}
11021 
11022 	/* add the VMID tags as per switch response */
11023 	if (unlikely(piocb->iocb_flag & LPFC_IO_VMID)) {
11024 		if (phba->pport->vmid_priority_tagging) {
11025 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
11026 			bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
11027 					(piocb->vmid_tag.cs_ctl_vmid));
11028 		} else {
11029 			bf_set(wqe_appid, &wqe->fcp_iwrite.wqe_com, 1);
11030 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
11031 			wqe->words[31] = piocb->vmid_tag.app_id;
11032 		}
11033 	}
11034 	rc = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
11035 	return rc;
11036 }
11037 
11038 /**
11039  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
11040  * @phba: Pointer to HBA context object.
11041  * @ring_number: SLI ring number to issue iocb on.
11042  * @piocb: Pointer to command iocb.
11043  * @flag: Flag indicating if this command can be put into txq.
11044  *
11045  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
11046  * an iocb command to an HBA with SLI-4 interface spec.
11047  *
11048  * This function is called with ringlock held. The function will return success
11049  * after it successfully submit the iocb to firmware or after adding to the
11050  * txq.
11051  **/
11052 static int
11053 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
11054 			 struct lpfc_iocbq *piocb, uint32_t flag)
11055 {
11056 	struct lpfc_sglq *sglq;
11057 	union lpfc_wqe128 wqe;
11058 	struct lpfc_queue *wq;
11059 	struct lpfc_sli_ring *pring;
11060 
11061 	/* Get the WQ */
11062 	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
11063 	    (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
11064 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
11065 	} else {
11066 		wq = phba->sli4_hba.els_wq;
11067 	}
11068 
11069 	/* Get corresponding ring */
11070 	pring = wq->pring;
11071 
11072 	/*
11073 	 * The WQE can be either 64 or 128 bytes,
11074 	 */
11075 
11076 	lockdep_assert_held(&pring->ring_lock);
11077 
11078 	if (piocb->sli4_xritag == NO_XRI) {
11079 		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
11080 		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
11081 			sglq = NULL;
11082 		else {
11083 			if (!list_empty(&pring->txq)) {
11084 				if (!(flag & SLI_IOCB_RET_IOCB)) {
11085 					__lpfc_sli_ringtx_put(phba,
11086 						pring, piocb);
11087 					return IOCB_SUCCESS;
11088 				} else {
11089 					return IOCB_BUSY;
11090 				}
11091 			} else {
11092 				sglq = __lpfc_sli_get_els_sglq(phba, piocb);
11093 				if (!sglq) {
11094 					if (!(flag & SLI_IOCB_RET_IOCB)) {
11095 						__lpfc_sli_ringtx_put(phba,
11096 								pring,
11097 								piocb);
11098 						return IOCB_SUCCESS;
11099 					} else
11100 						return IOCB_BUSY;
11101 				}
11102 			}
11103 		}
11104 	} else if (piocb->iocb_flag &  LPFC_IO_FCP) {
11105 		/* These IO's already have an XRI and a mapped sgl. */
11106 		sglq = NULL;
11107 	}
11108 	else {
11109 		/*
11110 		 * This is a continuation of a commandi,(CX) so this
11111 		 * sglq is on the active list
11112 		 */
11113 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
11114 		if (!sglq)
11115 			return IOCB_ERROR;
11116 	}
11117 
11118 	if (sglq) {
11119 		piocb->sli4_lxritag = sglq->sli4_lxritag;
11120 		piocb->sli4_xritag = sglq->sli4_xritag;
11121 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
11122 			return IOCB_ERROR;
11123 	}
11124 
11125 	if (lpfc_sli4_iocb2wqe(phba, piocb, &wqe))
11126 		return IOCB_ERROR;
11127 
11128 	if (lpfc_sli4_wq_put(wq, &wqe))
11129 		return IOCB_ERROR;
11130 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
11131 
11132 	return 0;
11133 }
11134 
11135 /*
11136  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
11137  *
11138  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
11139  * or IOCB for sli-3  function.
11140  * pointer from the lpfc_hba struct.
11141  *
11142  * Return codes:
11143  * IOCB_ERROR - Error
11144  * IOCB_SUCCESS - Success
11145  * IOCB_BUSY - Busy
11146  **/
11147 int
11148 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
11149 		      struct lpfc_iocbq *piocb, uint32_t flag)
11150 {
11151 	return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
11152 }
11153 
11154 /*
11155  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
11156  *
11157  * This routine wraps the actual lockless version for issusing IOCB function
11158  * pointer from the lpfc_hba struct.
11159  *
11160  * Return codes:
11161  * IOCB_ERROR - Error
11162  * IOCB_SUCCESS - Success
11163  * IOCB_BUSY - Busy
11164  **/
11165 int
11166 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
11167 		struct lpfc_iocbq *piocb, uint32_t flag)
11168 {
11169 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11170 }
11171 
11172 /**
11173  * lpfc_sli_api_table_setup - Set up sli api function jump table
11174  * @phba: The hba struct for which this call is being executed.
11175  * @dev_grp: The HBA PCI-Device group number.
11176  *
11177  * This routine sets up the SLI interface API function jump table in @phba
11178  * struct.
11179  * Returns: 0 - success, -ENODEV - failure.
11180  **/
11181 int
11182 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
11183 {
11184 
11185 	switch (dev_grp) {
11186 	case LPFC_PCI_DEV_LP:
11187 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
11188 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
11189 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
11190 		break;
11191 	case LPFC_PCI_DEV_OC:
11192 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
11193 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
11194 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
11195 		break;
11196 	default:
11197 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11198 				"1419 Invalid HBA PCI-device group: 0x%x\n",
11199 				dev_grp);
11200 		return -ENODEV;
11201 	}
11202 	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
11203 	return 0;
11204 }
11205 
11206 /**
11207  * lpfc_sli4_calc_ring - Calculates which ring to use
11208  * @phba: Pointer to HBA context object.
11209  * @piocb: Pointer to command iocb.
11210  *
11211  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
11212  * hba_wqidx, thus we need to calculate the corresponding ring.
11213  * Since ABORTS must go on the same WQ of the command they are
11214  * aborting, we use command's hba_wqidx.
11215  */
11216 struct lpfc_sli_ring *
11217 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
11218 {
11219 	struct lpfc_io_buf *lpfc_cmd;
11220 
11221 	if (piocb->iocb_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
11222 		if (unlikely(!phba->sli4_hba.hdwq))
11223 			return NULL;
11224 		/*
11225 		 * for abort iocb hba_wqidx should already
11226 		 * be setup based on what work queue we used.
11227 		 */
11228 		if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
11229 			lpfc_cmd = (struct lpfc_io_buf *)piocb->context1;
11230 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
11231 		}
11232 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
11233 	} else {
11234 		if (unlikely(!phba->sli4_hba.els_wq))
11235 			return NULL;
11236 		piocb->hba_wqidx = 0;
11237 		return phba->sli4_hba.els_wq->pring;
11238 	}
11239 }
11240 
11241 /**
11242  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
11243  * @phba: Pointer to HBA context object.
11244  * @ring_number: Ring number
11245  * @piocb: Pointer to command iocb.
11246  * @flag: Flag indicating if this command can be put into txq.
11247  *
11248  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
11249  * function. This function gets the hbalock and calls
11250  * __lpfc_sli_issue_iocb function and will return the error returned
11251  * by __lpfc_sli_issue_iocb function. This wrapper is used by
11252  * functions which do not hold hbalock.
11253  **/
11254 int
11255 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
11256 		    struct lpfc_iocbq *piocb, uint32_t flag)
11257 {
11258 	struct lpfc_sli_ring *pring;
11259 	struct lpfc_queue *eq;
11260 	unsigned long iflags;
11261 	int rc;
11262 
11263 	if (phba->sli_rev == LPFC_SLI_REV4) {
11264 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
11265 
11266 		pring = lpfc_sli4_calc_ring(phba, piocb);
11267 		if (unlikely(pring == NULL))
11268 			return IOCB_ERROR;
11269 
11270 		spin_lock_irqsave(&pring->ring_lock, iflags);
11271 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11272 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11273 
11274 		lpfc_sli4_poll_eq(eq, LPFC_POLL_FASTPATH);
11275 	} else {
11276 		/* For now, SLI2/3 will still use hbalock */
11277 		spin_lock_irqsave(&phba->hbalock, iflags);
11278 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11279 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11280 	}
11281 	return rc;
11282 }
11283 
11284 /**
11285  * lpfc_extra_ring_setup - Extra ring setup function
11286  * @phba: Pointer to HBA context object.
11287  *
11288  * This function is called while driver attaches with the
11289  * HBA to setup the extra ring. The extra ring is used
11290  * only when driver needs to support target mode functionality
11291  * or IP over FC functionalities.
11292  *
11293  * This function is called with no lock held. SLI3 only.
11294  **/
11295 static int
11296 lpfc_extra_ring_setup( struct lpfc_hba *phba)
11297 {
11298 	struct lpfc_sli *psli;
11299 	struct lpfc_sli_ring *pring;
11300 
11301 	psli = &phba->sli;
11302 
11303 	/* Adjust cmd/rsp ring iocb entries more evenly */
11304 
11305 	/* Take some away from the FCP ring */
11306 	pring = &psli->sli3_ring[LPFC_FCP_RING];
11307 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11308 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11309 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11310 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11311 
11312 	/* and give them to the extra ring */
11313 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
11314 
11315 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11316 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11317 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11318 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11319 
11320 	/* Setup default profile for this ring */
11321 	pring->iotag_max = 4096;
11322 	pring->num_mask = 1;
11323 	pring->prt[0].profile = 0;      /* Mask 0 */
11324 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
11325 	pring->prt[0].type = phba->cfg_multi_ring_type;
11326 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
11327 	return 0;
11328 }
11329 
11330 static void
11331 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
11332 			     struct lpfc_nodelist *ndlp)
11333 {
11334 	unsigned long iflags;
11335 	struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
11336 
11337 	spin_lock_irqsave(&phba->hbalock, iflags);
11338 	if (!list_empty(&evtp->evt_listp)) {
11339 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11340 		return;
11341 	}
11342 
11343 	/* Incrementing the reference count until the queued work is done. */
11344 	evtp->evt_arg1  = lpfc_nlp_get(ndlp);
11345 	if (!evtp->evt_arg1) {
11346 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11347 		return;
11348 	}
11349 	evtp->evt = LPFC_EVT_RECOVER_PORT;
11350 	list_add_tail(&evtp->evt_listp, &phba->work_list);
11351 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11352 
11353 	lpfc_worker_wake_up(phba);
11354 }
11355 
11356 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
11357  * @phba: Pointer to HBA context object.
11358  * @iocbq: Pointer to iocb object.
11359  *
11360  * The async_event handler calls this routine when it receives
11361  * an ASYNC_STATUS_CN event from the port.  The port generates
11362  * this event when an Abort Sequence request to an rport fails
11363  * twice in succession.  The abort could be originated by the
11364  * driver or by the port.  The ABTS could have been for an ELS
11365  * or FCP IO.  The port only generates this event when an ABTS
11366  * fails to complete after one retry.
11367  */
11368 static void
11369 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
11370 			  struct lpfc_iocbq *iocbq)
11371 {
11372 	struct lpfc_nodelist *ndlp = NULL;
11373 	uint16_t rpi = 0, vpi = 0;
11374 	struct lpfc_vport *vport = NULL;
11375 
11376 	/* The rpi in the ulpContext is vport-sensitive. */
11377 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
11378 	rpi = iocbq->iocb.ulpContext;
11379 
11380 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11381 			"3092 Port generated ABTS async event "
11382 			"on vpi %d rpi %d status 0x%x\n",
11383 			vpi, rpi, iocbq->iocb.ulpStatus);
11384 
11385 	vport = lpfc_find_vport_by_vpid(phba, vpi);
11386 	if (!vport)
11387 		goto err_exit;
11388 	ndlp = lpfc_findnode_rpi(vport, rpi);
11389 	if (!ndlp)
11390 		goto err_exit;
11391 
11392 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
11393 		lpfc_sli_abts_recover_port(vport, ndlp);
11394 	return;
11395 
11396  err_exit:
11397 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11398 			"3095 Event Context not found, no "
11399 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
11400 			iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
11401 			vpi, rpi);
11402 }
11403 
11404 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
11405  * @phba: pointer to HBA context object.
11406  * @ndlp: nodelist pointer for the impacted rport.
11407  * @axri: pointer to the wcqe containing the failed exchange.
11408  *
11409  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
11410  * port.  The port generates this event when an abort exchange request to an
11411  * rport fails twice in succession with no reply.  The abort could be originated
11412  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
11413  */
11414 void
11415 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
11416 			   struct lpfc_nodelist *ndlp,
11417 			   struct sli4_wcqe_xri_aborted *axri)
11418 {
11419 	uint32_t ext_status = 0;
11420 
11421 	if (!ndlp) {
11422 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11423 				"3115 Node Context not found, driver "
11424 				"ignoring abts err event\n");
11425 		return;
11426 	}
11427 
11428 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11429 			"3116 Port generated FCP XRI ABORT event on "
11430 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
11431 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
11432 			bf_get(lpfc_wcqe_xa_xri, axri),
11433 			bf_get(lpfc_wcqe_xa_status, axri),
11434 			axri->parameter);
11435 
11436 	/*
11437 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
11438 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
11439 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
11440 	 */
11441 	ext_status = axri->parameter & IOERR_PARAM_MASK;
11442 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
11443 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
11444 		lpfc_sli_post_recovery_event(phba, ndlp);
11445 }
11446 
11447 /**
11448  * lpfc_sli_async_event_handler - ASYNC iocb handler function
11449  * @phba: Pointer to HBA context object.
11450  * @pring: Pointer to driver SLI ring object.
11451  * @iocbq: Pointer to iocb object.
11452  *
11453  * This function is called by the slow ring event handler
11454  * function when there is an ASYNC event iocb in the ring.
11455  * This function is called with no lock held.
11456  * Currently this function handles only temperature related
11457  * ASYNC events. The function decodes the temperature sensor
11458  * event message and posts events for the management applications.
11459  **/
11460 static void
11461 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
11462 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
11463 {
11464 	IOCB_t *icmd;
11465 	uint16_t evt_code;
11466 	struct temp_event temp_event_data;
11467 	struct Scsi_Host *shost;
11468 	uint32_t *iocb_w;
11469 
11470 	icmd = &iocbq->iocb;
11471 	evt_code = icmd->un.asyncstat.evt_code;
11472 
11473 	switch (evt_code) {
11474 	case ASYNC_TEMP_WARN:
11475 	case ASYNC_TEMP_SAFE:
11476 		temp_event_data.data = (uint32_t) icmd->ulpContext;
11477 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
11478 		if (evt_code == ASYNC_TEMP_WARN) {
11479 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
11480 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11481 				"0347 Adapter is very hot, please take "
11482 				"corrective action. temperature : %d Celsius\n",
11483 				(uint32_t) icmd->ulpContext);
11484 		} else {
11485 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
11486 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11487 				"0340 Adapter temperature is OK now. "
11488 				"temperature : %d Celsius\n",
11489 				(uint32_t) icmd->ulpContext);
11490 		}
11491 
11492 		/* Send temperature change event to applications */
11493 		shost = lpfc_shost_from_vport(phba->pport);
11494 		fc_host_post_vendor_event(shost, fc_get_event_number(),
11495 			sizeof(temp_event_data), (char *) &temp_event_data,
11496 			LPFC_NL_VENDOR_ID);
11497 		break;
11498 	case ASYNC_STATUS_CN:
11499 		lpfc_sli_abts_err_handler(phba, iocbq);
11500 		break;
11501 	default:
11502 		iocb_w = (uint32_t *) icmd;
11503 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11504 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
11505 			" evt_code 0x%x\n"
11506 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
11507 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
11508 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
11509 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
11510 			pring->ringno, icmd->un.asyncstat.evt_code,
11511 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
11512 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
11513 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
11514 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
11515 
11516 		break;
11517 	}
11518 }
11519 
11520 
11521 /**
11522  * lpfc_sli4_setup - SLI ring setup function
11523  * @phba: Pointer to HBA context object.
11524  *
11525  * lpfc_sli_setup sets up rings of the SLI interface with
11526  * number of iocbs per ring and iotags. This function is
11527  * called while driver attach to the HBA and before the
11528  * interrupts are enabled. So there is no need for locking.
11529  *
11530  * This function always returns 0.
11531  **/
11532 int
11533 lpfc_sli4_setup(struct lpfc_hba *phba)
11534 {
11535 	struct lpfc_sli_ring *pring;
11536 
11537 	pring = phba->sli4_hba.els_wq->pring;
11538 	pring->num_mask = LPFC_MAX_RING_MASK;
11539 	pring->prt[0].profile = 0;	/* Mask 0 */
11540 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11541 	pring->prt[0].type = FC_TYPE_ELS;
11542 	pring->prt[0].lpfc_sli_rcv_unsol_event =
11543 	    lpfc_els_unsol_event;
11544 	pring->prt[1].profile = 0;	/* Mask 1 */
11545 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
11546 	pring->prt[1].type = FC_TYPE_ELS;
11547 	pring->prt[1].lpfc_sli_rcv_unsol_event =
11548 	    lpfc_els_unsol_event;
11549 	pring->prt[2].profile = 0;	/* Mask 2 */
11550 	/* NameServer Inquiry */
11551 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11552 	/* NameServer */
11553 	pring->prt[2].type = FC_TYPE_CT;
11554 	pring->prt[2].lpfc_sli_rcv_unsol_event =
11555 	    lpfc_ct_unsol_event;
11556 	pring->prt[3].profile = 0;	/* Mask 3 */
11557 	/* NameServer response */
11558 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11559 	/* NameServer */
11560 	pring->prt[3].type = FC_TYPE_CT;
11561 	pring->prt[3].lpfc_sli_rcv_unsol_event =
11562 	    lpfc_ct_unsol_event;
11563 	return 0;
11564 }
11565 
11566 /**
11567  * lpfc_sli_setup - SLI ring setup function
11568  * @phba: Pointer to HBA context object.
11569  *
11570  * lpfc_sli_setup sets up rings of the SLI interface with
11571  * number of iocbs per ring and iotags. This function is
11572  * called while driver attach to the HBA and before the
11573  * interrupts are enabled. So there is no need for locking.
11574  *
11575  * This function always returns 0. SLI3 only.
11576  **/
11577 int
11578 lpfc_sli_setup(struct lpfc_hba *phba)
11579 {
11580 	int i, totiocbsize = 0;
11581 	struct lpfc_sli *psli = &phba->sli;
11582 	struct lpfc_sli_ring *pring;
11583 
11584 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
11585 	psli->sli_flag = 0;
11586 
11587 	psli->iocbq_lookup = NULL;
11588 	psli->iocbq_lookup_len = 0;
11589 	psli->last_iotag = 0;
11590 
11591 	for (i = 0; i < psli->num_rings; i++) {
11592 		pring = &psli->sli3_ring[i];
11593 		switch (i) {
11594 		case LPFC_FCP_RING:	/* ring 0 - FCP */
11595 			/* numCiocb and numRiocb are used in config_port */
11596 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
11597 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
11598 			pring->sli.sli3.numCiocb +=
11599 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11600 			pring->sli.sli3.numRiocb +=
11601 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11602 			pring->sli.sli3.numCiocb +=
11603 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11604 			pring->sli.sli3.numRiocb +=
11605 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11606 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11607 							SLI3_IOCB_CMD_SIZE :
11608 							SLI2_IOCB_CMD_SIZE;
11609 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11610 							SLI3_IOCB_RSP_SIZE :
11611 							SLI2_IOCB_RSP_SIZE;
11612 			pring->iotag_ctr = 0;
11613 			pring->iotag_max =
11614 			    (phba->cfg_hba_queue_depth * 2);
11615 			pring->fast_iotag = pring->iotag_max;
11616 			pring->num_mask = 0;
11617 			break;
11618 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
11619 			/* numCiocb and numRiocb are used in config_port */
11620 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
11621 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
11622 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11623 							SLI3_IOCB_CMD_SIZE :
11624 							SLI2_IOCB_CMD_SIZE;
11625 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11626 							SLI3_IOCB_RSP_SIZE :
11627 							SLI2_IOCB_RSP_SIZE;
11628 			pring->iotag_max = phba->cfg_hba_queue_depth;
11629 			pring->num_mask = 0;
11630 			break;
11631 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
11632 			/* numCiocb and numRiocb are used in config_port */
11633 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
11634 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
11635 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11636 							SLI3_IOCB_CMD_SIZE :
11637 							SLI2_IOCB_CMD_SIZE;
11638 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11639 							SLI3_IOCB_RSP_SIZE :
11640 							SLI2_IOCB_RSP_SIZE;
11641 			pring->fast_iotag = 0;
11642 			pring->iotag_ctr = 0;
11643 			pring->iotag_max = 4096;
11644 			pring->lpfc_sli_rcv_async_status =
11645 				lpfc_sli_async_event_handler;
11646 			pring->num_mask = LPFC_MAX_RING_MASK;
11647 			pring->prt[0].profile = 0;	/* Mask 0 */
11648 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11649 			pring->prt[0].type = FC_TYPE_ELS;
11650 			pring->prt[0].lpfc_sli_rcv_unsol_event =
11651 			    lpfc_els_unsol_event;
11652 			pring->prt[1].profile = 0;	/* Mask 1 */
11653 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
11654 			pring->prt[1].type = FC_TYPE_ELS;
11655 			pring->prt[1].lpfc_sli_rcv_unsol_event =
11656 			    lpfc_els_unsol_event;
11657 			pring->prt[2].profile = 0;	/* Mask 2 */
11658 			/* NameServer Inquiry */
11659 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11660 			/* NameServer */
11661 			pring->prt[2].type = FC_TYPE_CT;
11662 			pring->prt[2].lpfc_sli_rcv_unsol_event =
11663 			    lpfc_ct_unsol_event;
11664 			pring->prt[3].profile = 0;	/* Mask 3 */
11665 			/* NameServer response */
11666 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11667 			/* NameServer */
11668 			pring->prt[3].type = FC_TYPE_CT;
11669 			pring->prt[3].lpfc_sli_rcv_unsol_event =
11670 			    lpfc_ct_unsol_event;
11671 			break;
11672 		}
11673 		totiocbsize += (pring->sli.sli3.numCiocb *
11674 			pring->sli.sli3.sizeCiocb) +
11675 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
11676 	}
11677 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
11678 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
11679 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
11680 		       "SLI2 SLIM Data: x%x x%lx\n",
11681 		       phba->brd_no, totiocbsize,
11682 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
11683 	}
11684 	if (phba->cfg_multi_ring_support == 2)
11685 		lpfc_extra_ring_setup(phba);
11686 
11687 	return 0;
11688 }
11689 
11690 /**
11691  * lpfc_sli4_queue_init - Queue initialization function
11692  * @phba: Pointer to HBA context object.
11693  *
11694  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
11695  * ring. This function also initializes ring indices of each ring.
11696  * This function is called during the initialization of the SLI
11697  * interface of an HBA.
11698  * This function is called with no lock held and always returns
11699  * 1.
11700  **/
11701 void
11702 lpfc_sli4_queue_init(struct lpfc_hba *phba)
11703 {
11704 	struct lpfc_sli *psli;
11705 	struct lpfc_sli_ring *pring;
11706 	int i;
11707 
11708 	psli = &phba->sli;
11709 	spin_lock_irq(&phba->hbalock);
11710 	INIT_LIST_HEAD(&psli->mboxq);
11711 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11712 	/* Initialize list headers for txq and txcmplq as double linked lists */
11713 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
11714 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
11715 		pring->flag = 0;
11716 		pring->ringno = LPFC_FCP_RING;
11717 		pring->txcmplq_cnt = 0;
11718 		INIT_LIST_HEAD(&pring->txq);
11719 		INIT_LIST_HEAD(&pring->txcmplq);
11720 		INIT_LIST_HEAD(&pring->iocb_continueq);
11721 		spin_lock_init(&pring->ring_lock);
11722 	}
11723 	pring = phba->sli4_hba.els_wq->pring;
11724 	pring->flag = 0;
11725 	pring->ringno = LPFC_ELS_RING;
11726 	pring->txcmplq_cnt = 0;
11727 	INIT_LIST_HEAD(&pring->txq);
11728 	INIT_LIST_HEAD(&pring->txcmplq);
11729 	INIT_LIST_HEAD(&pring->iocb_continueq);
11730 	spin_lock_init(&pring->ring_lock);
11731 
11732 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11733 		pring = phba->sli4_hba.nvmels_wq->pring;
11734 		pring->flag = 0;
11735 		pring->ringno = LPFC_ELS_RING;
11736 		pring->txcmplq_cnt = 0;
11737 		INIT_LIST_HEAD(&pring->txq);
11738 		INIT_LIST_HEAD(&pring->txcmplq);
11739 		INIT_LIST_HEAD(&pring->iocb_continueq);
11740 		spin_lock_init(&pring->ring_lock);
11741 	}
11742 
11743 	spin_unlock_irq(&phba->hbalock);
11744 }
11745 
11746 /**
11747  * lpfc_sli_queue_init - Queue initialization function
11748  * @phba: Pointer to HBA context object.
11749  *
11750  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11751  * ring. This function also initializes ring indices of each ring.
11752  * This function is called during the initialization of the SLI
11753  * interface of an HBA.
11754  * This function is called with no lock held and always returns
11755  * 1.
11756  **/
11757 void
11758 lpfc_sli_queue_init(struct lpfc_hba *phba)
11759 {
11760 	struct lpfc_sli *psli;
11761 	struct lpfc_sli_ring *pring;
11762 	int i;
11763 
11764 	psli = &phba->sli;
11765 	spin_lock_irq(&phba->hbalock);
11766 	INIT_LIST_HEAD(&psli->mboxq);
11767 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11768 	/* Initialize list headers for txq and txcmplq as double linked lists */
11769 	for (i = 0; i < psli->num_rings; i++) {
11770 		pring = &psli->sli3_ring[i];
11771 		pring->ringno = i;
11772 		pring->sli.sli3.next_cmdidx  = 0;
11773 		pring->sli.sli3.local_getidx = 0;
11774 		pring->sli.sli3.cmdidx = 0;
11775 		INIT_LIST_HEAD(&pring->iocb_continueq);
11776 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11777 		INIT_LIST_HEAD(&pring->postbufq);
11778 		pring->flag = 0;
11779 		INIT_LIST_HEAD(&pring->txq);
11780 		INIT_LIST_HEAD(&pring->txcmplq);
11781 		spin_lock_init(&pring->ring_lock);
11782 	}
11783 	spin_unlock_irq(&phba->hbalock);
11784 }
11785 
11786 /**
11787  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11788  * @phba: Pointer to HBA context object.
11789  *
11790  * This routine flushes the mailbox command subsystem. It will unconditionally
11791  * flush all the mailbox commands in the three possible stages in the mailbox
11792  * command sub-system: pending mailbox command queue; the outstanding mailbox
11793  * command; and completed mailbox command queue. It is caller's responsibility
11794  * to make sure that the driver is in the proper state to flush the mailbox
11795  * command sub-system. Namely, the posting of mailbox commands into the
11796  * pending mailbox command queue from the various clients must be stopped;
11797  * either the HBA is in a state that it will never works on the outstanding
11798  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11799  * mailbox command has been completed.
11800  **/
11801 static void
11802 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11803 {
11804 	LIST_HEAD(completions);
11805 	struct lpfc_sli *psli = &phba->sli;
11806 	LPFC_MBOXQ_t *pmb;
11807 	unsigned long iflag;
11808 
11809 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11810 	local_bh_disable();
11811 
11812 	/* Flush all the mailbox commands in the mbox system */
11813 	spin_lock_irqsave(&phba->hbalock, iflag);
11814 
11815 	/* The pending mailbox command queue */
11816 	list_splice_init(&phba->sli.mboxq, &completions);
11817 	/* The outstanding active mailbox command */
11818 	if (psli->mbox_active) {
11819 		list_add_tail(&psli->mbox_active->list, &completions);
11820 		psli->mbox_active = NULL;
11821 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11822 	}
11823 	/* The completed mailbox command queue */
11824 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11825 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11826 
11827 	/* Enable softirqs again, done with phba->hbalock */
11828 	local_bh_enable();
11829 
11830 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11831 	while (!list_empty(&completions)) {
11832 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11833 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11834 		if (pmb->mbox_cmpl)
11835 			pmb->mbox_cmpl(phba, pmb);
11836 	}
11837 }
11838 
11839 /**
11840  * lpfc_sli_host_down - Vport cleanup function
11841  * @vport: Pointer to virtual port object.
11842  *
11843  * lpfc_sli_host_down is called to clean up the resources
11844  * associated with a vport before destroying virtual
11845  * port data structures.
11846  * This function does following operations:
11847  * - Free discovery resources associated with this virtual
11848  *   port.
11849  * - Free iocbs associated with this virtual port in
11850  *   the txq.
11851  * - Send abort for all iocb commands associated with this
11852  *   vport in txcmplq.
11853  *
11854  * This function is called with no lock held and always returns 1.
11855  **/
11856 int
11857 lpfc_sli_host_down(struct lpfc_vport *vport)
11858 {
11859 	LIST_HEAD(completions);
11860 	struct lpfc_hba *phba = vport->phba;
11861 	struct lpfc_sli *psli = &phba->sli;
11862 	struct lpfc_queue *qp = NULL;
11863 	struct lpfc_sli_ring *pring;
11864 	struct lpfc_iocbq *iocb, *next_iocb;
11865 	int i;
11866 	unsigned long flags = 0;
11867 	uint16_t prev_pring_flag;
11868 
11869 	lpfc_cleanup_discovery_resources(vport);
11870 
11871 	spin_lock_irqsave(&phba->hbalock, flags);
11872 
11873 	/*
11874 	 * Error everything on the txq since these iocbs
11875 	 * have not been given to the FW yet.
11876 	 * Also issue ABTS for everything on the txcmplq
11877 	 */
11878 	if (phba->sli_rev != LPFC_SLI_REV4) {
11879 		for (i = 0; i < psli->num_rings; i++) {
11880 			pring = &psli->sli3_ring[i];
11881 			prev_pring_flag = pring->flag;
11882 			/* Only slow rings */
11883 			if (pring->ringno == LPFC_ELS_RING) {
11884 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11885 				/* Set the lpfc data pending flag */
11886 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11887 			}
11888 			list_for_each_entry_safe(iocb, next_iocb,
11889 						 &pring->txq, list) {
11890 				if (iocb->vport != vport)
11891 					continue;
11892 				list_move_tail(&iocb->list, &completions);
11893 			}
11894 			list_for_each_entry_safe(iocb, next_iocb,
11895 						 &pring->txcmplq, list) {
11896 				if (iocb->vport != vport)
11897 					continue;
11898 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11899 							   NULL);
11900 			}
11901 			pring->flag = prev_pring_flag;
11902 		}
11903 	} else {
11904 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11905 			pring = qp->pring;
11906 			if (!pring)
11907 				continue;
11908 			if (pring == phba->sli4_hba.els_wq->pring) {
11909 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11910 				/* Set the lpfc data pending flag */
11911 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11912 			}
11913 			prev_pring_flag = pring->flag;
11914 			spin_lock(&pring->ring_lock);
11915 			list_for_each_entry_safe(iocb, next_iocb,
11916 						 &pring->txq, list) {
11917 				if (iocb->vport != vport)
11918 					continue;
11919 				list_move_tail(&iocb->list, &completions);
11920 			}
11921 			spin_unlock(&pring->ring_lock);
11922 			list_for_each_entry_safe(iocb, next_iocb,
11923 						 &pring->txcmplq, list) {
11924 				if (iocb->vport != vport)
11925 					continue;
11926 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11927 							   NULL);
11928 			}
11929 			pring->flag = prev_pring_flag;
11930 		}
11931 	}
11932 	spin_unlock_irqrestore(&phba->hbalock, flags);
11933 
11934 	/* Make sure HBA is alive */
11935 	lpfc_issue_hb_tmo(phba);
11936 
11937 	/* Cancel all the IOCBs from the completions list */
11938 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11939 			      IOERR_SLI_DOWN);
11940 	return 1;
11941 }
11942 
11943 /**
11944  * lpfc_sli_hba_down - Resource cleanup function for the HBA
11945  * @phba: Pointer to HBA context object.
11946  *
11947  * This function cleans up all iocb, buffers, mailbox commands
11948  * while shutting down the HBA. This function is called with no
11949  * lock held and always returns 1.
11950  * This function does the following to cleanup driver resources:
11951  * - Free discovery resources for each virtual port
11952  * - Cleanup any pending fabric iocbs
11953  * - Iterate through the iocb txq and free each entry
11954  *   in the list.
11955  * - Free up any buffer posted to the HBA
11956  * - Free mailbox commands in the mailbox queue.
11957  **/
11958 int
11959 lpfc_sli_hba_down(struct lpfc_hba *phba)
11960 {
11961 	LIST_HEAD(completions);
11962 	struct lpfc_sli *psli = &phba->sli;
11963 	struct lpfc_queue *qp = NULL;
11964 	struct lpfc_sli_ring *pring;
11965 	struct lpfc_dmabuf *buf_ptr;
11966 	unsigned long flags = 0;
11967 	int i;
11968 
11969 	/* Shutdown the mailbox command sub-system */
11970 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
11971 
11972 	lpfc_hba_down_prep(phba);
11973 
11974 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11975 	local_bh_disable();
11976 
11977 	lpfc_fabric_abort_hba(phba);
11978 
11979 	spin_lock_irqsave(&phba->hbalock, flags);
11980 
11981 	/*
11982 	 * Error everything on the txq since these iocbs
11983 	 * have not been given to the FW yet.
11984 	 */
11985 	if (phba->sli_rev != LPFC_SLI_REV4) {
11986 		for (i = 0; i < psli->num_rings; i++) {
11987 			pring = &psli->sli3_ring[i];
11988 			/* Only slow rings */
11989 			if (pring->ringno == LPFC_ELS_RING) {
11990 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11991 				/* Set the lpfc data pending flag */
11992 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11993 			}
11994 			list_splice_init(&pring->txq, &completions);
11995 		}
11996 	} else {
11997 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11998 			pring = qp->pring;
11999 			if (!pring)
12000 				continue;
12001 			spin_lock(&pring->ring_lock);
12002 			list_splice_init(&pring->txq, &completions);
12003 			spin_unlock(&pring->ring_lock);
12004 			if (pring == phba->sli4_hba.els_wq->pring) {
12005 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12006 				/* Set the lpfc data pending flag */
12007 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12008 			}
12009 		}
12010 	}
12011 	spin_unlock_irqrestore(&phba->hbalock, flags);
12012 
12013 	/* Cancel all the IOCBs from the completions list */
12014 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
12015 			      IOERR_SLI_DOWN);
12016 
12017 	spin_lock_irqsave(&phba->hbalock, flags);
12018 	list_splice_init(&phba->elsbuf, &completions);
12019 	phba->elsbuf_cnt = 0;
12020 	phba->elsbuf_prev_cnt = 0;
12021 	spin_unlock_irqrestore(&phba->hbalock, flags);
12022 
12023 	while (!list_empty(&completions)) {
12024 		list_remove_head(&completions, buf_ptr,
12025 			struct lpfc_dmabuf, list);
12026 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
12027 		kfree(buf_ptr);
12028 	}
12029 
12030 	/* Enable softirqs again, done with phba->hbalock */
12031 	local_bh_enable();
12032 
12033 	/* Return any active mbox cmds */
12034 	del_timer_sync(&psli->mbox_tmo);
12035 
12036 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
12037 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
12038 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
12039 
12040 	return 1;
12041 }
12042 
12043 /**
12044  * lpfc_sli_pcimem_bcopy - SLI memory copy function
12045  * @srcp: Source memory pointer.
12046  * @destp: Destination memory pointer.
12047  * @cnt: Number of words required to be copied.
12048  *
12049  * This function is used for copying data between driver memory
12050  * and the SLI memory. This function also changes the endianness
12051  * of each word if native endianness is different from SLI
12052  * endianness. This function can be called with or without
12053  * lock.
12054  **/
12055 void
12056 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
12057 {
12058 	uint32_t *src = srcp;
12059 	uint32_t *dest = destp;
12060 	uint32_t ldata;
12061 	int i;
12062 
12063 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
12064 		ldata = *src;
12065 		ldata = le32_to_cpu(ldata);
12066 		*dest = ldata;
12067 		src++;
12068 		dest++;
12069 	}
12070 }
12071 
12072 
12073 /**
12074  * lpfc_sli_bemem_bcopy - SLI memory copy function
12075  * @srcp: Source memory pointer.
12076  * @destp: Destination memory pointer.
12077  * @cnt: Number of words required to be copied.
12078  *
12079  * This function is used for copying data between a data structure
12080  * with big endian representation to local endianness.
12081  * This function can be called with or without lock.
12082  **/
12083 void
12084 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
12085 {
12086 	uint32_t *src = srcp;
12087 	uint32_t *dest = destp;
12088 	uint32_t ldata;
12089 	int i;
12090 
12091 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
12092 		ldata = *src;
12093 		ldata = be32_to_cpu(ldata);
12094 		*dest = ldata;
12095 		src++;
12096 		dest++;
12097 	}
12098 }
12099 
12100 /**
12101  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
12102  * @phba: Pointer to HBA context object.
12103  * @pring: Pointer to driver SLI ring object.
12104  * @mp: Pointer to driver buffer object.
12105  *
12106  * This function is called with no lock held.
12107  * It always return zero after adding the buffer to the postbufq
12108  * buffer list.
12109  **/
12110 int
12111 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12112 			 struct lpfc_dmabuf *mp)
12113 {
12114 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
12115 	   later */
12116 	spin_lock_irq(&phba->hbalock);
12117 	list_add_tail(&mp->list, &pring->postbufq);
12118 	pring->postbufq_cnt++;
12119 	spin_unlock_irq(&phba->hbalock);
12120 	return 0;
12121 }
12122 
12123 /**
12124  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
12125  * @phba: Pointer to HBA context object.
12126  *
12127  * When HBQ is enabled, buffers are searched based on tags. This function
12128  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
12129  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
12130  * does not conflict with tags of buffer posted for unsolicited events.
12131  * The function returns the allocated tag. The function is called with
12132  * no locks held.
12133  **/
12134 uint32_t
12135 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
12136 {
12137 	spin_lock_irq(&phba->hbalock);
12138 	phba->buffer_tag_count++;
12139 	/*
12140 	 * Always set the QUE_BUFTAG_BIT to distiguish between
12141 	 * a tag assigned by HBQ.
12142 	 */
12143 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
12144 	spin_unlock_irq(&phba->hbalock);
12145 	return phba->buffer_tag_count;
12146 }
12147 
12148 /**
12149  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
12150  * @phba: Pointer to HBA context object.
12151  * @pring: Pointer to driver SLI ring object.
12152  * @tag: Buffer tag.
12153  *
12154  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
12155  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
12156  * iocb is posted to the response ring with the tag of the buffer.
12157  * This function searches the pring->postbufq list using the tag
12158  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
12159  * iocb. If the buffer is found then lpfc_dmabuf object of the
12160  * buffer is returned to the caller else NULL is returned.
12161  * This function is called with no lock held.
12162  **/
12163 struct lpfc_dmabuf *
12164 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12165 			uint32_t tag)
12166 {
12167 	struct lpfc_dmabuf *mp, *next_mp;
12168 	struct list_head *slp = &pring->postbufq;
12169 
12170 	/* Search postbufq, from the beginning, looking for a match on tag */
12171 	spin_lock_irq(&phba->hbalock);
12172 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12173 		if (mp->buffer_tag == tag) {
12174 			list_del_init(&mp->list);
12175 			pring->postbufq_cnt--;
12176 			spin_unlock_irq(&phba->hbalock);
12177 			return mp;
12178 		}
12179 	}
12180 
12181 	spin_unlock_irq(&phba->hbalock);
12182 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12183 			"0402 Cannot find virtual addr for buffer tag on "
12184 			"ring %d Data x%lx x%px x%px x%x\n",
12185 			pring->ringno, (unsigned long) tag,
12186 			slp->next, slp->prev, pring->postbufq_cnt);
12187 
12188 	return NULL;
12189 }
12190 
12191 /**
12192  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
12193  * @phba: Pointer to HBA context object.
12194  * @pring: Pointer to driver SLI ring object.
12195  * @phys: DMA address of the buffer.
12196  *
12197  * This function searches the buffer list using the dma_address
12198  * of unsolicited event to find the driver's lpfc_dmabuf object
12199  * corresponding to the dma_address. The function returns the
12200  * lpfc_dmabuf object if a buffer is found else it returns NULL.
12201  * This function is called by the ct and els unsolicited event
12202  * handlers to get the buffer associated with the unsolicited
12203  * event.
12204  *
12205  * This function is called with no lock held.
12206  **/
12207 struct lpfc_dmabuf *
12208 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12209 			 dma_addr_t phys)
12210 {
12211 	struct lpfc_dmabuf *mp, *next_mp;
12212 	struct list_head *slp = &pring->postbufq;
12213 
12214 	/* Search postbufq, from the beginning, looking for a match on phys */
12215 	spin_lock_irq(&phba->hbalock);
12216 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12217 		if (mp->phys == phys) {
12218 			list_del_init(&mp->list);
12219 			pring->postbufq_cnt--;
12220 			spin_unlock_irq(&phba->hbalock);
12221 			return mp;
12222 		}
12223 	}
12224 
12225 	spin_unlock_irq(&phba->hbalock);
12226 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12227 			"0410 Cannot find virtual addr for mapped buf on "
12228 			"ring %d Data x%llx x%px x%px x%x\n",
12229 			pring->ringno, (unsigned long long)phys,
12230 			slp->next, slp->prev, pring->postbufq_cnt);
12231 	return NULL;
12232 }
12233 
12234 /**
12235  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
12236  * @phba: Pointer to HBA context object.
12237  * @cmdiocb: Pointer to driver command iocb object.
12238  * @rspiocb: Pointer to driver response iocb object.
12239  *
12240  * This function is the completion handler for the abort iocbs for
12241  * ELS commands. This function is called from the ELS ring event
12242  * handler with no lock held. This function frees memory resources
12243  * associated with the abort iocb.
12244  **/
12245 static void
12246 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12247 			struct lpfc_iocbq *rspiocb)
12248 {
12249 	IOCB_t *irsp = &rspiocb->iocb;
12250 	uint16_t abort_iotag, abort_context;
12251 	struct lpfc_iocbq *abort_iocb = NULL;
12252 
12253 	if (irsp->ulpStatus) {
12254 
12255 		/*
12256 		 * Assume that the port already completed and returned, or
12257 		 * will return the iocb. Just Log the message.
12258 		 */
12259 		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
12260 		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
12261 
12262 		spin_lock_irq(&phba->hbalock);
12263 		if (phba->sli_rev < LPFC_SLI_REV4) {
12264 			if (irsp->ulpCommand == CMD_ABORT_XRI_CX &&
12265 			    irsp->ulpStatus == IOSTAT_LOCAL_REJECT &&
12266 			    irsp->un.ulpWord[4] == IOERR_ABORT_REQUESTED) {
12267 				spin_unlock_irq(&phba->hbalock);
12268 				goto release_iocb;
12269 			}
12270 			if (abort_iotag != 0 &&
12271 				abort_iotag <= phba->sli.last_iotag)
12272 				abort_iocb =
12273 					phba->sli.iocbq_lookup[abort_iotag];
12274 		} else
12275 			/* For sli4 the abort_tag is the XRI,
12276 			 * so the abort routine puts the iotag  of the iocb
12277 			 * being aborted in the context field of the abort
12278 			 * IOCB.
12279 			 */
12280 			abort_iocb = phba->sli.iocbq_lookup[abort_context];
12281 
12282 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
12283 				"0327 Cannot abort els iocb x%px "
12284 				"with tag %x context %x, abort status %x, "
12285 				"abort code %x\n",
12286 				abort_iocb, abort_iotag, abort_context,
12287 				irsp->ulpStatus, irsp->un.ulpWord[4]);
12288 
12289 		spin_unlock_irq(&phba->hbalock);
12290 	}
12291 release_iocb:
12292 	lpfc_sli_release_iocbq(phba, cmdiocb);
12293 	return;
12294 }
12295 
12296 /**
12297  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
12298  * @phba: Pointer to HBA context object.
12299  * @cmdiocb: Pointer to driver command iocb object.
12300  * @rspiocb: Pointer to driver response iocb object.
12301  *
12302  * The function is called from SLI ring event handler with no
12303  * lock held. This function is the completion handler for ELS commands
12304  * which are aborted. The function frees memory resources used for
12305  * the aborted ELS commands.
12306  **/
12307 void
12308 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12309 		     struct lpfc_iocbq *rspiocb)
12310 {
12311 	struct lpfc_nodelist *ndlp = (struct lpfc_nodelist *) cmdiocb->context1;
12312 	IOCB_t *irsp = &rspiocb->iocb;
12313 
12314 	/* ELS cmd tag <ulpIoTag> completes */
12315 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
12316 			"0139 Ignoring ELS cmd tag x%x completion Data: "
12317 			"x%x x%x x%x\n",
12318 			irsp->ulpIoTag, irsp->ulpStatus,
12319 			irsp->un.ulpWord[4], irsp->ulpTimeout);
12320 	/*
12321 	 * Deref the ndlp after free_iocb. sli_release_iocb will access the ndlp
12322 	 * if exchange is busy.
12323 	 */
12324 	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
12325 		lpfc_ct_free_iocb(phba, cmdiocb);
12326 	else
12327 		lpfc_els_free_iocb(phba, cmdiocb);
12328 
12329 	lpfc_nlp_put(ndlp);
12330 }
12331 
12332 /**
12333  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
12334  * @phba: Pointer to HBA context object.
12335  * @pring: Pointer to driver SLI ring object.
12336  * @cmdiocb: Pointer to driver command iocb object.
12337  * @cmpl: completion function.
12338  *
12339  * This function issues an abort iocb for the provided command iocb. In case
12340  * of unloading, the abort iocb will not be issued to commands on the ELS
12341  * ring. Instead, the callback function shall be changed to those commands
12342  * so that nothing happens when them finishes. This function is called with
12343  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
12344  * when the command iocb is an abort request.
12345  *
12346  **/
12347 int
12348 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12349 			   struct lpfc_iocbq *cmdiocb, void *cmpl)
12350 {
12351 	struct lpfc_vport *vport = cmdiocb->vport;
12352 	struct lpfc_iocbq *abtsiocbp;
12353 	IOCB_t *icmd = NULL;
12354 	IOCB_t *iabt = NULL;
12355 	int retval = IOCB_ERROR;
12356 	unsigned long iflags;
12357 	struct lpfc_nodelist *ndlp;
12358 
12359 	/*
12360 	 * There are certain command types we don't want to abort.  And we
12361 	 * don't want to abort commands that are already in the process of
12362 	 * being aborted.
12363 	 */
12364 	icmd = &cmdiocb->iocb;
12365 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
12366 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
12367 	    cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED)
12368 		return IOCB_ABORTING;
12369 
12370 	if (!pring) {
12371 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
12372 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
12373 		else
12374 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
12375 		return retval;
12376 	}
12377 
12378 	/*
12379 	 * If we're unloading, don't abort iocb on the ELS ring, but change
12380 	 * the callback so that nothing happens when it finishes.
12381 	 */
12382 	if ((vport->load_flag & FC_UNLOADING) &&
12383 	    pring->ringno == LPFC_ELS_RING) {
12384 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
12385 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
12386 		else
12387 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
12388 		return retval;
12389 	}
12390 
12391 	/* issue ABTS for this IOCB based on iotag */
12392 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
12393 	if (abtsiocbp == NULL)
12394 		return IOCB_NORESOURCE;
12395 
12396 	/* This signals the response to set the correct status
12397 	 * before calling the completion handler
12398 	 */
12399 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
12400 
12401 	iabt = &abtsiocbp->iocb;
12402 	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
12403 	iabt->un.acxri.abortContextTag = icmd->ulpContext;
12404 	if (phba->sli_rev == LPFC_SLI_REV4) {
12405 		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
12406 		if (pring->ringno == LPFC_ELS_RING)
12407 			iabt->un.acxri.abortContextTag = cmdiocb->iotag;
12408 	} else {
12409 		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
12410 		if (pring->ringno == LPFC_ELS_RING) {
12411 			ndlp = (struct lpfc_nodelist *)(cmdiocb->context1);
12412 			iabt->un.acxri.abortContextTag = ndlp->nlp_rpi;
12413 		}
12414 	}
12415 	iabt->ulpLe = 1;
12416 	iabt->ulpClass = icmd->ulpClass;
12417 
12418 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12419 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
12420 	if (cmdiocb->iocb_flag & LPFC_IO_FCP) {
12421 		abtsiocbp->iocb_flag |= LPFC_IO_FCP;
12422 		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
12423 	}
12424 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
12425 		abtsiocbp->iocb_flag |= LPFC_IO_FOF;
12426 
12427 	if (phba->link_state >= LPFC_LINK_UP)
12428 		iabt->ulpCommand = CMD_ABORT_XRI_CN;
12429 	else
12430 		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
12431 
12432 	if (cmpl)
12433 		abtsiocbp->iocb_cmpl = cmpl;
12434 	else
12435 		abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
12436 	abtsiocbp->vport = vport;
12437 
12438 	if (phba->sli_rev == LPFC_SLI_REV4) {
12439 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
12440 		if (unlikely(pring == NULL))
12441 			goto abort_iotag_exit;
12442 		/* Note: both hbalock and ring_lock need to be set here */
12443 		spin_lock_irqsave(&pring->ring_lock, iflags);
12444 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12445 			abtsiocbp, 0);
12446 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
12447 	} else {
12448 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12449 			abtsiocbp, 0);
12450 	}
12451 
12452 abort_iotag_exit:
12453 
12454 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
12455 			 "0339 Abort xri x%x, original iotag x%x, "
12456 			 "abort cmd iotag x%x retval x%x\n",
12457 			 iabt->un.acxri.abortIoTag,
12458 			 iabt->un.acxri.abortContextTag,
12459 			 abtsiocbp->iotag, retval);
12460 
12461 	if (retval) {
12462 		cmdiocb->iocb_flag &= ~LPFC_DRIVER_ABORTED;
12463 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
12464 	}
12465 
12466 	/*
12467 	 * Caller to this routine should check for IOCB_ERROR
12468 	 * and handle it properly.  This routine no longer removes
12469 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
12470 	 */
12471 	return retval;
12472 }
12473 
12474 /**
12475  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
12476  * @phba: pointer to lpfc HBA data structure.
12477  *
12478  * This routine will abort all pending and outstanding iocbs to an HBA.
12479  **/
12480 void
12481 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
12482 {
12483 	struct lpfc_sli *psli = &phba->sli;
12484 	struct lpfc_sli_ring *pring;
12485 	struct lpfc_queue *qp = NULL;
12486 	int i;
12487 
12488 	if (phba->sli_rev != LPFC_SLI_REV4) {
12489 		for (i = 0; i < psli->num_rings; i++) {
12490 			pring = &psli->sli3_ring[i];
12491 			lpfc_sli_abort_iocb_ring(phba, pring);
12492 		}
12493 		return;
12494 	}
12495 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12496 		pring = qp->pring;
12497 		if (!pring)
12498 			continue;
12499 		lpfc_sli_abort_iocb_ring(phba, pring);
12500 	}
12501 }
12502 
12503 /**
12504  * lpfc_sli_validate_fcp_iocb_for_abort - filter iocbs appropriate for FCP aborts
12505  * @iocbq: Pointer to iocb object.
12506  * @vport: Pointer to driver virtual port object.
12507  *
12508  * This function acts as an iocb filter for functions which abort FCP iocbs.
12509  *
12510  * Return values
12511  * -ENODEV, if a null iocb or vport ptr is encountered
12512  * -EINVAL, if the iocb is not an FCP I/O, not on the TX cmpl queue, premarked as
12513  *          driver already started the abort process, or is an abort iocb itself
12514  * 0, passes criteria for aborting the FCP I/O iocb
12515  **/
12516 static int
12517 lpfc_sli_validate_fcp_iocb_for_abort(struct lpfc_iocbq *iocbq,
12518 				     struct lpfc_vport *vport)
12519 {
12520 	IOCB_t *icmd = NULL;
12521 
12522 	/* No null ptr vports */
12523 	if (!iocbq || iocbq->vport != vport)
12524 		return -ENODEV;
12525 
12526 	/* iocb must be for FCP IO, already exists on the TX cmpl queue,
12527 	 * can't be premarked as driver aborted, nor be an ABORT iocb itself
12528 	 */
12529 	icmd = &iocbq->iocb;
12530 	if (!(iocbq->iocb_flag & LPFC_IO_FCP) ||
12531 	    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ) ||
12532 	    (iocbq->iocb_flag & LPFC_DRIVER_ABORTED) ||
12533 	    (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
12534 	     icmd->ulpCommand == CMD_CLOSE_XRI_CN))
12535 		return -EINVAL;
12536 
12537 	return 0;
12538 }
12539 
12540 /**
12541  * lpfc_sli_validate_fcp_iocb - validate commands associated with a SCSI target
12542  * @iocbq: Pointer to driver iocb object.
12543  * @vport: Pointer to driver virtual port object.
12544  * @tgt_id: SCSI ID of the target.
12545  * @lun_id: LUN ID of the scsi device.
12546  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
12547  *
12548  * This function acts as an iocb filter for validating a lun/SCSI target/SCSI
12549  * host.
12550  *
12551  * It will return
12552  * 0 if the filtering criteria is met for the given iocb and will return
12553  * 1 if the filtering criteria is not met.
12554  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
12555  * given iocb is for the SCSI device specified by vport, tgt_id and
12556  * lun_id parameter.
12557  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
12558  * given iocb is for the SCSI target specified by vport and tgt_id
12559  * parameters.
12560  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
12561  * given iocb is for the SCSI host associated with the given vport.
12562  * This function is called with no locks held.
12563  **/
12564 static int
12565 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
12566 			   uint16_t tgt_id, uint64_t lun_id,
12567 			   lpfc_ctx_cmd ctx_cmd)
12568 {
12569 	struct lpfc_io_buf *lpfc_cmd;
12570 	int rc = 1;
12571 
12572 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12573 
12574 	if (lpfc_cmd->pCmd == NULL)
12575 		return rc;
12576 
12577 	switch (ctx_cmd) {
12578 	case LPFC_CTX_LUN:
12579 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12580 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
12581 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
12582 			rc = 0;
12583 		break;
12584 	case LPFC_CTX_TGT:
12585 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12586 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
12587 			rc = 0;
12588 		break;
12589 	case LPFC_CTX_HOST:
12590 		rc = 0;
12591 		break;
12592 	default:
12593 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
12594 			__func__, ctx_cmd);
12595 		break;
12596 	}
12597 
12598 	return rc;
12599 }
12600 
12601 /**
12602  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
12603  * @vport: Pointer to virtual port.
12604  * @tgt_id: SCSI ID of the target.
12605  * @lun_id: LUN ID of the scsi device.
12606  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12607  *
12608  * This function returns number of FCP commands pending for the vport.
12609  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
12610  * commands pending on the vport associated with SCSI device specified
12611  * by tgt_id and lun_id parameters.
12612  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
12613  * commands pending on the vport associated with SCSI target specified
12614  * by tgt_id parameter.
12615  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
12616  * commands pending on the vport.
12617  * This function returns the number of iocbs which satisfy the filter.
12618  * This function is called without any lock held.
12619  **/
12620 int
12621 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
12622 		  lpfc_ctx_cmd ctx_cmd)
12623 {
12624 	struct lpfc_hba *phba = vport->phba;
12625 	struct lpfc_iocbq *iocbq;
12626 	IOCB_t *icmd = NULL;
12627 	int sum, i;
12628 	unsigned long iflags;
12629 
12630 	spin_lock_irqsave(&phba->hbalock, iflags);
12631 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
12632 		iocbq = phba->sli.iocbq_lookup[i];
12633 
12634 		if (!iocbq || iocbq->vport != vport)
12635 			continue;
12636 		if (!(iocbq->iocb_flag & LPFC_IO_FCP) ||
12637 		    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ))
12638 			continue;
12639 
12640 		/* Include counting outstanding aborts */
12641 		icmd = &iocbq->iocb;
12642 		if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
12643 		    icmd->ulpCommand == CMD_CLOSE_XRI_CN) {
12644 			sum++;
12645 			continue;
12646 		}
12647 
12648 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12649 					       ctx_cmd) == 0)
12650 			sum++;
12651 	}
12652 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12653 
12654 	return sum;
12655 }
12656 
12657 /**
12658  * lpfc_sli4_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
12659  * @phba: Pointer to HBA context object
12660  * @cmdiocb: Pointer to command iocb object.
12661  * @wcqe: pointer to the complete wcqe
12662  *
12663  * This function is called when an aborted FCP iocb completes. This
12664  * function is called by the ring event handler with no lock held.
12665  * This function frees the iocb. It is called for sli-4 adapters.
12666  **/
12667 void
12668 lpfc_sli4_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12669 			 struct lpfc_wcqe_complete *wcqe)
12670 {
12671 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12672 			"3017 ABORT_XRI_CN completing on rpi x%x "
12673 			"original iotag x%x, abort cmd iotag x%x "
12674 			"status 0x%x, reason 0x%x\n",
12675 			cmdiocb->iocb.un.acxri.abortContextTag,
12676 			cmdiocb->iocb.un.acxri.abortIoTag,
12677 			cmdiocb->iotag,
12678 			(bf_get(lpfc_wcqe_c_status, wcqe)
12679 			& LPFC_IOCB_STATUS_MASK),
12680 			wcqe->parameter);
12681 	lpfc_sli_release_iocbq(phba, cmdiocb);
12682 }
12683 
12684 /**
12685  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
12686  * @phba: Pointer to HBA context object
12687  * @cmdiocb: Pointer to command iocb object.
12688  * @rspiocb: Pointer to response iocb object.
12689  *
12690  * This function is called when an aborted FCP iocb completes. This
12691  * function is called by the ring event handler with no lock held.
12692  * This function frees the iocb.
12693  **/
12694 void
12695 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12696 			struct lpfc_iocbq *rspiocb)
12697 {
12698 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12699 			"3096 ABORT_XRI_CN completing on rpi x%x "
12700 			"original iotag x%x, abort cmd iotag x%x "
12701 			"status 0x%x, reason 0x%x\n",
12702 			cmdiocb->iocb.un.acxri.abortContextTag,
12703 			cmdiocb->iocb.un.acxri.abortIoTag,
12704 			cmdiocb->iotag, rspiocb->iocb.ulpStatus,
12705 			rspiocb->iocb.un.ulpWord[4]);
12706 	lpfc_sli_release_iocbq(phba, cmdiocb);
12707 	return;
12708 }
12709 
12710 /**
12711  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
12712  * @vport: Pointer to virtual port.
12713  * @tgt_id: SCSI ID of the target.
12714  * @lun_id: LUN ID of the scsi device.
12715  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12716  *
12717  * This function sends an abort command for every SCSI command
12718  * associated with the given virtual port pending on the ring
12719  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12720  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12721  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12722  * followed by lpfc_sli_validate_fcp_iocb.
12723  *
12724  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
12725  * FCP iocbs associated with lun specified by tgt_id and lun_id
12726  * parameters
12727  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
12728  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12729  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
12730  * FCP iocbs associated with virtual port.
12731  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
12732  * lpfc_sli4_calc_ring is used.
12733  * This function returns number of iocbs it failed to abort.
12734  * This function is called with no locks held.
12735  **/
12736 int
12737 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
12738 		    lpfc_ctx_cmd abort_cmd)
12739 {
12740 	struct lpfc_hba *phba = vport->phba;
12741 	struct lpfc_sli_ring *pring = NULL;
12742 	struct lpfc_iocbq *iocbq;
12743 	int errcnt = 0, ret_val = 0;
12744 	unsigned long iflags;
12745 	int i;
12746 	void *fcp_cmpl = NULL;
12747 
12748 	/* all I/Os are in process of being flushed */
12749 	if (phba->hba_flag & HBA_IOQ_FLUSH)
12750 		return errcnt;
12751 
12752 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12753 		iocbq = phba->sli.iocbq_lookup[i];
12754 
12755 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12756 			continue;
12757 
12758 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12759 					       abort_cmd) != 0)
12760 			continue;
12761 
12762 		spin_lock_irqsave(&phba->hbalock, iflags);
12763 		if (phba->sli_rev == LPFC_SLI_REV3) {
12764 			pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12765 			fcp_cmpl = lpfc_sli_abort_fcp_cmpl;
12766 		} else if (phba->sli_rev == LPFC_SLI_REV4) {
12767 			pring = lpfc_sli4_calc_ring(phba, iocbq);
12768 			fcp_cmpl = lpfc_sli4_abort_fcp_cmpl;
12769 		}
12770 		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
12771 						     fcp_cmpl);
12772 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12773 		if (ret_val != IOCB_SUCCESS)
12774 			errcnt++;
12775 	}
12776 
12777 	return errcnt;
12778 }
12779 
12780 /**
12781  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12782  * @vport: Pointer to virtual port.
12783  * @pring: Pointer to driver SLI ring object.
12784  * @tgt_id: SCSI ID of the target.
12785  * @lun_id: LUN ID of the scsi device.
12786  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12787  *
12788  * This function sends an abort command for every SCSI command
12789  * associated with the given virtual port pending on the ring
12790  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12791  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12792  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12793  * followed by lpfc_sli_validate_fcp_iocb.
12794  *
12795  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12796  * FCP iocbs associated with lun specified by tgt_id and lun_id
12797  * parameters
12798  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12799  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12800  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12801  * FCP iocbs associated with virtual port.
12802  * This function returns number of iocbs it aborted .
12803  * This function is called with no locks held right after a taskmgmt
12804  * command is sent.
12805  **/
12806 int
12807 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12808 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12809 {
12810 	struct lpfc_hba *phba = vport->phba;
12811 	struct lpfc_io_buf *lpfc_cmd;
12812 	struct lpfc_iocbq *abtsiocbq;
12813 	struct lpfc_nodelist *ndlp;
12814 	struct lpfc_iocbq *iocbq;
12815 	IOCB_t *icmd;
12816 	int sum, i, ret_val;
12817 	unsigned long iflags;
12818 	struct lpfc_sli_ring *pring_s4 = NULL;
12819 
12820 	spin_lock_irqsave(&phba->hbalock, iflags);
12821 
12822 	/* all I/Os are in process of being flushed */
12823 	if (phba->hba_flag & HBA_IOQ_FLUSH) {
12824 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12825 		return 0;
12826 	}
12827 	sum = 0;
12828 
12829 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12830 		iocbq = phba->sli.iocbq_lookup[i];
12831 
12832 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12833 			continue;
12834 
12835 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12836 					       cmd) != 0)
12837 			continue;
12838 
12839 		/* Guard against IO completion being called at same time */
12840 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12841 		spin_lock(&lpfc_cmd->buf_lock);
12842 
12843 		if (!lpfc_cmd->pCmd) {
12844 			spin_unlock(&lpfc_cmd->buf_lock);
12845 			continue;
12846 		}
12847 
12848 		if (phba->sli_rev == LPFC_SLI_REV4) {
12849 			pring_s4 =
12850 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12851 			if (!pring_s4) {
12852 				spin_unlock(&lpfc_cmd->buf_lock);
12853 				continue;
12854 			}
12855 			/* Note: both hbalock and ring_lock must be set here */
12856 			spin_lock(&pring_s4->ring_lock);
12857 		}
12858 
12859 		/*
12860 		 * If the iocbq is already being aborted, don't take a second
12861 		 * action, but do count it.
12862 		 */
12863 		if ((iocbq->iocb_flag & LPFC_DRIVER_ABORTED) ||
12864 		    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ)) {
12865 			if (phba->sli_rev == LPFC_SLI_REV4)
12866 				spin_unlock(&pring_s4->ring_lock);
12867 			spin_unlock(&lpfc_cmd->buf_lock);
12868 			continue;
12869 		}
12870 
12871 		/* issue ABTS for this IOCB based on iotag */
12872 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
12873 		if (!abtsiocbq) {
12874 			if (phba->sli_rev == LPFC_SLI_REV4)
12875 				spin_unlock(&pring_s4->ring_lock);
12876 			spin_unlock(&lpfc_cmd->buf_lock);
12877 			continue;
12878 		}
12879 
12880 		icmd = &iocbq->iocb;
12881 		abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
12882 		abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
12883 		if (phba->sli_rev == LPFC_SLI_REV4)
12884 			abtsiocbq->iocb.un.acxri.abortIoTag =
12885 							 iocbq->sli4_xritag;
12886 		else
12887 			abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
12888 		abtsiocbq->iocb.ulpLe = 1;
12889 		abtsiocbq->iocb.ulpClass = icmd->ulpClass;
12890 		abtsiocbq->vport = vport;
12891 
12892 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12893 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12894 		if (iocbq->iocb_flag & LPFC_IO_FCP)
12895 			abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
12896 		if (iocbq->iocb_flag & LPFC_IO_FOF)
12897 			abtsiocbq->iocb_flag |= LPFC_IO_FOF;
12898 
12899 		ndlp = lpfc_cmd->rdata->pnode;
12900 
12901 		if (lpfc_is_link_up(phba) &&
12902 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
12903 			abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
12904 		else
12905 			abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
12906 
12907 		/* Setup callback routine and issue the command. */
12908 		abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
12909 
12910 		/*
12911 		 * Indicate the IO is being aborted by the driver and set
12912 		 * the caller's flag into the aborted IO.
12913 		 */
12914 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
12915 
12916 		if (phba->sli_rev == LPFC_SLI_REV4) {
12917 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
12918 							abtsiocbq, 0);
12919 			spin_unlock(&pring_s4->ring_lock);
12920 		} else {
12921 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
12922 							abtsiocbq, 0);
12923 		}
12924 
12925 		spin_unlock(&lpfc_cmd->buf_lock);
12926 
12927 		if (ret_val == IOCB_ERROR)
12928 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
12929 		else
12930 			sum++;
12931 	}
12932 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12933 	return sum;
12934 }
12935 
12936 /**
12937  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
12938  * @phba: Pointer to HBA context object.
12939  * @cmdiocbq: Pointer to command iocb.
12940  * @rspiocbq: Pointer to response iocb.
12941  *
12942  * This function is the completion handler for iocbs issued using
12943  * lpfc_sli_issue_iocb_wait function. This function is called by the
12944  * ring event handler function without any lock held. This function
12945  * can be called from both worker thread context and interrupt
12946  * context. This function also can be called from other thread which
12947  * cleans up the SLI layer objects.
12948  * This function copy the contents of the response iocb to the
12949  * response iocb memory object provided by the caller of
12950  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
12951  * sleeps for the iocb completion.
12952  **/
12953 static void
12954 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
12955 			struct lpfc_iocbq *cmdiocbq,
12956 			struct lpfc_iocbq *rspiocbq)
12957 {
12958 	wait_queue_head_t *pdone_q;
12959 	unsigned long iflags;
12960 	struct lpfc_io_buf *lpfc_cmd;
12961 
12962 	spin_lock_irqsave(&phba->hbalock, iflags);
12963 	if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
12964 
12965 		/*
12966 		 * A time out has occurred for the iocb.  If a time out
12967 		 * completion handler has been supplied, call it.  Otherwise,
12968 		 * just free the iocbq.
12969 		 */
12970 
12971 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12972 		cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
12973 		cmdiocbq->wait_iocb_cmpl = NULL;
12974 		if (cmdiocbq->iocb_cmpl)
12975 			(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
12976 		else
12977 			lpfc_sli_release_iocbq(phba, cmdiocbq);
12978 		return;
12979 	}
12980 
12981 	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
12982 	if (cmdiocbq->context2 && rspiocbq)
12983 		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
12984 		       &rspiocbq->iocb, sizeof(IOCB_t));
12985 
12986 	/* Set the exchange busy flag for task management commands */
12987 	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
12988 		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
12989 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
12990 			cur_iocbq);
12991 		if (rspiocbq && (rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY))
12992 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
12993 		else
12994 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
12995 	}
12996 
12997 	pdone_q = cmdiocbq->context_un.wait_queue;
12998 	if (pdone_q)
12999 		wake_up(pdone_q);
13000 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13001 	return;
13002 }
13003 
13004 /**
13005  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
13006  * @phba: Pointer to HBA context object..
13007  * @piocbq: Pointer to command iocb.
13008  * @flag: Flag to test.
13009  *
13010  * This routine grabs the hbalock and then test the iocb_flag to
13011  * see if the passed in flag is set.
13012  * Returns:
13013  * 1 if flag is set.
13014  * 0 if flag is not set.
13015  **/
13016 static int
13017 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
13018 		 struct lpfc_iocbq *piocbq, uint32_t flag)
13019 {
13020 	unsigned long iflags;
13021 	int ret;
13022 
13023 	spin_lock_irqsave(&phba->hbalock, iflags);
13024 	ret = piocbq->iocb_flag & flag;
13025 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13026 	return ret;
13027 
13028 }
13029 
13030 /**
13031  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
13032  * @phba: Pointer to HBA context object..
13033  * @ring_number: Ring number
13034  * @piocb: Pointer to command iocb.
13035  * @prspiocbq: Pointer to response iocb.
13036  * @timeout: Timeout in number of seconds.
13037  *
13038  * This function issues the iocb to firmware and waits for the
13039  * iocb to complete. The iocb_cmpl field of the shall be used
13040  * to handle iocbs which time out. If the field is NULL, the
13041  * function shall free the iocbq structure.  If more clean up is
13042  * needed, the caller is expected to provide a completion function
13043  * that will provide the needed clean up.  If the iocb command is
13044  * not completed within timeout seconds, the function will either
13045  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
13046  * completion function set in the iocb_cmpl field and then return
13047  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
13048  * resources if this function returns IOCB_TIMEDOUT.
13049  * The function waits for the iocb completion using an
13050  * non-interruptible wait.
13051  * This function will sleep while waiting for iocb completion.
13052  * So, this function should not be called from any context which
13053  * does not allow sleeping. Due to the same reason, this function
13054  * cannot be called with interrupt disabled.
13055  * This function assumes that the iocb completions occur while
13056  * this function sleep. So, this function cannot be called from
13057  * the thread which process iocb completion for this ring.
13058  * This function clears the iocb_flag of the iocb object before
13059  * issuing the iocb and the iocb completion handler sets this
13060  * flag and wakes this thread when the iocb completes.
13061  * The contents of the response iocb will be copied to prspiocbq
13062  * by the completion handler when the command completes.
13063  * This function returns IOCB_SUCCESS when success.
13064  * This function is called with no lock held.
13065  **/
13066 int
13067 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
13068 			 uint32_t ring_number,
13069 			 struct lpfc_iocbq *piocb,
13070 			 struct lpfc_iocbq *prspiocbq,
13071 			 uint32_t timeout)
13072 {
13073 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
13074 	long timeleft, timeout_req = 0;
13075 	int retval = IOCB_SUCCESS;
13076 	uint32_t creg_val;
13077 	struct lpfc_iocbq *iocb;
13078 	int txq_cnt = 0;
13079 	int txcmplq_cnt = 0;
13080 	struct lpfc_sli_ring *pring;
13081 	unsigned long iflags;
13082 	bool iocb_completed = true;
13083 
13084 	if (phba->sli_rev >= LPFC_SLI_REV4)
13085 		pring = lpfc_sli4_calc_ring(phba, piocb);
13086 	else
13087 		pring = &phba->sli.sli3_ring[ring_number];
13088 	/*
13089 	 * If the caller has provided a response iocbq buffer, then context2
13090 	 * is NULL or its an error.
13091 	 */
13092 	if (prspiocbq) {
13093 		if (piocb->context2)
13094 			return IOCB_ERROR;
13095 		piocb->context2 = prspiocbq;
13096 	}
13097 
13098 	piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
13099 	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
13100 	piocb->context_un.wait_queue = &done_q;
13101 	piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
13102 
13103 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13104 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13105 			return IOCB_ERROR;
13106 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
13107 		writel(creg_val, phba->HCregaddr);
13108 		readl(phba->HCregaddr); /* flush */
13109 	}
13110 
13111 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
13112 				     SLI_IOCB_RET_IOCB);
13113 	if (retval == IOCB_SUCCESS) {
13114 		timeout_req = msecs_to_jiffies(timeout * 1000);
13115 		timeleft = wait_event_timeout(done_q,
13116 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
13117 				timeout_req);
13118 		spin_lock_irqsave(&phba->hbalock, iflags);
13119 		if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
13120 
13121 			/*
13122 			 * IOCB timed out.  Inform the wake iocb wait
13123 			 * completion function and set local status
13124 			 */
13125 
13126 			iocb_completed = false;
13127 			piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
13128 		}
13129 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13130 		if (iocb_completed) {
13131 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13132 					"0331 IOCB wake signaled\n");
13133 			/* Note: we are not indicating if the IOCB has a success
13134 			 * status or not - that's for the caller to check.
13135 			 * IOCB_SUCCESS means just that the command was sent and
13136 			 * completed. Not that it completed successfully.
13137 			 * */
13138 		} else if (timeleft == 0) {
13139 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13140 					"0338 IOCB wait timeout error - no "
13141 					"wake response Data x%x\n", timeout);
13142 			retval = IOCB_TIMEDOUT;
13143 		} else {
13144 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13145 					"0330 IOCB wake NOT set, "
13146 					"Data x%x x%lx\n",
13147 					timeout, (timeleft / jiffies));
13148 			retval = IOCB_TIMEDOUT;
13149 		}
13150 	} else if (retval == IOCB_BUSY) {
13151 		if (phba->cfg_log_verbose & LOG_SLI) {
13152 			list_for_each_entry(iocb, &pring->txq, list) {
13153 				txq_cnt++;
13154 			}
13155 			list_for_each_entry(iocb, &pring->txcmplq, list) {
13156 				txcmplq_cnt++;
13157 			}
13158 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13159 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
13160 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
13161 		}
13162 		return retval;
13163 	} else {
13164 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13165 				"0332 IOCB wait issue failed, Data x%x\n",
13166 				retval);
13167 		retval = IOCB_ERROR;
13168 	}
13169 
13170 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13171 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13172 			return IOCB_ERROR;
13173 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
13174 		writel(creg_val, phba->HCregaddr);
13175 		readl(phba->HCregaddr); /* flush */
13176 	}
13177 
13178 	if (prspiocbq)
13179 		piocb->context2 = NULL;
13180 
13181 	piocb->context_un.wait_queue = NULL;
13182 	piocb->iocb_cmpl = NULL;
13183 	return retval;
13184 }
13185 
13186 /**
13187  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
13188  * @phba: Pointer to HBA context object.
13189  * @pmboxq: Pointer to driver mailbox object.
13190  * @timeout: Timeout in number of seconds.
13191  *
13192  * This function issues the mailbox to firmware and waits for the
13193  * mailbox command to complete. If the mailbox command is not
13194  * completed within timeout seconds, it returns MBX_TIMEOUT.
13195  * The function waits for the mailbox completion using an
13196  * interruptible wait. If the thread is woken up due to a
13197  * signal, MBX_TIMEOUT error is returned to the caller. Caller
13198  * should not free the mailbox resources, if this function returns
13199  * MBX_TIMEOUT.
13200  * This function will sleep while waiting for mailbox completion.
13201  * So, this function should not be called from any context which
13202  * does not allow sleeping. Due to the same reason, this function
13203  * cannot be called with interrupt disabled.
13204  * This function assumes that the mailbox completion occurs while
13205  * this function sleep. So, this function cannot be called from
13206  * the worker thread which processes mailbox completion.
13207  * This function is called in the context of HBA management
13208  * applications.
13209  * This function returns MBX_SUCCESS when successful.
13210  * This function is called with no lock held.
13211  **/
13212 int
13213 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
13214 			 uint32_t timeout)
13215 {
13216 	struct completion mbox_done;
13217 	int retval;
13218 	unsigned long flag;
13219 
13220 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
13221 	/* setup wake call as IOCB callback */
13222 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
13223 
13224 	/* setup context3 field to pass wait_queue pointer to wake function  */
13225 	init_completion(&mbox_done);
13226 	pmboxq->context3 = &mbox_done;
13227 	/* now issue the command */
13228 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
13229 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
13230 		wait_for_completion_timeout(&mbox_done,
13231 					    msecs_to_jiffies(timeout * 1000));
13232 
13233 		spin_lock_irqsave(&phba->hbalock, flag);
13234 		pmboxq->context3 = NULL;
13235 		/*
13236 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
13237 		 * else do not free the resources.
13238 		 */
13239 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
13240 			retval = MBX_SUCCESS;
13241 		} else {
13242 			retval = MBX_TIMEOUT;
13243 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13244 		}
13245 		spin_unlock_irqrestore(&phba->hbalock, flag);
13246 	}
13247 	return retval;
13248 }
13249 
13250 /**
13251  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
13252  * @phba: Pointer to HBA context.
13253  * @mbx_action: Mailbox shutdown options.
13254  *
13255  * This function is called to shutdown the driver's mailbox sub-system.
13256  * It first marks the mailbox sub-system is in a block state to prevent
13257  * the asynchronous mailbox command from issued off the pending mailbox
13258  * command queue. If the mailbox command sub-system shutdown is due to
13259  * HBA error conditions such as EEH or ERATT, this routine shall invoke
13260  * the mailbox sub-system flush routine to forcefully bring down the
13261  * mailbox sub-system. Otherwise, if it is due to normal condition (such
13262  * as with offline or HBA function reset), this routine will wait for the
13263  * outstanding mailbox command to complete before invoking the mailbox
13264  * sub-system flush routine to gracefully bring down mailbox sub-system.
13265  **/
13266 void
13267 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
13268 {
13269 	struct lpfc_sli *psli = &phba->sli;
13270 	unsigned long timeout;
13271 
13272 	if (mbx_action == LPFC_MBX_NO_WAIT) {
13273 		/* delay 100ms for port state */
13274 		msleep(100);
13275 		lpfc_sli_mbox_sys_flush(phba);
13276 		return;
13277 	}
13278 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
13279 
13280 	/* Disable softirqs, including timers from obtaining phba->hbalock */
13281 	local_bh_disable();
13282 
13283 	spin_lock_irq(&phba->hbalock);
13284 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13285 
13286 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
13287 		/* Determine how long we might wait for the active mailbox
13288 		 * command to be gracefully completed by firmware.
13289 		 */
13290 		if (phba->sli.mbox_active)
13291 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
13292 						phba->sli.mbox_active) *
13293 						1000) + jiffies;
13294 		spin_unlock_irq(&phba->hbalock);
13295 
13296 		/* Enable softirqs again, done with phba->hbalock */
13297 		local_bh_enable();
13298 
13299 		while (phba->sli.mbox_active) {
13300 			/* Check active mailbox complete status every 2ms */
13301 			msleep(2);
13302 			if (time_after(jiffies, timeout))
13303 				/* Timeout, let the mailbox flush routine to
13304 				 * forcefully release active mailbox command
13305 				 */
13306 				break;
13307 		}
13308 	} else {
13309 		spin_unlock_irq(&phba->hbalock);
13310 
13311 		/* Enable softirqs again, done with phba->hbalock */
13312 		local_bh_enable();
13313 	}
13314 
13315 	lpfc_sli_mbox_sys_flush(phba);
13316 }
13317 
13318 /**
13319  * lpfc_sli_eratt_read - read sli-3 error attention events
13320  * @phba: Pointer to HBA context.
13321  *
13322  * This function is called to read the SLI3 device error attention registers
13323  * for possible error attention events. The caller must hold the hostlock
13324  * with spin_lock_irq().
13325  *
13326  * This function returns 1 when there is Error Attention in the Host Attention
13327  * Register and returns 0 otherwise.
13328  **/
13329 static int
13330 lpfc_sli_eratt_read(struct lpfc_hba *phba)
13331 {
13332 	uint32_t ha_copy;
13333 
13334 	/* Read chip Host Attention (HA) register */
13335 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
13336 		goto unplug_err;
13337 
13338 	if (ha_copy & HA_ERATT) {
13339 		/* Read host status register to retrieve error event */
13340 		if (lpfc_sli_read_hs(phba))
13341 			goto unplug_err;
13342 
13343 		/* Check if there is a deferred error condition is active */
13344 		if ((HS_FFER1 & phba->work_hs) &&
13345 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13346 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
13347 			phba->hba_flag |= DEFER_ERATT;
13348 			/* Clear all interrupt enable conditions */
13349 			writel(0, phba->HCregaddr);
13350 			readl(phba->HCregaddr);
13351 		}
13352 
13353 		/* Set the driver HA work bitmap */
13354 		phba->work_ha |= HA_ERATT;
13355 		/* Indicate polling handles this ERATT */
13356 		phba->hba_flag |= HBA_ERATT_HANDLED;
13357 		return 1;
13358 	}
13359 	return 0;
13360 
13361 unplug_err:
13362 	/* Set the driver HS work bitmap */
13363 	phba->work_hs |= UNPLUG_ERR;
13364 	/* Set the driver HA work bitmap */
13365 	phba->work_ha |= HA_ERATT;
13366 	/* Indicate polling handles this ERATT */
13367 	phba->hba_flag |= HBA_ERATT_HANDLED;
13368 	return 1;
13369 }
13370 
13371 /**
13372  * lpfc_sli4_eratt_read - read sli-4 error attention events
13373  * @phba: Pointer to HBA context.
13374  *
13375  * This function is called to read the SLI4 device error attention registers
13376  * for possible error attention events. The caller must hold the hostlock
13377  * with spin_lock_irq().
13378  *
13379  * This function returns 1 when there is Error Attention in the Host Attention
13380  * Register and returns 0 otherwise.
13381  **/
13382 static int
13383 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
13384 {
13385 	uint32_t uerr_sta_hi, uerr_sta_lo;
13386 	uint32_t if_type, portsmphr;
13387 	struct lpfc_register portstat_reg;
13388 
13389 	/*
13390 	 * For now, use the SLI4 device internal unrecoverable error
13391 	 * registers for error attention. This can be changed later.
13392 	 */
13393 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
13394 	switch (if_type) {
13395 	case LPFC_SLI_INTF_IF_TYPE_0:
13396 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
13397 			&uerr_sta_lo) ||
13398 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
13399 			&uerr_sta_hi)) {
13400 			phba->work_hs |= UNPLUG_ERR;
13401 			phba->work_ha |= HA_ERATT;
13402 			phba->hba_flag |= HBA_ERATT_HANDLED;
13403 			return 1;
13404 		}
13405 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
13406 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
13407 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13408 					"1423 HBA Unrecoverable error: "
13409 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
13410 					"ue_mask_lo_reg=0x%x, "
13411 					"ue_mask_hi_reg=0x%x\n",
13412 					uerr_sta_lo, uerr_sta_hi,
13413 					phba->sli4_hba.ue_mask_lo,
13414 					phba->sli4_hba.ue_mask_hi);
13415 			phba->work_status[0] = uerr_sta_lo;
13416 			phba->work_status[1] = uerr_sta_hi;
13417 			phba->work_ha |= HA_ERATT;
13418 			phba->hba_flag |= HBA_ERATT_HANDLED;
13419 			return 1;
13420 		}
13421 		break;
13422 	case LPFC_SLI_INTF_IF_TYPE_2:
13423 	case LPFC_SLI_INTF_IF_TYPE_6:
13424 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
13425 			&portstat_reg.word0) ||
13426 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
13427 			&portsmphr)){
13428 			phba->work_hs |= UNPLUG_ERR;
13429 			phba->work_ha |= HA_ERATT;
13430 			phba->hba_flag |= HBA_ERATT_HANDLED;
13431 			return 1;
13432 		}
13433 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
13434 			phba->work_status[0] =
13435 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
13436 			phba->work_status[1] =
13437 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
13438 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13439 					"2885 Port Status Event: "
13440 					"port status reg 0x%x, "
13441 					"port smphr reg 0x%x, "
13442 					"error 1=0x%x, error 2=0x%x\n",
13443 					portstat_reg.word0,
13444 					portsmphr,
13445 					phba->work_status[0],
13446 					phba->work_status[1]);
13447 			phba->work_ha |= HA_ERATT;
13448 			phba->hba_flag |= HBA_ERATT_HANDLED;
13449 			return 1;
13450 		}
13451 		break;
13452 	case LPFC_SLI_INTF_IF_TYPE_1:
13453 	default:
13454 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13455 				"2886 HBA Error Attention on unsupported "
13456 				"if type %d.", if_type);
13457 		return 1;
13458 	}
13459 
13460 	return 0;
13461 }
13462 
13463 /**
13464  * lpfc_sli_check_eratt - check error attention events
13465  * @phba: Pointer to HBA context.
13466  *
13467  * This function is called from timer soft interrupt context to check HBA's
13468  * error attention register bit for error attention events.
13469  *
13470  * This function returns 1 when there is Error Attention in the Host Attention
13471  * Register and returns 0 otherwise.
13472  **/
13473 int
13474 lpfc_sli_check_eratt(struct lpfc_hba *phba)
13475 {
13476 	uint32_t ha_copy;
13477 
13478 	/* If somebody is waiting to handle an eratt, don't process it
13479 	 * here. The brdkill function will do this.
13480 	 */
13481 	if (phba->link_flag & LS_IGNORE_ERATT)
13482 		return 0;
13483 
13484 	/* Check if interrupt handler handles this ERATT */
13485 	spin_lock_irq(&phba->hbalock);
13486 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
13487 		/* Interrupt handler has handled ERATT */
13488 		spin_unlock_irq(&phba->hbalock);
13489 		return 0;
13490 	}
13491 
13492 	/*
13493 	 * If there is deferred error attention, do not check for error
13494 	 * attention
13495 	 */
13496 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13497 		spin_unlock_irq(&phba->hbalock);
13498 		return 0;
13499 	}
13500 
13501 	/* If PCI channel is offline, don't process it */
13502 	if (unlikely(pci_channel_offline(phba->pcidev))) {
13503 		spin_unlock_irq(&phba->hbalock);
13504 		return 0;
13505 	}
13506 
13507 	switch (phba->sli_rev) {
13508 	case LPFC_SLI_REV2:
13509 	case LPFC_SLI_REV3:
13510 		/* Read chip Host Attention (HA) register */
13511 		ha_copy = lpfc_sli_eratt_read(phba);
13512 		break;
13513 	case LPFC_SLI_REV4:
13514 		/* Read device Uncoverable Error (UERR) registers */
13515 		ha_copy = lpfc_sli4_eratt_read(phba);
13516 		break;
13517 	default:
13518 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13519 				"0299 Invalid SLI revision (%d)\n",
13520 				phba->sli_rev);
13521 		ha_copy = 0;
13522 		break;
13523 	}
13524 	spin_unlock_irq(&phba->hbalock);
13525 
13526 	return ha_copy;
13527 }
13528 
13529 /**
13530  * lpfc_intr_state_check - Check device state for interrupt handling
13531  * @phba: Pointer to HBA context.
13532  *
13533  * This inline routine checks whether a device or its PCI slot is in a state
13534  * that the interrupt should be handled.
13535  *
13536  * This function returns 0 if the device or the PCI slot is in a state that
13537  * interrupt should be handled, otherwise -EIO.
13538  */
13539 static inline int
13540 lpfc_intr_state_check(struct lpfc_hba *phba)
13541 {
13542 	/* If the pci channel is offline, ignore all the interrupts */
13543 	if (unlikely(pci_channel_offline(phba->pcidev)))
13544 		return -EIO;
13545 
13546 	/* Update device level interrupt statistics */
13547 	phba->sli.slistat.sli_intr++;
13548 
13549 	/* Ignore all interrupts during initialization. */
13550 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
13551 		return -EIO;
13552 
13553 	return 0;
13554 }
13555 
13556 /**
13557  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
13558  * @irq: Interrupt number.
13559  * @dev_id: The device context pointer.
13560  *
13561  * This function is directly called from the PCI layer as an interrupt
13562  * service routine when device with SLI-3 interface spec is enabled with
13563  * MSI-X multi-message interrupt mode and there are slow-path events in
13564  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
13565  * interrupt mode, this function is called as part of the device-level
13566  * interrupt handler. When the PCI slot is in error recovery or the HBA
13567  * is undergoing initialization, the interrupt handler will not process
13568  * the interrupt. The link attention and ELS ring attention events are
13569  * handled by the worker thread. The interrupt handler signals the worker
13570  * thread and returns for these events. This function is called without
13571  * any lock held. It gets the hbalock to access and update SLI data
13572  * structures.
13573  *
13574  * This function returns IRQ_HANDLED when interrupt is handled else it
13575  * returns IRQ_NONE.
13576  **/
13577 irqreturn_t
13578 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
13579 {
13580 	struct lpfc_hba  *phba;
13581 	uint32_t ha_copy, hc_copy;
13582 	uint32_t work_ha_copy;
13583 	unsigned long status;
13584 	unsigned long iflag;
13585 	uint32_t control;
13586 
13587 	MAILBOX_t *mbox, *pmbox;
13588 	struct lpfc_vport *vport;
13589 	struct lpfc_nodelist *ndlp;
13590 	struct lpfc_dmabuf *mp;
13591 	LPFC_MBOXQ_t *pmb;
13592 	int rc;
13593 
13594 	/*
13595 	 * Get the driver's phba structure from the dev_id and
13596 	 * assume the HBA is not interrupting.
13597 	 */
13598 	phba = (struct lpfc_hba *)dev_id;
13599 
13600 	if (unlikely(!phba))
13601 		return IRQ_NONE;
13602 
13603 	/*
13604 	 * Stuff needs to be attented to when this function is invoked as an
13605 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13606 	 */
13607 	if (phba->intr_type == MSIX) {
13608 		/* Check device state for handling interrupt */
13609 		if (lpfc_intr_state_check(phba))
13610 			return IRQ_NONE;
13611 		/* Need to read HA REG for slow-path events */
13612 		spin_lock_irqsave(&phba->hbalock, iflag);
13613 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13614 			goto unplug_error;
13615 		/* If somebody is waiting to handle an eratt don't process it
13616 		 * here. The brdkill function will do this.
13617 		 */
13618 		if (phba->link_flag & LS_IGNORE_ERATT)
13619 			ha_copy &= ~HA_ERATT;
13620 		/* Check the need for handling ERATT in interrupt handler */
13621 		if (ha_copy & HA_ERATT) {
13622 			if (phba->hba_flag & HBA_ERATT_HANDLED)
13623 				/* ERATT polling has handled ERATT */
13624 				ha_copy &= ~HA_ERATT;
13625 			else
13626 				/* Indicate interrupt handler handles ERATT */
13627 				phba->hba_flag |= HBA_ERATT_HANDLED;
13628 		}
13629 
13630 		/*
13631 		 * If there is deferred error attention, do not check for any
13632 		 * interrupt.
13633 		 */
13634 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13635 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13636 			return IRQ_NONE;
13637 		}
13638 
13639 		/* Clear up only attention source related to slow-path */
13640 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
13641 			goto unplug_error;
13642 
13643 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
13644 			HC_LAINT_ENA | HC_ERINT_ENA),
13645 			phba->HCregaddr);
13646 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
13647 			phba->HAregaddr);
13648 		writel(hc_copy, phba->HCregaddr);
13649 		readl(phba->HAregaddr); /* flush */
13650 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13651 	} else
13652 		ha_copy = phba->ha_copy;
13653 
13654 	work_ha_copy = ha_copy & phba->work_ha_mask;
13655 
13656 	if (work_ha_copy) {
13657 		if (work_ha_copy & HA_LATT) {
13658 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
13659 				/*
13660 				 * Turn off Link Attention interrupts
13661 				 * until CLEAR_LA done
13662 				 */
13663 				spin_lock_irqsave(&phba->hbalock, iflag);
13664 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
13665 				if (lpfc_readl(phba->HCregaddr, &control))
13666 					goto unplug_error;
13667 				control &= ~HC_LAINT_ENA;
13668 				writel(control, phba->HCregaddr);
13669 				readl(phba->HCregaddr); /* flush */
13670 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13671 			}
13672 			else
13673 				work_ha_copy &= ~HA_LATT;
13674 		}
13675 
13676 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
13677 			/*
13678 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
13679 			 * the only slow ring.
13680 			 */
13681 			status = (work_ha_copy &
13682 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
13683 			status >>= (4*LPFC_ELS_RING);
13684 			if (status & HA_RXMASK) {
13685 				spin_lock_irqsave(&phba->hbalock, iflag);
13686 				if (lpfc_readl(phba->HCregaddr, &control))
13687 					goto unplug_error;
13688 
13689 				lpfc_debugfs_slow_ring_trc(phba,
13690 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
13691 				control, status,
13692 				(uint32_t)phba->sli.slistat.sli_intr);
13693 
13694 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
13695 					lpfc_debugfs_slow_ring_trc(phba,
13696 						"ISR Disable ring:"
13697 						"pwork:x%x hawork:x%x wait:x%x",
13698 						phba->work_ha, work_ha_copy,
13699 						(uint32_t)((unsigned long)
13700 						&phba->work_waitq));
13701 
13702 					control &=
13703 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
13704 					writel(control, phba->HCregaddr);
13705 					readl(phba->HCregaddr); /* flush */
13706 				}
13707 				else {
13708 					lpfc_debugfs_slow_ring_trc(phba,
13709 						"ISR slow ring:   pwork:"
13710 						"x%x hawork:x%x wait:x%x",
13711 						phba->work_ha, work_ha_copy,
13712 						(uint32_t)((unsigned long)
13713 						&phba->work_waitq));
13714 				}
13715 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13716 			}
13717 		}
13718 		spin_lock_irqsave(&phba->hbalock, iflag);
13719 		if (work_ha_copy & HA_ERATT) {
13720 			if (lpfc_sli_read_hs(phba))
13721 				goto unplug_error;
13722 			/*
13723 			 * Check if there is a deferred error condition
13724 			 * is active
13725 			 */
13726 			if ((HS_FFER1 & phba->work_hs) &&
13727 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13728 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
13729 				  phba->work_hs)) {
13730 				phba->hba_flag |= DEFER_ERATT;
13731 				/* Clear all interrupt enable conditions */
13732 				writel(0, phba->HCregaddr);
13733 				readl(phba->HCregaddr);
13734 			}
13735 		}
13736 
13737 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
13738 			pmb = phba->sli.mbox_active;
13739 			pmbox = &pmb->u.mb;
13740 			mbox = phba->mbox;
13741 			vport = pmb->vport;
13742 
13743 			/* First check out the status word */
13744 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
13745 			if (pmbox->mbxOwner != OWN_HOST) {
13746 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13747 				/*
13748 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
13749 				 * mbxStatus <status>
13750 				 */
13751 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13752 						"(%d):0304 Stray Mailbox "
13753 						"Interrupt mbxCommand x%x "
13754 						"mbxStatus x%x\n",
13755 						(vport ? vport->vpi : 0),
13756 						pmbox->mbxCommand,
13757 						pmbox->mbxStatus);
13758 				/* clear mailbox attention bit */
13759 				work_ha_copy &= ~HA_MBATT;
13760 			} else {
13761 				phba->sli.mbox_active = NULL;
13762 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13763 				phba->last_completion_time = jiffies;
13764 				del_timer(&phba->sli.mbox_tmo);
13765 				if (pmb->mbox_cmpl) {
13766 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
13767 							MAILBOX_CMD_SIZE);
13768 					if (pmb->out_ext_byte_len &&
13769 						pmb->ctx_buf)
13770 						lpfc_sli_pcimem_bcopy(
13771 						phba->mbox_ext,
13772 						pmb->ctx_buf,
13773 						pmb->out_ext_byte_len);
13774 				}
13775 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13776 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13777 
13778 					lpfc_debugfs_disc_trc(vport,
13779 						LPFC_DISC_TRC_MBOX_VPORT,
13780 						"MBOX dflt rpi: : "
13781 						"status:x%x rpi:x%x",
13782 						(uint32_t)pmbox->mbxStatus,
13783 						pmbox->un.varWords[0], 0);
13784 
13785 					if (!pmbox->mbxStatus) {
13786 						mp = (struct lpfc_dmabuf *)
13787 							(pmb->ctx_buf);
13788 						ndlp = (struct lpfc_nodelist *)
13789 							pmb->ctx_ndlp;
13790 
13791 						/* Reg_LOGIN of dflt RPI was
13792 						 * successful. new lets get
13793 						 * rid of the RPI using the
13794 						 * same mbox buffer.
13795 						 */
13796 						lpfc_unreg_login(phba,
13797 							vport->vpi,
13798 							pmbox->un.varWords[0],
13799 							pmb);
13800 						pmb->mbox_cmpl =
13801 							lpfc_mbx_cmpl_dflt_rpi;
13802 						pmb->ctx_buf = mp;
13803 						pmb->ctx_ndlp = ndlp;
13804 						pmb->vport = vport;
13805 						rc = lpfc_sli_issue_mbox(phba,
13806 								pmb,
13807 								MBX_NOWAIT);
13808 						if (rc != MBX_BUSY)
13809 							lpfc_printf_log(phba,
13810 							KERN_ERR,
13811 							LOG_TRACE_EVENT,
13812 							"0350 rc should have"
13813 							"been MBX_BUSY\n");
13814 						if (rc != MBX_NOT_FINISHED)
13815 							goto send_current_mbox;
13816 					}
13817 				}
13818 				spin_lock_irqsave(
13819 						&phba->pport->work_port_lock,
13820 						iflag);
13821 				phba->pport->work_port_events &=
13822 					~WORKER_MBOX_TMO;
13823 				spin_unlock_irqrestore(
13824 						&phba->pport->work_port_lock,
13825 						iflag);
13826 
13827 				/* Do NOT queue MBX_HEARTBEAT to the worker
13828 				 * thread for processing.
13829 				 */
13830 				if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13831 					/* Process mbox now */
13832 					phba->sli.mbox_active = NULL;
13833 					phba->sli.sli_flag &=
13834 						~LPFC_SLI_MBOX_ACTIVE;
13835 					if (pmb->mbox_cmpl)
13836 						pmb->mbox_cmpl(phba, pmb);
13837 				} else {
13838 					/* Queue to worker thread to process */
13839 					lpfc_mbox_cmpl_put(phba, pmb);
13840 				}
13841 			}
13842 		} else
13843 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13844 
13845 		if ((work_ha_copy & HA_MBATT) &&
13846 		    (phba->sli.mbox_active == NULL)) {
13847 send_current_mbox:
13848 			/* Process next mailbox command if there is one */
13849 			do {
13850 				rc = lpfc_sli_issue_mbox(phba, NULL,
13851 							 MBX_NOWAIT);
13852 			} while (rc == MBX_NOT_FINISHED);
13853 			if (rc != MBX_SUCCESS)
13854 				lpfc_printf_log(phba, KERN_ERR,
13855 						LOG_TRACE_EVENT,
13856 						"0349 rc should be "
13857 						"MBX_SUCCESS\n");
13858 		}
13859 
13860 		spin_lock_irqsave(&phba->hbalock, iflag);
13861 		phba->work_ha |= work_ha_copy;
13862 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13863 		lpfc_worker_wake_up(phba);
13864 	}
13865 	return IRQ_HANDLED;
13866 unplug_error:
13867 	spin_unlock_irqrestore(&phba->hbalock, iflag);
13868 	return IRQ_HANDLED;
13869 
13870 } /* lpfc_sli_sp_intr_handler */
13871 
13872 /**
13873  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13874  * @irq: Interrupt number.
13875  * @dev_id: The device context pointer.
13876  *
13877  * This function is directly called from the PCI layer as an interrupt
13878  * service routine when device with SLI-3 interface spec is enabled with
13879  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13880  * ring event in the HBA. However, when the device is enabled with either
13881  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13882  * device-level interrupt handler. When the PCI slot is in error recovery
13883  * or the HBA is undergoing initialization, the interrupt handler will not
13884  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13885  * the intrrupt context. This function is called without any lock held.
13886  * It gets the hbalock to access and update SLI data structures.
13887  *
13888  * This function returns IRQ_HANDLED when interrupt is handled else it
13889  * returns IRQ_NONE.
13890  **/
13891 irqreturn_t
13892 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13893 {
13894 	struct lpfc_hba  *phba;
13895 	uint32_t ha_copy;
13896 	unsigned long status;
13897 	unsigned long iflag;
13898 	struct lpfc_sli_ring *pring;
13899 
13900 	/* Get the driver's phba structure from the dev_id and
13901 	 * assume the HBA is not interrupting.
13902 	 */
13903 	phba = (struct lpfc_hba *) dev_id;
13904 
13905 	if (unlikely(!phba))
13906 		return IRQ_NONE;
13907 
13908 	/*
13909 	 * Stuff needs to be attented to when this function is invoked as an
13910 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13911 	 */
13912 	if (phba->intr_type == MSIX) {
13913 		/* Check device state for handling interrupt */
13914 		if (lpfc_intr_state_check(phba))
13915 			return IRQ_NONE;
13916 		/* Need to read HA REG for FCP ring and other ring events */
13917 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13918 			return IRQ_HANDLED;
13919 		/* Clear up only attention source related to fast-path */
13920 		spin_lock_irqsave(&phba->hbalock, iflag);
13921 		/*
13922 		 * If there is deferred error attention, do not check for
13923 		 * any interrupt.
13924 		 */
13925 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13926 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13927 			return IRQ_NONE;
13928 		}
13929 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
13930 			phba->HAregaddr);
13931 		readl(phba->HAregaddr); /* flush */
13932 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13933 	} else
13934 		ha_copy = phba->ha_copy;
13935 
13936 	/*
13937 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
13938 	 */
13939 	ha_copy &= ~(phba->work_ha_mask);
13940 
13941 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13942 	status >>= (4*LPFC_FCP_RING);
13943 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
13944 	if (status & HA_RXMASK)
13945 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
13946 
13947 	if (phba->cfg_multi_ring_support == 2) {
13948 		/*
13949 		 * Process all events on extra ring. Take the optimized path
13950 		 * for extra ring IO.
13951 		 */
13952 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13953 		status >>= (4*LPFC_EXTRA_RING);
13954 		if (status & HA_RXMASK) {
13955 			lpfc_sli_handle_fast_ring_event(phba,
13956 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
13957 					status);
13958 		}
13959 	}
13960 	return IRQ_HANDLED;
13961 }  /* lpfc_sli_fp_intr_handler */
13962 
13963 /**
13964  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
13965  * @irq: Interrupt number.
13966  * @dev_id: The device context pointer.
13967  *
13968  * This function is the HBA device-level interrupt handler to device with
13969  * SLI-3 interface spec, called from the PCI layer when either MSI or
13970  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
13971  * requires driver attention. This function invokes the slow-path interrupt
13972  * attention handling function and fast-path interrupt attention handling
13973  * function in turn to process the relevant HBA attention events. This
13974  * function is called without any lock held. It gets the hbalock to access
13975  * and update SLI data structures.
13976  *
13977  * This function returns IRQ_HANDLED when interrupt is handled, else it
13978  * returns IRQ_NONE.
13979  **/
13980 irqreturn_t
13981 lpfc_sli_intr_handler(int irq, void *dev_id)
13982 {
13983 	struct lpfc_hba  *phba;
13984 	irqreturn_t sp_irq_rc, fp_irq_rc;
13985 	unsigned long status1, status2;
13986 	uint32_t hc_copy;
13987 
13988 	/*
13989 	 * Get the driver's phba structure from the dev_id and
13990 	 * assume the HBA is not interrupting.
13991 	 */
13992 	phba = (struct lpfc_hba *) dev_id;
13993 
13994 	if (unlikely(!phba))
13995 		return IRQ_NONE;
13996 
13997 	/* Check device state for handling interrupt */
13998 	if (lpfc_intr_state_check(phba))
13999 		return IRQ_NONE;
14000 
14001 	spin_lock(&phba->hbalock);
14002 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
14003 		spin_unlock(&phba->hbalock);
14004 		return IRQ_HANDLED;
14005 	}
14006 
14007 	if (unlikely(!phba->ha_copy)) {
14008 		spin_unlock(&phba->hbalock);
14009 		return IRQ_NONE;
14010 	} else if (phba->ha_copy & HA_ERATT) {
14011 		if (phba->hba_flag & HBA_ERATT_HANDLED)
14012 			/* ERATT polling has handled ERATT */
14013 			phba->ha_copy &= ~HA_ERATT;
14014 		else
14015 			/* Indicate interrupt handler handles ERATT */
14016 			phba->hba_flag |= HBA_ERATT_HANDLED;
14017 	}
14018 
14019 	/*
14020 	 * If there is deferred error attention, do not check for any interrupt.
14021 	 */
14022 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
14023 		spin_unlock(&phba->hbalock);
14024 		return IRQ_NONE;
14025 	}
14026 
14027 	/* Clear attention sources except link and error attentions */
14028 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
14029 		spin_unlock(&phba->hbalock);
14030 		return IRQ_HANDLED;
14031 	}
14032 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
14033 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
14034 		phba->HCregaddr);
14035 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
14036 	writel(hc_copy, phba->HCregaddr);
14037 	readl(phba->HAregaddr); /* flush */
14038 	spin_unlock(&phba->hbalock);
14039 
14040 	/*
14041 	 * Invokes slow-path host attention interrupt handling as appropriate.
14042 	 */
14043 
14044 	/* status of events with mailbox and link attention */
14045 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
14046 
14047 	/* status of events with ELS ring */
14048 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
14049 	status2 >>= (4*LPFC_ELS_RING);
14050 
14051 	if (status1 || (status2 & HA_RXMASK))
14052 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
14053 	else
14054 		sp_irq_rc = IRQ_NONE;
14055 
14056 	/*
14057 	 * Invoke fast-path host attention interrupt handling as appropriate.
14058 	 */
14059 
14060 	/* status of events with FCP ring */
14061 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
14062 	status1 >>= (4*LPFC_FCP_RING);
14063 
14064 	/* status of events with extra ring */
14065 	if (phba->cfg_multi_ring_support == 2) {
14066 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14067 		status2 >>= (4*LPFC_EXTRA_RING);
14068 	} else
14069 		status2 = 0;
14070 
14071 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
14072 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
14073 	else
14074 		fp_irq_rc = IRQ_NONE;
14075 
14076 	/* Return device-level interrupt handling status */
14077 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
14078 }  /* lpfc_sli_intr_handler */
14079 
14080 /**
14081  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
14082  * @phba: pointer to lpfc hba data structure.
14083  *
14084  * This routine is invoked by the worker thread to process all the pending
14085  * SLI4 els abort xri events.
14086  **/
14087 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
14088 {
14089 	struct lpfc_cq_event *cq_event;
14090 	unsigned long iflags;
14091 
14092 	/* First, declare the els xri abort event has been handled */
14093 	spin_lock_irqsave(&phba->hbalock, iflags);
14094 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
14095 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14096 
14097 	/* Now, handle all the els xri abort events */
14098 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14099 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
14100 		/* Get the first event from the head of the event queue */
14101 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
14102 				 cq_event, struct lpfc_cq_event, list);
14103 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14104 				       iflags);
14105 		/* Notify aborted XRI for ELS work queue */
14106 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
14107 
14108 		/* Free the event processed back to the free pool */
14109 		lpfc_sli4_cq_event_release(phba, cq_event);
14110 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14111 				  iflags);
14112 	}
14113 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14114 }
14115 
14116 /**
14117  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
14118  * @phba: pointer to lpfc hba data structure
14119  * @pIocbIn: pointer to the rspiocbq
14120  * @pIocbOut: pointer to the cmdiocbq
14121  * @wcqe: pointer to the complete wcqe
14122  *
14123  * This routine transfers the fields of a command iocbq to a response iocbq
14124  * by copying all the IOCB fields from command iocbq and transferring the
14125  * completion status information from the complete wcqe.
14126  **/
14127 static void
14128 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
14129 			      struct lpfc_iocbq *pIocbIn,
14130 			      struct lpfc_iocbq *pIocbOut,
14131 			      struct lpfc_wcqe_complete *wcqe)
14132 {
14133 	int numBdes, i;
14134 	unsigned long iflags;
14135 	uint32_t status, max_response;
14136 	struct lpfc_dmabuf *dmabuf;
14137 	struct ulp_bde64 *bpl, bde;
14138 	size_t offset = offsetof(struct lpfc_iocbq, iocb);
14139 
14140 	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
14141 	       sizeof(struct lpfc_iocbq) - offset);
14142 	/* Map WCQE parameters into irspiocb parameters */
14143 	status = bf_get(lpfc_wcqe_c_status, wcqe);
14144 	pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
14145 	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
14146 		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
14147 			pIocbIn->iocb.un.fcpi.fcpi_parm =
14148 					pIocbOut->iocb.un.fcpi.fcpi_parm -
14149 					wcqe->total_data_placed;
14150 		else
14151 			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
14152 	else {
14153 		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
14154 		switch (pIocbOut->iocb.ulpCommand) {
14155 		case CMD_ELS_REQUEST64_CR:
14156 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
14157 			bpl  = (struct ulp_bde64 *)dmabuf->virt;
14158 			bde.tus.w = le32_to_cpu(bpl[1].tus.w);
14159 			max_response = bde.tus.f.bdeSize;
14160 			break;
14161 		case CMD_GEN_REQUEST64_CR:
14162 			max_response = 0;
14163 			if (!pIocbOut->context3)
14164 				break;
14165 			numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
14166 					sizeof(struct ulp_bde64);
14167 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
14168 			bpl = (struct ulp_bde64 *)dmabuf->virt;
14169 			for (i = 0; i < numBdes; i++) {
14170 				bde.tus.w = le32_to_cpu(bpl[i].tus.w);
14171 				if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
14172 					max_response += bde.tus.f.bdeSize;
14173 			}
14174 			break;
14175 		default:
14176 			max_response = wcqe->total_data_placed;
14177 			break;
14178 		}
14179 		if (max_response < wcqe->total_data_placed)
14180 			pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
14181 		else
14182 			pIocbIn->iocb.un.genreq64.bdl.bdeSize =
14183 				wcqe->total_data_placed;
14184 	}
14185 
14186 	/* Convert BG errors for completion status */
14187 	if (status == CQE_STATUS_DI_ERROR) {
14188 		pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
14189 
14190 		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
14191 			pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
14192 		else
14193 			pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
14194 
14195 		pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
14196 		if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
14197 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
14198 				BGS_GUARD_ERR_MASK;
14199 		if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
14200 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
14201 				BGS_APPTAG_ERR_MASK;
14202 		if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
14203 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
14204 				BGS_REFTAG_ERR_MASK;
14205 
14206 		/* Check to see if there was any good data before the error */
14207 		if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
14208 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
14209 				BGS_HI_WATER_MARK_PRESENT_MASK;
14210 			pIocbIn->iocb.unsli3.sli3_bg.bghm =
14211 				wcqe->total_data_placed;
14212 		}
14213 
14214 		/*
14215 		* Set ALL the error bits to indicate we don't know what
14216 		* type of error it is.
14217 		*/
14218 		if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
14219 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
14220 				(BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
14221 				BGS_GUARD_ERR_MASK);
14222 	}
14223 
14224 	/* Pick up HBA exchange busy condition */
14225 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
14226 		spin_lock_irqsave(&phba->hbalock, iflags);
14227 		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
14228 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14229 	}
14230 }
14231 
14232 /**
14233  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
14234  * @phba: Pointer to HBA context object.
14235  * @irspiocbq: Pointer to work-queue completion queue entry.
14236  *
14237  * This routine handles an ELS work-queue completion event and construct
14238  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
14239  * discovery engine to handle.
14240  *
14241  * Return: Pointer to the receive IOCBQ, NULL otherwise.
14242  **/
14243 static struct lpfc_iocbq *
14244 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
14245 			       struct lpfc_iocbq *irspiocbq)
14246 {
14247 	struct lpfc_sli_ring *pring;
14248 	struct lpfc_iocbq *cmdiocbq;
14249 	struct lpfc_wcqe_complete *wcqe;
14250 	unsigned long iflags;
14251 
14252 	pring = lpfc_phba_elsring(phba);
14253 	if (unlikely(!pring))
14254 		return NULL;
14255 
14256 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
14257 	pring->stats.iocb_event++;
14258 	/* Look up the ELS command IOCB and create pseudo response IOCB */
14259 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14260 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14261 	if (unlikely(!cmdiocbq)) {
14262 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14263 				"0386 ELS complete with no corresponding "
14264 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
14265 				wcqe->word0, wcqe->total_data_placed,
14266 				wcqe->parameter, wcqe->word3);
14267 		lpfc_sli_release_iocbq(phba, irspiocbq);
14268 		return NULL;
14269 	}
14270 
14271 	spin_lock_irqsave(&pring->ring_lock, iflags);
14272 	/* Put the iocb back on the txcmplq */
14273 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
14274 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
14275 
14276 	/* Fake the irspiocbq and copy necessary response information */
14277 	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
14278 
14279 	return irspiocbq;
14280 }
14281 
14282 inline struct lpfc_cq_event *
14283 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
14284 {
14285 	struct lpfc_cq_event *cq_event;
14286 
14287 	/* Allocate a new internal CQ_EVENT entry */
14288 	cq_event = lpfc_sli4_cq_event_alloc(phba);
14289 	if (!cq_event) {
14290 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14291 				"0602 Failed to alloc CQ_EVENT entry\n");
14292 		return NULL;
14293 	}
14294 
14295 	/* Move the CQE into the event */
14296 	memcpy(&cq_event->cqe, entry, size);
14297 	return cq_event;
14298 }
14299 
14300 /**
14301  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
14302  * @phba: Pointer to HBA context object.
14303  * @mcqe: Pointer to mailbox completion queue entry.
14304  *
14305  * This routine process a mailbox completion queue entry with asynchronous
14306  * event.
14307  *
14308  * Return: true if work posted to worker thread, otherwise false.
14309  **/
14310 static bool
14311 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14312 {
14313 	struct lpfc_cq_event *cq_event;
14314 	unsigned long iflags;
14315 
14316 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14317 			"0392 Async Event: word0:x%x, word1:x%x, "
14318 			"word2:x%x, word3:x%x\n", mcqe->word0,
14319 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
14320 
14321 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
14322 	if (!cq_event)
14323 		return false;
14324 
14325 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
14326 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
14327 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
14328 
14329 	/* Set the async event flag */
14330 	spin_lock_irqsave(&phba->hbalock, iflags);
14331 	phba->hba_flag |= ASYNC_EVENT;
14332 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14333 
14334 	return true;
14335 }
14336 
14337 /**
14338  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
14339  * @phba: Pointer to HBA context object.
14340  * @mcqe: Pointer to mailbox completion queue entry.
14341  *
14342  * This routine process a mailbox completion queue entry with mailbox
14343  * completion event.
14344  *
14345  * Return: true if work posted to worker thread, otherwise false.
14346  **/
14347 static bool
14348 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14349 {
14350 	uint32_t mcqe_status;
14351 	MAILBOX_t *mbox, *pmbox;
14352 	struct lpfc_mqe *mqe;
14353 	struct lpfc_vport *vport;
14354 	struct lpfc_nodelist *ndlp;
14355 	struct lpfc_dmabuf *mp;
14356 	unsigned long iflags;
14357 	LPFC_MBOXQ_t *pmb;
14358 	bool workposted = false;
14359 	int rc;
14360 
14361 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
14362 	if (!bf_get(lpfc_trailer_completed, mcqe))
14363 		goto out_no_mqe_complete;
14364 
14365 	/* Get the reference to the active mbox command */
14366 	spin_lock_irqsave(&phba->hbalock, iflags);
14367 	pmb = phba->sli.mbox_active;
14368 	if (unlikely(!pmb)) {
14369 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14370 				"1832 No pending MBOX command to handle\n");
14371 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14372 		goto out_no_mqe_complete;
14373 	}
14374 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14375 	mqe = &pmb->u.mqe;
14376 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
14377 	mbox = phba->mbox;
14378 	vport = pmb->vport;
14379 
14380 	/* Reset heartbeat timer */
14381 	phba->last_completion_time = jiffies;
14382 	del_timer(&phba->sli.mbox_tmo);
14383 
14384 	/* Move mbox data to caller's mailbox region, do endian swapping */
14385 	if (pmb->mbox_cmpl && mbox)
14386 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
14387 
14388 	/*
14389 	 * For mcqe errors, conditionally move a modified error code to
14390 	 * the mbox so that the error will not be missed.
14391 	 */
14392 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
14393 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
14394 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
14395 			bf_set(lpfc_mqe_status, mqe,
14396 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
14397 	}
14398 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
14399 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
14400 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
14401 				      "MBOX dflt rpi: status:x%x rpi:x%x",
14402 				      mcqe_status,
14403 				      pmbox->un.varWords[0], 0);
14404 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
14405 			mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
14406 			ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
14407 
14408 			/* Reg_LOGIN of dflt RPI was successful. Mark the
14409 			 * node as having an UNREG_LOGIN in progress to stop
14410 			 * an unsolicited PLOGI from the same NPortId from
14411 			 * starting another mailbox transaction.
14412 			 */
14413 			spin_lock_irqsave(&ndlp->lock, iflags);
14414 			ndlp->nlp_flag |= NLP_UNREG_INP;
14415 			spin_unlock_irqrestore(&ndlp->lock, iflags);
14416 			lpfc_unreg_login(phba, vport->vpi,
14417 					 pmbox->un.varWords[0], pmb);
14418 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
14419 			pmb->ctx_buf = mp;
14420 
14421 			/* No reference taken here.  This is a default
14422 			 * RPI reg/immediate unreg cycle. The reference was
14423 			 * taken in the reg rpi path and is released when
14424 			 * this mailbox completes.
14425 			 */
14426 			pmb->ctx_ndlp = ndlp;
14427 			pmb->vport = vport;
14428 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
14429 			if (rc != MBX_BUSY)
14430 				lpfc_printf_log(phba, KERN_ERR,
14431 						LOG_TRACE_EVENT,
14432 						"0385 rc should "
14433 						"have been MBX_BUSY\n");
14434 			if (rc != MBX_NOT_FINISHED)
14435 				goto send_current_mbox;
14436 		}
14437 	}
14438 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
14439 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
14440 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
14441 
14442 	/* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
14443 	if (pmbox->mbxCommand == MBX_HEARTBEAT) {
14444 		spin_lock_irqsave(&phba->hbalock, iflags);
14445 		/* Release the mailbox command posting token */
14446 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14447 		phba->sli.mbox_active = NULL;
14448 		if (bf_get(lpfc_trailer_consumed, mcqe))
14449 			lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14450 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14451 
14452 		/* Post the next mbox command, if there is one */
14453 		lpfc_sli4_post_async_mbox(phba);
14454 
14455 		/* Process cmpl now */
14456 		if (pmb->mbox_cmpl)
14457 			pmb->mbox_cmpl(phba, pmb);
14458 		return false;
14459 	}
14460 
14461 	/* There is mailbox completion work to queue to the worker thread */
14462 	spin_lock_irqsave(&phba->hbalock, iflags);
14463 	__lpfc_mbox_cmpl_put(phba, pmb);
14464 	phba->work_ha |= HA_MBATT;
14465 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14466 	workposted = true;
14467 
14468 send_current_mbox:
14469 	spin_lock_irqsave(&phba->hbalock, iflags);
14470 	/* Release the mailbox command posting token */
14471 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14472 	/* Setting active mailbox pointer need to be in sync to flag clear */
14473 	phba->sli.mbox_active = NULL;
14474 	if (bf_get(lpfc_trailer_consumed, mcqe))
14475 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14476 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14477 	/* Wake up worker thread to post the next pending mailbox command */
14478 	lpfc_worker_wake_up(phba);
14479 	return workposted;
14480 
14481 out_no_mqe_complete:
14482 	spin_lock_irqsave(&phba->hbalock, iflags);
14483 	if (bf_get(lpfc_trailer_consumed, mcqe))
14484 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14485 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14486 	return false;
14487 }
14488 
14489 /**
14490  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
14491  * @phba: Pointer to HBA context object.
14492  * @cq: Pointer to associated CQ
14493  * @cqe: Pointer to mailbox completion queue entry.
14494  *
14495  * This routine process a mailbox completion queue entry, it invokes the
14496  * proper mailbox complete handling or asynchronous event handling routine
14497  * according to the MCQE's async bit.
14498  *
14499  * Return: true if work posted to worker thread, otherwise false.
14500  **/
14501 static bool
14502 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14503 			 struct lpfc_cqe *cqe)
14504 {
14505 	struct lpfc_mcqe mcqe;
14506 	bool workposted;
14507 
14508 	cq->CQ_mbox++;
14509 
14510 	/* Copy the mailbox MCQE and convert endian order as needed */
14511 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
14512 
14513 	/* Invoke the proper event handling routine */
14514 	if (!bf_get(lpfc_trailer_async, &mcqe))
14515 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
14516 	else
14517 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
14518 	return workposted;
14519 }
14520 
14521 /**
14522  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
14523  * @phba: Pointer to HBA context object.
14524  * @cq: Pointer to associated CQ
14525  * @wcqe: Pointer to work-queue completion queue entry.
14526  *
14527  * This routine handles an ELS work-queue completion event.
14528  *
14529  * Return: true if work posted to worker thread, otherwise false.
14530  **/
14531 static bool
14532 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14533 			     struct lpfc_wcqe_complete *wcqe)
14534 {
14535 	struct lpfc_iocbq *irspiocbq;
14536 	unsigned long iflags;
14537 	struct lpfc_sli_ring *pring = cq->pring;
14538 	int txq_cnt = 0;
14539 	int txcmplq_cnt = 0;
14540 
14541 	/* Check for response status */
14542 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14543 		/* Log the error status */
14544 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14545 				"0357 ELS CQE error: status=x%x: "
14546 				"CQE: %08x %08x %08x %08x\n",
14547 				bf_get(lpfc_wcqe_c_status, wcqe),
14548 				wcqe->word0, wcqe->total_data_placed,
14549 				wcqe->parameter, wcqe->word3);
14550 	}
14551 
14552 	/* Get an irspiocbq for later ELS response processing use */
14553 	irspiocbq = lpfc_sli_get_iocbq(phba);
14554 	if (!irspiocbq) {
14555 		if (!list_empty(&pring->txq))
14556 			txq_cnt++;
14557 		if (!list_empty(&pring->txcmplq))
14558 			txcmplq_cnt++;
14559 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14560 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
14561 			"els_txcmplq_cnt=%d\n",
14562 			txq_cnt, phba->iocb_cnt,
14563 			txcmplq_cnt);
14564 		return false;
14565 	}
14566 
14567 	/* Save off the slow-path queue event for work thread to process */
14568 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
14569 	spin_lock_irqsave(&phba->hbalock, iflags);
14570 	list_add_tail(&irspiocbq->cq_event.list,
14571 		      &phba->sli4_hba.sp_queue_event);
14572 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
14573 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14574 
14575 	return true;
14576 }
14577 
14578 /**
14579  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
14580  * @phba: Pointer to HBA context object.
14581  * @wcqe: Pointer to work-queue completion queue entry.
14582  *
14583  * This routine handles slow-path WQ entry consumed event by invoking the
14584  * proper WQ release routine to the slow-path WQ.
14585  **/
14586 static void
14587 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
14588 			     struct lpfc_wcqe_release *wcqe)
14589 {
14590 	/* sanity check on queue memory */
14591 	if (unlikely(!phba->sli4_hba.els_wq))
14592 		return;
14593 	/* Check for the slow-path ELS work queue */
14594 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
14595 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
14596 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14597 	else
14598 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14599 				"2579 Slow-path wqe consume event carries "
14600 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
14601 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
14602 				phba->sli4_hba.els_wq->queue_id);
14603 }
14604 
14605 /**
14606  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
14607  * @phba: Pointer to HBA context object.
14608  * @cq: Pointer to a WQ completion queue.
14609  * @wcqe: Pointer to work-queue completion queue entry.
14610  *
14611  * This routine handles an XRI abort event.
14612  *
14613  * Return: true if work posted to worker thread, otherwise false.
14614  **/
14615 static bool
14616 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
14617 				   struct lpfc_queue *cq,
14618 				   struct sli4_wcqe_xri_aborted *wcqe)
14619 {
14620 	bool workposted = false;
14621 	struct lpfc_cq_event *cq_event;
14622 	unsigned long iflags;
14623 
14624 	switch (cq->subtype) {
14625 	case LPFC_IO:
14626 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
14627 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14628 			/* Notify aborted XRI for NVME work queue */
14629 			if (phba->nvmet_support)
14630 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
14631 		}
14632 		workposted = false;
14633 		break;
14634 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
14635 	case LPFC_ELS:
14636 		cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
14637 		if (!cq_event) {
14638 			workposted = false;
14639 			break;
14640 		}
14641 		cq_event->hdwq = cq->hdwq;
14642 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14643 				  iflags);
14644 		list_add_tail(&cq_event->list,
14645 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
14646 		/* Set the els xri abort event flag */
14647 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
14648 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14649 				       iflags);
14650 		workposted = true;
14651 		break;
14652 	default:
14653 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14654 				"0603 Invalid CQ subtype %d: "
14655 				"%08x %08x %08x %08x\n",
14656 				cq->subtype, wcqe->word0, wcqe->parameter,
14657 				wcqe->word2, wcqe->word3);
14658 		workposted = false;
14659 		break;
14660 	}
14661 	return workposted;
14662 }
14663 
14664 #define FC_RCTL_MDS_DIAGS	0xF4
14665 
14666 /**
14667  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
14668  * @phba: Pointer to HBA context object.
14669  * @rcqe: Pointer to receive-queue completion queue entry.
14670  *
14671  * This routine process a receive-queue completion queue entry.
14672  *
14673  * Return: true if work posted to worker thread, otherwise false.
14674  **/
14675 static bool
14676 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
14677 {
14678 	bool workposted = false;
14679 	struct fc_frame_header *fc_hdr;
14680 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
14681 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
14682 	struct lpfc_nvmet_tgtport *tgtp;
14683 	struct hbq_dmabuf *dma_buf;
14684 	uint32_t status, rq_id;
14685 	unsigned long iflags;
14686 
14687 	/* sanity check on queue memory */
14688 	if (unlikely(!hrq) || unlikely(!drq))
14689 		return workposted;
14690 
14691 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14692 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14693 	else
14694 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14695 	if (rq_id != hrq->queue_id)
14696 		goto out;
14697 
14698 	status = bf_get(lpfc_rcqe_status, rcqe);
14699 	switch (status) {
14700 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14701 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14702 				"2537 Receive Frame Truncated!!\n");
14703 		fallthrough;
14704 	case FC_STATUS_RQ_SUCCESS:
14705 		spin_lock_irqsave(&phba->hbalock, iflags);
14706 		lpfc_sli4_rq_release(hrq, drq);
14707 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14708 		if (!dma_buf) {
14709 			hrq->RQ_no_buf_found++;
14710 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14711 			goto out;
14712 		}
14713 		hrq->RQ_rcv_buf++;
14714 		hrq->RQ_buf_posted--;
14715 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
14716 
14717 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14718 
14719 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
14720 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
14721 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14722 			/* Handle MDS Loopback frames */
14723 			if  (!(phba->pport->load_flag & FC_UNLOADING))
14724 				lpfc_sli4_handle_mds_loopback(phba->pport,
14725 							      dma_buf);
14726 			else
14727 				lpfc_in_buf_free(phba, &dma_buf->dbuf);
14728 			break;
14729 		}
14730 
14731 		/* save off the frame for the work thread to process */
14732 		list_add_tail(&dma_buf->cq_event.list,
14733 			      &phba->sli4_hba.sp_queue_event);
14734 		/* Frame received */
14735 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
14736 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14737 		workposted = true;
14738 		break;
14739 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14740 		if (phba->nvmet_support) {
14741 			tgtp = phba->targetport->private;
14742 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14743 					"6402 RQE Error x%x, posted %d err_cnt "
14744 					"%d: %x %x %x\n",
14745 					status, hrq->RQ_buf_posted,
14746 					hrq->RQ_no_posted_buf,
14747 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14748 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14749 					atomic_read(&tgtp->xmt_fcp_release));
14750 		}
14751 		fallthrough;
14752 
14753 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14754 		hrq->RQ_no_posted_buf++;
14755 		/* Post more buffers if possible */
14756 		spin_lock_irqsave(&phba->hbalock, iflags);
14757 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
14758 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14759 		workposted = true;
14760 		break;
14761 	}
14762 out:
14763 	return workposted;
14764 }
14765 
14766 /**
14767  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
14768  * @phba: Pointer to HBA context object.
14769  * @cq: Pointer to the completion queue.
14770  * @cqe: Pointer to a completion queue entry.
14771  *
14772  * This routine process a slow-path work-queue or receive queue completion queue
14773  * entry.
14774  *
14775  * Return: true if work posted to worker thread, otherwise false.
14776  **/
14777 static bool
14778 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14779 			 struct lpfc_cqe *cqe)
14780 {
14781 	struct lpfc_cqe cqevt;
14782 	bool workposted = false;
14783 
14784 	/* Copy the work queue CQE and convert endian order if needed */
14785 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14786 
14787 	/* Check and process for different type of WCQE and dispatch */
14788 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
14789 	case CQE_CODE_COMPL_WQE:
14790 		/* Process the WQ/RQ complete event */
14791 		phba->last_completion_time = jiffies;
14792 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14793 				(struct lpfc_wcqe_complete *)&cqevt);
14794 		break;
14795 	case CQE_CODE_RELEASE_WQE:
14796 		/* Process the WQ release event */
14797 		lpfc_sli4_sp_handle_rel_wcqe(phba,
14798 				(struct lpfc_wcqe_release *)&cqevt);
14799 		break;
14800 	case CQE_CODE_XRI_ABORTED:
14801 		/* Process the WQ XRI abort event */
14802 		phba->last_completion_time = jiffies;
14803 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14804 				(struct sli4_wcqe_xri_aborted *)&cqevt);
14805 		break;
14806 	case CQE_CODE_RECEIVE:
14807 	case CQE_CODE_RECEIVE_V1:
14808 		/* Process the RQ event */
14809 		phba->last_completion_time = jiffies;
14810 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
14811 				(struct lpfc_rcqe *)&cqevt);
14812 		break;
14813 	default:
14814 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14815 				"0388 Not a valid WCQE code: x%x\n",
14816 				bf_get(lpfc_cqe_code, &cqevt));
14817 		break;
14818 	}
14819 	return workposted;
14820 }
14821 
14822 /**
14823  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14824  * @phba: Pointer to HBA context object.
14825  * @eqe: Pointer to fast-path event queue entry.
14826  * @speq: Pointer to slow-path event queue.
14827  *
14828  * This routine process a event queue entry from the slow-path event queue.
14829  * It will check the MajorCode and MinorCode to determine this is for a
14830  * completion event on a completion queue, if not, an error shall be logged
14831  * and just return. Otherwise, it will get to the corresponding completion
14832  * queue and process all the entries on that completion queue, rearm the
14833  * completion queue, and then return.
14834  *
14835  **/
14836 static void
14837 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14838 	struct lpfc_queue *speq)
14839 {
14840 	struct lpfc_queue *cq = NULL, *childq;
14841 	uint16_t cqid;
14842 	int ret = 0;
14843 
14844 	/* Get the reference to the corresponding CQ */
14845 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14846 
14847 	list_for_each_entry(childq, &speq->child_list, list) {
14848 		if (childq->queue_id == cqid) {
14849 			cq = childq;
14850 			break;
14851 		}
14852 	}
14853 	if (unlikely(!cq)) {
14854 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14855 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14856 					"0365 Slow-path CQ identifier "
14857 					"(%d) does not exist\n", cqid);
14858 		return;
14859 	}
14860 
14861 	/* Save EQ associated with this CQ */
14862 	cq->assoc_qp = speq;
14863 
14864 	if (is_kdump_kernel())
14865 		ret = queue_work(phba->wq, &cq->spwork);
14866 	else
14867 		ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14868 
14869 	if (!ret)
14870 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14871 				"0390 Cannot schedule queue work "
14872 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14873 				cqid, cq->queue_id, raw_smp_processor_id());
14874 }
14875 
14876 /**
14877  * __lpfc_sli4_process_cq - Process elements of a CQ
14878  * @phba: Pointer to HBA context object.
14879  * @cq: Pointer to CQ to be processed
14880  * @handler: Routine to process each cqe
14881  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14882  * @poll_mode: Polling mode we were called from
14883  *
14884  * This routine processes completion queue entries in a CQ. While a valid
14885  * queue element is found, the handler is called. During processing checks
14886  * are made for periodic doorbell writes to let the hardware know of
14887  * element consumption.
14888  *
14889  * If the max limit on cqes to process is hit, or there are no more valid
14890  * entries, the loop stops. If we processed a sufficient number of elements,
14891  * meaning there is sufficient load, rather than rearming and generating
14892  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14893  * indicates no rescheduling.
14894  *
14895  * Returns True if work scheduled, False otherwise.
14896  **/
14897 static bool
14898 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14899 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14900 			struct lpfc_cqe *), unsigned long *delay,
14901 			enum lpfc_poll_mode poll_mode)
14902 {
14903 	struct lpfc_cqe *cqe;
14904 	bool workposted = false;
14905 	int count = 0, consumed = 0;
14906 	bool arm = true;
14907 
14908 	/* default - no reschedule */
14909 	*delay = 0;
14910 
14911 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14912 		goto rearm_and_exit;
14913 
14914 	/* Process all the entries to the CQ */
14915 	cq->q_flag = 0;
14916 	cqe = lpfc_sli4_cq_get(cq);
14917 	while (cqe) {
14918 		workposted |= handler(phba, cq, cqe);
14919 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
14920 
14921 		consumed++;
14922 		if (!(++count % cq->max_proc_limit))
14923 			break;
14924 
14925 		if (!(count % cq->notify_interval)) {
14926 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14927 						LPFC_QUEUE_NOARM);
14928 			consumed = 0;
14929 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14930 		}
14931 
14932 		if (count == LPFC_NVMET_CQ_NOTIFY)
14933 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14934 
14935 		cqe = lpfc_sli4_cq_get(cq);
14936 	}
14937 	if (count >= phba->cfg_cq_poll_threshold) {
14938 		*delay = 1;
14939 		arm = false;
14940 	}
14941 
14942 	/* Note: complete the irq_poll softirq before rearming CQ */
14943 	if (poll_mode == LPFC_IRQ_POLL)
14944 		irq_poll_complete(&cq->iop);
14945 
14946 	/* Track the max number of CQEs processed in 1 EQ */
14947 	if (count > cq->CQ_max_cqe)
14948 		cq->CQ_max_cqe = count;
14949 
14950 	cq->assoc_qp->EQ_cqe_cnt += count;
14951 
14952 	/* Catch the no cq entry condition */
14953 	if (unlikely(count == 0))
14954 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14955 				"0369 No entry from completion queue "
14956 				"qid=%d\n", cq->queue_id);
14957 
14958 	xchg(&cq->queue_claimed, 0);
14959 
14960 rearm_and_exit:
14961 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14962 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14963 
14964 	return workposted;
14965 }
14966 
14967 /**
14968  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14969  * @cq: pointer to CQ to process
14970  *
14971  * This routine calls the cq processing routine with a handler specific
14972  * to the type of queue bound to it.
14973  *
14974  * The CQ routine returns two values: the first is the calling status,
14975  * which indicates whether work was queued to the  background discovery
14976  * thread. If true, the routine should wakeup the discovery thread;
14977  * the second is the delay parameter. If non-zero, rather than rearming
14978  * the CQ and yet another interrupt, the CQ handler should be queued so
14979  * that it is processed in a subsequent polling action. The value of
14980  * the delay indicates when to reschedule it.
14981  **/
14982 static void
14983 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14984 {
14985 	struct lpfc_hba *phba = cq->phba;
14986 	unsigned long delay;
14987 	bool workposted = false;
14988 	int ret = 0;
14989 
14990 	/* Process and rearm the CQ */
14991 	switch (cq->type) {
14992 	case LPFC_MCQ:
14993 		workposted |= __lpfc_sli4_process_cq(phba, cq,
14994 						lpfc_sli4_sp_handle_mcqe,
14995 						&delay, LPFC_QUEUE_WORK);
14996 		break;
14997 	case LPFC_WCQ:
14998 		if (cq->subtype == LPFC_IO)
14999 			workposted |= __lpfc_sli4_process_cq(phba, cq,
15000 						lpfc_sli4_fp_handle_cqe,
15001 						&delay, LPFC_QUEUE_WORK);
15002 		else
15003 			workposted |= __lpfc_sli4_process_cq(phba, cq,
15004 						lpfc_sli4_sp_handle_cqe,
15005 						&delay, LPFC_QUEUE_WORK);
15006 		break;
15007 	default:
15008 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15009 				"0370 Invalid completion queue type (%d)\n",
15010 				cq->type);
15011 		return;
15012 	}
15013 
15014 	if (delay) {
15015 		if (is_kdump_kernel())
15016 			ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
15017 						delay);
15018 		else
15019 			ret = queue_delayed_work_on(cq->chann, phba->wq,
15020 						&cq->sched_spwork, delay);
15021 		if (!ret)
15022 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15023 				"0394 Cannot schedule queue work "
15024 				"for cqid=%d on CPU %d\n",
15025 				cq->queue_id, cq->chann);
15026 	}
15027 
15028 	/* wake up worker thread if there are works to be done */
15029 	if (workposted)
15030 		lpfc_worker_wake_up(phba);
15031 }
15032 
15033 /**
15034  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
15035  *   interrupt
15036  * @work: pointer to work element
15037  *
15038  * translates from the work handler and calls the slow-path handler.
15039  **/
15040 static void
15041 lpfc_sli4_sp_process_cq(struct work_struct *work)
15042 {
15043 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
15044 
15045 	__lpfc_sli4_sp_process_cq(cq);
15046 }
15047 
15048 /**
15049  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
15050  * @work: pointer to work element
15051  *
15052  * translates from the work handler and calls the slow-path handler.
15053  **/
15054 static void
15055 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
15056 {
15057 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15058 					struct lpfc_queue, sched_spwork);
15059 
15060 	__lpfc_sli4_sp_process_cq(cq);
15061 }
15062 
15063 /**
15064  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
15065  * @phba: Pointer to HBA context object.
15066  * @cq: Pointer to associated CQ
15067  * @wcqe: Pointer to work-queue completion queue entry.
15068  *
15069  * This routine process a fast-path work queue completion entry from fast-path
15070  * event queue for FCP command response completion.
15071  **/
15072 static void
15073 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15074 			     struct lpfc_wcqe_complete *wcqe)
15075 {
15076 	struct lpfc_sli_ring *pring = cq->pring;
15077 	struct lpfc_iocbq *cmdiocbq;
15078 	struct lpfc_iocbq irspiocbq;
15079 	unsigned long iflags;
15080 
15081 	/* Check for response status */
15082 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
15083 		/* If resource errors reported from HBA, reduce queue
15084 		 * depth of the SCSI device.
15085 		 */
15086 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
15087 		     IOSTAT_LOCAL_REJECT)) &&
15088 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
15089 		     IOERR_NO_RESOURCES))
15090 			phba->lpfc_rampdown_queue_depth(phba);
15091 
15092 		/* Log the cmpl status */
15093 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15094 				"0373 FCP CQE cmpl: status=x%x: "
15095 				"CQE: %08x %08x %08x %08x\n",
15096 				bf_get(lpfc_wcqe_c_status, wcqe),
15097 				wcqe->word0, wcqe->total_data_placed,
15098 				wcqe->parameter, wcqe->word3);
15099 	}
15100 
15101 	/* Look up the FCP command IOCB and create pseudo response IOCB */
15102 	spin_lock_irqsave(&pring->ring_lock, iflags);
15103 	pring->stats.iocb_event++;
15104 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
15105 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
15106 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15107 	if (unlikely(!cmdiocbq)) {
15108 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15109 				"0374 FCP complete with no corresponding "
15110 				"cmdiocb: iotag (%d)\n",
15111 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15112 		return;
15113 	}
15114 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
15115 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
15116 #endif
15117 	if (cmdiocbq->iocb_cmpl == NULL) {
15118 		if (cmdiocbq->wqe_cmpl) {
15119 			/* For FCP the flag is cleared in wqe_cmpl */
15120 			if (!(cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
15121 			    cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
15122 				spin_lock_irqsave(&phba->hbalock, iflags);
15123 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
15124 				spin_unlock_irqrestore(&phba->hbalock, iflags);
15125 			}
15126 
15127 			/* Pass the cmd_iocb and the wcqe to the upper layer */
15128 			(cmdiocbq->wqe_cmpl)(phba, cmdiocbq, wcqe);
15129 			return;
15130 		}
15131 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15132 				"0375 FCP cmdiocb not callback function "
15133 				"iotag: (%d)\n",
15134 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15135 		return;
15136 	}
15137 
15138 	/* Only SLI4 non-IO commands stil use IOCB */
15139 	/* Fake the irspiocb and copy necessary response information */
15140 	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
15141 
15142 	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
15143 		spin_lock_irqsave(&phba->hbalock, iflags);
15144 		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
15145 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15146 	}
15147 
15148 	/* Pass the cmd_iocb and the rsp state to the upper layer */
15149 	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
15150 }
15151 
15152 /**
15153  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
15154  * @phba: Pointer to HBA context object.
15155  * @cq: Pointer to completion queue.
15156  * @wcqe: Pointer to work-queue completion queue entry.
15157  *
15158  * This routine handles an fast-path WQ entry consumed event by invoking the
15159  * proper WQ release routine to the slow-path WQ.
15160  **/
15161 static void
15162 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15163 			     struct lpfc_wcqe_release *wcqe)
15164 {
15165 	struct lpfc_queue *childwq;
15166 	bool wqid_matched = false;
15167 	uint16_t hba_wqid;
15168 
15169 	/* Check for fast-path FCP work queue release */
15170 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
15171 	list_for_each_entry(childwq, &cq->child_list, list) {
15172 		if (childwq->queue_id == hba_wqid) {
15173 			lpfc_sli4_wq_release(childwq,
15174 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
15175 			if (childwq->q_flag & HBA_NVMET_WQFULL)
15176 				lpfc_nvmet_wqfull_process(phba, childwq);
15177 			wqid_matched = true;
15178 			break;
15179 		}
15180 	}
15181 	/* Report warning log message if no match found */
15182 	if (wqid_matched != true)
15183 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15184 				"2580 Fast-path wqe consume event carries "
15185 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
15186 }
15187 
15188 /**
15189  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
15190  * @phba: Pointer to HBA context object.
15191  * @cq: Pointer to completion queue.
15192  * @rcqe: Pointer to receive-queue completion queue entry.
15193  *
15194  * This routine process a receive-queue completion queue entry.
15195  *
15196  * Return: true if work posted to worker thread, otherwise false.
15197  **/
15198 static bool
15199 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15200 			    struct lpfc_rcqe *rcqe)
15201 {
15202 	bool workposted = false;
15203 	struct lpfc_queue *hrq;
15204 	struct lpfc_queue *drq;
15205 	struct rqb_dmabuf *dma_buf;
15206 	struct fc_frame_header *fc_hdr;
15207 	struct lpfc_nvmet_tgtport *tgtp;
15208 	uint32_t status, rq_id;
15209 	unsigned long iflags;
15210 	uint32_t fctl, idx;
15211 
15212 	if ((phba->nvmet_support == 0) ||
15213 	    (phba->sli4_hba.nvmet_cqset == NULL))
15214 		return workposted;
15215 
15216 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
15217 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
15218 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
15219 
15220 	/* sanity check on queue memory */
15221 	if (unlikely(!hrq) || unlikely(!drq))
15222 		return workposted;
15223 
15224 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
15225 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
15226 	else
15227 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
15228 
15229 	if ((phba->nvmet_support == 0) ||
15230 	    (rq_id != hrq->queue_id))
15231 		return workposted;
15232 
15233 	status = bf_get(lpfc_rcqe_status, rcqe);
15234 	switch (status) {
15235 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
15236 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15237 				"6126 Receive Frame Truncated!!\n");
15238 		fallthrough;
15239 	case FC_STATUS_RQ_SUCCESS:
15240 		spin_lock_irqsave(&phba->hbalock, iflags);
15241 		lpfc_sli4_rq_release(hrq, drq);
15242 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15243 		if (!dma_buf) {
15244 			hrq->RQ_no_buf_found++;
15245 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15246 			goto out;
15247 		}
15248 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15249 		hrq->RQ_rcv_buf++;
15250 		hrq->RQ_buf_posted--;
15251 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
15252 
15253 		/* Just some basic sanity checks on FCP Command frame */
15254 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
15255 			fc_hdr->fh_f_ctl[1] << 8 |
15256 			fc_hdr->fh_f_ctl[2]);
15257 		if (((fctl &
15258 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
15259 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
15260 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
15261 			goto drop;
15262 
15263 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
15264 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
15265 			lpfc_nvmet_unsol_fcp_event(
15266 				phba, idx, dma_buf, cq->isr_timestamp,
15267 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
15268 			return false;
15269 		}
15270 drop:
15271 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15272 		break;
15273 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
15274 		if (phba->nvmet_support) {
15275 			tgtp = phba->targetport->private;
15276 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15277 					"6401 RQE Error x%x, posted %d err_cnt "
15278 					"%d: %x %x %x\n",
15279 					status, hrq->RQ_buf_posted,
15280 					hrq->RQ_no_posted_buf,
15281 					atomic_read(&tgtp->rcv_fcp_cmd_in),
15282 					atomic_read(&tgtp->rcv_fcp_cmd_out),
15283 					atomic_read(&tgtp->xmt_fcp_release));
15284 		}
15285 		fallthrough;
15286 
15287 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
15288 		hrq->RQ_no_posted_buf++;
15289 		/* Post more buffers if possible */
15290 		break;
15291 	}
15292 out:
15293 	return workposted;
15294 }
15295 
15296 /**
15297  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
15298  * @phba: adapter with cq
15299  * @cq: Pointer to the completion queue.
15300  * @cqe: Pointer to fast-path completion queue entry.
15301  *
15302  * This routine process a fast-path work queue completion entry from fast-path
15303  * event queue for FCP command response completion.
15304  *
15305  * Return: true if work posted to worker thread, otherwise false.
15306  **/
15307 static bool
15308 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15309 			 struct lpfc_cqe *cqe)
15310 {
15311 	struct lpfc_wcqe_release wcqe;
15312 	bool workposted = false;
15313 
15314 	/* Copy the work queue CQE and convert endian order if needed */
15315 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
15316 
15317 	/* Check and process for different type of WCQE and dispatch */
15318 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
15319 	case CQE_CODE_COMPL_WQE:
15320 	case CQE_CODE_NVME_ERSP:
15321 		cq->CQ_wq++;
15322 		/* Process the WQ complete event */
15323 		phba->last_completion_time = jiffies;
15324 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
15325 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
15326 				(struct lpfc_wcqe_complete *)&wcqe);
15327 		break;
15328 	case CQE_CODE_RELEASE_WQE:
15329 		cq->CQ_release_wqe++;
15330 		/* Process the WQ release event */
15331 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
15332 				(struct lpfc_wcqe_release *)&wcqe);
15333 		break;
15334 	case CQE_CODE_XRI_ABORTED:
15335 		cq->CQ_xri_aborted++;
15336 		/* Process the WQ XRI abort event */
15337 		phba->last_completion_time = jiffies;
15338 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
15339 				(struct sli4_wcqe_xri_aborted *)&wcqe);
15340 		break;
15341 	case CQE_CODE_RECEIVE_V1:
15342 	case CQE_CODE_RECEIVE:
15343 		phba->last_completion_time = jiffies;
15344 		if (cq->subtype == LPFC_NVMET) {
15345 			workposted = lpfc_sli4_nvmet_handle_rcqe(
15346 				phba, cq, (struct lpfc_rcqe *)&wcqe);
15347 		}
15348 		break;
15349 	default:
15350 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15351 				"0144 Not a valid CQE code: x%x\n",
15352 				bf_get(lpfc_wcqe_c_code, &wcqe));
15353 		break;
15354 	}
15355 	return workposted;
15356 }
15357 
15358 /**
15359  * lpfc_sli4_sched_cq_work - Schedules cq work
15360  * @phba: Pointer to HBA context object.
15361  * @cq: Pointer to CQ
15362  * @cqid: CQ ID
15363  *
15364  * This routine checks the poll mode of the CQ corresponding to
15365  * cq->chann, then either schedules a softirq or queue_work to complete
15366  * cq work.
15367  *
15368  * queue_work path is taken if in NVMET mode, or if poll_mode is in
15369  * LPFC_QUEUE_WORK mode.  Otherwise, softirq path is taken.
15370  *
15371  **/
15372 static void lpfc_sli4_sched_cq_work(struct lpfc_hba *phba,
15373 				    struct lpfc_queue *cq, uint16_t cqid)
15374 {
15375 	int ret = 0;
15376 
15377 	switch (cq->poll_mode) {
15378 	case LPFC_IRQ_POLL:
15379 		/* CGN mgmt is mutually exclusive from softirq processing */
15380 		if (phba->cmf_active_mode == LPFC_CFG_OFF) {
15381 			irq_poll_sched(&cq->iop);
15382 			break;
15383 		}
15384 		fallthrough;
15385 	case LPFC_QUEUE_WORK:
15386 	default:
15387 		if (is_kdump_kernel())
15388 			ret = queue_work(phba->wq, &cq->irqwork);
15389 		else
15390 			ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
15391 		if (!ret)
15392 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15393 					"0383 Cannot schedule queue work "
15394 					"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
15395 					cqid, cq->queue_id,
15396 					raw_smp_processor_id());
15397 	}
15398 }
15399 
15400 /**
15401  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
15402  * @phba: Pointer to HBA context object.
15403  * @eq: Pointer to the queue structure.
15404  * @eqe: Pointer to fast-path event queue entry.
15405  *
15406  * This routine process a event queue entry from the fast-path event queue.
15407  * It will check the MajorCode and MinorCode to determine this is for a
15408  * completion event on a completion queue, if not, an error shall be logged
15409  * and just return. Otherwise, it will get to the corresponding completion
15410  * queue and process all the entries on the completion queue, rearm the
15411  * completion queue, and then return.
15412  **/
15413 static void
15414 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
15415 			 struct lpfc_eqe *eqe)
15416 {
15417 	struct lpfc_queue *cq = NULL;
15418 	uint32_t qidx = eq->hdwq;
15419 	uint16_t cqid, id;
15420 
15421 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
15422 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15423 				"0366 Not a valid completion "
15424 				"event: majorcode=x%x, minorcode=x%x\n",
15425 				bf_get_le32(lpfc_eqe_major_code, eqe),
15426 				bf_get_le32(lpfc_eqe_minor_code, eqe));
15427 		return;
15428 	}
15429 
15430 	/* Get the reference to the corresponding CQ */
15431 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
15432 
15433 	/* Use the fast lookup method first */
15434 	if (cqid <= phba->sli4_hba.cq_max) {
15435 		cq = phba->sli4_hba.cq_lookup[cqid];
15436 		if (cq)
15437 			goto  work_cq;
15438 	}
15439 
15440 	/* Next check for NVMET completion */
15441 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
15442 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
15443 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
15444 			/* Process NVMET unsol rcv */
15445 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
15446 			goto  process_cq;
15447 		}
15448 	}
15449 
15450 	if (phba->sli4_hba.nvmels_cq &&
15451 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
15452 		/* Process NVME unsol rcv */
15453 		cq = phba->sli4_hba.nvmels_cq;
15454 	}
15455 
15456 	/* Otherwise this is a Slow path event */
15457 	if (cq == NULL) {
15458 		lpfc_sli4_sp_handle_eqe(phba, eqe,
15459 					phba->sli4_hba.hdwq[qidx].hba_eq);
15460 		return;
15461 	}
15462 
15463 process_cq:
15464 	if (unlikely(cqid != cq->queue_id)) {
15465 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15466 				"0368 Miss-matched fast-path completion "
15467 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
15468 				cqid, cq->queue_id);
15469 		return;
15470 	}
15471 
15472 work_cq:
15473 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
15474 	if (phba->ktime_on)
15475 		cq->isr_timestamp = ktime_get_ns();
15476 	else
15477 		cq->isr_timestamp = 0;
15478 #endif
15479 	lpfc_sli4_sched_cq_work(phba, cq, cqid);
15480 }
15481 
15482 /**
15483  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
15484  * @cq: Pointer to CQ to be processed
15485  * @poll_mode: Enum lpfc_poll_state to determine poll mode
15486  *
15487  * This routine calls the cq processing routine with the handler for
15488  * fast path CQEs.
15489  *
15490  * The CQ routine returns two values: the first is the calling status,
15491  * which indicates whether work was queued to the  background discovery
15492  * thread. If true, the routine should wakeup the discovery thread;
15493  * the second is the delay parameter. If non-zero, rather than rearming
15494  * the CQ and yet another interrupt, the CQ handler should be queued so
15495  * that it is processed in a subsequent polling action. The value of
15496  * the delay indicates when to reschedule it.
15497  **/
15498 static void
15499 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq,
15500 			   enum lpfc_poll_mode poll_mode)
15501 {
15502 	struct lpfc_hba *phba = cq->phba;
15503 	unsigned long delay;
15504 	bool workposted = false;
15505 	int ret = 0;
15506 
15507 	/* process and rearm the CQ */
15508 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
15509 					     &delay, poll_mode);
15510 
15511 	if (delay) {
15512 		if (is_kdump_kernel())
15513 			ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
15514 						delay);
15515 		else
15516 			ret = queue_delayed_work_on(cq->chann, phba->wq,
15517 						&cq->sched_irqwork, delay);
15518 		if (!ret)
15519 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15520 					"0367 Cannot schedule queue work "
15521 					"for cqid=%d on CPU %d\n",
15522 					cq->queue_id, cq->chann);
15523 	}
15524 
15525 	/* wake up worker thread if there are works to be done */
15526 	if (workposted)
15527 		lpfc_worker_wake_up(phba);
15528 }
15529 
15530 /**
15531  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
15532  *   interrupt
15533  * @work: pointer to work element
15534  *
15535  * translates from the work handler and calls the fast-path handler.
15536  **/
15537 static void
15538 lpfc_sli4_hba_process_cq(struct work_struct *work)
15539 {
15540 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
15541 
15542 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
15543 }
15544 
15545 /**
15546  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
15547  * @work: pointer to work element
15548  *
15549  * translates from the work handler and calls the fast-path handler.
15550  **/
15551 static void
15552 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
15553 {
15554 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15555 					struct lpfc_queue, sched_irqwork);
15556 
15557 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
15558 }
15559 
15560 /**
15561  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
15562  * @irq: Interrupt number.
15563  * @dev_id: The device context pointer.
15564  *
15565  * This function is directly called from the PCI layer as an interrupt
15566  * service routine when device with SLI-4 interface spec is enabled with
15567  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
15568  * ring event in the HBA. However, when the device is enabled with either
15569  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
15570  * device-level interrupt handler. When the PCI slot is in error recovery
15571  * or the HBA is undergoing initialization, the interrupt handler will not
15572  * process the interrupt. The SCSI FCP fast-path ring event are handled in
15573  * the intrrupt context. This function is called without any lock held.
15574  * It gets the hbalock to access and update SLI data structures. Note that,
15575  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
15576  * equal to that of FCP CQ index.
15577  *
15578  * The link attention and ELS ring attention events are handled
15579  * by the worker thread. The interrupt handler signals the worker thread
15580  * and returns for these events. This function is called without any lock
15581  * held. It gets the hbalock to access and update SLI data structures.
15582  *
15583  * This function returns IRQ_HANDLED when interrupt is handled else it
15584  * returns IRQ_NONE.
15585  **/
15586 irqreturn_t
15587 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
15588 {
15589 	struct lpfc_hba *phba;
15590 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
15591 	struct lpfc_queue *fpeq;
15592 	unsigned long iflag;
15593 	int ecount = 0;
15594 	int hba_eqidx;
15595 	struct lpfc_eq_intr_info *eqi;
15596 
15597 	/* Get the driver's phba structure from the dev_id */
15598 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
15599 	phba = hba_eq_hdl->phba;
15600 	hba_eqidx = hba_eq_hdl->idx;
15601 
15602 	if (unlikely(!phba))
15603 		return IRQ_NONE;
15604 	if (unlikely(!phba->sli4_hba.hdwq))
15605 		return IRQ_NONE;
15606 
15607 	/* Get to the EQ struct associated with this vector */
15608 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
15609 	if (unlikely(!fpeq))
15610 		return IRQ_NONE;
15611 
15612 	/* Check device state for handling interrupt */
15613 	if (unlikely(lpfc_intr_state_check(phba))) {
15614 		/* Check again for link_state with lock held */
15615 		spin_lock_irqsave(&phba->hbalock, iflag);
15616 		if (phba->link_state < LPFC_LINK_DOWN)
15617 			/* Flush, clear interrupt, and rearm the EQ */
15618 			lpfc_sli4_eqcq_flush(phba, fpeq);
15619 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15620 		return IRQ_NONE;
15621 	}
15622 
15623 	eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
15624 	eqi->icnt++;
15625 
15626 	fpeq->last_cpu = raw_smp_processor_id();
15627 
15628 	if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
15629 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
15630 	    phba->cfg_auto_imax &&
15631 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
15632 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
15633 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
15634 
15635 	/* process and rearm the EQ */
15636 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
15637 
15638 	if (unlikely(ecount == 0)) {
15639 		fpeq->EQ_no_entry++;
15640 		if (phba->intr_type == MSIX)
15641 			/* MSI-X treated interrupt served as no EQ share INT */
15642 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15643 					"0358 MSI-X interrupt with no EQE\n");
15644 		else
15645 			/* Non MSI-X treated on interrupt as EQ share INT */
15646 			return IRQ_NONE;
15647 	}
15648 
15649 	return IRQ_HANDLED;
15650 } /* lpfc_sli4_hba_intr_handler */
15651 
15652 /**
15653  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
15654  * @irq: Interrupt number.
15655  * @dev_id: The device context pointer.
15656  *
15657  * This function is the device-level interrupt handler to device with SLI-4
15658  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
15659  * interrupt mode is enabled and there is an event in the HBA which requires
15660  * driver attention. This function invokes the slow-path interrupt attention
15661  * handling function and fast-path interrupt attention handling function in
15662  * turn to process the relevant HBA attention events. This function is called
15663  * without any lock held. It gets the hbalock to access and update SLI data
15664  * structures.
15665  *
15666  * This function returns IRQ_HANDLED when interrupt is handled, else it
15667  * returns IRQ_NONE.
15668  **/
15669 irqreturn_t
15670 lpfc_sli4_intr_handler(int irq, void *dev_id)
15671 {
15672 	struct lpfc_hba  *phba;
15673 	irqreturn_t hba_irq_rc;
15674 	bool hba_handled = false;
15675 	int qidx;
15676 
15677 	/* Get the driver's phba structure from the dev_id */
15678 	phba = (struct lpfc_hba *)dev_id;
15679 
15680 	if (unlikely(!phba))
15681 		return IRQ_NONE;
15682 
15683 	/*
15684 	 * Invoke fast-path host attention interrupt handling as appropriate.
15685 	 */
15686 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
15687 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
15688 					&phba->sli4_hba.hba_eq_hdl[qidx]);
15689 		if (hba_irq_rc == IRQ_HANDLED)
15690 			hba_handled |= true;
15691 	}
15692 
15693 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
15694 } /* lpfc_sli4_intr_handler */
15695 
15696 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
15697 {
15698 	struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
15699 	struct lpfc_queue *eq;
15700 	int i = 0;
15701 
15702 	rcu_read_lock();
15703 
15704 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
15705 		i += lpfc_sli4_poll_eq(eq, LPFC_POLL_SLOWPATH);
15706 	if (!list_empty(&phba->poll_list))
15707 		mod_timer(&phba->cpuhp_poll_timer,
15708 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15709 
15710 	rcu_read_unlock();
15711 }
15712 
15713 inline int lpfc_sli4_poll_eq(struct lpfc_queue *eq, uint8_t path)
15714 {
15715 	struct lpfc_hba *phba = eq->phba;
15716 	int i = 0;
15717 
15718 	/*
15719 	 * Unlocking an irq is one of the entry point to check
15720 	 * for re-schedule, but we are good for io submission
15721 	 * path as midlayer does a get_cpu to glue us in. Flush
15722 	 * out the invalidate queue so we can see the updated
15723 	 * value for flag.
15724 	 */
15725 	smp_rmb();
15726 
15727 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
15728 		/* We will not likely get the completion for the caller
15729 		 * during this iteration but i guess that's fine.
15730 		 * Future io's coming on this eq should be able to
15731 		 * pick it up.  As for the case of single io's, they
15732 		 * will be handled through a sched from polling timer
15733 		 * function which is currently triggered every 1msec.
15734 		 */
15735 		i = lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM);
15736 
15737 	return i;
15738 }
15739 
15740 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
15741 {
15742 	struct lpfc_hba *phba = eq->phba;
15743 
15744 	/* kickstart slowpath processing if needed */
15745 	if (list_empty(&phba->poll_list))
15746 		mod_timer(&phba->cpuhp_poll_timer,
15747 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15748 
15749 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
15750 	synchronize_rcu();
15751 }
15752 
15753 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
15754 {
15755 	struct lpfc_hba *phba = eq->phba;
15756 
15757 	/* Disable slowpath processing for this eq.  Kick start the eq
15758 	 * by RE-ARMING the eq's ASAP
15759 	 */
15760 	list_del_rcu(&eq->_poll_list);
15761 	synchronize_rcu();
15762 
15763 	if (list_empty(&phba->poll_list))
15764 		del_timer_sync(&phba->cpuhp_poll_timer);
15765 }
15766 
15767 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
15768 {
15769 	struct lpfc_queue *eq, *next;
15770 
15771 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
15772 		list_del(&eq->_poll_list);
15773 
15774 	INIT_LIST_HEAD(&phba->poll_list);
15775 	synchronize_rcu();
15776 }
15777 
15778 static inline void
15779 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
15780 {
15781 	if (mode == eq->mode)
15782 		return;
15783 	/*
15784 	 * currently this function is only called during a hotplug
15785 	 * event and the cpu on which this function is executing
15786 	 * is going offline.  By now the hotplug has instructed
15787 	 * the scheduler to remove this cpu from cpu active mask.
15788 	 * So we don't need to work about being put aside by the
15789 	 * scheduler for a high priority process.  Yes, the inte-
15790 	 * rrupts could come but they are known to retire ASAP.
15791 	 */
15792 
15793 	/* Disable polling in the fastpath */
15794 	WRITE_ONCE(eq->mode, mode);
15795 	/* flush out the store buffer */
15796 	smp_wmb();
15797 
15798 	/*
15799 	 * Add this eq to the polling list and start polling. For
15800 	 * a grace period both interrupt handler and poller will
15801 	 * try to process the eq _but_ that's fine.  We have a
15802 	 * synchronization mechanism in place (queue_claimed) to
15803 	 * deal with it.  This is just a draining phase for int-
15804 	 * errupt handler (not eq's) as we have guranteed through
15805 	 * barrier that all the CPUs have seen the new CQ_POLLED
15806 	 * state. which will effectively disable the REARMING of
15807 	 * the EQ.  The whole idea is eq's die off eventually as
15808 	 * we are not rearming EQ's anymore.
15809 	 */
15810 	mode ? lpfc_sli4_add_to_poll_list(eq) :
15811 	       lpfc_sli4_remove_from_poll_list(eq);
15812 }
15813 
15814 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15815 {
15816 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15817 }
15818 
15819 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15820 {
15821 	struct lpfc_hba *phba = eq->phba;
15822 
15823 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15824 
15825 	/* Kick start for the pending io's in h/w.
15826 	 * Once we switch back to interrupt processing on a eq
15827 	 * the io path completion will only arm eq's when it
15828 	 * receives a completion.  But since eq's are in disa-
15829 	 * rmed state it doesn't receive a completion.  This
15830 	 * creates a deadlock scenaro.
15831 	 */
15832 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15833 }
15834 
15835 /**
15836  * lpfc_sli4_queue_free - free a queue structure and associated memory
15837  * @queue: The queue structure to free.
15838  *
15839  * This function frees a queue structure and the DMAable memory used for
15840  * the host resident queue. This function must be called after destroying the
15841  * queue on the HBA.
15842  **/
15843 void
15844 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15845 {
15846 	struct lpfc_dmabuf *dmabuf;
15847 
15848 	if (!queue)
15849 		return;
15850 
15851 	if (!list_empty(&queue->wq_list))
15852 		list_del(&queue->wq_list);
15853 
15854 	while (!list_empty(&queue->page_list)) {
15855 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15856 				 list);
15857 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15858 				  dmabuf->virt, dmabuf->phys);
15859 		kfree(dmabuf);
15860 	}
15861 	if (queue->rqbp) {
15862 		lpfc_free_rq_buffer(queue->phba, queue);
15863 		kfree(queue->rqbp);
15864 	}
15865 
15866 	if (!list_empty(&queue->cpu_list))
15867 		list_del(&queue->cpu_list);
15868 
15869 	kfree(queue);
15870 	return;
15871 }
15872 
15873 /**
15874  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15875  * @phba: The HBA that this queue is being created on.
15876  * @page_size: The size of a queue page
15877  * @entry_size: The size of each queue entry for this queue.
15878  * @entry_count: The number of entries that this queue will handle.
15879  * @cpu: The cpu that will primarily utilize this queue.
15880  *
15881  * This function allocates a queue structure and the DMAable memory used for
15882  * the host resident queue. This function must be called before creating the
15883  * queue on the HBA.
15884  **/
15885 struct lpfc_queue *
15886 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15887 		      uint32_t entry_size, uint32_t entry_count, int cpu)
15888 {
15889 	struct lpfc_queue *queue;
15890 	struct lpfc_dmabuf *dmabuf;
15891 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15892 	uint16_t x, pgcnt;
15893 
15894 	if (!phba->sli4_hba.pc_sli4_params.supported)
15895 		hw_page_size = page_size;
15896 
15897 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15898 
15899 	/* If needed, Adjust page count to match the max the adapter supports */
15900 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15901 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15902 
15903 	queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
15904 			     GFP_KERNEL, cpu_to_node(cpu));
15905 	if (!queue)
15906 		return NULL;
15907 
15908 	INIT_LIST_HEAD(&queue->list);
15909 	INIT_LIST_HEAD(&queue->_poll_list);
15910 	INIT_LIST_HEAD(&queue->wq_list);
15911 	INIT_LIST_HEAD(&queue->wqfull_list);
15912 	INIT_LIST_HEAD(&queue->page_list);
15913 	INIT_LIST_HEAD(&queue->child_list);
15914 	INIT_LIST_HEAD(&queue->cpu_list);
15915 
15916 	/* Set queue parameters now.  If the system cannot provide memory
15917 	 * resources, the free routine needs to know what was allocated.
15918 	 */
15919 	queue->page_count = pgcnt;
15920 	queue->q_pgs = (void **)&queue[1];
15921 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
15922 	queue->entry_size = entry_size;
15923 	queue->entry_count = entry_count;
15924 	queue->page_size = hw_page_size;
15925 	queue->phba = phba;
15926 
15927 	for (x = 0; x < queue->page_count; x++) {
15928 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15929 				      dev_to_node(&phba->pcidev->dev));
15930 		if (!dmabuf)
15931 			goto out_fail;
15932 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15933 						  hw_page_size, &dmabuf->phys,
15934 						  GFP_KERNEL);
15935 		if (!dmabuf->virt) {
15936 			kfree(dmabuf);
15937 			goto out_fail;
15938 		}
15939 		dmabuf->buffer_tag = x;
15940 		list_add_tail(&dmabuf->list, &queue->page_list);
15941 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
15942 		queue->q_pgs[x] = dmabuf->virt;
15943 	}
15944 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15945 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15946 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15947 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15948 
15949 	/* notify_interval will be set during q creation */
15950 
15951 	return queue;
15952 out_fail:
15953 	lpfc_sli4_queue_free(queue);
15954 	return NULL;
15955 }
15956 
15957 /**
15958  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15959  * @phba: HBA structure that indicates port to create a queue on.
15960  * @pci_barset: PCI BAR set flag.
15961  *
15962  * This function shall perform iomap of the specified PCI BAR address to host
15963  * memory address if not already done so and return it. The returned host
15964  * memory address can be NULL.
15965  */
15966 static void __iomem *
15967 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15968 {
15969 	if (!phba->pcidev)
15970 		return NULL;
15971 
15972 	switch (pci_barset) {
15973 	case WQ_PCI_BAR_0_AND_1:
15974 		return phba->pci_bar0_memmap_p;
15975 	case WQ_PCI_BAR_2_AND_3:
15976 		return phba->pci_bar2_memmap_p;
15977 	case WQ_PCI_BAR_4_AND_5:
15978 		return phba->pci_bar4_memmap_p;
15979 	default:
15980 		break;
15981 	}
15982 	return NULL;
15983 }
15984 
15985 /**
15986  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
15987  * @phba: HBA structure that EQs are on.
15988  * @startq: The starting EQ index to modify
15989  * @numq: The number of EQs (consecutive indexes) to modify
15990  * @usdelay: amount of delay
15991  *
15992  * This function revises the EQ delay on 1 or more EQs. The EQ delay
15993  * is set either by writing to a register (if supported by the SLI Port)
15994  * or by mailbox command. The mailbox command allows several EQs to be
15995  * updated at once.
15996  *
15997  * The @phba struct is used to send a mailbox command to HBA. The @startq
15998  * is used to get the starting EQ index to change. The @numq value is
15999  * used to specify how many consecutive EQ indexes, starting at EQ index,
16000  * are to be changed. This function is asynchronous and will wait for any
16001  * mailbox commands to finish before returning.
16002  *
16003  * On success this function will return a zero. If unable to allocate
16004  * enough memory this function will return -ENOMEM. If a mailbox command
16005  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
16006  * have had their delay multipler changed.
16007  **/
16008 void
16009 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
16010 			 uint32_t numq, uint32_t usdelay)
16011 {
16012 	struct lpfc_mbx_modify_eq_delay *eq_delay;
16013 	LPFC_MBOXQ_t *mbox;
16014 	struct lpfc_queue *eq;
16015 	int cnt = 0, rc, length;
16016 	uint32_t shdr_status, shdr_add_status;
16017 	uint32_t dmult;
16018 	int qidx;
16019 	union lpfc_sli4_cfg_shdr *shdr;
16020 
16021 	if (startq >= phba->cfg_irq_chann)
16022 		return;
16023 
16024 	if (usdelay > 0xFFFF) {
16025 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
16026 				"6429 usdelay %d too large. Scaled down to "
16027 				"0xFFFF.\n", usdelay);
16028 		usdelay = 0xFFFF;
16029 	}
16030 
16031 	/* set values by EQ_DELAY register if supported */
16032 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
16033 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
16034 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
16035 			if (!eq)
16036 				continue;
16037 
16038 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
16039 
16040 			if (++cnt >= numq)
16041 				break;
16042 		}
16043 		return;
16044 	}
16045 
16046 	/* Otherwise, set values by mailbox cmd */
16047 
16048 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16049 	if (!mbox) {
16050 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16051 				"6428 Failed allocating mailbox cmd buffer."
16052 				" EQ delay was not set.\n");
16053 		return;
16054 	}
16055 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
16056 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16057 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16058 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
16059 			 length, LPFC_SLI4_MBX_EMBED);
16060 	eq_delay = &mbox->u.mqe.un.eq_delay;
16061 
16062 	/* Calculate delay multiper from maximum interrupt per second */
16063 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
16064 	if (dmult)
16065 		dmult--;
16066 	if (dmult > LPFC_DMULT_MAX)
16067 		dmult = LPFC_DMULT_MAX;
16068 
16069 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
16070 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
16071 		if (!eq)
16072 			continue;
16073 		eq->q_mode = usdelay;
16074 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
16075 		eq_delay->u.request.eq[cnt].phase = 0;
16076 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
16077 
16078 		if (++cnt >= numq)
16079 			break;
16080 	}
16081 	eq_delay->u.request.num_eq = cnt;
16082 
16083 	mbox->vport = phba->pport;
16084 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16085 	mbox->ctx_buf = NULL;
16086 	mbox->ctx_ndlp = NULL;
16087 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16088 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
16089 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16090 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16091 	if (shdr_status || shdr_add_status || rc) {
16092 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16093 				"2512 MODIFY_EQ_DELAY mailbox failed with "
16094 				"status x%x add_status x%x, mbx status x%x\n",
16095 				shdr_status, shdr_add_status, rc);
16096 	}
16097 	mempool_free(mbox, phba->mbox_mem_pool);
16098 	return;
16099 }
16100 
16101 /**
16102  * lpfc_eq_create - Create an Event Queue on the HBA
16103  * @phba: HBA structure that indicates port to create a queue on.
16104  * @eq: The queue structure to use to create the event queue.
16105  * @imax: The maximum interrupt per second limit.
16106  *
16107  * This function creates an event queue, as detailed in @eq, on a port,
16108  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
16109  *
16110  * The @phba struct is used to send mailbox command to HBA. The @eq struct
16111  * is used to get the entry count and entry size that are necessary to
16112  * determine the number of pages to allocate and use for this queue. This
16113  * function will send the EQ_CREATE mailbox command to the HBA to setup the
16114  * event queue. This function is asynchronous and will wait for the mailbox
16115  * command to finish before continuing.
16116  *
16117  * On success this function will return a zero. If unable to allocate enough
16118  * memory this function will return -ENOMEM. If the queue create mailbox command
16119  * fails this function will return -ENXIO.
16120  **/
16121 int
16122 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
16123 {
16124 	struct lpfc_mbx_eq_create *eq_create;
16125 	LPFC_MBOXQ_t *mbox;
16126 	int rc, length, status = 0;
16127 	struct lpfc_dmabuf *dmabuf;
16128 	uint32_t shdr_status, shdr_add_status;
16129 	union lpfc_sli4_cfg_shdr *shdr;
16130 	uint16_t dmult;
16131 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16132 
16133 	/* sanity check on queue memory */
16134 	if (!eq)
16135 		return -ENODEV;
16136 	if (!phba->sli4_hba.pc_sli4_params.supported)
16137 		hw_page_size = SLI4_PAGE_SIZE;
16138 
16139 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16140 	if (!mbox)
16141 		return -ENOMEM;
16142 	length = (sizeof(struct lpfc_mbx_eq_create) -
16143 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16144 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16145 			 LPFC_MBOX_OPCODE_EQ_CREATE,
16146 			 length, LPFC_SLI4_MBX_EMBED);
16147 	eq_create = &mbox->u.mqe.un.eq_create;
16148 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
16149 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
16150 	       eq->page_count);
16151 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
16152 	       LPFC_EQE_SIZE);
16153 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
16154 
16155 	/* Use version 2 of CREATE_EQ if eqav is set */
16156 	if (phba->sli4_hba.pc_sli4_params.eqav) {
16157 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16158 		       LPFC_Q_CREATE_VERSION_2);
16159 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
16160 		       phba->sli4_hba.pc_sli4_params.eqav);
16161 	}
16162 
16163 	/* don't setup delay multiplier using EQ_CREATE */
16164 	dmult = 0;
16165 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
16166 	       dmult);
16167 	switch (eq->entry_count) {
16168 	default:
16169 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16170 				"0360 Unsupported EQ count. (%d)\n",
16171 				eq->entry_count);
16172 		if (eq->entry_count < 256) {
16173 			status = -EINVAL;
16174 			goto out;
16175 		}
16176 		fallthrough;	/* otherwise default to smallest count */
16177 	case 256:
16178 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16179 		       LPFC_EQ_CNT_256);
16180 		break;
16181 	case 512:
16182 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16183 		       LPFC_EQ_CNT_512);
16184 		break;
16185 	case 1024:
16186 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16187 		       LPFC_EQ_CNT_1024);
16188 		break;
16189 	case 2048:
16190 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16191 		       LPFC_EQ_CNT_2048);
16192 		break;
16193 	case 4096:
16194 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16195 		       LPFC_EQ_CNT_4096);
16196 		break;
16197 	}
16198 	list_for_each_entry(dmabuf, &eq->page_list, list) {
16199 		memset(dmabuf->virt, 0, hw_page_size);
16200 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16201 					putPaddrLow(dmabuf->phys);
16202 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16203 					putPaddrHigh(dmabuf->phys);
16204 	}
16205 	mbox->vport = phba->pport;
16206 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16207 	mbox->ctx_buf = NULL;
16208 	mbox->ctx_ndlp = NULL;
16209 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16210 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16211 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16212 	if (shdr_status || shdr_add_status || rc) {
16213 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16214 				"2500 EQ_CREATE mailbox failed with "
16215 				"status x%x add_status x%x, mbx status x%x\n",
16216 				shdr_status, shdr_add_status, rc);
16217 		status = -ENXIO;
16218 	}
16219 	eq->type = LPFC_EQ;
16220 	eq->subtype = LPFC_NONE;
16221 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
16222 	if (eq->queue_id == 0xFFFF)
16223 		status = -ENXIO;
16224 	eq->host_index = 0;
16225 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
16226 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
16227 out:
16228 	mempool_free(mbox, phba->mbox_mem_pool);
16229 	return status;
16230 }
16231 
16232 static int lpfc_cq_poll_hdler(struct irq_poll *iop, int budget)
16233 {
16234 	struct lpfc_queue *cq = container_of(iop, struct lpfc_queue, iop);
16235 
16236 	__lpfc_sli4_hba_process_cq(cq, LPFC_IRQ_POLL);
16237 
16238 	return 1;
16239 }
16240 
16241 /**
16242  * lpfc_cq_create - Create a Completion Queue on the HBA
16243  * @phba: HBA structure that indicates port to create a queue on.
16244  * @cq: The queue structure to use to create the completion queue.
16245  * @eq: The event queue to bind this completion queue to.
16246  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16247  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16248  *
16249  * This function creates a completion queue, as detailed in @wq, on a port,
16250  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
16251  *
16252  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16253  * is used to get the entry count and entry size that are necessary to
16254  * determine the number of pages to allocate and use for this queue. The @eq
16255  * is used to indicate which event queue to bind this completion queue to. This
16256  * function will send the CQ_CREATE mailbox command to the HBA to setup the
16257  * completion queue. This function is asynchronous and will wait for the mailbox
16258  * command to finish before continuing.
16259  *
16260  * On success this function will return a zero. If unable to allocate enough
16261  * memory this function will return -ENOMEM. If the queue create mailbox command
16262  * fails this function will return -ENXIO.
16263  **/
16264 int
16265 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
16266 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
16267 {
16268 	struct lpfc_mbx_cq_create *cq_create;
16269 	struct lpfc_dmabuf *dmabuf;
16270 	LPFC_MBOXQ_t *mbox;
16271 	int rc, length, status = 0;
16272 	uint32_t shdr_status, shdr_add_status;
16273 	union lpfc_sli4_cfg_shdr *shdr;
16274 
16275 	/* sanity check on queue memory */
16276 	if (!cq || !eq)
16277 		return -ENODEV;
16278 
16279 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16280 	if (!mbox)
16281 		return -ENOMEM;
16282 	length = (sizeof(struct lpfc_mbx_cq_create) -
16283 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16284 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16285 			 LPFC_MBOX_OPCODE_CQ_CREATE,
16286 			 length, LPFC_SLI4_MBX_EMBED);
16287 	cq_create = &mbox->u.mqe.un.cq_create;
16288 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
16289 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
16290 		    cq->page_count);
16291 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
16292 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
16293 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16294 	       phba->sli4_hba.pc_sli4_params.cqv);
16295 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
16296 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
16297 		       (cq->page_size / SLI4_PAGE_SIZE));
16298 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
16299 		       eq->queue_id);
16300 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
16301 		       phba->sli4_hba.pc_sli4_params.cqav);
16302 	} else {
16303 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
16304 		       eq->queue_id);
16305 	}
16306 	switch (cq->entry_count) {
16307 	case 2048:
16308 	case 4096:
16309 		if (phba->sli4_hba.pc_sli4_params.cqv ==
16310 		    LPFC_Q_CREATE_VERSION_2) {
16311 			cq_create->u.request.context.lpfc_cq_context_count =
16312 				cq->entry_count;
16313 			bf_set(lpfc_cq_context_count,
16314 			       &cq_create->u.request.context,
16315 			       LPFC_CQ_CNT_WORD7);
16316 			break;
16317 		}
16318 		fallthrough;
16319 	default:
16320 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16321 				"0361 Unsupported CQ count: "
16322 				"entry cnt %d sz %d pg cnt %d\n",
16323 				cq->entry_count, cq->entry_size,
16324 				cq->page_count);
16325 		if (cq->entry_count < 256) {
16326 			status = -EINVAL;
16327 			goto out;
16328 		}
16329 		fallthrough;	/* otherwise default to smallest count */
16330 	case 256:
16331 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16332 		       LPFC_CQ_CNT_256);
16333 		break;
16334 	case 512:
16335 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16336 		       LPFC_CQ_CNT_512);
16337 		break;
16338 	case 1024:
16339 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16340 		       LPFC_CQ_CNT_1024);
16341 		break;
16342 	}
16343 	list_for_each_entry(dmabuf, &cq->page_list, list) {
16344 		memset(dmabuf->virt, 0, cq->page_size);
16345 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16346 					putPaddrLow(dmabuf->phys);
16347 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16348 					putPaddrHigh(dmabuf->phys);
16349 	}
16350 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16351 
16352 	/* The IOCTL status is embedded in the mailbox subheader. */
16353 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16354 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16355 	if (shdr_status || shdr_add_status || rc) {
16356 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16357 				"2501 CQ_CREATE mailbox failed with "
16358 				"status x%x add_status x%x, mbx status x%x\n",
16359 				shdr_status, shdr_add_status, rc);
16360 		status = -ENXIO;
16361 		goto out;
16362 	}
16363 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16364 	if (cq->queue_id == 0xFFFF) {
16365 		status = -ENXIO;
16366 		goto out;
16367 	}
16368 	/* link the cq onto the parent eq child list */
16369 	list_add_tail(&cq->list, &eq->child_list);
16370 	/* Set up completion queue's type and subtype */
16371 	cq->type = type;
16372 	cq->subtype = subtype;
16373 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16374 	cq->assoc_qid = eq->queue_id;
16375 	cq->assoc_qp = eq;
16376 	cq->host_index = 0;
16377 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16378 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
16379 
16380 	if (cq->queue_id > phba->sli4_hba.cq_max)
16381 		phba->sli4_hba.cq_max = cq->queue_id;
16382 
16383 	irq_poll_init(&cq->iop, LPFC_IRQ_POLL_WEIGHT, lpfc_cq_poll_hdler);
16384 out:
16385 	mempool_free(mbox, phba->mbox_mem_pool);
16386 	return status;
16387 }
16388 
16389 /**
16390  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
16391  * @phba: HBA structure that indicates port to create a queue on.
16392  * @cqp: The queue structure array to use to create the completion queues.
16393  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
16394  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16395  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16396  *
16397  * This function creates a set of  completion queue, s to support MRQ
16398  * as detailed in @cqp, on a port,
16399  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
16400  *
16401  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16402  * is used to get the entry count and entry size that are necessary to
16403  * determine the number of pages to allocate and use for this queue. The @eq
16404  * is used to indicate which event queue to bind this completion queue to. This
16405  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
16406  * completion queue. This function is asynchronous and will wait for the mailbox
16407  * command to finish before continuing.
16408  *
16409  * On success this function will return a zero. If unable to allocate enough
16410  * memory this function will return -ENOMEM. If the queue create mailbox command
16411  * fails this function will return -ENXIO.
16412  **/
16413 int
16414 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
16415 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
16416 		   uint32_t subtype)
16417 {
16418 	struct lpfc_queue *cq;
16419 	struct lpfc_queue *eq;
16420 	struct lpfc_mbx_cq_create_set *cq_set;
16421 	struct lpfc_dmabuf *dmabuf;
16422 	LPFC_MBOXQ_t *mbox;
16423 	int rc, length, alloclen, status = 0;
16424 	int cnt, idx, numcq, page_idx = 0;
16425 	uint32_t shdr_status, shdr_add_status;
16426 	union lpfc_sli4_cfg_shdr *shdr;
16427 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16428 
16429 	/* sanity check on queue memory */
16430 	numcq = phba->cfg_nvmet_mrq;
16431 	if (!cqp || !hdwq || !numcq)
16432 		return -ENODEV;
16433 
16434 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16435 	if (!mbox)
16436 		return -ENOMEM;
16437 
16438 	length = sizeof(struct lpfc_mbx_cq_create_set);
16439 	length += ((numcq * cqp[0]->page_count) *
16440 		   sizeof(struct dma_address));
16441 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16442 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
16443 			LPFC_SLI4_MBX_NEMBED);
16444 	if (alloclen < length) {
16445 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16446 				"3098 Allocated DMA memory size (%d) is "
16447 				"less than the requested DMA memory size "
16448 				"(%d)\n", alloclen, length);
16449 		status = -ENOMEM;
16450 		goto out;
16451 	}
16452 	cq_set = mbox->sge_array->addr[0];
16453 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
16454 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
16455 
16456 	for (idx = 0; idx < numcq; idx++) {
16457 		cq = cqp[idx];
16458 		eq = hdwq[idx].hba_eq;
16459 		if (!cq || !eq) {
16460 			status = -ENOMEM;
16461 			goto out;
16462 		}
16463 		if (!phba->sli4_hba.pc_sli4_params.supported)
16464 			hw_page_size = cq->page_size;
16465 
16466 		switch (idx) {
16467 		case 0:
16468 			bf_set(lpfc_mbx_cq_create_set_page_size,
16469 			       &cq_set->u.request,
16470 			       (hw_page_size / SLI4_PAGE_SIZE));
16471 			bf_set(lpfc_mbx_cq_create_set_num_pages,
16472 			       &cq_set->u.request, cq->page_count);
16473 			bf_set(lpfc_mbx_cq_create_set_evt,
16474 			       &cq_set->u.request, 1);
16475 			bf_set(lpfc_mbx_cq_create_set_valid,
16476 			       &cq_set->u.request, 1);
16477 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
16478 			       &cq_set->u.request, 0);
16479 			bf_set(lpfc_mbx_cq_create_set_num_cq,
16480 			       &cq_set->u.request, numcq);
16481 			bf_set(lpfc_mbx_cq_create_set_autovalid,
16482 			       &cq_set->u.request,
16483 			       phba->sli4_hba.pc_sli4_params.cqav);
16484 			switch (cq->entry_count) {
16485 			case 2048:
16486 			case 4096:
16487 				if (phba->sli4_hba.pc_sli4_params.cqv ==
16488 				    LPFC_Q_CREATE_VERSION_2) {
16489 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16490 					       &cq_set->u.request,
16491 						cq->entry_count);
16492 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16493 					       &cq_set->u.request,
16494 					       LPFC_CQ_CNT_WORD7);
16495 					break;
16496 				}
16497 				fallthrough;
16498 			default:
16499 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16500 						"3118 Bad CQ count. (%d)\n",
16501 						cq->entry_count);
16502 				if (cq->entry_count < 256) {
16503 					status = -EINVAL;
16504 					goto out;
16505 				}
16506 				fallthrough;	/* otherwise default to smallest */
16507 			case 256:
16508 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16509 				       &cq_set->u.request, LPFC_CQ_CNT_256);
16510 				break;
16511 			case 512:
16512 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16513 				       &cq_set->u.request, LPFC_CQ_CNT_512);
16514 				break;
16515 			case 1024:
16516 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16517 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
16518 				break;
16519 			}
16520 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
16521 			       &cq_set->u.request, eq->queue_id);
16522 			break;
16523 		case 1:
16524 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
16525 			       &cq_set->u.request, eq->queue_id);
16526 			break;
16527 		case 2:
16528 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
16529 			       &cq_set->u.request, eq->queue_id);
16530 			break;
16531 		case 3:
16532 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
16533 			       &cq_set->u.request, eq->queue_id);
16534 			break;
16535 		case 4:
16536 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
16537 			       &cq_set->u.request, eq->queue_id);
16538 			break;
16539 		case 5:
16540 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
16541 			       &cq_set->u.request, eq->queue_id);
16542 			break;
16543 		case 6:
16544 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
16545 			       &cq_set->u.request, eq->queue_id);
16546 			break;
16547 		case 7:
16548 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
16549 			       &cq_set->u.request, eq->queue_id);
16550 			break;
16551 		case 8:
16552 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
16553 			       &cq_set->u.request, eq->queue_id);
16554 			break;
16555 		case 9:
16556 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
16557 			       &cq_set->u.request, eq->queue_id);
16558 			break;
16559 		case 10:
16560 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
16561 			       &cq_set->u.request, eq->queue_id);
16562 			break;
16563 		case 11:
16564 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
16565 			       &cq_set->u.request, eq->queue_id);
16566 			break;
16567 		case 12:
16568 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
16569 			       &cq_set->u.request, eq->queue_id);
16570 			break;
16571 		case 13:
16572 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
16573 			       &cq_set->u.request, eq->queue_id);
16574 			break;
16575 		case 14:
16576 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
16577 			       &cq_set->u.request, eq->queue_id);
16578 			break;
16579 		case 15:
16580 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
16581 			       &cq_set->u.request, eq->queue_id);
16582 			break;
16583 		}
16584 
16585 		/* link the cq onto the parent eq child list */
16586 		list_add_tail(&cq->list, &eq->child_list);
16587 		/* Set up completion queue's type and subtype */
16588 		cq->type = type;
16589 		cq->subtype = subtype;
16590 		cq->assoc_qid = eq->queue_id;
16591 		cq->assoc_qp = eq;
16592 		cq->host_index = 0;
16593 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16594 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
16595 					 cq->entry_count);
16596 		cq->chann = idx;
16597 
16598 		rc = 0;
16599 		list_for_each_entry(dmabuf, &cq->page_list, list) {
16600 			memset(dmabuf->virt, 0, hw_page_size);
16601 			cnt = page_idx + dmabuf->buffer_tag;
16602 			cq_set->u.request.page[cnt].addr_lo =
16603 					putPaddrLow(dmabuf->phys);
16604 			cq_set->u.request.page[cnt].addr_hi =
16605 					putPaddrHigh(dmabuf->phys);
16606 			rc++;
16607 		}
16608 		page_idx += rc;
16609 	}
16610 
16611 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16612 
16613 	/* The IOCTL status is embedded in the mailbox subheader. */
16614 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16615 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16616 	if (shdr_status || shdr_add_status || rc) {
16617 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16618 				"3119 CQ_CREATE_SET mailbox failed with "
16619 				"status x%x add_status x%x, mbx status x%x\n",
16620 				shdr_status, shdr_add_status, rc);
16621 		status = -ENXIO;
16622 		goto out;
16623 	}
16624 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
16625 	if (rc == 0xFFFF) {
16626 		status = -ENXIO;
16627 		goto out;
16628 	}
16629 
16630 	for (idx = 0; idx < numcq; idx++) {
16631 		cq = cqp[idx];
16632 		cq->queue_id = rc + idx;
16633 		if (cq->queue_id > phba->sli4_hba.cq_max)
16634 			phba->sli4_hba.cq_max = cq->queue_id;
16635 	}
16636 
16637 out:
16638 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16639 	return status;
16640 }
16641 
16642 /**
16643  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
16644  * @phba: HBA structure that indicates port to create a queue on.
16645  * @mq: The queue structure to use to create the mailbox queue.
16646  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
16647  * @cq: The completion queue to associate with this cq.
16648  *
16649  * This function provides failback (fb) functionality when the
16650  * mq_create_ext fails on older FW generations.  It's purpose is identical
16651  * to mq_create_ext otherwise.
16652  *
16653  * This routine cannot fail as all attributes were previously accessed and
16654  * initialized in mq_create_ext.
16655  **/
16656 static void
16657 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
16658 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
16659 {
16660 	struct lpfc_mbx_mq_create *mq_create;
16661 	struct lpfc_dmabuf *dmabuf;
16662 	int length;
16663 
16664 	length = (sizeof(struct lpfc_mbx_mq_create) -
16665 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16666 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16667 			 LPFC_MBOX_OPCODE_MQ_CREATE,
16668 			 length, LPFC_SLI4_MBX_EMBED);
16669 	mq_create = &mbox->u.mqe.un.mq_create;
16670 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
16671 	       mq->page_count);
16672 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
16673 	       cq->queue_id);
16674 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
16675 	switch (mq->entry_count) {
16676 	case 16:
16677 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16678 		       LPFC_MQ_RING_SIZE_16);
16679 		break;
16680 	case 32:
16681 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16682 		       LPFC_MQ_RING_SIZE_32);
16683 		break;
16684 	case 64:
16685 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16686 		       LPFC_MQ_RING_SIZE_64);
16687 		break;
16688 	case 128:
16689 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16690 		       LPFC_MQ_RING_SIZE_128);
16691 		break;
16692 	}
16693 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16694 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16695 			putPaddrLow(dmabuf->phys);
16696 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16697 			putPaddrHigh(dmabuf->phys);
16698 	}
16699 }
16700 
16701 /**
16702  * lpfc_mq_create - Create a mailbox Queue on the HBA
16703  * @phba: HBA structure that indicates port to create a queue on.
16704  * @mq: The queue structure to use to create the mailbox queue.
16705  * @cq: The completion queue to associate with this cq.
16706  * @subtype: The queue's subtype.
16707  *
16708  * This function creates a mailbox queue, as detailed in @mq, on a port,
16709  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
16710  *
16711  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16712  * is used to get the entry count and entry size that are necessary to
16713  * determine the number of pages to allocate and use for this queue. This
16714  * function will send the MQ_CREATE mailbox command to the HBA to setup the
16715  * mailbox queue. This function is asynchronous and will wait for the mailbox
16716  * command to finish before continuing.
16717  *
16718  * On success this function will return a zero. If unable to allocate enough
16719  * memory this function will return -ENOMEM. If the queue create mailbox command
16720  * fails this function will return -ENXIO.
16721  **/
16722 int32_t
16723 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
16724 	       struct lpfc_queue *cq, uint32_t subtype)
16725 {
16726 	struct lpfc_mbx_mq_create *mq_create;
16727 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
16728 	struct lpfc_dmabuf *dmabuf;
16729 	LPFC_MBOXQ_t *mbox;
16730 	int rc, length, status = 0;
16731 	uint32_t shdr_status, shdr_add_status;
16732 	union lpfc_sli4_cfg_shdr *shdr;
16733 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16734 
16735 	/* sanity check on queue memory */
16736 	if (!mq || !cq)
16737 		return -ENODEV;
16738 	if (!phba->sli4_hba.pc_sli4_params.supported)
16739 		hw_page_size = SLI4_PAGE_SIZE;
16740 
16741 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16742 	if (!mbox)
16743 		return -ENOMEM;
16744 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
16745 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16746 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16747 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
16748 			 length, LPFC_SLI4_MBX_EMBED);
16749 
16750 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
16751 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
16752 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
16753 	       &mq_create_ext->u.request, mq->page_count);
16754 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
16755 	       &mq_create_ext->u.request, 1);
16756 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
16757 	       &mq_create_ext->u.request, 1);
16758 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
16759 	       &mq_create_ext->u.request, 1);
16760 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
16761 	       &mq_create_ext->u.request, 1);
16762 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
16763 	       &mq_create_ext->u.request, 1);
16764 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
16765 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16766 	       phba->sli4_hba.pc_sli4_params.mqv);
16767 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
16768 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
16769 		       cq->queue_id);
16770 	else
16771 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
16772 		       cq->queue_id);
16773 	switch (mq->entry_count) {
16774 	default:
16775 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16776 				"0362 Unsupported MQ count. (%d)\n",
16777 				mq->entry_count);
16778 		if (mq->entry_count < 16) {
16779 			status = -EINVAL;
16780 			goto out;
16781 		}
16782 		fallthrough;	/* otherwise default to smallest count */
16783 	case 16:
16784 		bf_set(lpfc_mq_context_ring_size,
16785 		       &mq_create_ext->u.request.context,
16786 		       LPFC_MQ_RING_SIZE_16);
16787 		break;
16788 	case 32:
16789 		bf_set(lpfc_mq_context_ring_size,
16790 		       &mq_create_ext->u.request.context,
16791 		       LPFC_MQ_RING_SIZE_32);
16792 		break;
16793 	case 64:
16794 		bf_set(lpfc_mq_context_ring_size,
16795 		       &mq_create_ext->u.request.context,
16796 		       LPFC_MQ_RING_SIZE_64);
16797 		break;
16798 	case 128:
16799 		bf_set(lpfc_mq_context_ring_size,
16800 		       &mq_create_ext->u.request.context,
16801 		       LPFC_MQ_RING_SIZE_128);
16802 		break;
16803 	}
16804 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16805 		memset(dmabuf->virt, 0, hw_page_size);
16806 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16807 					putPaddrLow(dmabuf->phys);
16808 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16809 					putPaddrHigh(dmabuf->phys);
16810 	}
16811 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16812 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16813 			      &mq_create_ext->u.response);
16814 	if (rc != MBX_SUCCESS) {
16815 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16816 				"2795 MQ_CREATE_EXT failed with "
16817 				"status x%x. Failback to MQ_CREATE.\n",
16818 				rc);
16819 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16820 		mq_create = &mbox->u.mqe.un.mq_create;
16821 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16822 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16823 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16824 				      &mq_create->u.response);
16825 	}
16826 
16827 	/* The IOCTL status is embedded in the mailbox subheader. */
16828 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16829 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16830 	if (shdr_status || shdr_add_status || rc) {
16831 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16832 				"2502 MQ_CREATE mailbox failed with "
16833 				"status x%x add_status x%x, mbx status x%x\n",
16834 				shdr_status, shdr_add_status, rc);
16835 		status = -ENXIO;
16836 		goto out;
16837 	}
16838 	if (mq->queue_id == 0xFFFF) {
16839 		status = -ENXIO;
16840 		goto out;
16841 	}
16842 	mq->type = LPFC_MQ;
16843 	mq->assoc_qid = cq->queue_id;
16844 	mq->subtype = subtype;
16845 	mq->host_index = 0;
16846 	mq->hba_index = 0;
16847 
16848 	/* link the mq onto the parent cq child list */
16849 	list_add_tail(&mq->list, &cq->child_list);
16850 out:
16851 	mempool_free(mbox, phba->mbox_mem_pool);
16852 	return status;
16853 }
16854 
16855 /**
16856  * lpfc_wq_create - Create a Work Queue on the HBA
16857  * @phba: HBA structure that indicates port to create a queue on.
16858  * @wq: The queue structure to use to create the work queue.
16859  * @cq: The completion queue to bind this work queue to.
16860  * @subtype: The subtype of the work queue indicating its functionality.
16861  *
16862  * This function creates a work queue, as detailed in @wq, on a port, described
16863  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16864  *
16865  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16866  * is used to get the entry count and entry size that are necessary to
16867  * determine the number of pages to allocate and use for this queue. The @cq
16868  * is used to indicate which completion queue to bind this work queue to. This
16869  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16870  * work queue. This function is asynchronous and will wait for the mailbox
16871  * command to finish before continuing.
16872  *
16873  * On success this function will return a zero. If unable to allocate enough
16874  * memory this function will return -ENOMEM. If the queue create mailbox command
16875  * fails this function will return -ENXIO.
16876  **/
16877 int
16878 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16879 	       struct lpfc_queue *cq, uint32_t subtype)
16880 {
16881 	struct lpfc_mbx_wq_create *wq_create;
16882 	struct lpfc_dmabuf *dmabuf;
16883 	LPFC_MBOXQ_t *mbox;
16884 	int rc, length, status = 0;
16885 	uint32_t shdr_status, shdr_add_status;
16886 	union lpfc_sli4_cfg_shdr *shdr;
16887 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16888 	struct dma_address *page;
16889 	void __iomem *bar_memmap_p;
16890 	uint32_t db_offset;
16891 	uint16_t pci_barset;
16892 	uint8_t dpp_barset;
16893 	uint32_t dpp_offset;
16894 	uint8_t wq_create_version;
16895 #ifdef CONFIG_X86
16896 	unsigned long pg_addr;
16897 #endif
16898 
16899 	/* sanity check on queue memory */
16900 	if (!wq || !cq)
16901 		return -ENODEV;
16902 	if (!phba->sli4_hba.pc_sli4_params.supported)
16903 		hw_page_size = wq->page_size;
16904 
16905 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16906 	if (!mbox)
16907 		return -ENOMEM;
16908 	length = (sizeof(struct lpfc_mbx_wq_create) -
16909 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16910 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16911 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16912 			 length, LPFC_SLI4_MBX_EMBED);
16913 	wq_create = &mbox->u.mqe.un.wq_create;
16914 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16915 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16916 		    wq->page_count);
16917 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16918 		    cq->queue_id);
16919 
16920 	/* wqv is the earliest version supported, NOT the latest */
16921 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16922 	       phba->sli4_hba.pc_sli4_params.wqv);
16923 
16924 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16925 	    (wq->page_size > SLI4_PAGE_SIZE))
16926 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
16927 	else
16928 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
16929 
16930 	switch (wq_create_version) {
16931 	case LPFC_Q_CREATE_VERSION_1:
16932 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
16933 		       wq->entry_count);
16934 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16935 		       LPFC_Q_CREATE_VERSION_1);
16936 
16937 		switch (wq->entry_size) {
16938 		default:
16939 		case 64:
16940 			bf_set(lpfc_mbx_wq_create_wqe_size,
16941 			       &wq_create->u.request_1,
16942 			       LPFC_WQ_WQE_SIZE_64);
16943 			break;
16944 		case 128:
16945 			bf_set(lpfc_mbx_wq_create_wqe_size,
16946 			       &wq_create->u.request_1,
16947 			       LPFC_WQ_WQE_SIZE_128);
16948 			break;
16949 		}
16950 		/* Request DPP by default */
16951 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
16952 		bf_set(lpfc_mbx_wq_create_page_size,
16953 		       &wq_create->u.request_1,
16954 		       (wq->page_size / SLI4_PAGE_SIZE));
16955 		page = wq_create->u.request_1.page;
16956 		break;
16957 	default:
16958 		page = wq_create->u.request.page;
16959 		break;
16960 	}
16961 
16962 	list_for_each_entry(dmabuf, &wq->page_list, list) {
16963 		memset(dmabuf->virt, 0, hw_page_size);
16964 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
16965 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
16966 	}
16967 
16968 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16969 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
16970 
16971 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16972 	/* The IOCTL status is embedded in the mailbox subheader. */
16973 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16974 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16975 	if (shdr_status || shdr_add_status || rc) {
16976 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16977 				"2503 WQ_CREATE mailbox failed with "
16978 				"status x%x add_status x%x, mbx status x%x\n",
16979 				shdr_status, shdr_add_status, rc);
16980 		status = -ENXIO;
16981 		goto out;
16982 	}
16983 
16984 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
16985 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
16986 					&wq_create->u.response);
16987 	else
16988 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
16989 					&wq_create->u.response_1);
16990 
16991 	if (wq->queue_id == 0xFFFF) {
16992 		status = -ENXIO;
16993 		goto out;
16994 	}
16995 
16996 	wq->db_format = LPFC_DB_LIST_FORMAT;
16997 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
16998 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16999 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
17000 					       &wq_create->u.response);
17001 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
17002 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
17003 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17004 						"3265 WQ[%d] doorbell format "
17005 						"not supported: x%x\n",
17006 						wq->queue_id, wq->db_format);
17007 				status = -EINVAL;
17008 				goto out;
17009 			}
17010 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
17011 					    &wq_create->u.response);
17012 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17013 								   pci_barset);
17014 			if (!bar_memmap_p) {
17015 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17016 						"3263 WQ[%d] failed to memmap "
17017 						"pci barset:x%x\n",
17018 						wq->queue_id, pci_barset);
17019 				status = -ENOMEM;
17020 				goto out;
17021 			}
17022 			db_offset = wq_create->u.response.doorbell_offset;
17023 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
17024 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
17025 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17026 						"3252 WQ[%d] doorbell offset "
17027 						"not supported: x%x\n",
17028 						wq->queue_id, db_offset);
17029 				status = -EINVAL;
17030 				goto out;
17031 			}
17032 			wq->db_regaddr = bar_memmap_p + db_offset;
17033 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17034 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
17035 					"format:x%x\n", wq->queue_id,
17036 					pci_barset, db_offset, wq->db_format);
17037 		} else
17038 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17039 	} else {
17040 		/* Check if DPP was honored by the firmware */
17041 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
17042 				    &wq_create->u.response_1);
17043 		if (wq->dpp_enable) {
17044 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
17045 					    &wq_create->u.response_1);
17046 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17047 								   pci_barset);
17048 			if (!bar_memmap_p) {
17049 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17050 						"3267 WQ[%d] failed to memmap "
17051 						"pci barset:x%x\n",
17052 						wq->queue_id, pci_barset);
17053 				status = -ENOMEM;
17054 				goto out;
17055 			}
17056 			db_offset = wq_create->u.response_1.doorbell_offset;
17057 			wq->db_regaddr = bar_memmap_p + db_offset;
17058 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
17059 					    &wq_create->u.response_1);
17060 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
17061 					    &wq_create->u.response_1);
17062 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17063 								   dpp_barset);
17064 			if (!bar_memmap_p) {
17065 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17066 						"3268 WQ[%d] failed to memmap "
17067 						"pci barset:x%x\n",
17068 						wq->queue_id, dpp_barset);
17069 				status = -ENOMEM;
17070 				goto out;
17071 			}
17072 			dpp_offset = wq_create->u.response_1.dpp_offset;
17073 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
17074 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17075 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
17076 					"dpp_id:x%x dpp_barset:x%x "
17077 					"dpp_offset:x%x\n",
17078 					wq->queue_id, pci_barset, db_offset,
17079 					wq->dpp_id, dpp_barset, dpp_offset);
17080 
17081 #ifdef CONFIG_X86
17082 			/* Enable combined writes for DPP aperture */
17083 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
17084 			rc = set_memory_wc(pg_addr, 1);
17085 			if (rc) {
17086 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17087 					"3272 Cannot setup Combined "
17088 					"Write on WQ[%d] - disable DPP\n",
17089 					wq->queue_id);
17090 				phba->cfg_enable_dpp = 0;
17091 			}
17092 #else
17093 			phba->cfg_enable_dpp = 0;
17094 #endif
17095 		} else
17096 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17097 	}
17098 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
17099 	if (wq->pring == NULL) {
17100 		status = -ENOMEM;
17101 		goto out;
17102 	}
17103 	wq->type = LPFC_WQ;
17104 	wq->assoc_qid = cq->queue_id;
17105 	wq->subtype = subtype;
17106 	wq->host_index = 0;
17107 	wq->hba_index = 0;
17108 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
17109 
17110 	/* link the wq onto the parent cq child list */
17111 	list_add_tail(&wq->list, &cq->child_list);
17112 out:
17113 	mempool_free(mbox, phba->mbox_mem_pool);
17114 	return status;
17115 }
17116 
17117 /**
17118  * lpfc_rq_create - Create a Receive Queue on the HBA
17119  * @phba: HBA structure that indicates port to create a queue on.
17120  * @hrq: The queue structure to use to create the header receive queue.
17121  * @drq: The queue structure to use to create the data receive queue.
17122  * @cq: The completion queue to bind this work queue to.
17123  * @subtype: The subtype of the work queue indicating its functionality.
17124  *
17125  * This function creates a receive buffer queue pair , as detailed in @hrq and
17126  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17127  * to the HBA.
17128  *
17129  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17130  * struct is used to get the entry count that is necessary to determine the
17131  * number of pages to use for this queue. The @cq is used to indicate which
17132  * completion queue to bind received buffers that are posted to these queues to.
17133  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17134  * receive queue pair. This function is asynchronous and will wait for the
17135  * mailbox command to finish before continuing.
17136  *
17137  * On success this function will return a zero. If unable to allocate enough
17138  * memory this function will return -ENOMEM. If the queue create mailbox command
17139  * fails this function will return -ENXIO.
17140  **/
17141 int
17142 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17143 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
17144 {
17145 	struct lpfc_mbx_rq_create *rq_create;
17146 	struct lpfc_dmabuf *dmabuf;
17147 	LPFC_MBOXQ_t *mbox;
17148 	int rc, length, status = 0;
17149 	uint32_t shdr_status, shdr_add_status;
17150 	union lpfc_sli4_cfg_shdr *shdr;
17151 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17152 	void __iomem *bar_memmap_p;
17153 	uint32_t db_offset;
17154 	uint16_t pci_barset;
17155 
17156 	/* sanity check on queue memory */
17157 	if (!hrq || !drq || !cq)
17158 		return -ENODEV;
17159 	if (!phba->sli4_hba.pc_sli4_params.supported)
17160 		hw_page_size = SLI4_PAGE_SIZE;
17161 
17162 	if (hrq->entry_count != drq->entry_count)
17163 		return -EINVAL;
17164 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17165 	if (!mbox)
17166 		return -ENOMEM;
17167 	length = (sizeof(struct lpfc_mbx_rq_create) -
17168 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17169 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17170 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17171 			 length, LPFC_SLI4_MBX_EMBED);
17172 	rq_create = &mbox->u.mqe.un.rq_create;
17173 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17174 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17175 	       phba->sli4_hba.pc_sli4_params.rqv);
17176 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17177 		bf_set(lpfc_rq_context_rqe_count_1,
17178 		       &rq_create->u.request.context,
17179 		       hrq->entry_count);
17180 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
17181 		bf_set(lpfc_rq_context_rqe_size,
17182 		       &rq_create->u.request.context,
17183 		       LPFC_RQE_SIZE_8);
17184 		bf_set(lpfc_rq_context_page_size,
17185 		       &rq_create->u.request.context,
17186 		       LPFC_RQ_PAGE_SIZE_4096);
17187 	} else {
17188 		switch (hrq->entry_count) {
17189 		default:
17190 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17191 					"2535 Unsupported RQ count. (%d)\n",
17192 					hrq->entry_count);
17193 			if (hrq->entry_count < 512) {
17194 				status = -EINVAL;
17195 				goto out;
17196 			}
17197 			fallthrough;	/* otherwise default to smallest count */
17198 		case 512:
17199 			bf_set(lpfc_rq_context_rqe_count,
17200 			       &rq_create->u.request.context,
17201 			       LPFC_RQ_RING_SIZE_512);
17202 			break;
17203 		case 1024:
17204 			bf_set(lpfc_rq_context_rqe_count,
17205 			       &rq_create->u.request.context,
17206 			       LPFC_RQ_RING_SIZE_1024);
17207 			break;
17208 		case 2048:
17209 			bf_set(lpfc_rq_context_rqe_count,
17210 			       &rq_create->u.request.context,
17211 			       LPFC_RQ_RING_SIZE_2048);
17212 			break;
17213 		case 4096:
17214 			bf_set(lpfc_rq_context_rqe_count,
17215 			       &rq_create->u.request.context,
17216 			       LPFC_RQ_RING_SIZE_4096);
17217 			break;
17218 		}
17219 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
17220 		       LPFC_HDR_BUF_SIZE);
17221 	}
17222 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17223 	       cq->queue_id);
17224 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17225 	       hrq->page_count);
17226 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
17227 		memset(dmabuf->virt, 0, hw_page_size);
17228 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17229 					putPaddrLow(dmabuf->phys);
17230 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17231 					putPaddrHigh(dmabuf->phys);
17232 	}
17233 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17234 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17235 
17236 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17237 	/* The IOCTL status is embedded in the mailbox subheader. */
17238 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17239 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17240 	if (shdr_status || shdr_add_status || rc) {
17241 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17242 				"2504 RQ_CREATE mailbox failed with "
17243 				"status x%x add_status x%x, mbx status x%x\n",
17244 				shdr_status, shdr_add_status, rc);
17245 		status = -ENXIO;
17246 		goto out;
17247 	}
17248 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17249 	if (hrq->queue_id == 0xFFFF) {
17250 		status = -ENXIO;
17251 		goto out;
17252 	}
17253 
17254 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
17255 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
17256 					&rq_create->u.response);
17257 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
17258 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
17259 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17260 					"3262 RQ [%d] doorbell format not "
17261 					"supported: x%x\n", hrq->queue_id,
17262 					hrq->db_format);
17263 			status = -EINVAL;
17264 			goto out;
17265 		}
17266 
17267 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
17268 				    &rq_create->u.response);
17269 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
17270 		if (!bar_memmap_p) {
17271 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17272 					"3269 RQ[%d] failed to memmap pci "
17273 					"barset:x%x\n", hrq->queue_id,
17274 					pci_barset);
17275 			status = -ENOMEM;
17276 			goto out;
17277 		}
17278 
17279 		db_offset = rq_create->u.response.doorbell_offset;
17280 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
17281 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
17282 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17283 					"3270 RQ[%d] doorbell offset not "
17284 					"supported: x%x\n", hrq->queue_id,
17285 					db_offset);
17286 			status = -EINVAL;
17287 			goto out;
17288 		}
17289 		hrq->db_regaddr = bar_memmap_p + db_offset;
17290 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17291 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
17292 				"format:x%x\n", hrq->queue_id, pci_barset,
17293 				db_offset, hrq->db_format);
17294 	} else {
17295 		hrq->db_format = LPFC_DB_RING_FORMAT;
17296 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17297 	}
17298 	hrq->type = LPFC_HRQ;
17299 	hrq->assoc_qid = cq->queue_id;
17300 	hrq->subtype = subtype;
17301 	hrq->host_index = 0;
17302 	hrq->hba_index = 0;
17303 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17304 
17305 	/* now create the data queue */
17306 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17307 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17308 			 length, LPFC_SLI4_MBX_EMBED);
17309 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17310 	       phba->sli4_hba.pc_sli4_params.rqv);
17311 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17312 		bf_set(lpfc_rq_context_rqe_count_1,
17313 		       &rq_create->u.request.context, hrq->entry_count);
17314 		if (subtype == LPFC_NVMET)
17315 			rq_create->u.request.context.buffer_size =
17316 				LPFC_NVMET_DATA_BUF_SIZE;
17317 		else
17318 			rq_create->u.request.context.buffer_size =
17319 				LPFC_DATA_BUF_SIZE;
17320 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
17321 		       LPFC_RQE_SIZE_8);
17322 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
17323 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
17324 	} else {
17325 		switch (drq->entry_count) {
17326 		default:
17327 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17328 					"2536 Unsupported RQ count. (%d)\n",
17329 					drq->entry_count);
17330 			if (drq->entry_count < 512) {
17331 				status = -EINVAL;
17332 				goto out;
17333 			}
17334 			fallthrough;	/* otherwise default to smallest count */
17335 		case 512:
17336 			bf_set(lpfc_rq_context_rqe_count,
17337 			       &rq_create->u.request.context,
17338 			       LPFC_RQ_RING_SIZE_512);
17339 			break;
17340 		case 1024:
17341 			bf_set(lpfc_rq_context_rqe_count,
17342 			       &rq_create->u.request.context,
17343 			       LPFC_RQ_RING_SIZE_1024);
17344 			break;
17345 		case 2048:
17346 			bf_set(lpfc_rq_context_rqe_count,
17347 			       &rq_create->u.request.context,
17348 			       LPFC_RQ_RING_SIZE_2048);
17349 			break;
17350 		case 4096:
17351 			bf_set(lpfc_rq_context_rqe_count,
17352 			       &rq_create->u.request.context,
17353 			       LPFC_RQ_RING_SIZE_4096);
17354 			break;
17355 		}
17356 		if (subtype == LPFC_NVMET)
17357 			bf_set(lpfc_rq_context_buf_size,
17358 			       &rq_create->u.request.context,
17359 			       LPFC_NVMET_DATA_BUF_SIZE);
17360 		else
17361 			bf_set(lpfc_rq_context_buf_size,
17362 			       &rq_create->u.request.context,
17363 			       LPFC_DATA_BUF_SIZE);
17364 	}
17365 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17366 	       cq->queue_id);
17367 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17368 	       drq->page_count);
17369 	list_for_each_entry(dmabuf, &drq->page_list, list) {
17370 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17371 					putPaddrLow(dmabuf->phys);
17372 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17373 					putPaddrHigh(dmabuf->phys);
17374 	}
17375 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17376 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17377 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17378 	/* The IOCTL status is embedded in the mailbox subheader. */
17379 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17380 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17381 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17382 	if (shdr_status || shdr_add_status || rc) {
17383 		status = -ENXIO;
17384 		goto out;
17385 	}
17386 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17387 	if (drq->queue_id == 0xFFFF) {
17388 		status = -ENXIO;
17389 		goto out;
17390 	}
17391 	drq->type = LPFC_DRQ;
17392 	drq->assoc_qid = cq->queue_id;
17393 	drq->subtype = subtype;
17394 	drq->host_index = 0;
17395 	drq->hba_index = 0;
17396 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17397 
17398 	/* link the header and data RQs onto the parent cq child list */
17399 	list_add_tail(&hrq->list, &cq->child_list);
17400 	list_add_tail(&drq->list, &cq->child_list);
17401 
17402 out:
17403 	mempool_free(mbox, phba->mbox_mem_pool);
17404 	return status;
17405 }
17406 
17407 /**
17408  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
17409  * @phba: HBA structure that indicates port to create a queue on.
17410  * @hrqp: The queue structure array to use to create the header receive queues.
17411  * @drqp: The queue structure array to use to create the data receive queues.
17412  * @cqp: The completion queue array to bind these receive queues to.
17413  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
17414  *
17415  * This function creates a receive buffer queue pair , as detailed in @hrq and
17416  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17417  * to the HBA.
17418  *
17419  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17420  * struct is used to get the entry count that is necessary to determine the
17421  * number of pages to use for this queue. The @cq is used to indicate which
17422  * completion queue to bind received buffers that are posted to these queues to.
17423  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17424  * receive queue pair. This function is asynchronous and will wait for the
17425  * mailbox command to finish before continuing.
17426  *
17427  * On success this function will return a zero. If unable to allocate enough
17428  * memory this function will return -ENOMEM. If the queue create mailbox command
17429  * fails this function will return -ENXIO.
17430  **/
17431 int
17432 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
17433 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
17434 		uint32_t subtype)
17435 {
17436 	struct lpfc_queue *hrq, *drq, *cq;
17437 	struct lpfc_mbx_rq_create_v2 *rq_create;
17438 	struct lpfc_dmabuf *dmabuf;
17439 	LPFC_MBOXQ_t *mbox;
17440 	int rc, length, alloclen, status = 0;
17441 	int cnt, idx, numrq, page_idx = 0;
17442 	uint32_t shdr_status, shdr_add_status;
17443 	union lpfc_sli4_cfg_shdr *shdr;
17444 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17445 
17446 	numrq = phba->cfg_nvmet_mrq;
17447 	/* sanity check on array memory */
17448 	if (!hrqp || !drqp || !cqp || !numrq)
17449 		return -ENODEV;
17450 	if (!phba->sli4_hba.pc_sli4_params.supported)
17451 		hw_page_size = SLI4_PAGE_SIZE;
17452 
17453 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17454 	if (!mbox)
17455 		return -ENOMEM;
17456 
17457 	length = sizeof(struct lpfc_mbx_rq_create_v2);
17458 	length += ((2 * numrq * hrqp[0]->page_count) *
17459 		   sizeof(struct dma_address));
17460 
17461 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17462 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
17463 				    LPFC_SLI4_MBX_NEMBED);
17464 	if (alloclen < length) {
17465 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17466 				"3099 Allocated DMA memory size (%d) is "
17467 				"less than the requested DMA memory size "
17468 				"(%d)\n", alloclen, length);
17469 		status = -ENOMEM;
17470 		goto out;
17471 	}
17472 
17473 
17474 
17475 	rq_create = mbox->sge_array->addr[0];
17476 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
17477 
17478 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
17479 	cnt = 0;
17480 
17481 	for (idx = 0; idx < numrq; idx++) {
17482 		hrq = hrqp[idx];
17483 		drq = drqp[idx];
17484 		cq  = cqp[idx];
17485 
17486 		/* sanity check on queue memory */
17487 		if (!hrq || !drq || !cq) {
17488 			status = -ENODEV;
17489 			goto out;
17490 		}
17491 
17492 		if (hrq->entry_count != drq->entry_count) {
17493 			status = -EINVAL;
17494 			goto out;
17495 		}
17496 
17497 		if (idx == 0) {
17498 			bf_set(lpfc_mbx_rq_create_num_pages,
17499 			       &rq_create->u.request,
17500 			       hrq->page_count);
17501 			bf_set(lpfc_mbx_rq_create_rq_cnt,
17502 			       &rq_create->u.request, (numrq * 2));
17503 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
17504 			       1);
17505 			bf_set(lpfc_rq_context_base_cq,
17506 			       &rq_create->u.request.context,
17507 			       cq->queue_id);
17508 			bf_set(lpfc_rq_context_data_size,
17509 			       &rq_create->u.request.context,
17510 			       LPFC_NVMET_DATA_BUF_SIZE);
17511 			bf_set(lpfc_rq_context_hdr_size,
17512 			       &rq_create->u.request.context,
17513 			       LPFC_HDR_BUF_SIZE);
17514 			bf_set(lpfc_rq_context_rqe_count_1,
17515 			       &rq_create->u.request.context,
17516 			       hrq->entry_count);
17517 			bf_set(lpfc_rq_context_rqe_size,
17518 			       &rq_create->u.request.context,
17519 			       LPFC_RQE_SIZE_8);
17520 			bf_set(lpfc_rq_context_page_size,
17521 			       &rq_create->u.request.context,
17522 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
17523 		}
17524 		rc = 0;
17525 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
17526 			memset(dmabuf->virt, 0, hw_page_size);
17527 			cnt = page_idx + dmabuf->buffer_tag;
17528 			rq_create->u.request.page[cnt].addr_lo =
17529 					putPaddrLow(dmabuf->phys);
17530 			rq_create->u.request.page[cnt].addr_hi =
17531 					putPaddrHigh(dmabuf->phys);
17532 			rc++;
17533 		}
17534 		page_idx += rc;
17535 
17536 		rc = 0;
17537 		list_for_each_entry(dmabuf, &drq->page_list, list) {
17538 			memset(dmabuf->virt, 0, hw_page_size);
17539 			cnt = page_idx + dmabuf->buffer_tag;
17540 			rq_create->u.request.page[cnt].addr_lo =
17541 					putPaddrLow(dmabuf->phys);
17542 			rq_create->u.request.page[cnt].addr_hi =
17543 					putPaddrHigh(dmabuf->phys);
17544 			rc++;
17545 		}
17546 		page_idx += rc;
17547 
17548 		hrq->db_format = LPFC_DB_RING_FORMAT;
17549 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17550 		hrq->type = LPFC_HRQ;
17551 		hrq->assoc_qid = cq->queue_id;
17552 		hrq->subtype = subtype;
17553 		hrq->host_index = 0;
17554 		hrq->hba_index = 0;
17555 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17556 
17557 		drq->db_format = LPFC_DB_RING_FORMAT;
17558 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17559 		drq->type = LPFC_DRQ;
17560 		drq->assoc_qid = cq->queue_id;
17561 		drq->subtype = subtype;
17562 		drq->host_index = 0;
17563 		drq->hba_index = 0;
17564 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17565 
17566 		list_add_tail(&hrq->list, &cq->child_list);
17567 		list_add_tail(&drq->list, &cq->child_list);
17568 	}
17569 
17570 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17571 	/* The IOCTL status is embedded in the mailbox subheader. */
17572 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17573 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17574 	if (shdr_status || shdr_add_status || rc) {
17575 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17576 				"3120 RQ_CREATE mailbox failed with "
17577 				"status x%x add_status x%x, mbx status x%x\n",
17578 				shdr_status, shdr_add_status, rc);
17579 		status = -ENXIO;
17580 		goto out;
17581 	}
17582 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17583 	if (rc == 0xFFFF) {
17584 		status = -ENXIO;
17585 		goto out;
17586 	}
17587 
17588 	/* Initialize all RQs with associated queue id */
17589 	for (idx = 0; idx < numrq; idx++) {
17590 		hrq = hrqp[idx];
17591 		hrq->queue_id = rc + (2 * idx);
17592 		drq = drqp[idx];
17593 		drq->queue_id = rc + (2 * idx) + 1;
17594 	}
17595 
17596 out:
17597 	lpfc_sli4_mbox_cmd_free(phba, mbox);
17598 	return status;
17599 }
17600 
17601 /**
17602  * lpfc_eq_destroy - Destroy an event Queue on the HBA
17603  * @phba: HBA structure that indicates port to destroy a queue on.
17604  * @eq: The queue structure associated with the queue to destroy.
17605  *
17606  * This function destroys a queue, as detailed in @eq by sending an mailbox
17607  * command, specific to the type of queue, to the HBA.
17608  *
17609  * The @eq struct is used to get the queue ID of the queue to destroy.
17610  *
17611  * On success this function will return a zero. If the queue destroy mailbox
17612  * command fails this function will return -ENXIO.
17613  **/
17614 int
17615 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
17616 {
17617 	LPFC_MBOXQ_t *mbox;
17618 	int rc, length, status = 0;
17619 	uint32_t shdr_status, shdr_add_status;
17620 	union lpfc_sli4_cfg_shdr *shdr;
17621 
17622 	/* sanity check on queue memory */
17623 	if (!eq)
17624 		return -ENODEV;
17625 
17626 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
17627 	if (!mbox)
17628 		return -ENOMEM;
17629 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
17630 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17631 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17632 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
17633 			 length, LPFC_SLI4_MBX_EMBED);
17634 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
17635 	       eq->queue_id);
17636 	mbox->vport = eq->phba->pport;
17637 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17638 
17639 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
17640 	/* The IOCTL status is embedded in the mailbox subheader. */
17641 	shdr = (union lpfc_sli4_cfg_shdr *)
17642 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
17643 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17644 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17645 	if (shdr_status || shdr_add_status || rc) {
17646 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17647 				"2505 EQ_DESTROY mailbox failed with "
17648 				"status x%x add_status x%x, mbx status x%x\n",
17649 				shdr_status, shdr_add_status, rc);
17650 		status = -ENXIO;
17651 	}
17652 
17653 	/* Remove eq from any list */
17654 	list_del_init(&eq->list);
17655 	mempool_free(mbox, eq->phba->mbox_mem_pool);
17656 	return status;
17657 }
17658 
17659 /**
17660  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
17661  * @phba: HBA structure that indicates port to destroy a queue on.
17662  * @cq: The queue structure associated with the queue to destroy.
17663  *
17664  * This function destroys a queue, as detailed in @cq by sending an mailbox
17665  * command, specific to the type of queue, to the HBA.
17666  *
17667  * The @cq struct is used to get the queue ID of the queue to destroy.
17668  *
17669  * On success this function will return a zero. If the queue destroy mailbox
17670  * command fails this function will return -ENXIO.
17671  **/
17672 int
17673 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
17674 {
17675 	LPFC_MBOXQ_t *mbox;
17676 	int rc, length, status = 0;
17677 	uint32_t shdr_status, shdr_add_status;
17678 	union lpfc_sli4_cfg_shdr *shdr;
17679 
17680 	/* sanity check on queue memory */
17681 	if (!cq)
17682 		return -ENODEV;
17683 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
17684 	if (!mbox)
17685 		return -ENOMEM;
17686 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
17687 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17688 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17689 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
17690 			 length, LPFC_SLI4_MBX_EMBED);
17691 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
17692 	       cq->queue_id);
17693 	mbox->vport = cq->phba->pport;
17694 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17695 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
17696 	/* The IOCTL status is embedded in the mailbox subheader. */
17697 	shdr = (union lpfc_sli4_cfg_shdr *)
17698 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
17699 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17700 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17701 	if (shdr_status || shdr_add_status || rc) {
17702 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17703 				"2506 CQ_DESTROY mailbox failed with "
17704 				"status x%x add_status x%x, mbx status x%x\n",
17705 				shdr_status, shdr_add_status, rc);
17706 		status = -ENXIO;
17707 	}
17708 	/* Remove cq from any list */
17709 	list_del_init(&cq->list);
17710 	mempool_free(mbox, cq->phba->mbox_mem_pool);
17711 	return status;
17712 }
17713 
17714 /**
17715  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
17716  * @phba: HBA structure that indicates port to destroy a queue on.
17717  * @mq: The queue structure associated with the queue to destroy.
17718  *
17719  * This function destroys a queue, as detailed in @mq by sending an mailbox
17720  * command, specific to the type of queue, to the HBA.
17721  *
17722  * The @mq struct is used to get the queue ID of the queue to destroy.
17723  *
17724  * On success this function will return a zero. If the queue destroy mailbox
17725  * command fails this function will return -ENXIO.
17726  **/
17727 int
17728 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
17729 {
17730 	LPFC_MBOXQ_t *mbox;
17731 	int rc, length, status = 0;
17732 	uint32_t shdr_status, shdr_add_status;
17733 	union lpfc_sli4_cfg_shdr *shdr;
17734 
17735 	/* sanity check on queue memory */
17736 	if (!mq)
17737 		return -ENODEV;
17738 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
17739 	if (!mbox)
17740 		return -ENOMEM;
17741 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
17742 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17743 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17744 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
17745 			 length, LPFC_SLI4_MBX_EMBED);
17746 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
17747 	       mq->queue_id);
17748 	mbox->vport = mq->phba->pport;
17749 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17750 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
17751 	/* The IOCTL status is embedded in the mailbox subheader. */
17752 	shdr = (union lpfc_sli4_cfg_shdr *)
17753 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
17754 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17755 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17756 	if (shdr_status || shdr_add_status || rc) {
17757 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17758 				"2507 MQ_DESTROY mailbox failed with "
17759 				"status x%x add_status x%x, mbx status x%x\n",
17760 				shdr_status, shdr_add_status, rc);
17761 		status = -ENXIO;
17762 	}
17763 	/* Remove mq from any list */
17764 	list_del_init(&mq->list);
17765 	mempool_free(mbox, mq->phba->mbox_mem_pool);
17766 	return status;
17767 }
17768 
17769 /**
17770  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
17771  * @phba: HBA structure that indicates port to destroy a queue on.
17772  * @wq: The queue structure associated with the queue to destroy.
17773  *
17774  * This function destroys a queue, as detailed in @wq by sending an mailbox
17775  * command, specific to the type of queue, to the HBA.
17776  *
17777  * The @wq struct is used to get the queue ID of the queue to destroy.
17778  *
17779  * On success this function will return a zero. If the queue destroy mailbox
17780  * command fails this function will return -ENXIO.
17781  **/
17782 int
17783 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
17784 {
17785 	LPFC_MBOXQ_t *mbox;
17786 	int rc, length, status = 0;
17787 	uint32_t shdr_status, shdr_add_status;
17788 	union lpfc_sli4_cfg_shdr *shdr;
17789 
17790 	/* sanity check on queue memory */
17791 	if (!wq)
17792 		return -ENODEV;
17793 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17794 	if (!mbox)
17795 		return -ENOMEM;
17796 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
17797 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17798 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17799 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17800 			 length, LPFC_SLI4_MBX_EMBED);
17801 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17802 	       wq->queue_id);
17803 	mbox->vport = wq->phba->pport;
17804 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17805 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17806 	shdr = (union lpfc_sli4_cfg_shdr *)
17807 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17808 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17809 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17810 	if (shdr_status || shdr_add_status || rc) {
17811 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17812 				"2508 WQ_DESTROY mailbox failed with "
17813 				"status x%x add_status x%x, mbx status x%x\n",
17814 				shdr_status, shdr_add_status, rc);
17815 		status = -ENXIO;
17816 	}
17817 	/* Remove wq from any list */
17818 	list_del_init(&wq->list);
17819 	kfree(wq->pring);
17820 	wq->pring = NULL;
17821 	mempool_free(mbox, wq->phba->mbox_mem_pool);
17822 	return status;
17823 }
17824 
17825 /**
17826  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17827  * @phba: HBA structure that indicates port to destroy a queue on.
17828  * @hrq: The queue structure associated with the queue to destroy.
17829  * @drq: The queue structure associated with the queue to destroy.
17830  *
17831  * This function destroys a queue, as detailed in @rq by sending an mailbox
17832  * command, specific to the type of queue, to the HBA.
17833  *
17834  * The @rq struct is used to get the queue ID of the queue to destroy.
17835  *
17836  * On success this function will return a zero. If the queue destroy mailbox
17837  * command fails this function will return -ENXIO.
17838  **/
17839 int
17840 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17841 		struct lpfc_queue *drq)
17842 {
17843 	LPFC_MBOXQ_t *mbox;
17844 	int rc, length, status = 0;
17845 	uint32_t shdr_status, shdr_add_status;
17846 	union lpfc_sli4_cfg_shdr *shdr;
17847 
17848 	/* sanity check on queue memory */
17849 	if (!hrq || !drq)
17850 		return -ENODEV;
17851 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17852 	if (!mbox)
17853 		return -ENOMEM;
17854 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
17855 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17856 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17857 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17858 			 length, LPFC_SLI4_MBX_EMBED);
17859 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17860 	       hrq->queue_id);
17861 	mbox->vport = hrq->phba->pport;
17862 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17863 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17864 	/* The IOCTL status is embedded in the mailbox subheader. */
17865 	shdr = (union lpfc_sli4_cfg_shdr *)
17866 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17867 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17868 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17869 	if (shdr_status || shdr_add_status || rc) {
17870 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17871 				"2509 RQ_DESTROY mailbox failed with "
17872 				"status x%x add_status x%x, mbx status x%x\n",
17873 				shdr_status, shdr_add_status, rc);
17874 		mempool_free(mbox, hrq->phba->mbox_mem_pool);
17875 		return -ENXIO;
17876 	}
17877 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17878 	       drq->queue_id);
17879 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17880 	shdr = (union lpfc_sli4_cfg_shdr *)
17881 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17882 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17883 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17884 	if (shdr_status || shdr_add_status || rc) {
17885 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17886 				"2510 RQ_DESTROY mailbox failed with "
17887 				"status x%x add_status x%x, mbx status x%x\n",
17888 				shdr_status, shdr_add_status, rc);
17889 		status = -ENXIO;
17890 	}
17891 	list_del_init(&hrq->list);
17892 	list_del_init(&drq->list);
17893 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
17894 	return status;
17895 }
17896 
17897 /**
17898  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17899  * @phba: The virtual port for which this call being executed.
17900  * @pdma_phys_addr0: Physical address of the 1st SGL page.
17901  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
17902  * @xritag: the xritag that ties this io to the SGL pages.
17903  *
17904  * This routine will post the sgl pages for the IO that has the xritag
17905  * that is in the iocbq structure. The xritag is assigned during iocbq
17906  * creation and persists for as long as the driver is loaded.
17907  * if the caller has fewer than 256 scatter gather segments to map then
17908  * pdma_phys_addr1 should be 0.
17909  * If the caller needs to map more than 256 scatter gather segment then
17910  * pdma_phys_addr1 should be a valid physical address.
17911  * physical address for SGLs must be 64 byte aligned.
17912  * If you are going to map 2 SGL's then the first one must have 256 entries
17913  * the second sgl can have between 1 and 256 entries.
17914  *
17915  * Return codes:
17916  * 	0 - Success
17917  * 	-ENXIO, -ENOMEM - Failure
17918  **/
17919 int
17920 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
17921 		dma_addr_t pdma_phys_addr0,
17922 		dma_addr_t pdma_phys_addr1,
17923 		uint16_t xritag)
17924 {
17925 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
17926 	LPFC_MBOXQ_t *mbox;
17927 	int rc;
17928 	uint32_t shdr_status, shdr_add_status;
17929 	uint32_t mbox_tmo;
17930 	union lpfc_sli4_cfg_shdr *shdr;
17931 
17932 	if (xritag == NO_XRI) {
17933 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17934 				"0364 Invalid param:\n");
17935 		return -EINVAL;
17936 	}
17937 
17938 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17939 	if (!mbox)
17940 		return -ENOMEM;
17941 
17942 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17943 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17944 			sizeof(struct lpfc_mbx_post_sgl_pages) -
17945 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17946 
17947 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
17948 				&mbox->u.mqe.un.post_sgl_pages;
17949 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
17950 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
17951 
17952 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
17953 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
17954 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
17955 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
17956 
17957 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
17958 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
17959 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
17960 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
17961 	if (!phba->sli4_hba.intr_enable)
17962 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17963 	else {
17964 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17965 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17966 	}
17967 	/* The IOCTL status is embedded in the mailbox subheader. */
17968 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
17969 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17970 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17971 	if (!phba->sli4_hba.intr_enable)
17972 		mempool_free(mbox, phba->mbox_mem_pool);
17973 	else if (rc != MBX_TIMEOUT)
17974 		mempool_free(mbox, phba->mbox_mem_pool);
17975 	if (shdr_status || shdr_add_status || rc) {
17976 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17977 				"2511 POST_SGL mailbox failed with "
17978 				"status x%x add_status x%x, mbx status x%x\n",
17979 				shdr_status, shdr_add_status, rc);
17980 	}
17981 	return 0;
17982 }
17983 
17984 /**
17985  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
17986  * @phba: pointer to lpfc hba data structure.
17987  *
17988  * This routine is invoked to post rpi header templates to the
17989  * HBA consistent with the SLI-4 interface spec.  This routine
17990  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
17991  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
17992  *
17993  * Returns
17994  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
17995  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
17996  **/
17997 static uint16_t
17998 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
17999 {
18000 	unsigned long xri;
18001 
18002 	/*
18003 	 * Fetch the next logical xri.  Because this index is logical,
18004 	 * the driver starts at 0 each time.
18005 	 */
18006 	spin_lock_irq(&phba->hbalock);
18007 	xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
18008 				 phba->sli4_hba.max_cfg_param.max_xri, 0);
18009 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
18010 		spin_unlock_irq(&phba->hbalock);
18011 		return NO_XRI;
18012 	} else {
18013 		set_bit(xri, phba->sli4_hba.xri_bmask);
18014 		phba->sli4_hba.max_cfg_param.xri_used++;
18015 	}
18016 	spin_unlock_irq(&phba->hbalock);
18017 	return xri;
18018 }
18019 
18020 /**
18021  * __lpfc_sli4_free_xri - Release an xri for reuse.
18022  * @phba: pointer to lpfc hba data structure.
18023  * @xri: xri to release.
18024  *
18025  * This routine is invoked to release an xri to the pool of
18026  * available rpis maintained by the driver.
18027  **/
18028 static void
18029 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18030 {
18031 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
18032 		phba->sli4_hba.max_cfg_param.xri_used--;
18033 	}
18034 }
18035 
18036 /**
18037  * lpfc_sli4_free_xri - Release an xri for reuse.
18038  * @phba: pointer to lpfc hba data structure.
18039  * @xri: xri to release.
18040  *
18041  * This routine is invoked to release an xri to the pool of
18042  * available rpis maintained by the driver.
18043  **/
18044 void
18045 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18046 {
18047 	spin_lock_irq(&phba->hbalock);
18048 	__lpfc_sli4_free_xri(phba, xri);
18049 	spin_unlock_irq(&phba->hbalock);
18050 }
18051 
18052 /**
18053  * lpfc_sli4_next_xritag - Get an xritag for the io
18054  * @phba: Pointer to HBA context object.
18055  *
18056  * This function gets an xritag for the iocb. If there is no unused xritag
18057  * it will return 0xffff.
18058  * The function returns the allocated xritag if successful, else returns zero.
18059  * Zero is not a valid xritag.
18060  * The caller is not required to hold any lock.
18061  **/
18062 uint16_t
18063 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
18064 {
18065 	uint16_t xri_index;
18066 
18067 	xri_index = lpfc_sli4_alloc_xri(phba);
18068 	if (xri_index == NO_XRI)
18069 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18070 				"2004 Failed to allocate XRI.last XRITAG is %d"
18071 				" Max XRI is %d, Used XRI is %d\n",
18072 				xri_index,
18073 				phba->sli4_hba.max_cfg_param.max_xri,
18074 				phba->sli4_hba.max_cfg_param.xri_used);
18075 	return xri_index;
18076 }
18077 
18078 /**
18079  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
18080  * @phba: pointer to lpfc hba data structure.
18081  * @post_sgl_list: pointer to els sgl entry list.
18082  * @post_cnt: number of els sgl entries on the list.
18083  *
18084  * This routine is invoked to post a block of driver's sgl pages to the
18085  * HBA using non-embedded mailbox command. No Lock is held. This routine
18086  * is only called when the driver is loading and after all IO has been
18087  * stopped.
18088  **/
18089 static int
18090 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
18091 			    struct list_head *post_sgl_list,
18092 			    int post_cnt)
18093 {
18094 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
18095 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18096 	struct sgl_page_pairs *sgl_pg_pairs;
18097 	void *viraddr;
18098 	LPFC_MBOXQ_t *mbox;
18099 	uint32_t reqlen, alloclen, pg_pairs;
18100 	uint32_t mbox_tmo;
18101 	uint16_t xritag_start = 0;
18102 	int rc = 0;
18103 	uint32_t shdr_status, shdr_add_status;
18104 	union lpfc_sli4_cfg_shdr *shdr;
18105 
18106 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
18107 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18108 	if (reqlen > SLI4_PAGE_SIZE) {
18109 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18110 				"2559 Block sgl registration required DMA "
18111 				"size (%d) great than a page\n", reqlen);
18112 		return -ENOMEM;
18113 	}
18114 
18115 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18116 	if (!mbox)
18117 		return -ENOMEM;
18118 
18119 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18120 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18121 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
18122 			 LPFC_SLI4_MBX_NEMBED);
18123 
18124 	if (alloclen < reqlen) {
18125 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18126 				"0285 Allocated DMA memory size (%d) is "
18127 				"less than the requested DMA memory "
18128 				"size (%d)\n", alloclen, reqlen);
18129 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18130 		return -ENOMEM;
18131 	}
18132 	/* Set up the SGL pages in the non-embedded DMA pages */
18133 	viraddr = mbox->sge_array->addr[0];
18134 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18135 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18136 
18137 	pg_pairs = 0;
18138 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
18139 		/* Set up the sge entry */
18140 		sgl_pg_pairs->sgl_pg0_addr_lo =
18141 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
18142 		sgl_pg_pairs->sgl_pg0_addr_hi =
18143 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
18144 		sgl_pg_pairs->sgl_pg1_addr_lo =
18145 				cpu_to_le32(putPaddrLow(0));
18146 		sgl_pg_pairs->sgl_pg1_addr_hi =
18147 				cpu_to_le32(putPaddrHigh(0));
18148 
18149 		/* Keep the first xritag on the list */
18150 		if (pg_pairs == 0)
18151 			xritag_start = sglq_entry->sli4_xritag;
18152 		sgl_pg_pairs++;
18153 		pg_pairs++;
18154 	}
18155 
18156 	/* Complete initialization and perform endian conversion. */
18157 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18158 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
18159 	sgl->word0 = cpu_to_le32(sgl->word0);
18160 
18161 	if (!phba->sli4_hba.intr_enable)
18162 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18163 	else {
18164 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18165 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18166 	}
18167 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
18168 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18169 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18170 	if (!phba->sli4_hba.intr_enable)
18171 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18172 	else if (rc != MBX_TIMEOUT)
18173 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18174 	if (shdr_status || shdr_add_status || rc) {
18175 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18176 				"2513 POST_SGL_BLOCK mailbox command failed "
18177 				"status x%x add_status x%x mbx status x%x\n",
18178 				shdr_status, shdr_add_status, rc);
18179 		rc = -ENXIO;
18180 	}
18181 	return rc;
18182 }
18183 
18184 /**
18185  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
18186  * @phba: pointer to lpfc hba data structure.
18187  * @nblist: pointer to nvme buffer list.
18188  * @count: number of scsi buffers on the list.
18189  *
18190  * This routine is invoked to post a block of @count scsi sgl pages from a
18191  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
18192  * No Lock is held.
18193  *
18194  **/
18195 static int
18196 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
18197 			    int count)
18198 {
18199 	struct lpfc_io_buf *lpfc_ncmd;
18200 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18201 	struct sgl_page_pairs *sgl_pg_pairs;
18202 	void *viraddr;
18203 	LPFC_MBOXQ_t *mbox;
18204 	uint32_t reqlen, alloclen, pg_pairs;
18205 	uint32_t mbox_tmo;
18206 	uint16_t xritag_start = 0;
18207 	int rc = 0;
18208 	uint32_t shdr_status, shdr_add_status;
18209 	dma_addr_t pdma_phys_bpl1;
18210 	union lpfc_sli4_cfg_shdr *shdr;
18211 
18212 	/* Calculate the requested length of the dma memory */
18213 	reqlen = count * sizeof(struct sgl_page_pairs) +
18214 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18215 	if (reqlen > SLI4_PAGE_SIZE) {
18216 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
18217 				"6118 Block sgl registration required DMA "
18218 				"size (%d) great than a page\n", reqlen);
18219 		return -ENOMEM;
18220 	}
18221 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18222 	if (!mbox) {
18223 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18224 				"6119 Failed to allocate mbox cmd memory\n");
18225 		return -ENOMEM;
18226 	}
18227 
18228 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18229 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18230 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
18231 				    reqlen, LPFC_SLI4_MBX_NEMBED);
18232 
18233 	if (alloclen < reqlen) {
18234 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18235 				"6120 Allocated DMA memory size (%d) is "
18236 				"less than the requested DMA memory "
18237 				"size (%d)\n", alloclen, reqlen);
18238 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18239 		return -ENOMEM;
18240 	}
18241 
18242 	/* Get the first SGE entry from the non-embedded DMA memory */
18243 	viraddr = mbox->sge_array->addr[0];
18244 
18245 	/* Set up the SGL pages in the non-embedded DMA pages */
18246 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18247 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18248 
18249 	pg_pairs = 0;
18250 	list_for_each_entry(lpfc_ncmd, nblist, list) {
18251 		/* Set up the sge entry */
18252 		sgl_pg_pairs->sgl_pg0_addr_lo =
18253 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
18254 		sgl_pg_pairs->sgl_pg0_addr_hi =
18255 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
18256 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
18257 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
18258 						SGL_PAGE_SIZE;
18259 		else
18260 			pdma_phys_bpl1 = 0;
18261 		sgl_pg_pairs->sgl_pg1_addr_lo =
18262 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
18263 		sgl_pg_pairs->sgl_pg1_addr_hi =
18264 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
18265 		/* Keep the first xritag on the list */
18266 		if (pg_pairs == 0)
18267 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
18268 		sgl_pg_pairs++;
18269 		pg_pairs++;
18270 	}
18271 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18272 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
18273 	/* Perform endian conversion if necessary */
18274 	sgl->word0 = cpu_to_le32(sgl->word0);
18275 
18276 	if (!phba->sli4_hba.intr_enable) {
18277 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18278 	} else {
18279 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18280 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18281 	}
18282 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
18283 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18284 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18285 	if (!phba->sli4_hba.intr_enable)
18286 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18287 	else if (rc != MBX_TIMEOUT)
18288 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18289 	if (shdr_status || shdr_add_status || rc) {
18290 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18291 				"6125 POST_SGL_BLOCK mailbox command failed "
18292 				"status x%x add_status x%x mbx status x%x\n",
18293 				shdr_status, shdr_add_status, rc);
18294 		rc = -ENXIO;
18295 	}
18296 	return rc;
18297 }
18298 
18299 /**
18300  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
18301  * @phba: pointer to lpfc hba data structure.
18302  * @post_nblist: pointer to the nvme buffer list.
18303  * @sb_count: number of nvme buffers.
18304  *
18305  * This routine walks a list of nvme buffers that was passed in. It attempts
18306  * to construct blocks of nvme buffer sgls which contains contiguous xris and
18307  * uses the non-embedded SGL block post mailbox commands to post to the port.
18308  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
18309  * embedded SGL post mailbox command for posting. The @post_nblist passed in
18310  * must be local list, thus no lock is needed when manipulate the list.
18311  *
18312  * Returns: 0 = failure, non-zero number of successfully posted buffers.
18313  **/
18314 int
18315 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
18316 			   struct list_head *post_nblist, int sb_count)
18317 {
18318 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
18319 	int status, sgl_size;
18320 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
18321 	dma_addr_t pdma_phys_sgl1;
18322 	int last_xritag = NO_XRI;
18323 	int cur_xritag;
18324 	LIST_HEAD(prep_nblist);
18325 	LIST_HEAD(blck_nblist);
18326 	LIST_HEAD(nvme_nblist);
18327 
18328 	/* sanity check */
18329 	if (sb_count <= 0)
18330 		return -EINVAL;
18331 
18332 	sgl_size = phba->cfg_sg_dma_buf_size;
18333 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
18334 		list_del_init(&lpfc_ncmd->list);
18335 		block_cnt++;
18336 		if ((last_xritag != NO_XRI) &&
18337 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
18338 			/* a hole in xri block, form a sgl posting block */
18339 			list_splice_init(&prep_nblist, &blck_nblist);
18340 			post_cnt = block_cnt - 1;
18341 			/* prepare list for next posting block */
18342 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18343 			block_cnt = 1;
18344 		} else {
18345 			/* prepare list for next posting block */
18346 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18347 			/* enough sgls for non-embed sgl mbox command */
18348 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
18349 				list_splice_init(&prep_nblist, &blck_nblist);
18350 				post_cnt = block_cnt;
18351 				block_cnt = 0;
18352 			}
18353 		}
18354 		num_posting++;
18355 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18356 
18357 		/* end of repost sgl list condition for NVME buffers */
18358 		if (num_posting == sb_count) {
18359 			if (post_cnt == 0) {
18360 				/* last sgl posting block */
18361 				list_splice_init(&prep_nblist, &blck_nblist);
18362 				post_cnt = block_cnt;
18363 			} else if (block_cnt == 1) {
18364 				/* last single sgl with non-contiguous xri */
18365 				if (sgl_size > SGL_PAGE_SIZE)
18366 					pdma_phys_sgl1 =
18367 						lpfc_ncmd->dma_phys_sgl +
18368 						SGL_PAGE_SIZE;
18369 				else
18370 					pdma_phys_sgl1 = 0;
18371 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18372 				status = lpfc_sli4_post_sgl(
18373 						phba, lpfc_ncmd->dma_phys_sgl,
18374 						pdma_phys_sgl1, cur_xritag);
18375 				if (status) {
18376 					/* Post error.  Buffer unavailable. */
18377 					lpfc_ncmd->flags |=
18378 						LPFC_SBUF_NOT_POSTED;
18379 				} else {
18380 					/* Post success. Bffer available. */
18381 					lpfc_ncmd->flags &=
18382 						~LPFC_SBUF_NOT_POSTED;
18383 					lpfc_ncmd->status = IOSTAT_SUCCESS;
18384 					num_posted++;
18385 				}
18386 				/* success, put on NVME buffer sgl list */
18387 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18388 			}
18389 		}
18390 
18391 		/* continue until a nembed page worth of sgls */
18392 		if (post_cnt == 0)
18393 			continue;
18394 
18395 		/* post block of NVME buffer list sgls */
18396 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
18397 						     post_cnt);
18398 
18399 		/* don't reset xirtag due to hole in xri block */
18400 		if (block_cnt == 0)
18401 			last_xritag = NO_XRI;
18402 
18403 		/* reset NVME buffer post count for next round of posting */
18404 		post_cnt = 0;
18405 
18406 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
18407 		while (!list_empty(&blck_nblist)) {
18408 			list_remove_head(&blck_nblist, lpfc_ncmd,
18409 					 struct lpfc_io_buf, list);
18410 			if (status) {
18411 				/* Post error.  Mark buffer unavailable. */
18412 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
18413 			} else {
18414 				/* Post success, Mark buffer available. */
18415 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
18416 				lpfc_ncmd->status = IOSTAT_SUCCESS;
18417 				num_posted++;
18418 			}
18419 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18420 		}
18421 	}
18422 	/* Push NVME buffers with sgl posted to the available list */
18423 	lpfc_io_buf_replenish(phba, &nvme_nblist);
18424 
18425 	return num_posted;
18426 }
18427 
18428 /**
18429  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
18430  * @phba: pointer to lpfc_hba struct that the frame was received on
18431  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18432  *
18433  * This function checks the fields in the @fc_hdr to see if the FC frame is a
18434  * valid type of frame that the LPFC driver will handle. This function will
18435  * return a zero if the frame is a valid frame or a non zero value when the
18436  * frame does not pass the check.
18437  **/
18438 static int
18439 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
18440 {
18441 	/*  make rctl_names static to save stack space */
18442 	struct fc_vft_header *fc_vft_hdr;
18443 	uint32_t *header = (uint32_t *) fc_hdr;
18444 
18445 #define FC_RCTL_MDS_DIAGS	0xF4
18446 
18447 	switch (fc_hdr->fh_r_ctl) {
18448 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
18449 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
18450 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
18451 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
18452 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
18453 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
18454 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
18455 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
18456 	case FC_RCTL_ELS_REQ:	/* extended link services request */
18457 	case FC_RCTL_ELS_REP:	/* extended link services reply */
18458 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
18459 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
18460 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
18461 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
18462 	case FC_RCTL_BA_RMC: 	/* remove connection */
18463 	case FC_RCTL_BA_ACC:	/* basic accept */
18464 	case FC_RCTL_BA_RJT:	/* basic reject */
18465 	case FC_RCTL_BA_PRMT:
18466 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
18467 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
18468 	case FC_RCTL_P_RJT:	/* port reject */
18469 	case FC_RCTL_F_RJT:	/* fabric reject */
18470 	case FC_RCTL_P_BSY:	/* port busy */
18471 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
18472 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
18473 	case FC_RCTL_LCR:	/* link credit reset */
18474 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
18475 	case FC_RCTL_END:	/* end */
18476 		break;
18477 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
18478 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18479 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
18480 		return lpfc_fc_frame_check(phba, fc_hdr);
18481 	default:
18482 		goto drop;
18483 	}
18484 
18485 	switch (fc_hdr->fh_type) {
18486 	case FC_TYPE_BLS:
18487 	case FC_TYPE_ELS:
18488 	case FC_TYPE_FCP:
18489 	case FC_TYPE_CT:
18490 	case FC_TYPE_NVME:
18491 		break;
18492 	case FC_TYPE_IP:
18493 	case FC_TYPE_ILS:
18494 	default:
18495 		goto drop;
18496 	}
18497 
18498 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
18499 			"2538 Received frame rctl:x%x, type:x%x, "
18500 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
18501 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
18502 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
18503 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
18504 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
18505 			be32_to_cpu(header[6]));
18506 	return 0;
18507 drop:
18508 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
18509 			"2539 Dropped frame rctl:x%x type:x%x\n",
18510 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18511 	return 1;
18512 }
18513 
18514 /**
18515  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
18516  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18517  *
18518  * This function processes the FC header to retrieve the VFI from the VF
18519  * header, if one exists. This function will return the VFI if one exists
18520  * or 0 if no VSAN Header exists.
18521  **/
18522 static uint32_t
18523 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
18524 {
18525 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18526 
18527 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
18528 		return 0;
18529 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
18530 }
18531 
18532 /**
18533  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
18534  * @phba: Pointer to the HBA structure to search for the vport on
18535  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18536  * @fcfi: The FC Fabric ID that the frame came from
18537  * @did: Destination ID to match against
18538  *
18539  * This function searches the @phba for a vport that matches the content of the
18540  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
18541  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
18542  * returns the matching vport pointer or NULL if unable to match frame to a
18543  * vport.
18544  **/
18545 static struct lpfc_vport *
18546 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
18547 		       uint16_t fcfi, uint32_t did)
18548 {
18549 	struct lpfc_vport **vports;
18550 	struct lpfc_vport *vport = NULL;
18551 	int i;
18552 
18553 	if (did == Fabric_DID)
18554 		return phba->pport;
18555 	if ((phba->pport->fc_flag & FC_PT2PT) &&
18556 		!(phba->link_state == LPFC_HBA_READY))
18557 		return phba->pport;
18558 
18559 	vports = lpfc_create_vport_work_array(phba);
18560 	if (vports != NULL) {
18561 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
18562 			if (phba->fcf.fcfi == fcfi &&
18563 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
18564 			    vports[i]->fc_myDID == did) {
18565 				vport = vports[i];
18566 				break;
18567 			}
18568 		}
18569 	}
18570 	lpfc_destroy_vport_work_array(phba, vports);
18571 	return vport;
18572 }
18573 
18574 /**
18575  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
18576  * @vport: The vport to work on.
18577  *
18578  * This function updates the receive sequence time stamp for this vport. The
18579  * receive sequence time stamp indicates the time that the last frame of the
18580  * the sequence that has been idle for the longest amount of time was received.
18581  * the driver uses this time stamp to indicate if any received sequences have
18582  * timed out.
18583  **/
18584 static void
18585 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
18586 {
18587 	struct lpfc_dmabuf *h_buf;
18588 	struct hbq_dmabuf *dmabuf = NULL;
18589 
18590 	/* get the oldest sequence on the rcv list */
18591 	h_buf = list_get_first(&vport->rcv_buffer_list,
18592 			       struct lpfc_dmabuf, list);
18593 	if (!h_buf)
18594 		return;
18595 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18596 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
18597 }
18598 
18599 /**
18600  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
18601  * @vport: The vport that the received sequences were sent to.
18602  *
18603  * This function cleans up all outstanding received sequences. This is called
18604  * by the driver when a link event or user action invalidates all the received
18605  * sequences.
18606  **/
18607 void
18608 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
18609 {
18610 	struct lpfc_dmabuf *h_buf, *hnext;
18611 	struct lpfc_dmabuf *d_buf, *dnext;
18612 	struct hbq_dmabuf *dmabuf = NULL;
18613 
18614 	/* start with the oldest sequence on the rcv list */
18615 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18616 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18617 		list_del_init(&dmabuf->hbuf.list);
18618 		list_for_each_entry_safe(d_buf, dnext,
18619 					 &dmabuf->dbuf.list, list) {
18620 			list_del_init(&d_buf->list);
18621 			lpfc_in_buf_free(vport->phba, d_buf);
18622 		}
18623 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18624 	}
18625 }
18626 
18627 /**
18628  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
18629  * @vport: The vport that the received sequences were sent to.
18630  *
18631  * This function determines whether any received sequences have timed out by
18632  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
18633  * indicates that there is at least one timed out sequence this routine will
18634  * go through the received sequences one at a time from most inactive to most
18635  * active to determine which ones need to be cleaned up. Once it has determined
18636  * that a sequence needs to be cleaned up it will simply free up the resources
18637  * without sending an abort.
18638  **/
18639 void
18640 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
18641 {
18642 	struct lpfc_dmabuf *h_buf, *hnext;
18643 	struct lpfc_dmabuf *d_buf, *dnext;
18644 	struct hbq_dmabuf *dmabuf = NULL;
18645 	unsigned long timeout;
18646 	int abort_count = 0;
18647 
18648 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18649 		   vport->rcv_buffer_time_stamp);
18650 	if (list_empty(&vport->rcv_buffer_list) ||
18651 	    time_before(jiffies, timeout))
18652 		return;
18653 	/* start with the oldest sequence on the rcv list */
18654 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18655 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18656 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18657 			   dmabuf->time_stamp);
18658 		if (time_before(jiffies, timeout))
18659 			break;
18660 		abort_count++;
18661 		list_del_init(&dmabuf->hbuf.list);
18662 		list_for_each_entry_safe(d_buf, dnext,
18663 					 &dmabuf->dbuf.list, list) {
18664 			list_del_init(&d_buf->list);
18665 			lpfc_in_buf_free(vport->phba, d_buf);
18666 		}
18667 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18668 	}
18669 	if (abort_count)
18670 		lpfc_update_rcv_time_stamp(vport);
18671 }
18672 
18673 /**
18674  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
18675  * @vport: pointer to a vitural port
18676  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
18677  *
18678  * This function searches through the existing incomplete sequences that have
18679  * been sent to this @vport. If the frame matches one of the incomplete
18680  * sequences then the dbuf in the @dmabuf is added to the list of frames that
18681  * make up that sequence. If no sequence is found that matches this frame then
18682  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
18683  * This function returns a pointer to the first dmabuf in the sequence list that
18684  * the frame was linked to.
18685  **/
18686 static struct hbq_dmabuf *
18687 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18688 {
18689 	struct fc_frame_header *new_hdr;
18690 	struct fc_frame_header *temp_hdr;
18691 	struct lpfc_dmabuf *d_buf;
18692 	struct lpfc_dmabuf *h_buf;
18693 	struct hbq_dmabuf *seq_dmabuf = NULL;
18694 	struct hbq_dmabuf *temp_dmabuf = NULL;
18695 	uint8_t	found = 0;
18696 
18697 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18698 	dmabuf->time_stamp = jiffies;
18699 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18700 
18701 	/* Use the hdr_buf to find the sequence that this frame belongs to */
18702 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18703 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18704 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18705 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18706 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18707 			continue;
18708 		/* found a pending sequence that matches this frame */
18709 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18710 		break;
18711 	}
18712 	if (!seq_dmabuf) {
18713 		/*
18714 		 * This indicates first frame received for this sequence.
18715 		 * Queue the buffer on the vport's rcv_buffer_list.
18716 		 */
18717 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18718 		lpfc_update_rcv_time_stamp(vport);
18719 		return dmabuf;
18720 	}
18721 	temp_hdr = seq_dmabuf->hbuf.virt;
18722 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
18723 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18724 		list_del_init(&seq_dmabuf->hbuf.list);
18725 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18726 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18727 		lpfc_update_rcv_time_stamp(vport);
18728 		return dmabuf;
18729 	}
18730 	/* move this sequence to the tail to indicate a young sequence */
18731 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
18732 	seq_dmabuf->time_stamp = jiffies;
18733 	lpfc_update_rcv_time_stamp(vport);
18734 	if (list_empty(&seq_dmabuf->dbuf.list)) {
18735 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18736 		return seq_dmabuf;
18737 	}
18738 	/* find the correct place in the sequence to insert this frame */
18739 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
18740 	while (!found) {
18741 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18742 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
18743 		/*
18744 		 * If the frame's sequence count is greater than the frame on
18745 		 * the list then insert the frame right after this frame
18746 		 */
18747 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
18748 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18749 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
18750 			found = 1;
18751 			break;
18752 		}
18753 
18754 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
18755 			break;
18756 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
18757 	}
18758 
18759 	if (found)
18760 		return seq_dmabuf;
18761 	return NULL;
18762 }
18763 
18764 /**
18765  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
18766  * @vport: pointer to a vitural port
18767  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18768  *
18769  * This function tries to abort from the partially assembed sequence, described
18770  * by the information from basic abbort @dmabuf. It checks to see whether such
18771  * partially assembled sequence held by the driver. If so, it shall free up all
18772  * the frames from the partially assembled sequence.
18773  *
18774  * Return
18775  * true  -- if there is matching partially assembled sequence present and all
18776  *          the frames freed with the sequence;
18777  * false -- if there is no matching partially assembled sequence present so
18778  *          nothing got aborted in the lower layer driver
18779  **/
18780 static bool
18781 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
18782 			    struct hbq_dmabuf *dmabuf)
18783 {
18784 	struct fc_frame_header *new_hdr;
18785 	struct fc_frame_header *temp_hdr;
18786 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
18787 	struct hbq_dmabuf *seq_dmabuf = NULL;
18788 
18789 	/* Use the hdr_buf to find the sequence that matches this frame */
18790 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18791 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
18792 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18793 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18794 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18795 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18796 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18797 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18798 			continue;
18799 		/* found a pending sequence that matches this frame */
18800 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18801 		break;
18802 	}
18803 
18804 	/* Free up all the frames from the partially assembled sequence */
18805 	if (seq_dmabuf) {
18806 		list_for_each_entry_safe(d_buf, n_buf,
18807 					 &seq_dmabuf->dbuf.list, list) {
18808 			list_del_init(&d_buf->list);
18809 			lpfc_in_buf_free(vport->phba, d_buf);
18810 		}
18811 		return true;
18812 	}
18813 	return false;
18814 }
18815 
18816 /**
18817  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18818  * @vport: pointer to a vitural port
18819  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18820  *
18821  * This function tries to abort from the assembed sequence from upper level
18822  * protocol, described by the information from basic abbort @dmabuf. It
18823  * checks to see whether such pending context exists at upper level protocol.
18824  * If so, it shall clean up the pending context.
18825  *
18826  * Return
18827  * true  -- if there is matching pending context of the sequence cleaned
18828  *          at ulp;
18829  * false -- if there is no matching pending context of the sequence present
18830  *          at ulp.
18831  **/
18832 static bool
18833 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18834 {
18835 	struct lpfc_hba *phba = vport->phba;
18836 	int handled;
18837 
18838 	/* Accepting abort at ulp with SLI4 only */
18839 	if (phba->sli_rev < LPFC_SLI_REV4)
18840 		return false;
18841 
18842 	/* Register all caring upper level protocols to attend abort */
18843 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18844 	if (handled)
18845 		return true;
18846 
18847 	return false;
18848 }
18849 
18850 /**
18851  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18852  * @phba: Pointer to HBA context object.
18853  * @cmd_iocbq: pointer to the command iocbq structure.
18854  * @rsp_iocbq: pointer to the response iocbq structure.
18855  *
18856  * This function handles the sequence abort response iocb command complete
18857  * event. It properly releases the memory allocated to the sequence abort
18858  * accept iocb.
18859  **/
18860 static void
18861 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18862 			     struct lpfc_iocbq *cmd_iocbq,
18863 			     struct lpfc_iocbq *rsp_iocbq)
18864 {
18865 	struct lpfc_nodelist *ndlp;
18866 
18867 	if (cmd_iocbq) {
18868 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
18869 		lpfc_nlp_put(ndlp);
18870 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
18871 	}
18872 
18873 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
18874 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18875 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18876 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
18877 			rsp_iocbq->iocb.ulpStatus,
18878 			rsp_iocbq->iocb.un.ulpWord[4]);
18879 }
18880 
18881 /**
18882  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
18883  * @phba: Pointer to HBA context object.
18884  * @xri: xri id in transaction.
18885  *
18886  * This function validates the xri maps to the known range of XRIs allocated an
18887  * used by the driver.
18888  **/
18889 uint16_t
18890 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
18891 		      uint16_t xri)
18892 {
18893 	uint16_t i;
18894 
18895 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
18896 		if (xri == phba->sli4_hba.xri_ids[i])
18897 			return i;
18898 	}
18899 	return NO_XRI;
18900 }
18901 
18902 /**
18903  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
18904  * @vport: pointer to a virtual port.
18905  * @fc_hdr: pointer to a FC frame header.
18906  * @aborted: was the partially assembled receive sequence successfully aborted
18907  *
18908  * This function sends a basic response to a previous unsol sequence abort
18909  * event after aborting the sequence handling.
18910  **/
18911 void
18912 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
18913 			struct fc_frame_header *fc_hdr, bool aborted)
18914 {
18915 	struct lpfc_hba *phba = vport->phba;
18916 	struct lpfc_iocbq *ctiocb = NULL;
18917 	struct lpfc_nodelist *ndlp;
18918 	uint16_t oxid, rxid, xri, lxri;
18919 	uint32_t sid, fctl;
18920 	IOCB_t *icmd;
18921 	int rc;
18922 
18923 	if (!lpfc_is_link_up(phba))
18924 		return;
18925 
18926 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18927 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
18928 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
18929 
18930 	ndlp = lpfc_findnode_did(vport, sid);
18931 	if (!ndlp) {
18932 		ndlp = lpfc_nlp_init(vport, sid);
18933 		if (!ndlp) {
18934 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
18935 					 "1268 Failed to allocate ndlp for "
18936 					 "oxid:x%x SID:x%x\n", oxid, sid);
18937 			return;
18938 		}
18939 		/* Put ndlp onto pport node list */
18940 		lpfc_enqueue_node(vport, ndlp);
18941 	}
18942 
18943 	/* Allocate buffer for rsp iocb */
18944 	ctiocb = lpfc_sli_get_iocbq(phba);
18945 	if (!ctiocb)
18946 		return;
18947 
18948 	/* Extract the F_CTL field from FC_HDR */
18949 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
18950 
18951 	icmd = &ctiocb->iocb;
18952 	icmd->un.xseq64.bdl.bdeSize = 0;
18953 	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
18954 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
18955 	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
18956 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
18957 
18958 	/* Fill in the rest of iocb fields */
18959 	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
18960 	icmd->ulpBdeCount = 0;
18961 	icmd->ulpLe = 1;
18962 	icmd->ulpClass = CLASS3;
18963 	icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
18964 	ctiocb->context1 = lpfc_nlp_get(ndlp);
18965 	if (!ctiocb->context1) {
18966 		lpfc_sli_release_iocbq(phba, ctiocb);
18967 		return;
18968 	}
18969 
18970 	ctiocb->vport = phba->pport;
18971 	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
18972 	ctiocb->sli4_lxritag = NO_XRI;
18973 	ctiocb->sli4_xritag = NO_XRI;
18974 
18975 	if (fctl & FC_FC_EX_CTX)
18976 		/* Exchange responder sent the abort so we
18977 		 * own the oxid.
18978 		 */
18979 		xri = oxid;
18980 	else
18981 		xri = rxid;
18982 	lxri = lpfc_sli4_xri_inrange(phba, xri);
18983 	if (lxri != NO_XRI)
18984 		lpfc_set_rrq_active(phba, ndlp, lxri,
18985 			(xri == oxid) ? rxid : oxid, 0);
18986 	/* For BA_ABTS from exchange responder, if the logical xri with
18987 	 * the oxid maps to the FCP XRI range, the port no longer has
18988 	 * that exchange context, send a BLS_RJT. Override the IOCB for
18989 	 * a BA_RJT.
18990 	 */
18991 	if ((fctl & FC_FC_EX_CTX) &&
18992 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
18993 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
18994 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
18995 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
18996 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
18997 	}
18998 
18999 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
19000 	 * the driver no longer has that exchange, send a BLS_RJT. Override
19001 	 * the IOCB for a BA_RJT.
19002 	 */
19003 	if (aborted == false) {
19004 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
19005 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
19006 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
19007 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
19008 	}
19009 
19010 	if (fctl & FC_FC_EX_CTX) {
19011 		/* ABTS sent by responder to CT exchange, construction
19012 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
19013 		 * field and RX_ID from ABTS for RX_ID field.
19014 		 */
19015 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
19016 	} else {
19017 		/* ABTS sent by initiator to CT exchange, construction
19018 		 * of BA_ACC will need to allocate a new XRI as for the
19019 		 * XRI_TAG field.
19020 		 */
19021 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
19022 	}
19023 	bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
19024 	bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
19025 
19026 	/* Xmit CT abts response on exchange <xid> */
19027 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
19028 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
19029 			 icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
19030 
19031 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
19032 	if (rc == IOCB_ERROR) {
19033 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19034 				 "2925 Failed to issue CT ABTS RSP x%x on "
19035 				 "xri x%x, Data x%x\n",
19036 				 icmd->un.xseq64.w5.hcsw.Rctl, oxid,
19037 				 phba->link_state);
19038 		lpfc_nlp_put(ndlp);
19039 		ctiocb->context1 = NULL;
19040 		lpfc_sli_release_iocbq(phba, ctiocb);
19041 	}
19042 }
19043 
19044 /**
19045  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
19046  * @vport: Pointer to the vport on which this sequence was received
19047  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19048  *
19049  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
19050  * receive sequence is only partially assembed by the driver, it shall abort
19051  * the partially assembled frames for the sequence. Otherwise, if the
19052  * unsolicited receive sequence has been completely assembled and passed to
19053  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
19054  * unsolicited sequence has been aborted. After that, it will issue a basic
19055  * accept to accept the abort.
19056  **/
19057 static void
19058 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
19059 			     struct hbq_dmabuf *dmabuf)
19060 {
19061 	struct lpfc_hba *phba = vport->phba;
19062 	struct fc_frame_header fc_hdr;
19063 	uint32_t fctl;
19064 	bool aborted;
19065 
19066 	/* Make a copy of fc_hdr before the dmabuf being released */
19067 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
19068 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
19069 
19070 	if (fctl & FC_FC_EX_CTX) {
19071 		/* ABTS by responder to exchange, no cleanup needed */
19072 		aborted = true;
19073 	} else {
19074 		/* ABTS by initiator to exchange, need to do cleanup */
19075 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
19076 		if (aborted == false)
19077 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
19078 	}
19079 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19080 
19081 	if (phba->nvmet_support) {
19082 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
19083 		return;
19084 	}
19085 
19086 	/* Respond with BA_ACC or BA_RJT accordingly */
19087 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
19088 }
19089 
19090 /**
19091  * lpfc_seq_complete - Indicates if a sequence is complete
19092  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19093  *
19094  * This function checks the sequence, starting with the frame described by
19095  * @dmabuf, to see if all the frames associated with this sequence are present.
19096  * the frames associated with this sequence are linked to the @dmabuf using the
19097  * dbuf list. This function looks for two major things. 1) That the first frame
19098  * has a sequence count of zero. 2) There is a frame with last frame of sequence
19099  * set. 3) That there are no holes in the sequence count. The function will
19100  * return 1 when the sequence is complete, otherwise it will return 0.
19101  **/
19102 static int
19103 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
19104 {
19105 	struct fc_frame_header *hdr;
19106 	struct lpfc_dmabuf *d_buf;
19107 	struct hbq_dmabuf *seq_dmabuf;
19108 	uint32_t fctl;
19109 	int seq_count = 0;
19110 
19111 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19112 	/* make sure first fame of sequence has a sequence count of zero */
19113 	if (hdr->fh_seq_cnt != seq_count)
19114 		return 0;
19115 	fctl = (hdr->fh_f_ctl[0] << 16 |
19116 		hdr->fh_f_ctl[1] << 8 |
19117 		hdr->fh_f_ctl[2]);
19118 	/* If last frame of sequence we can return success. */
19119 	if (fctl & FC_FC_END_SEQ)
19120 		return 1;
19121 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
19122 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19123 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19124 		/* If there is a hole in the sequence count then fail. */
19125 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
19126 			return 0;
19127 		fctl = (hdr->fh_f_ctl[0] << 16 |
19128 			hdr->fh_f_ctl[1] << 8 |
19129 			hdr->fh_f_ctl[2]);
19130 		/* If last frame of sequence we can return success. */
19131 		if (fctl & FC_FC_END_SEQ)
19132 			return 1;
19133 	}
19134 	return 0;
19135 }
19136 
19137 /**
19138  * lpfc_prep_seq - Prep sequence for ULP processing
19139  * @vport: Pointer to the vport on which this sequence was received
19140  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
19141  *
19142  * This function takes a sequence, described by a list of frames, and creates
19143  * a list of iocbq structures to describe the sequence. This iocbq list will be
19144  * used to issue to the generic unsolicited sequence handler. This routine
19145  * returns a pointer to the first iocbq in the list. If the function is unable
19146  * to allocate an iocbq then it throw out the received frames that were not
19147  * able to be described and return a pointer to the first iocbq. If unable to
19148  * allocate any iocbqs (including the first) this function will return NULL.
19149  **/
19150 static struct lpfc_iocbq *
19151 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
19152 {
19153 	struct hbq_dmabuf *hbq_buf;
19154 	struct lpfc_dmabuf *d_buf, *n_buf;
19155 	struct lpfc_iocbq *first_iocbq, *iocbq;
19156 	struct fc_frame_header *fc_hdr;
19157 	uint32_t sid;
19158 	uint32_t len, tot_len;
19159 	struct ulp_bde64 *pbde;
19160 
19161 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19162 	/* remove from receive buffer list */
19163 	list_del_init(&seq_dmabuf->hbuf.list);
19164 	lpfc_update_rcv_time_stamp(vport);
19165 	/* get the Remote Port's SID */
19166 	sid = sli4_sid_from_fc_hdr(fc_hdr);
19167 	tot_len = 0;
19168 	/* Get an iocbq struct to fill in. */
19169 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
19170 	if (first_iocbq) {
19171 		/* Initialize the first IOCB. */
19172 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
19173 		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
19174 		first_iocbq->vport = vport;
19175 
19176 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
19177 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
19178 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
19179 			first_iocbq->iocb.un.rcvels.parmRo =
19180 				sli4_did_from_fc_hdr(fc_hdr);
19181 			first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
19182 		} else
19183 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
19184 		first_iocbq->iocb.ulpContext = NO_XRI;
19185 		first_iocbq->iocb.unsli3.rcvsli3.ox_id =
19186 			be16_to_cpu(fc_hdr->fh_ox_id);
19187 		/* iocbq is prepped for internal consumption.  Physical vpi. */
19188 		first_iocbq->iocb.unsli3.rcvsli3.vpi =
19189 			vport->phba->vpi_ids[vport->vpi];
19190 		/* put the first buffer into the first IOCBq */
19191 		tot_len = bf_get(lpfc_rcqe_length,
19192 				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
19193 
19194 		first_iocbq->context2 = &seq_dmabuf->dbuf;
19195 		first_iocbq->context3 = NULL;
19196 		first_iocbq->iocb.ulpBdeCount = 1;
19197 		if (tot_len > LPFC_DATA_BUF_SIZE)
19198 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
19199 							LPFC_DATA_BUF_SIZE;
19200 		else
19201 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
19202 
19203 		first_iocbq->iocb.un.rcvels.remoteID = sid;
19204 
19205 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
19206 	}
19207 	iocbq = first_iocbq;
19208 	/*
19209 	 * Each IOCBq can have two Buffers assigned, so go through the list
19210 	 * of buffers for this sequence and save two buffers in each IOCBq
19211 	 */
19212 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
19213 		if (!iocbq) {
19214 			lpfc_in_buf_free(vport->phba, d_buf);
19215 			continue;
19216 		}
19217 		if (!iocbq->context3) {
19218 			iocbq->context3 = d_buf;
19219 			iocbq->iocb.ulpBdeCount++;
19220 			/* We need to get the size out of the right CQE */
19221 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19222 			len = bf_get(lpfc_rcqe_length,
19223 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19224 			pbde = (struct ulp_bde64 *)
19225 					&iocbq->iocb.unsli3.sli3Words[4];
19226 			if (len > LPFC_DATA_BUF_SIZE)
19227 				pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
19228 			else
19229 				pbde->tus.f.bdeSize = len;
19230 
19231 			iocbq->iocb.unsli3.rcvsli3.acc_len += len;
19232 			tot_len += len;
19233 		} else {
19234 			iocbq = lpfc_sli_get_iocbq(vport->phba);
19235 			if (!iocbq) {
19236 				if (first_iocbq) {
19237 					first_iocbq->iocb.ulpStatus =
19238 							IOSTAT_FCP_RSP_ERROR;
19239 					first_iocbq->iocb.un.ulpWord[4] =
19240 							IOERR_NO_RESOURCES;
19241 				}
19242 				lpfc_in_buf_free(vport->phba, d_buf);
19243 				continue;
19244 			}
19245 			/* We need to get the size out of the right CQE */
19246 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19247 			len = bf_get(lpfc_rcqe_length,
19248 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19249 			iocbq->context2 = d_buf;
19250 			iocbq->context3 = NULL;
19251 			iocbq->iocb.ulpBdeCount = 1;
19252 			if (len > LPFC_DATA_BUF_SIZE)
19253 				iocbq->iocb.un.cont64[0].tus.f.bdeSize =
19254 							LPFC_DATA_BUF_SIZE;
19255 			else
19256 				iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
19257 
19258 			tot_len += len;
19259 			iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
19260 
19261 			iocbq->iocb.un.rcvels.remoteID = sid;
19262 			list_add_tail(&iocbq->list, &first_iocbq->list);
19263 		}
19264 	}
19265 	/* Free the sequence's header buffer */
19266 	if (!first_iocbq)
19267 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
19268 
19269 	return first_iocbq;
19270 }
19271 
19272 static void
19273 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
19274 			  struct hbq_dmabuf *seq_dmabuf)
19275 {
19276 	struct fc_frame_header *fc_hdr;
19277 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
19278 	struct lpfc_hba *phba = vport->phba;
19279 
19280 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19281 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
19282 	if (!iocbq) {
19283 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19284 				"2707 Ring %d handler: Failed to allocate "
19285 				"iocb Rctl x%x Type x%x received\n",
19286 				LPFC_ELS_RING,
19287 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19288 		return;
19289 	}
19290 	if (!lpfc_complete_unsol_iocb(phba,
19291 				      phba->sli4_hba.els_wq->pring,
19292 				      iocbq, fc_hdr->fh_r_ctl,
19293 				      fc_hdr->fh_type))
19294 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19295 				"2540 Ring %d handler: unexpected Rctl "
19296 				"x%x Type x%x received\n",
19297 				LPFC_ELS_RING,
19298 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19299 
19300 	/* Free iocb created in lpfc_prep_seq */
19301 	list_for_each_entry_safe(curr_iocb, next_iocb,
19302 		&iocbq->list, list) {
19303 		list_del_init(&curr_iocb->list);
19304 		lpfc_sli_release_iocbq(phba, curr_iocb);
19305 	}
19306 	lpfc_sli_release_iocbq(phba, iocbq);
19307 }
19308 
19309 static void
19310 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
19311 			    struct lpfc_iocbq *rspiocb)
19312 {
19313 	struct lpfc_dmabuf *pcmd = cmdiocb->context2;
19314 
19315 	if (pcmd && pcmd->virt)
19316 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19317 	kfree(pcmd);
19318 	lpfc_sli_release_iocbq(phba, cmdiocb);
19319 	lpfc_drain_txq(phba);
19320 }
19321 
19322 static void
19323 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
19324 			      struct hbq_dmabuf *dmabuf)
19325 {
19326 	struct fc_frame_header *fc_hdr;
19327 	struct lpfc_hba *phba = vport->phba;
19328 	struct lpfc_iocbq *iocbq = NULL;
19329 	union  lpfc_wqe *wqe;
19330 	struct lpfc_dmabuf *pcmd = NULL;
19331 	uint32_t frame_len;
19332 	int rc;
19333 	unsigned long iflags;
19334 
19335 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19336 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
19337 
19338 	/* Send the received frame back */
19339 	iocbq = lpfc_sli_get_iocbq(phba);
19340 	if (!iocbq) {
19341 		/* Queue cq event and wakeup worker thread to process it */
19342 		spin_lock_irqsave(&phba->hbalock, iflags);
19343 		list_add_tail(&dmabuf->cq_event.list,
19344 			      &phba->sli4_hba.sp_queue_event);
19345 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
19346 		spin_unlock_irqrestore(&phba->hbalock, iflags);
19347 		lpfc_worker_wake_up(phba);
19348 		return;
19349 	}
19350 
19351 	/* Allocate buffer for command payload */
19352 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
19353 	if (pcmd)
19354 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
19355 					    &pcmd->phys);
19356 	if (!pcmd || !pcmd->virt)
19357 		goto exit;
19358 
19359 	INIT_LIST_HEAD(&pcmd->list);
19360 
19361 	/* copyin the payload */
19362 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
19363 
19364 	/* fill in BDE's for command */
19365 	iocbq->iocb.un.xseq64.bdl.addrHigh = putPaddrHigh(pcmd->phys);
19366 	iocbq->iocb.un.xseq64.bdl.addrLow = putPaddrLow(pcmd->phys);
19367 	iocbq->iocb.un.xseq64.bdl.bdeFlags = BUFF_TYPE_BDE_64;
19368 	iocbq->iocb.un.xseq64.bdl.bdeSize = frame_len;
19369 
19370 	iocbq->context2 = pcmd;
19371 	iocbq->vport = vport;
19372 	iocbq->iocb_flag &= ~LPFC_FIP_ELS_ID_MASK;
19373 	iocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
19374 
19375 	/*
19376 	 * Setup rest of the iocb as though it were a WQE
19377 	 * Build the SEND_FRAME WQE
19378 	 */
19379 	wqe = (union lpfc_wqe *)&iocbq->iocb;
19380 
19381 	wqe->send_frame.frame_len = frame_len;
19382 	wqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((uint32_t *)fc_hdr));
19383 	wqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((uint32_t *)fc_hdr + 1));
19384 	wqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((uint32_t *)fc_hdr + 2));
19385 	wqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((uint32_t *)fc_hdr + 3));
19386 	wqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((uint32_t *)fc_hdr + 4));
19387 	wqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((uint32_t *)fc_hdr + 5));
19388 
19389 	iocbq->iocb.ulpCommand = CMD_SEND_FRAME;
19390 	iocbq->iocb.ulpLe = 1;
19391 	iocbq->iocb_cmpl = lpfc_sli4_mds_loopback_cmpl;
19392 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
19393 	if (rc == IOCB_ERROR)
19394 		goto exit;
19395 
19396 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19397 	return;
19398 
19399 exit:
19400 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
19401 			"2023 Unable to process MDS loopback frame\n");
19402 	if (pcmd && pcmd->virt)
19403 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19404 	kfree(pcmd);
19405 	if (iocbq)
19406 		lpfc_sli_release_iocbq(phba, iocbq);
19407 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19408 }
19409 
19410 /**
19411  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
19412  * @phba: Pointer to HBA context object.
19413  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
19414  *
19415  * This function is called with no lock held. This function processes all
19416  * the received buffers and gives it to upper layers when a received buffer
19417  * indicates that it is the final frame in the sequence. The interrupt
19418  * service routine processes received buffers at interrupt contexts.
19419  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
19420  * appropriate receive function when the final frame in a sequence is received.
19421  **/
19422 void
19423 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
19424 				 struct hbq_dmabuf *dmabuf)
19425 {
19426 	struct hbq_dmabuf *seq_dmabuf;
19427 	struct fc_frame_header *fc_hdr;
19428 	struct lpfc_vport *vport;
19429 	uint32_t fcfi;
19430 	uint32_t did;
19431 
19432 	/* Process each received buffer */
19433 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19434 
19435 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
19436 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
19437 		vport = phba->pport;
19438 		/* Handle MDS Loopback frames */
19439 		if  (!(phba->pport->load_flag & FC_UNLOADING))
19440 			lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19441 		else
19442 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19443 		return;
19444 	}
19445 
19446 	/* check to see if this a valid type of frame */
19447 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
19448 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19449 		return;
19450 	}
19451 
19452 	if ((bf_get(lpfc_cqe_code,
19453 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
19454 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
19455 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19456 	else
19457 		fcfi = bf_get(lpfc_rcqe_fcf_id,
19458 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19459 
19460 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
19461 		vport = phba->pport;
19462 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
19463 				"2023 MDS Loopback %d bytes\n",
19464 				bf_get(lpfc_rcqe_length,
19465 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
19466 		/* Handle MDS Loopback frames */
19467 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19468 		return;
19469 	}
19470 
19471 	/* d_id this frame is directed to */
19472 	did = sli4_did_from_fc_hdr(fc_hdr);
19473 
19474 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
19475 	if (!vport) {
19476 		/* throw out the frame */
19477 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19478 		return;
19479 	}
19480 
19481 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
19482 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
19483 		(did != Fabric_DID)) {
19484 		/*
19485 		 * Throw out the frame if we are not pt2pt.
19486 		 * The pt2pt protocol allows for discovery frames
19487 		 * to be received without a registered VPI.
19488 		 */
19489 		if (!(vport->fc_flag & FC_PT2PT) ||
19490 			(phba->link_state == LPFC_HBA_READY)) {
19491 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19492 			return;
19493 		}
19494 	}
19495 
19496 	/* Handle the basic abort sequence (BA_ABTS) event */
19497 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
19498 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
19499 		return;
19500 	}
19501 
19502 	/* Link this frame */
19503 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
19504 	if (!seq_dmabuf) {
19505 		/* unable to add frame to vport - throw it out */
19506 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19507 		return;
19508 	}
19509 	/* If not last frame in sequence continue processing frames. */
19510 	if (!lpfc_seq_complete(seq_dmabuf))
19511 		return;
19512 
19513 	/* Send the complete sequence to the upper layer protocol */
19514 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
19515 }
19516 
19517 /**
19518  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
19519  * @phba: pointer to lpfc hba data structure.
19520  *
19521  * This routine is invoked to post rpi header templates to the
19522  * HBA consistent with the SLI-4 interface spec.  This routine
19523  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19524  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19525  *
19526  * This routine does not require any locks.  It's usage is expected
19527  * to be driver load or reset recovery when the driver is
19528  * sequential.
19529  *
19530  * Return codes
19531  * 	0 - successful
19532  *      -EIO - The mailbox failed to complete successfully.
19533  * 	When this error occurs, the driver is not guaranteed
19534  *	to have any rpi regions posted to the device and
19535  *	must either attempt to repost the regions or take a
19536  *	fatal error.
19537  **/
19538 int
19539 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
19540 {
19541 	struct lpfc_rpi_hdr *rpi_page;
19542 	uint32_t rc = 0;
19543 	uint16_t lrpi = 0;
19544 
19545 	/* SLI4 ports that support extents do not require RPI headers. */
19546 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19547 		goto exit;
19548 	if (phba->sli4_hba.extents_in_use)
19549 		return -EIO;
19550 
19551 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
19552 		/*
19553 		 * Assign the rpi headers a physical rpi only if the driver
19554 		 * has not initialized those resources.  A port reset only
19555 		 * needs the headers posted.
19556 		 */
19557 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
19558 		    LPFC_RPI_RSRC_RDY)
19559 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19560 
19561 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
19562 		if (rc != MBX_SUCCESS) {
19563 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19564 					"2008 Error %d posting all rpi "
19565 					"headers\n", rc);
19566 			rc = -EIO;
19567 			break;
19568 		}
19569 	}
19570 
19571  exit:
19572 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
19573 	       LPFC_RPI_RSRC_RDY);
19574 	return rc;
19575 }
19576 
19577 /**
19578  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
19579  * @phba: pointer to lpfc hba data structure.
19580  * @rpi_page:  pointer to the rpi memory region.
19581  *
19582  * This routine is invoked to post a single rpi header to the
19583  * HBA consistent with the SLI-4 interface spec.  This memory region
19584  * maps up to 64 rpi context regions.
19585  *
19586  * Return codes
19587  * 	0 - successful
19588  * 	-ENOMEM - No available memory
19589  *      -EIO - The mailbox failed to complete successfully.
19590  **/
19591 int
19592 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
19593 {
19594 	LPFC_MBOXQ_t *mboxq;
19595 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
19596 	uint32_t rc = 0;
19597 	uint32_t shdr_status, shdr_add_status;
19598 	union lpfc_sli4_cfg_shdr *shdr;
19599 
19600 	/* SLI4 ports that support extents do not require RPI headers. */
19601 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19602 		return rc;
19603 	if (phba->sli4_hba.extents_in_use)
19604 		return -EIO;
19605 
19606 	/* The port is notified of the header region via a mailbox command. */
19607 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19608 	if (!mboxq) {
19609 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19610 				"2001 Unable to allocate memory for issuing "
19611 				"SLI_CONFIG_SPECIAL mailbox command\n");
19612 		return -ENOMEM;
19613 	}
19614 
19615 	/* Post all rpi memory regions to the port. */
19616 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
19617 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19618 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
19619 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
19620 			 sizeof(struct lpfc_sli4_cfg_mhdr),
19621 			 LPFC_SLI4_MBX_EMBED);
19622 
19623 
19624 	/* Post the physical rpi to the port for this rpi header. */
19625 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
19626 	       rpi_page->start_rpi);
19627 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
19628 	       hdr_tmpl, rpi_page->page_count);
19629 
19630 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
19631 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
19632 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19633 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
19634 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19635 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19636 	mempool_free(mboxq, phba->mbox_mem_pool);
19637 	if (shdr_status || shdr_add_status || rc) {
19638 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19639 				"2514 POST_RPI_HDR mailbox failed with "
19640 				"status x%x add_status x%x, mbx status x%x\n",
19641 				shdr_status, shdr_add_status, rc);
19642 		rc = -ENXIO;
19643 	} else {
19644 		/*
19645 		 * The next_rpi stores the next logical module-64 rpi value used
19646 		 * to post physical rpis in subsequent rpi postings.
19647 		 */
19648 		spin_lock_irq(&phba->hbalock);
19649 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
19650 		spin_unlock_irq(&phba->hbalock);
19651 	}
19652 	return rc;
19653 }
19654 
19655 /**
19656  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
19657  * @phba: pointer to lpfc hba data structure.
19658  *
19659  * This routine is invoked to post rpi header templates to the
19660  * HBA consistent with the SLI-4 interface spec.  This routine
19661  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19662  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19663  *
19664  * Returns
19665  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
19666  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
19667  **/
19668 int
19669 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
19670 {
19671 	unsigned long rpi;
19672 	uint16_t max_rpi, rpi_limit;
19673 	uint16_t rpi_remaining, lrpi = 0;
19674 	struct lpfc_rpi_hdr *rpi_hdr;
19675 	unsigned long iflag;
19676 
19677 	/*
19678 	 * Fetch the next logical rpi.  Because this index is logical,
19679 	 * the  driver starts at 0 each time.
19680 	 */
19681 	spin_lock_irqsave(&phba->hbalock, iflag);
19682 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
19683 	rpi_limit = phba->sli4_hba.next_rpi;
19684 
19685 	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
19686 	if (rpi >= rpi_limit)
19687 		rpi = LPFC_RPI_ALLOC_ERROR;
19688 	else {
19689 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
19690 		phba->sli4_hba.max_cfg_param.rpi_used++;
19691 		phba->sli4_hba.rpi_count++;
19692 	}
19693 	lpfc_printf_log(phba, KERN_INFO,
19694 			LOG_NODE | LOG_DISCOVERY,
19695 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
19696 			(int) rpi, max_rpi, rpi_limit);
19697 
19698 	/*
19699 	 * Don't try to allocate more rpi header regions if the device limit
19700 	 * has been exhausted.
19701 	 */
19702 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
19703 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
19704 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19705 		return rpi;
19706 	}
19707 
19708 	/*
19709 	 * RPI header postings are not required for SLI4 ports capable of
19710 	 * extents.
19711 	 */
19712 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
19713 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19714 		return rpi;
19715 	}
19716 
19717 	/*
19718 	 * If the driver is running low on rpi resources, allocate another
19719 	 * page now.  Note that the next_rpi value is used because
19720 	 * it represents how many are actually in use whereas max_rpi notes
19721 	 * how many are supported max by the device.
19722 	 */
19723 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
19724 	spin_unlock_irqrestore(&phba->hbalock, iflag);
19725 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
19726 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
19727 		if (!rpi_hdr) {
19728 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19729 					"2002 Error Could not grow rpi "
19730 					"count\n");
19731 		} else {
19732 			lrpi = rpi_hdr->start_rpi;
19733 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19734 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
19735 		}
19736 	}
19737 
19738 	return rpi;
19739 }
19740 
19741 /**
19742  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
19743  * @phba: pointer to lpfc hba data structure.
19744  * @rpi: rpi to free
19745  *
19746  * This routine is invoked to release an rpi to the pool of
19747  * available rpis maintained by the driver.
19748  **/
19749 static void
19750 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19751 {
19752 	/*
19753 	 * if the rpi value indicates a prior unreg has already
19754 	 * been done, skip the unreg.
19755 	 */
19756 	if (rpi == LPFC_RPI_ALLOC_ERROR)
19757 		return;
19758 
19759 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
19760 		phba->sli4_hba.rpi_count--;
19761 		phba->sli4_hba.max_cfg_param.rpi_used--;
19762 	} else {
19763 		lpfc_printf_log(phba, KERN_INFO,
19764 				LOG_NODE | LOG_DISCOVERY,
19765 				"2016 rpi %x not inuse\n",
19766 				rpi);
19767 	}
19768 }
19769 
19770 /**
19771  * lpfc_sli4_free_rpi - Release an rpi for reuse.
19772  * @phba: pointer to lpfc hba data structure.
19773  * @rpi: rpi to free
19774  *
19775  * This routine is invoked to release an rpi to the pool of
19776  * available rpis maintained by the driver.
19777  **/
19778 void
19779 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19780 {
19781 	spin_lock_irq(&phba->hbalock);
19782 	__lpfc_sli4_free_rpi(phba, rpi);
19783 	spin_unlock_irq(&phba->hbalock);
19784 }
19785 
19786 /**
19787  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19788  * @phba: pointer to lpfc hba data structure.
19789  *
19790  * This routine is invoked to remove the memory region that
19791  * provided rpi via a bitmask.
19792  **/
19793 void
19794 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19795 {
19796 	kfree(phba->sli4_hba.rpi_bmask);
19797 	kfree(phba->sli4_hba.rpi_ids);
19798 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19799 }
19800 
19801 /**
19802  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
19803  * @ndlp: pointer to lpfc nodelist data structure.
19804  * @cmpl: completion call-back.
19805  * @arg: data to load as MBox 'caller buffer information'
19806  *
19807  * This routine is invoked to remove the memory region that
19808  * provided rpi via a bitmask.
19809  **/
19810 int
19811 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19812 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
19813 {
19814 	LPFC_MBOXQ_t *mboxq;
19815 	struct lpfc_hba *phba = ndlp->phba;
19816 	int rc;
19817 
19818 	/* The port is notified of the header region via a mailbox command. */
19819 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19820 	if (!mboxq)
19821 		return -ENOMEM;
19822 
19823 	/* If cmpl assigned, then this nlp_get pairs with
19824 	 * lpfc_mbx_cmpl_resume_rpi.
19825 	 *
19826 	 * Else cmpl is NULL, then this nlp_get pairs with
19827 	 * lpfc_sli_def_mbox_cmpl.
19828 	 */
19829 	if (!lpfc_nlp_get(ndlp)) {
19830 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19831 				"2122 %s: Failed to get nlp ref\n",
19832 				__func__);
19833 		mempool_free(mboxq, phba->mbox_mem_pool);
19834 		return -EIO;
19835 	}
19836 
19837 	/* Post all rpi memory regions to the port. */
19838 	lpfc_resume_rpi(mboxq, ndlp);
19839 	if (cmpl) {
19840 		mboxq->mbox_cmpl = cmpl;
19841 		mboxq->ctx_buf = arg;
19842 	} else
19843 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19844 	mboxq->ctx_ndlp = ndlp;
19845 	mboxq->vport = ndlp->vport;
19846 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19847 	if (rc == MBX_NOT_FINISHED) {
19848 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19849 				"2010 Resume RPI Mailbox failed "
19850 				"status %d, mbxStatus x%x\n", rc,
19851 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19852 		lpfc_nlp_put(ndlp);
19853 		mempool_free(mboxq, phba->mbox_mem_pool);
19854 		return -EIO;
19855 	}
19856 	return 0;
19857 }
19858 
19859 /**
19860  * lpfc_sli4_init_vpi - Initialize a vpi with the port
19861  * @vport: Pointer to the vport for which the vpi is being initialized
19862  *
19863  * This routine is invoked to activate a vpi with the port.
19864  *
19865  * Returns:
19866  *    0 success
19867  *    -Evalue otherwise
19868  **/
19869 int
19870 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
19871 {
19872 	LPFC_MBOXQ_t *mboxq;
19873 	int rc = 0;
19874 	int retval = MBX_SUCCESS;
19875 	uint32_t mbox_tmo;
19876 	struct lpfc_hba *phba = vport->phba;
19877 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19878 	if (!mboxq)
19879 		return -ENOMEM;
19880 	lpfc_init_vpi(phba, mboxq, vport->vpi);
19881 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
19882 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
19883 	if (rc != MBX_SUCCESS) {
19884 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19885 				"2022 INIT VPI Mailbox failed "
19886 				"status %d, mbxStatus x%x\n", rc,
19887 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19888 		retval = -EIO;
19889 	}
19890 	if (rc != MBX_TIMEOUT)
19891 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
19892 
19893 	return retval;
19894 }
19895 
19896 /**
19897  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
19898  * @phba: pointer to lpfc hba data structure.
19899  * @mboxq: Pointer to mailbox object.
19900  *
19901  * This routine is invoked to manually add a single FCF record. The caller
19902  * must pass a completely initialized FCF_Record.  This routine takes
19903  * care of the nonembedded mailbox operations.
19904  **/
19905 static void
19906 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
19907 {
19908 	void *virt_addr;
19909 	union lpfc_sli4_cfg_shdr *shdr;
19910 	uint32_t shdr_status, shdr_add_status;
19911 
19912 	virt_addr = mboxq->sge_array->addr[0];
19913 	/* The IOCTL status is embedded in the mailbox subheader. */
19914 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
19915 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19916 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19917 
19918 	if ((shdr_status || shdr_add_status) &&
19919 		(shdr_status != STATUS_FCF_IN_USE))
19920 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19921 			"2558 ADD_FCF_RECORD mailbox failed with "
19922 			"status x%x add_status x%x\n",
19923 			shdr_status, shdr_add_status);
19924 
19925 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
19926 }
19927 
19928 /**
19929  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
19930  * @phba: pointer to lpfc hba data structure.
19931  * @fcf_record:  pointer to the initialized fcf record to add.
19932  *
19933  * This routine is invoked to manually add a single FCF record. The caller
19934  * must pass a completely initialized FCF_Record.  This routine takes
19935  * care of the nonembedded mailbox operations.
19936  **/
19937 int
19938 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
19939 {
19940 	int rc = 0;
19941 	LPFC_MBOXQ_t *mboxq;
19942 	uint8_t *bytep;
19943 	void *virt_addr;
19944 	struct lpfc_mbx_sge sge;
19945 	uint32_t alloc_len, req_len;
19946 	uint32_t fcfindex;
19947 
19948 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19949 	if (!mboxq) {
19950 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19951 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
19952 		return -ENOMEM;
19953 	}
19954 
19955 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
19956 		  sizeof(uint32_t);
19957 
19958 	/* Allocate DMA memory and set up the non-embedded mailbox command */
19959 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19960 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
19961 				     req_len, LPFC_SLI4_MBX_NEMBED);
19962 	if (alloc_len < req_len) {
19963 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19964 			"2523 Allocated DMA memory size (x%x) is "
19965 			"less than the requested DMA memory "
19966 			"size (x%x)\n", alloc_len, req_len);
19967 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19968 		return -ENOMEM;
19969 	}
19970 
19971 	/*
19972 	 * Get the first SGE entry from the non-embedded DMA memory.  This
19973 	 * routine only uses a single SGE.
19974 	 */
19975 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
19976 	virt_addr = mboxq->sge_array->addr[0];
19977 	/*
19978 	 * Configure the FCF record for FCFI 0.  This is the driver's
19979 	 * hardcoded default and gets used in nonFIP mode.
19980 	 */
19981 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
19982 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
19983 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
19984 
19985 	/*
19986 	 * Copy the fcf_index and the FCF Record Data. The data starts after
19987 	 * the FCoE header plus word10. The data copy needs to be endian
19988 	 * correct.
19989 	 */
19990 	bytep += sizeof(uint32_t);
19991 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
19992 	mboxq->vport = phba->pport;
19993 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
19994 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19995 	if (rc == MBX_NOT_FINISHED) {
19996 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19997 			"2515 ADD_FCF_RECORD mailbox failed with "
19998 			"status 0x%x\n", rc);
19999 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20000 		rc = -EIO;
20001 	} else
20002 		rc = 0;
20003 
20004 	return rc;
20005 }
20006 
20007 /**
20008  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
20009  * @phba: pointer to lpfc hba data structure.
20010  * @fcf_record:  pointer to the fcf record to write the default data.
20011  * @fcf_index: FCF table entry index.
20012  *
20013  * This routine is invoked to build the driver's default FCF record.  The
20014  * values used are hardcoded.  This routine handles memory initialization.
20015  *
20016  **/
20017 void
20018 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
20019 				struct fcf_record *fcf_record,
20020 				uint16_t fcf_index)
20021 {
20022 	memset(fcf_record, 0, sizeof(struct fcf_record));
20023 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
20024 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
20025 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
20026 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
20027 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
20028 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
20029 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
20030 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
20031 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
20032 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
20033 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
20034 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
20035 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
20036 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
20037 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
20038 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
20039 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
20040 	/* Set the VLAN bit map */
20041 	if (phba->valid_vlan) {
20042 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
20043 			= 1 << (phba->vlan_id % 8);
20044 	}
20045 }
20046 
20047 /**
20048  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
20049  * @phba: pointer to lpfc hba data structure.
20050  * @fcf_index: FCF table entry offset.
20051  *
20052  * This routine is invoked to scan the entire FCF table by reading FCF
20053  * record and processing it one at a time starting from the @fcf_index
20054  * for initial FCF discovery or fast FCF failover rediscovery.
20055  *
20056  * Return 0 if the mailbox command is submitted successfully, none 0
20057  * otherwise.
20058  **/
20059 int
20060 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20061 {
20062 	int rc = 0, error;
20063 	LPFC_MBOXQ_t *mboxq;
20064 
20065 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
20066 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
20067 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20068 	if (!mboxq) {
20069 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20070 				"2000 Failed to allocate mbox for "
20071 				"READ_FCF cmd\n");
20072 		error = -ENOMEM;
20073 		goto fail_fcf_scan;
20074 	}
20075 	/* Construct the read FCF record mailbox command */
20076 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20077 	if (rc) {
20078 		error = -EINVAL;
20079 		goto fail_fcf_scan;
20080 	}
20081 	/* Issue the mailbox command asynchronously */
20082 	mboxq->vport = phba->pport;
20083 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
20084 
20085 	spin_lock_irq(&phba->hbalock);
20086 	phba->hba_flag |= FCF_TS_INPROG;
20087 	spin_unlock_irq(&phba->hbalock);
20088 
20089 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20090 	if (rc == MBX_NOT_FINISHED)
20091 		error = -EIO;
20092 	else {
20093 		/* Reset eligible FCF count for new scan */
20094 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
20095 			phba->fcf.eligible_fcf_cnt = 0;
20096 		error = 0;
20097 	}
20098 fail_fcf_scan:
20099 	if (error) {
20100 		if (mboxq)
20101 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
20102 		/* FCF scan failed, clear FCF_TS_INPROG flag */
20103 		spin_lock_irq(&phba->hbalock);
20104 		phba->hba_flag &= ~FCF_TS_INPROG;
20105 		spin_unlock_irq(&phba->hbalock);
20106 	}
20107 	return error;
20108 }
20109 
20110 /**
20111  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
20112  * @phba: pointer to lpfc hba data structure.
20113  * @fcf_index: FCF table entry offset.
20114  *
20115  * This routine is invoked to read an FCF record indicated by @fcf_index
20116  * and to use it for FLOGI roundrobin FCF failover.
20117  *
20118  * Return 0 if the mailbox command is submitted successfully, none 0
20119  * otherwise.
20120  **/
20121 int
20122 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20123 {
20124 	int rc = 0, error;
20125 	LPFC_MBOXQ_t *mboxq;
20126 
20127 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20128 	if (!mboxq) {
20129 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20130 				"2763 Failed to allocate mbox for "
20131 				"READ_FCF cmd\n");
20132 		error = -ENOMEM;
20133 		goto fail_fcf_read;
20134 	}
20135 	/* Construct the read FCF record mailbox command */
20136 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20137 	if (rc) {
20138 		error = -EINVAL;
20139 		goto fail_fcf_read;
20140 	}
20141 	/* Issue the mailbox command asynchronously */
20142 	mboxq->vport = phba->pport;
20143 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
20144 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20145 	if (rc == MBX_NOT_FINISHED)
20146 		error = -EIO;
20147 	else
20148 		error = 0;
20149 
20150 fail_fcf_read:
20151 	if (error && mboxq)
20152 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20153 	return error;
20154 }
20155 
20156 /**
20157  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
20158  * @phba: pointer to lpfc hba data structure.
20159  * @fcf_index: FCF table entry offset.
20160  *
20161  * This routine is invoked to read an FCF record indicated by @fcf_index to
20162  * determine whether it's eligible for FLOGI roundrobin failover list.
20163  *
20164  * Return 0 if the mailbox command is submitted successfully, none 0
20165  * otherwise.
20166  **/
20167 int
20168 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20169 {
20170 	int rc = 0, error;
20171 	LPFC_MBOXQ_t *mboxq;
20172 
20173 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20174 	if (!mboxq) {
20175 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20176 				"2758 Failed to allocate mbox for "
20177 				"READ_FCF cmd\n");
20178 				error = -ENOMEM;
20179 				goto fail_fcf_read;
20180 	}
20181 	/* Construct the read FCF record mailbox command */
20182 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20183 	if (rc) {
20184 		error = -EINVAL;
20185 		goto fail_fcf_read;
20186 	}
20187 	/* Issue the mailbox command asynchronously */
20188 	mboxq->vport = phba->pport;
20189 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
20190 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20191 	if (rc == MBX_NOT_FINISHED)
20192 		error = -EIO;
20193 	else
20194 		error = 0;
20195 
20196 fail_fcf_read:
20197 	if (error && mboxq)
20198 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20199 	return error;
20200 }
20201 
20202 /**
20203  * lpfc_check_next_fcf_pri_level
20204  * @phba: pointer to the lpfc_hba struct for this port.
20205  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
20206  * routine when the rr_bmask is empty. The FCF indecies are put into the
20207  * rr_bmask based on their priority level. Starting from the highest priority
20208  * to the lowest. The most likely FCF candidate will be in the highest
20209  * priority group. When this routine is called it searches the fcf_pri list for
20210  * next lowest priority group and repopulates the rr_bmask with only those
20211  * fcf_indexes.
20212  * returns:
20213  * 1=success 0=failure
20214  **/
20215 static int
20216 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
20217 {
20218 	uint16_t next_fcf_pri;
20219 	uint16_t last_index;
20220 	struct lpfc_fcf_pri *fcf_pri;
20221 	int rc;
20222 	int ret = 0;
20223 
20224 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20225 			LPFC_SLI4_FCF_TBL_INDX_MAX);
20226 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20227 			"3060 Last IDX %d\n", last_index);
20228 
20229 	/* Verify the priority list has 2 or more entries */
20230 	spin_lock_irq(&phba->hbalock);
20231 	if (list_empty(&phba->fcf.fcf_pri_list) ||
20232 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
20233 		spin_unlock_irq(&phba->hbalock);
20234 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20235 			"3061 Last IDX %d\n", last_index);
20236 		return 0; /* Empty rr list */
20237 	}
20238 	spin_unlock_irq(&phba->hbalock);
20239 
20240 	next_fcf_pri = 0;
20241 	/*
20242 	 * Clear the rr_bmask and set all of the bits that are at this
20243 	 * priority.
20244 	 */
20245 	memset(phba->fcf.fcf_rr_bmask, 0,
20246 			sizeof(*phba->fcf.fcf_rr_bmask));
20247 	spin_lock_irq(&phba->hbalock);
20248 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20249 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
20250 			continue;
20251 		/*
20252 		 * the 1st priority that has not FLOGI failed
20253 		 * will be the highest.
20254 		 */
20255 		if (!next_fcf_pri)
20256 			next_fcf_pri = fcf_pri->fcf_rec.priority;
20257 		spin_unlock_irq(&phba->hbalock);
20258 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20259 			rc = lpfc_sli4_fcf_rr_index_set(phba,
20260 						fcf_pri->fcf_rec.fcf_index);
20261 			if (rc)
20262 				return 0;
20263 		}
20264 		spin_lock_irq(&phba->hbalock);
20265 	}
20266 	/*
20267 	 * if next_fcf_pri was not set above and the list is not empty then
20268 	 * we have failed flogis on all of them. So reset flogi failed
20269 	 * and start at the beginning.
20270 	 */
20271 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
20272 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20273 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
20274 			/*
20275 			 * the 1st priority that has not FLOGI failed
20276 			 * will be the highest.
20277 			 */
20278 			if (!next_fcf_pri)
20279 				next_fcf_pri = fcf_pri->fcf_rec.priority;
20280 			spin_unlock_irq(&phba->hbalock);
20281 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20282 				rc = lpfc_sli4_fcf_rr_index_set(phba,
20283 						fcf_pri->fcf_rec.fcf_index);
20284 				if (rc)
20285 					return 0;
20286 			}
20287 			spin_lock_irq(&phba->hbalock);
20288 		}
20289 	} else
20290 		ret = 1;
20291 	spin_unlock_irq(&phba->hbalock);
20292 
20293 	return ret;
20294 }
20295 /**
20296  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
20297  * @phba: pointer to lpfc hba data structure.
20298  *
20299  * This routine is to get the next eligible FCF record index in a round
20300  * robin fashion. If the next eligible FCF record index equals to the
20301  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
20302  * shall be returned, otherwise, the next eligible FCF record's index
20303  * shall be returned.
20304  **/
20305 uint16_t
20306 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
20307 {
20308 	uint16_t next_fcf_index;
20309 
20310 initial_priority:
20311 	/* Search start from next bit of currently registered FCF index */
20312 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
20313 
20314 next_priority:
20315 	/* Determine the next fcf index to check */
20316 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
20317 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
20318 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
20319 				       next_fcf_index);
20320 
20321 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
20322 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20323 		/*
20324 		 * If we have wrapped then we need to clear the bits that
20325 		 * have been tested so that we can detect when we should
20326 		 * change the priority level.
20327 		 */
20328 		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
20329 					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
20330 	}
20331 
20332 
20333 	/* Check roundrobin failover list empty condition */
20334 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
20335 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
20336 		/*
20337 		 * If next fcf index is not found check if there are lower
20338 		 * Priority level fcf's in the fcf_priority list.
20339 		 * Set up the rr_bmask with all of the avaiable fcf bits
20340 		 * at that level and continue the selection process.
20341 		 */
20342 		if (lpfc_check_next_fcf_pri_level(phba))
20343 			goto initial_priority;
20344 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
20345 				"2844 No roundrobin failover FCF available\n");
20346 
20347 		return LPFC_FCOE_FCF_NEXT_NONE;
20348 	}
20349 
20350 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
20351 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
20352 		LPFC_FCF_FLOGI_FAILED) {
20353 		if (list_is_singular(&phba->fcf.fcf_pri_list))
20354 			return LPFC_FCOE_FCF_NEXT_NONE;
20355 
20356 		goto next_priority;
20357 	}
20358 
20359 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20360 			"2845 Get next roundrobin failover FCF (x%x)\n",
20361 			next_fcf_index);
20362 
20363 	return next_fcf_index;
20364 }
20365 
20366 /**
20367  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
20368  * @phba: pointer to lpfc hba data structure.
20369  * @fcf_index: index into the FCF table to 'set'
20370  *
20371  * This routine sets the FCF record index in to the eligible bmask for
20372  * roundrobin failover search. It checks to make sure that the index
20373  * does not go beyond the range of the driver allocated bmask dimension
20374  * before setting the bit.
20375  *
20376  * Returns 0 if the index bit successfully set, otherwise, it returns
20377  * -EINVAL.
20378  **/
20379 int
20380 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
20381 {
20382 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20383 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20384 				"2610 FCF (x%x) reached driver's book "
20385 				"keeping dimension:x%x\n",
20386 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20387 		return -EINVAL;
20388 	}
20389 	/* Set the eligible FCF record index bmask */
20390 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20391 
20392 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20393 			"2790 Set FCF (x%x) to roundrobin FCF failover "
20394 			"bmask\n", fcf_index);
20395 
20396 	return 0;
20397 }
20398 
20399 /**
20400  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
20401  * @phba: pointer to lpfc hba data structure.
20402  * @fcf_index: index into the FCF table to 'clear'
20403  *
20404  * This routine clears the FCF record index from the eligible bmask for
20405  * roundrobin failover search. It checks to make sure that the index
20406  * does not go beyond the range of the driver allocated bmask dimension
20407  * before clearing the bit.
20408  **/
20409 void
20410 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
20411 {
20412 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
20413 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20414 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20415 				"2762 FCF (x%x) reached driver's book "
20416 				"keeping dimension:x%x\n",
20417 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20418 		return;
20419 	}
20420 	/* Clear the eligible FCF record index bmask */
20421 	spin_lock_irq(&phba->hbalock);
20422 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
20423 				 list) {
20424 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
20425 			list_del_init(&fcf_pri->list);
20426 			break;
20427 		}
20428 	}
20429 	spin_unlock_irq(&phba->hbalock);
20430 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20431 
20432 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20433 			"2791 Clear FCF (x%x) from roundrobin failover "
20434 			"bmask\n", fcf_index);
20435 }
20436 
20437 /**
20438  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
20439  * @phba: pointer to lpfc hba data structure.
20440  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
20441  *
20442  * This routine is the completion routine for the rediscover FCF table mailbox
20443  * command. If the mailbox command returned failure, it will try to stop the
20444  * FCF rediscover wait timer.
20445  **/
20446 static void
20447 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
20448 {
20449 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20450 	uint32_t shdr_status, shdr_add_status;
20451 
20452 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20453 
20454 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20455 			     &redisc_fcf->header.cfg_shdr.response);
20456 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20457 			     &redisc_fcf->header.cfg_shdr.response);
20458 	if (shdr_status || shdr_add_status) {
20459 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20460 				"2746 Requesting for FCF rediscovery failed "
20461 				"status x%x add_status x%x\n",
20462 				shdr_status, shdr_add_status);
20463 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
20464 			spin_lock_irq(&phba->hbalock);
20465 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
20466 			spin_unlock_irq(&phba->hbalock);
20467 			/*
20468 			 * CVL event triggered FCF rediscover request failed,
20469 			 * last resort to re-try current registered FCF entry.
20470 			 */
20471 			lpfc_retry_pport_discovery(phba);
20472 		} else {
20473 			spin_lock_irq(&phba->hbalock);
20474 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
20475 			spin_unlock_irq(&phba->hbalock);
20476 			/*
20477 			 * DEAD FCF event triggered FCF rediscover request
20478 			 * failed, last resort to fail over as a link down
20479 			 * to FCF registration.
20480 			 */
20481 			lpfc_sli4_fcf_dead_failthrough(phba);
20482 		}
20483 	} else {
20484 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20485 				"2775 Start FCF rediscover quiescent timer\n");
20486 		/*
20487 		 * Start FCF rediscovery wait timer for pending FCF
20488 		 * before rescan FCF record table.
20489 		 */
20490 		lpfc_fcf_redisc_wait_start_timer(phba);
20491 	}
20492 
20493 	mempool_free(mbox, phba->mbox_mem_pool);
20494 }
20495 
20496 /**
20497  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
20498  * @phba: pointer to lpfc hba data structure.
20499  *
20500  * This routine is invoked to request for rediscovery of the entire FCF table
20501  * by the port.
20502  **/
20503 int
20504 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
20505 {
20506 	LPFC_MBOXQ_t *mbox;
20507 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20508 	int rc, length;
20509 
20510 	/* Cancel retry delay timers to all vports before FCF rediscover */
20511 	lpfc_cancel_all_vport_retry_delay_timer(phba);
20512 
20513 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20514 	if (!mbox) {
20515 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20516 				"2745 Failed to allocate mbox for "
20517 				"requesting FCF rediscover.\n");
20518 		return -ENOMEM;
20519 	}
20520 
20521 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
20522 		  sizeof(struct lpfc_sli4_cfg_mhdr));
20523 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
20524 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
20525 			 length, LPFC_SLI4_MBX_EMBED);
20526 
20527 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20528 	/* Set count to 0 for invalidating the entire FCF database */
20529 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
20530 
20531 	/* Issue the mailbox command asynchronously */
20532 	mbox->vport = phba->pport;
20533 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
20534 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
20535 
20536 	if (rc == MBX_NOT_FINISHED) {
20537 		mempool_free(mbox, phba->mbox_mem_pool);
20538 		return -EIO;
20539 	}
20540 	return 0;
20541 }
20542 
20543 /**
20544  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
20545  * @phba: pointer to lpfc hba data structure.
20546  *
20547  * This function is the failover routine as a last resort to the FCF DEAD
20548  * event when driver failed to perform fast FCF failover.
20549  **/
20550 void
20551 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
20552 {
20553 	uint32_t link_state;
20554 
20555 	/*
20556 	 * Last resort as FCF DEAD event failover will treat this as
20557 	 * a link down, but save the link state because we don't want
20558 	 * it to be changed to Link Down unless it is already down.
20559 	 */
20560 	link_state = phba->link_state;
20561 	lpfc_linkdown(phba);
20562 	phba->link_state = link_state;
20563 
20564 	/* Unregister FCF if no devices connected to it */
20565 	lpfc_unregister_unused_fcf(phba);
20566 }
20567 
20568 /**
20569  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
20570  * @phba: pointer to lpfc hba data structure.
20571  * @rgn23_data: pointer to configure region 23 data.
20572  *
20573  * This function gets SLI3 port configure region 23 data through memory dump
20574  * mailbox command. When it successfully retrieves data, the size of the data
20575  * will be returned, otherwise, 0 will be returned.
20576  **/
20577 static uint32_t
20578 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20579 {
20580 	LPFC_MBOXQ_t *pmb = NULL;
20581 	MAILBOX_t *mb;
20582 	uint32_t offset = 0;
20583 	int rc;
20584 
20585 	if (!rgn23_data)
20586 		return 0;
20587 
20588 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20589 	if (!pmb) {
20590 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20591 				"2600 failed to allocate mailbox memory\n");
20592 		return 0;
20593 	}
20594 	mb = &pmb->u.mb;
20595 
20596 	do {
20597 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
20598 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
20599 
20600 		if (rc != MBX_SUCCESS) {
20601 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20602 					"2601 failed to read config "
20603 					"region 23, rc 0x%x Status 0x%x\n",
20604 					rc, mb->mbxStatus);
20605 			mb->un.varDmp.word_cnt = 0;
20606 		}
20607 		/*
20608 		 * dump mem may return a zero when finished or we got a
20609 		 * mailbox error, either way we are done.
20610 		 */
20611 		if (mb->un.varDmp.word_cnt == 0)
20612 			break;
20613 
20614 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
20615 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
20616 
20617 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
20618 				       rgn23_data + offset,
20619 				       mb->un.varDmp.word_cnt);
20620 		offset += mb->un.varDmp.word_cnt;
20621 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
20622 
20623 	mempool_free(pmb, phba->mbox_mem_pool);
20624 	return offset;
20625 }
20626 
20627 /**
20628  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
20629  * @phba: pointer to lpfc hba data structure.
20630  * @rgn23_data: pointer to configure region 23 data.
20631  *
20632  * This function gets SLI4 port configure region 23 data through memory dump
20633  * mailbox command. When it successfully retrieves data, the size of the data
20634  * will be returned, otherwise, 0 will be returned.
20635  **/
20636 static uint32_t
20637 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20638 {
20639 	LPFC_MBOXQ_t *mboxq = NULL;
20640 	struct lpfc_dmabuf *mp = NULL;
20641 	struct lpfc_mqe *mqe;
20642 	uint32_t data_length = 0;
20643 	int rc;
20644 
20645 	if (!rgn23_data)
20646 		return 0;
20647 
20648 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20649 	if (!mboxq) {
20650 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20651 				"3105 failed to allocate mailbox memory\n");
20652 		return 0;
20653 	}
20654 
20655 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
20656 		goto out;
20657 	mqe = &mboxq->u.mqe;
20658 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
20659 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
20660 	if (rc)
20661 		goto out;
20662 	data_length = mqe->un.mb_words[5];
20663 	if (data_length == 0)
20664 		goto out;
20665 	if (data_length > DMP_RGN23_SIZE) {
20666 		data_length = 0;
20667 		goto out;
20668 	}
20669 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
20670 out:
20671 	mempool_free(mboxq, phba->mbox_mem_pool);
20672 	if (mp) {
20673 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
20674 		kfree(mp);
20675 	}
20676 	return data_length;
20677 }
20678 
20679 /**
20680  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
20681  * @phba: pointer to lpfc hba data structure.
20682  *
20683  * This function read region 23 and parse TLV for port status to
20684  * decide if the user disaled the port. If the TLV indicates the
20685  * port is disabled, the hba_flag is set accordingly.
20686  **/
20687 void
20688 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
20689 {
20690 	uint8_t *rgn23_data = NULL;
20691 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
20692 	uint32_t offset = 0;
20693 
20694 	/* Get adapter Region 23 data */
20695 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
20696 	if (!rgn23_data)
20697 		goto out;
20698 
20699 	if (phba->sli_rev < LPFC_SLI_REV4)
20700 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
20701 	else {
20702 		if_type = bf_get(lpfc_sli_intf_if_type,
20703 				 &phba->sli4_hba.sli_intf);
20704 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
20705 			goto out;
20706 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
20707 	}
20708 
20709 	if (!data_size)
20710 		goto out;
20711 
20712 	/* Check the region signature first */
20713 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
20714 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20715 			"2619 Config region 23 has bad signature\n");
20716 			goto out;
20717 	}
20718 	offset += 4;
20719 
20720 	/* Check the data structure version */
20721 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
20722 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20723 			"2620 Config region 23 has bad version\n");
20724 		goto out;
20725 	}
20726 	offset += 4;
20727 
20728 	/* Parse TLV entries in the region */
20729 	while (offset < data_size) {
20730 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
20731 			break;
20732 		/*
20733 		 * If the TLV is not driver specific TLV or driver id is
20734 		 * not linux driver id, skip the record.
20735 		 */
20736 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
20737 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
20738 		    (rgn23_data[offset + 3] != 0)) {
20739 			offset += rgn23_data[offset + 1] * 4 + 4;
20740 			continue;
20741 		}
20742 
20743 		/* Driver found a driver specific TLV in the config region */
20744 		sub_tlv_len = rgn23_data[offset + 1] * 4;
20745 		offset += 4;
20746 		tlv_offset = 0;
20747 
20748 		/*
20749 		 * Search for configured port state sub-TLV.
20750 		 */
20751 		while ((offset < data_size) &&
20752 			(tlv_offset < sub_tlv_len)) {
20753 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
20754 				offset += 4;
20755 				tlv_offset += 4;
20756 				break;
20757 			}
20758 			if (rgn23_data[offset] != PORT_STE_TYPE) {
20759 				offset += rgn23_data[offset + 1] * 4 + 4;
20760 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
20761 				continue;
20762 			}
20763 
20764 			/* This HBA contains PORT_STE configured */
20765 			if (!rgn23_data[offset + 2])
20766 				phba->hba_flag |= LINK_DISABLED;
20767 
20768 			goto out;
20769 		}
20770 	}
20771 
20772 out:
20773 	kfree(rgn23_data);
20774 	return;
20775 }
20776 
20777 /**
20778  * lpfc_log_fw_write_cmpl - logs firmware write completion status
20779  * @phba: pointer to lpfc hba data structure
20780  * @shdr_status: wr_object rsp's status field
20781  * @shdr_add_status: wr_object rsp's add_status field
20782  * @shdr_add_status_2: wr_object rsp's add_status_2 field
20783  * @shdr_change_status: wr_object rsp's change_status field
20784  * @shdr_csf: wr_object rsp's csf bit
20785  *
20786  * This routine is intended to be called after a firmware write completes.
20787  * It will log next action items to be performed by the user to instantiate
20788  * the newly downloaded firmware or reason for incompatibility.
20789  **/
20790 static void
20791 lpfc_log_fw_write_cmpl(struct lpfc_hba *phba, u32 shdr_status,
20792 		       u32 shdr_add_status, u32 shdr_add_status_2,
20793 		       u32 shdr_change_status, u32 shdr_csf)
20794 {
20795 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20796 			"4198 %s: flash_id x%02x, asic_rev x%02x, "
20797 			"status x%02x, add_status x%02x, add_status_2 x%02x, "
20798 			"change_status x%02x, csf %01x\n", __func__,
20799 			phba->sli4_hba.flash_id, phba->sli4_hba.asic_rev,
20800 			shdr_status, shdr_add_status, shdr_add_status_2,
20801 			shdr_change_status, shdr_csf);
20802 
20803 	if (shdr_add_status == LPFC_ADD_STATUS_INCOMPAT_OBJ) {
20804 		switch (shdr_add_status_2) {
20805 		case LPFC_ADD_STATUS_2_INCOMPAT_FLASH:
20806 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20807 					"4199 Firmware write failed: "
20808 					"image incompatible with flash x%02x\n",
20809 					phba->sli4_hba.flash_id);
20810 			break;
20811 		case LPFC_ADD_STATUS_2_INCORRECT_ASIC:
20812 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20813 					"4200 Firmware write failed: "
20814 					"image incompatible with ASIC "
20815 					"architecture x%02x\n",
20816 					phba->sli4_hba.asic_rev);
20817 			break;
20818 		default:
20819 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20820 					"4210 Firmware write failed: "
20821 					"add_status_2 x%02x\n",
20822 					shdr_add_status_2);
20823 			break;
20824 		}
20825 	} else if (!shdr_status && !shdr_add_status) {
20826 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20827 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20828 			if (shdr_csf)
20829 				shdr_change_status =
20830 						   LPFC_CHANGE_STATUS_PCI_RESET;
20831 		}
20832 
20833 		switch (shdr_change_status) {
20834 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20835 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20836 					"3198 Firmware write complete: System "
20837 					"reboot required to instantiate\n");
20838 			break;
20839 		case (LPFC_CHANGE_STATUS_FW_RESET):
20840 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20841 					"3199 Firmware write complete: "
20842 					"Firmware reset required to "
20843 					"instantiate\n");
20844 			break;
20845 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20846 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20847 					"3200 Firmware write complete: Port "
20848 					"Migration or PCI Reset required to "
20849 					"instantiate\n");
20850 			break;
20851 		case (LPFC_CHANGE_STATUS_PCI_RESET):
20852 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20853 					"3201 Firmware write complete: PCI "
20854 					"Reset required to instantiate\n");
20855 			break;
20856 		default:
20857 			break;
20858 		}
20859 	}
20860 }
20861 
20862 /**
20863  * lpfc_wr_object - write an object to the firmware
20864  * @phba: HBA structure that indicates port to create a queue on.
20865  * @dmabuf_list: list of dmabufs to write to the port.
20866  * @size: the total byte value of the objects to write to the port.
20867  * @offset: the current offset to be used to start the transfer.
20868  *
20869  * This routine will create a wr_object mailbox command to send to the port.
20870  * the mailbox command will be constructed using the dma buffers described in
20871  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
20872  * BDEs that the imbedded mailbox can support. The @offset variable will be
20873  * used to indicate the starting offset of the transfer and will also return
20874  * the offset after the write object mailbox has completed. @size is used to
20875  * determine the end of the object and whether the eof bit should be set.
20876  *
20877  * Return 0 is successful and offset will contain the the new offset to use
20878  * for the next write.
20879  * Return negative value for error cases.
20880  **/
20881 int
20882 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
20883 	       uint32_t size, uint32_t *offset)
20884 {
20885 	struct lpfc_mbx_wr_object *wr_object;
20886 	LPFC_MBOXQ_t *mbox;
20887 	int rc = 0, i = 0;
20888 	uint32_t shdr_status, shdr_add_status, shdr_add_status_2;
20889 	uint32_t shdr_change_status = 0, shdr_csf = 0;
20890 	uint32_t mbox_tmo;
20891 	struct lpfc_dmabuf *dmabuf;
20892 	uint32_t written = 0;
20893 	bool check_change_status = false;
20894 
20895 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20896 	if (!mbox)
20897 		return -ENOMEM;
20898 
20899 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
20900 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
20901 			sizeof(struct lpfc_mbx_wr_object) -
20902 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
20903 
20904 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
20905 	wr_object->u.request.write_offset = *offset;
20906 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
20907 	wr_object->u.request.object_name[0] =
20908 		cpu_to_le32(wr_object->u.request.object_name[0]);
20909 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
20910 	list_for_each_entry(dmabuf, dmabuf_list, list) {
20911 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
20912 			break;
20913 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
20914 		wr_object->u.request.bde[i].addrHigh =
20915 			putPaddrHigh(dmabuf->phys);
20916 		if (written + SLI4_PAGE_SIZE >= size) {
20917 			wr_object->u.request.bde[i].tus.f.bdeSize =
20918 				(size - written);
20919 			written += (size - written);
20920 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
20921 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
20922 			check_change_status = true;
20923 		} else {
20924 			wr_object->u.request.bde[i].tus.f.bdeSize =
20925 				SLI4_PAGE_SIZE;
20926 			written += SLI4_PAGE_SIZE;
20927 		}
20928 		i++;
20929 	}
20930 	wr_object->u.request.bde_count = i;
20931 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
20932 	if (!phba->sli4_hba.intr_enable)
20933 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
20934 	else {
20935 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
20936 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
20937 	}
20938 	/* The IOCTL status is embedded in the mailbox subheader. */
20939 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20940 			     &wr_object->header.cfg_shdr.response);
20941 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20942 				 &wr_object->header.cfg_shdr.response);
20943 	shdr_add_status_2 = bf_get(lpfc_mbox_hdr_add_status_2,
20944 				   &wr_object->header.cfg_shdr.response);
20945 	if (check_change_status) {
20946 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
20947 					    &wr_object->u.response);
20948 		shdr_csf = bf_get(lpfc_wr_object_csf,
20949 				  &wr_object->u.response);
20950 	}
20951 
20952 	if (!phba->sli4_hba.intr_enable)
20953 		mempool_free(mbox, phba->mbox_mem_pool);
20954 	else if (rc != MBX_TIMEOUT)
20955 		mempool_free(mbox, phba->mbox_mem_pool);
20956 	if (shdr_status || shdr_add_status || shdr_add_status_2 || rc) {
20957 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20958 				"3025 Write Object mailbox failed with "
20959 				"status x%x add_status x%x, add_status_2 x%x, "
20960 				"mbx status x%x\n",
20961 				shdr_status, shdr_add_status, shdr_add_status_2,
20962 				rc);
20963 		rc = -ENXIO;
20964 		*offset = shdr_add_status;
20965 	} else {
20966 		*offset += wr_object->u.response.actual_write_length;
20967 	}
20968 
20969 	if (rc || check_change_status)
20970 		lpfc_log_fw_write_cmpl(phba, shdr_status, shdr_add_status,
20971 				       shdr_add_status_2, shdr_change_status,
20972 				       shdr_csf);
20973 	return rc;
20974 }
20975 
20976 /**
20977  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
20978  * @vport: pointer to vport data structure.
20979  *
20980  * This function iterate through the mailboxq and clean up all REG_LOGIN
20981  * and REG_VPI mailbox commands associated with the vport. This function
20982  * is called when driver want to restart discovery of the vport due to
20983  * a Clear Virtual Link event.
20984  **/
20985 void
20986 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
20987 {
20988 	struct lpfc_hba *phba = vport->phba;
20989 	LPFC_MBOXQ_t *mb, *nextmb;
20990 	struct lpfc_dmabuf *mp;
20991 	struct lpfc_nodelist *ndlp;
20992 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
20993 	LIST_HEAD(mbox_cmd_list);
20994 	uint8_t restart_loop;
20995 
20996 	/* Clean up internally queued mailbox commands with the vport */
20997 	spin_lock_irq(&phba->hbalock);
20998 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
20999 		if (mb->vport != vport)
21000 			continue;
21001 
21002 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21003 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
21004 			continue;
21005 
21006 		list_move_tail(&mb->list, &mbox_cmd_list);
21007 	}
21008 	/* Clean up active mailbox command with the vport */
21009 	mb = phba->sli.mbox_active;
21010 	if (mb && (mb->vport == vport)) {
21011 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
21012 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
21013 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21014 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21015 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
21016 			/* Put reference count for delayed processing */
21017 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
21018 			/* Unregister the RPI when mailbox complete */
21019 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21020 		}
21021 	}
21022 	/* Cleanup any mailbox completions which are not yet processed */
21023 	do {
21024 		restart_loop = 0;
21025 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
21026 			/*
21027 			 * If this mailox is already processed or it is
21028 			 * for another vport ignore it.
21029 			 */
21030 			if ((mb->vport != vport) ||
21031 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
21032 				continue;
21033 
21034 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21035 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
21036 				continue;
21037 
21038 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21039 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21040 				ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
21041 				/* Unregister the RPI when mailbox complete */
21042 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21043 				restart_loop = 1;
21044 				spin_unlock_irq(&phba->hbalock);
21045 				spin_lock(&ndlp->lock);
21046 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21047 				spin_unlock(&ndlp->lock);
21048 				spin_lock_irq(&phba->hbalock);
21049 				break;
21050 			}
21051 		}
21052 	} while (restart_loop);
21053 
21054 	spin_unlock_irq(&phba->hbalock);
21055 
21056 	/* Release the cleaned-up mailbox commands */
21057 	while (!list_empty(&mbox_cmd_list)) {
21058 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
21059 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21060 			mp = (struct lpfc_dmabuf *)(mb->ctx_buf);
21061 			if (mp) {
21062 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
21063 				kfree(mp);
21064 			}
21065 			mb->ctx_buf = NULL;
21066 			ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
21067 			mb->ctx_ndlp = NULL;
21068 			if (ndlp) {
21069 				spin_lock(&ndlp->lock);
21070 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21071 				spin_unlock(&ndlp->lock);
21072 				lpfc_nlp_put(ndlp);
21073 			}
21074 		}
21075 		mempool_free(mb, phba->mbox_mem_pool);
21076 	}
21077 
21078 	/* Release the ndlp with the cleaned-up active mailbox command */
21079 	if (act_mbx_ndlp) {
21080 		spin_lock(&act_mbx_ndlp->lock);
21081 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21082 		spin_unlock(&act_mbx_ndlp->lock);
21083 		lpfc_nlp_put(act_mbx_ndlp);
21084 	}
21085 }
21086 
21087 /**
21088  * lpfc_drain_txq - Drain the txq
21089  * @phba: Pointer to HBA context object.
21090  *
21091  * This function attempt to submit IOCBs on the txq
21092  * to the adapter.  For SLI4 adapters, the txq contains
21093  * ELS IOCBs that have been deferred because the there
21094  * are no SGLs.  This congestion can occur with large
21095  * vport counts during node discovery.
21096  **/
21097 
21098 uint32_t
21099 lpfc_drain_txq(struct lpfc_hba *phba)
21100 {
21101 	LIST_HEAD(completions);
21102 	struct lpfc_sli_ring *pring;
21103 	struct lpfc_iocbq *piocbq = NULL;
21104 	unsigned long iflags = 0;
21105 	char *fail_msg = NULL;
21106 	struct lpfc_sglq *sglq;
21107 	union lpfc_wqe128 wqe;
21108 	uint32_t txq_cnt = 0;
21109 	struct lpfc_queue *wq;
21110 
21111 	if (phba->link_flag & LS_MDS_LOOPBACK) {
21112 		/* MDS WQE are posted only to first WQ*/
21113 		wq = phba->sli4_hba.hdwq[0].io_wq;
21114 		if (unlikely(!wq))
21115 			return 0;
21116 		pring = wq->pring;
21117 	} else {
21118 		wq = phba->sli4_hba.els_wq;
21119 		if (unlikely(!wq))
21120 			return 0;
21121 		pring = lpfc_phba_elsring(phba);
21122 	}
21123 
21124 	if (unlikely(!pring) || list_empty(&pring->txq))
21125 		return 0;
21126 
21127 	spin_lock_irqsave(&pring->ring_lock, iflags);
21128 	list_for_each_entry(piocbq, &pring->txq, list) {
21129 		txq_cnt++;
21130 	}
21131 
21132 	if (txq_cnt > pring->txq_max)
21133 		pring->txq_max = txq_cnt;
21134 
21135 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
21136 
21137 	while (!list_empty(&pring->txq)) {
21138 		spin_lock_irqsave(&pring->ring_lock, iflags);
21139 
21140 		piocbq = lpfc_sli_ringtx_get(phba, pring);
21141 		if (!piocbq) {
21142 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21143 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21144 				"2823 txq empty and txq_cnt is %d\n ",
21145 				txq_cnt);
21146 			break;
21147 		}
21148 		sglq = __lpfc_sli_get_els_sglq(phba, piocbq);
21149 		if (!sglq) {
21150 			__lpfc_sli_ringtx_put(phba, pring, piocbq);
21151 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21152 			break;
21153 		}
21154 		txq_cnt--;
21155 
21156 		/* The xri and iocb resources secured,
21157 		 * attempt to issue request
21158 		 */
21159 		piocbq->sli4_lxritag = sglq->sli4_lxritag;
21160 		piocbq->sli4_xritag = sglq->sli4_xritag;
21161 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
21162 			fail_msg = "to convert bpl to sgl";
21163 		else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
21164 			fail_msg = "to convert iocb to wqe";
21165 		else if (lpfc_sli4_wq_put(wq, &wqe))
21166 			fail_msg = " - Wq is full";
21167 		else
21168 			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
21169 
21170 		if (fail_msg) {
21171 			/* Failed means we can't issue and need to cancel */
21172 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21173 					"2822 IOCB failed %s iotag 0x%x "
21174 					"xri 0x%x\n",
21175 					fail_msg,
21176 					piocbq->iotag, piocbq->sli4_xritag);
21177 			list_add_tail(&piocbq->list, &completions);
21178 			fail_msg = NULL;
21179 		}
21180 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21181 	}
21182 
21183 	/* Cancel all the IOCBs that cannot be issued */
21184 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
21185 				IOERR_SLI_ABORTED);
21186 
21187 	return txq_cnt;
21188 }
21189 
21190 /**
21191  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
21192  * @phba: Pointer to HBA context object.
21193  * @pwqeq: Pointer to command WQE.
21194  * @sglq: Pointer to the scatter gather queue object.
21195  *
21196  * This routine converts the bpl or bde that is in the WQE
21197  * to a sgl list for the sli4 hardware. The physical address
21198  * of the bpl/bde is converted back to a virtual address.
21199  * If the WQE contains a BPL then the list of BDE's is
21200  * converted to sli4_sge's. If the WQE contains a single
21201  * BDE then it is converted to a single sli_sge.
21202  * The WQE is still in cpu endianness so the contents of
21203  * the bpl can be used without byte swapping.
21204  *
21205  * Returns valid XRI = Success, NO_XRI = Failure.
21206  */
21207 static uint16_t
21208 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
21209 		 struct lpfc_sglq *sglq)
21210 {
21211 	uint16_t xritag = NO_XRI;
21212 	struct ulp_bde64 *bpl = NULL;
21213 	struct ulp_bde64 bde;
21214 	struct sli4_sge *sgl  = NULL;
21215 	struct lpfc_dmabuf *dmabuf;
21216 	union lpfc_wqe128 *wqe;
21217 	int numBdes = 0;
21218 	int i = 0;
21219 	uint32_t offset = 0; /* accumulated offset in the sg request list */
21220 	int inbound = 0; /* number of sg reply entries inbound from firmware */
21221 	uint32_t cmd;
21222 
21223 	if (!pwqeq || !sglq)
21224 		return xritag;
21225 
21226 	sgl  = (struct sli4_sge *)sglq->sgl;
21227 	wqe = &pwqeq->wqe;
21228 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
21229 
21230 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
21231 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
21232 		return sglq->sli4_xritag;
21233 	numBdes = pwqeq->rsvd2;
21234 	if (numBdes) {
21235 		/* The addrHigh and addrLow fields within the WQE
21236 		 * have not been byteswapped yet so there is no
21237 		 * need to swap them back.
21238 		 */
21239 		if (pwqeq->context3)
21240 			dmabuf = (struct lpfc_dmabuf *)pwqeq->context3;
21241 		else
21242 			return xritag;
21243 
21244 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
21245 		if (!bpl)
21246 			return xritag;
21247 
21248 		for (i = 0; i < numBdes; i++) {
21249 			/* Should already be byte swapped. */
21250 			sgl->addr_hi = bpl->addrHigh;
21251 			sgl->addr_lo = bpl->addrLow;
21252 
21253 			sgl->word2 = le32_to_cpu(sgl->word2);
21254 			if ((i+1) == numBdes)
21255 				bf_set(lpfc_sli4_sge_last, sgl, 1);
21256 			else
21257 				bf_set(lpfc_sli4_sge_last, sgl, 0);
21258 			/* swap the size field back to the cpu so we
21259 			 * can assign it to the sgl.
21260 			 */
21261 			bde.tus.w = le32_to_cpu(bpl->tus.w);
21262 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
21263 			/* The offsets in the sgl need to be accumulated
21264 			 * separately for the request and reply lists.
21265 			 * The request is always first, the reply follows.
21266 			 */
21267 			switch (cmd) {
21268 			case CMD_GEN_REQUEST64_WQE:
21269 				/* add up the reply sg entries */
21270 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
21271 					inbound++;
21272 				/* first inbound? reset the offset */
21273 				if (inbound == 1)
21274 					offset = 0;
21275 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21276 				bf_set(lpfc_sli4_sge_type, sgl,
21277 					LPFC_SGE_TYPE_DATA);
21278 				offset += bde.tus.f.bdeSize;
21279 				break;
21280 			case CMD_FCP_TRSP64_WQE:
21281 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
21282 				bf_set(lpfc_sli4_sge_type, sgl,
21283 					LPFC_SGE_TYPE_DATA);
21284 				break;
21285 			case CMD_FCP_TSEND64_WQE:
21286 			case CMD_FCP_TRECEIVE64_WQE:
21287 				bf_set(lpfc_sli4_sge_type, sgl,
21288 					bpl->tus.f.bdeFlags);
21289 				if (i < 3)
21290 					offset = 0;
21291 				else
21292 					offset += bde.tus.f.bdeSize;
21293 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21294 				break;
21295 			}
21296 			sgl->word2 = cpu_to_le32(sgl->word2);
21297 			bpl++;
21298 			sgl++;
21299 		}
21300 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
21301 		/* The addrHigh and addrLow fields of the BDE have not
21302 		 * been byteswapped yet so they need to be swapped
21303 		 * before putting them in the sgl.
21304 		 */
21305 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
21306 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
21307 		sgl->word2 = le32_to_cpu(sgl->word2);
21308 		bf_set(lpfc_sli4_sge_last, sgl, 1);
21309 		sgl->word2 = cpu_to_le32(sgl->word2);
21310 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
21311 	}
21312 	return sglq->sli4_xritag;
21313 }
21314 
21315 /**
21316  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
21317  * @phba: Pointer to HBA context object.
21318  * @qp: Pointer to HDW queue.
21319  * @pwqe: Pointer to command WQE.
21320  **/
21321 int
21322 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21323 		    struct lpfc_iocbq *pwqe)
21324 {
21325 	union lpfc_wqe128 *wqe = &pwqe->wqe;
21326 	struct lpfc_async_xchg_ctx *ctxp;
21327 	struct lpfc_queue *wq;
21328 	struct lpfc_sglq *sglq;
21329 	struct lpfc_sli_ring *pring;
21330 	unsigned long iflags;
21331 	uint32_t ret = 0;
21332 
21333 	/* NVME_LS and NVME_LS ABTS requests. */
21334 	if (pwqe->iocb_flag & LPFC_IO_NVME_LS) {
21335 		pring =  phba->sli4_hba.nvmels_wq->pring;
21336 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21337 					  qp, wq_access);
21338 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
21339 		if (!sglq) {
21340 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21341 			return WQE_BUSY;
21342 		}
21343 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
21344 		pwqe->sli4_xritag = sglq->sli4_xritag;
21345 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
21346 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21347 			return WQE_ERROR;
21348 		}
21349 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21350 		       pwqe->sli4_xritag);
21351 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
21352 		if (ret) {
21353 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21354 			return ret;
21355 		}
21356 
21357 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21358 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21359 
21360 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
21361 		return 0;
21362 	}
21363 
21364 	/* NVME_FCREQ and NVME_ABTS requests */
21365 	if (pwqe->iocb_flag & (LPFC_IO_NVME | LPFC_IO_FCP | LPFC_IO_CMF)) {
21366 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21367 		wq = qp->io_wq;
21368 		pring = wq->pring;
21369 
21370 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21371 
21372 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21373 					  qp, wq_access);
21374 		ret = lpfc_sli4_wq_put(wq, wqe);
21375 		if (ret) {
21376 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21377 			return ret;
21378 		}
21379 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21380 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21381 
21382 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
21383 		return 0;
21384 	}
21385 
21386 	/* NVMET requests */
21387 	if (pwqe->iocb_flag & LPFC_IO_NVMET) {
21388 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21389 		wq = qp->io_wq;
21390 		pring = wq->pring;
21391 
21392 		ctxp = pwqe->context2;
21393 		sglq = ctxp->ctxbuf->sglq;
21394 		if (pwqe->sli4_xritag ==  NO_XRI) {
21395 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
21396 			pwqe->sli4_xritag = sglq->sli4_xritag;
21397 		}
21398 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21399 		       pwqe->sli4_xritag);
21400 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21401 
21402 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21403 					  qp, wq_access);
21404 		ret = lpfc_sli4_wq_put(wq, wqe);
21405 		if (ret) {
21406 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21407 			return ret;
21408 		}
21409 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21410 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21411 
21412 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
21413 		return 0;
21414 	}
21415 	return WQE_ERROR;
21416 }
21417 
21418 /**
21419  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
21420  * @phba: Pointer to HBA context object.
21421  * @cmdiocb: Pointer to driver command iocb object.
21422  * @cmpl: completion function.
21423  *
21424  * Fill the appropriate fields for the abort WQE and call
21425  * internal routine lpfc_sli4_issue_wqe to send the WQE
21426  * This function is called with hbalock held and no ring_lock held.
21427  *
21428  * RETURNS 0 - SUCCESS
21429  **/
21430 
21431 int
21432 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
21433 			    void *cmpl)
21434 {
21435 	struct lpfc_vport *vport = cmdiocb->vport;
21436 	struct lpfc_iocbq *abtsiocb = NULL;
21437 	union lpfc_wqe128 *abtswqe;
21438 	struct lpfc_io_buf *lpfc_cmd;
21439 	int retval = IOCB_ERROR;
21440 	u16 xritag = cmdiocb->sli4_xritag;
21441 
21442 	/*
21443 	 * The scsi command can not be in txq and it is in flight because the
21444 	 * pCmd is still pointing at the SCSI command we have to abort. There
21445 	 * is no need to search the txcmplq. Just send an abort to the FW.
21446 	 */
21447 
21448 	abtsiocb = __lpfc_sli_get_iocbq(phba);
21449 	if (!abtsiocb)
21450 		return WQE_NORESOURCE;
21451 
21452 	/* Indicate the IO is being aborted by the driver. */
21453 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
21454 
21455 	abtswqe = &abtsiocb->wqe;
21456 	memset(abtswqe, 0, sizeof(*abtswqe));
21457 
21458 	if (!lpfc_is_link_up(phba))
21459 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
21460 	bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
21461 	abtswqe->abort_cmd.rsrvd5 = 0;
21462 	abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
21463 	bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
21464 	bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
21465 	bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
21466 	bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
21467 	bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
21468 	bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
21469 
21470 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
21471 	abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
21472 	abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
21473 	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
21474 		abtsiocb->iocb_flag |= LPFC_IO_FCP;
21475 	if (cmdiocb->iocb_flag & LPFC_IO_NVME)
21476 		abtsiocb->iocb_flag |= LPFC_IO_NVME;
21477 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
21478 		abtsiocb->iocb_flag |= LPFC_IO_FOF;
21479 	abtsiocb->vport = vport;
21480 	abtsiocb->wqe_cmpl = cmpl;
21481 
21482 	lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
21483 	retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
21484 
21485 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21486 			 "0359 Abort xri x%x, original iotag x%x, "
21487 			 "abort cmd iotag x%x retval x%x\n",
21488 			 xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
21489 
21490 	if (retval) {
21491 		cmdiocb->iocb_flag &= ~LPFC_DRIVER_ABORTED;
21492 		__lpfc_sli_release_iocbq(phba, abtsiocb);
21493 	}
21494 
21495 	return retval;
21496 }
21497 
21498 #ifdef LPFC_MXP_STAT
21499 /**
21500  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
21501  * @phba: pointer to lpfc hba data structure.
21502  * @hwqid: belong to which HWQ.
21503  *
21504  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
21505  * 15 seconds after a test case is running.
21506  *
21507  * The user should call lpfc_debugfs_multixripools_write before running a test
21508  * case to clear stat_snapshot_taken. Then the user starts a test case. During
21509  * test case is running, stat_snapshot_taken is incremented by 1 every time when
21510  * this routine is called from heartbeat timer. When stat_snapshot_taken is
21511  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
21512  **/
21513 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
21514 {
21515 	struct lpfc_sli4_hdw_queue *qp;
21516 	struct lpfc_multixri_pool *multixri_pool;
21517 	struct lpfc_pvt_pool *pvt_pool;
21518 	struct lpfc_pbl_pool *pbl_pool;
21519 	u32 txcmplq_cnt;
21520 
21521 	qp = &phba->sli4_hba.hdwq[hwqid];
21522 	multixri_pool = qp->p_multixri_pool;
21523 	if (!multixri_pool)
21524 		return;
21525 
21526 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
21527 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21528 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21529 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21530 
21531 		multixri_pool->stat_pbl_count = pbl_pool->count;
21532 		multixri_pool->stat_pvt_count = pvt_pool->count;
21533 		multixri_pool->stat_busy_count = txcmplq_cnt;
21534 	}
21535 
21536 	multixri_pool->stat_snapshot_taken++;
21537 }
21538 #endif
21539 
21540 /**
21541  * lpfc_adjust_pvt_pool_count - Adjust private pool count
21542  * @phba: pointer to lpfc hba data structure.
21543  * @hwqid: belong to which HWQ.
21544  *
21545  * This routine moves some XRIs from private to public pool when private pool
21546  * is not busy.
21547  **/
21548 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
21549 {
21550 	struct lpfc_multixri_pool *multixri_pool;
21551 	u32 io_req_count;
21552 	u32 prev_io_req_count;
21553 
21554 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21555 	if (!multixri_pool)
21556 		return;
21557 	io_req_count = multixri_pool->io_req_count;
21558 	prev_io_req_count = multixri_pool->prev_io_req_count;
21559 
21560 	if (prev_io_req_count != io_req_count) {
21561 		/* Private pool is busy */
21562 		multixri_pool->prev_io_req_count = io_req_count;
21563 	} else {
21564 		/* Private pool is not busy.
21565 		 * Move XRIs from private to public pool.
21566 		 */
21567 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
21568 	}
21569 }
21570 
21571 /**
21572  * lpfc_adjust_high_watermark - Adjust high watermark
21573  * @phba: pointer to lpfc hba data structure.
21574  * @hwqid: belong to which HWQ.
21575  *
21576  * This routine sets high watermark as number of outstanding XRIs,
21577  * but make sure the new value is between xri_limit/2 and xri_limit.
21578  **/
21579 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
21580 {
21581 	u32 new_watermark;
21582 	u32 watermark_max;
21583 	u32 watermark_min;
21584 	u32 xri_limit;
21585 	u32 txcmplq_cnt;
21586 	u32 abts_io_bufs;
21587 	struct lpfc_multixri_pool *multixri_pool;
21588 	struct lpfc_sli4_hdw_queue *qp;
21589 
21590 	qp = &phba->sli4_hba.hdwq[hwqid];
21591 	multixri_pool = qp->p_multixri_pool;
21592 	if (!multixri_pool)
21593 		return;
21594 	xri_limit = multixri_pool->xri_limit;
21595 
21596 	watermark_max = xri_limit;
21597 	watermark_min = xri_limit / 2;
21598 
21599 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21600 	abts_io_bufs = qp->abts_scsi_io_bufs;
21601 	abts_io_bufs += qp->abts_nvme_io_bufs;
21602 
21603 	new_watermark = txcmplq_cnt + abts_io_bufs;
21604 	new_watermark = min(watermark_max, new_watermark);
21605 	new_watermark = max(watermark_min, new_watermark);
21606 	multixri_pool->pvt_pool.high_watermark = new_watermark;
21607 
21608 #ifdef LPFC_MXP_STAT
21609 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
21610 					  new_watermark);
21611 #endif
21612 }
21613 
21614 /**
21615  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
21616  * @phba: pointer to lpfc hba data structure.
21617  * @hwqid: belong to which HWQ.
21618  *
21619  * This routine is called from hearbeat timer when pvt_pool is idle.
21620  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
21621  * The first step moves (all - low_watermark) amount of XRIs.
21622  * The second step moves the rest of XRIs.
21623  **/
21624 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
21625 {
21626 	struct lpfc_pbl_pool *pbl_pool;
21627 	struct lpfc_pvt_pool *pvt_pool;
21628 	struct lpfc_sli4_hdw_queue *qp;
21629 	struct lpfc_io_buf *lpfc_ncmd;
21630 	struct lpfc_io_buf *lpfc_ncmd_next;
21631 	unsigned long iflag;
21632 	struct list_head tmp_list;
21633 	u32 tmp_count;
21634 
21635 	qp = &phba->sli4_hba.hdwq[hwqid];
21636 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
21637 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
21638 	tmp_count = 0;
21639 
21640 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
21641 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
21642 
21643 	if (pvt_pool->count > pvt_pool->low_watermark) {
21644 		/* Step 1: move (all - low_watermark) from pvt_pool
21645 		 * to pbl_pool
21646 		 */
21647 
21648 		/* Move low watermark of bufs from pvt_pool to tmp_list */
21649 		INIT_LIST_HEAD(&tmp_list);
21650 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21651 					 &pvt_pool->list, list) {
21652 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
21653 			tmp_count++;
21654 			if (tmp_count >= pvt_pool->low_watermark)
21655 				break;
21656 		}
21657 
21658 		/* Move all bufs from pvt_pool to pbl_pool */
21659 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21660 
21661 		/* Move all bufs from tmp_list to pvt_pool */
21662 		list_splice(&tmp_list, &pvt_pool->list);
21663 
21664 		pbl_pool->count += (pvt_pool->count - tmp_count);
21665 		pvt_pool->count = tmp_count;
21666 	} else {
21667 		/* Step 2: move the rest from pvt_pool to pbl_pool */
21668 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21669 		pbl_pool->count += pvt_pool->count;
21670 		pvt_pool->count = 0;
21671 	}
21672 
21673 	spin_unlock(&pvt_pool->lock);
21674 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21675 }
21676 
21677 /**
21678  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21679  * @phba: pointer to lpfc hba data structure
21680  * @qp: pointer to HDW queue
21681  * @pbl_pool: specified public free XRI pool
21682  * @pvt_pool: specified private free XRI pool
21683  * @count: number of XRIs to move
21684  *
21685  * This routine tries to move some free common bufs from the specified pbl_pool
21686  * to the specified pvt_pool. It might move less than count XRIs if there's not
21687  * enough in public pool.
21688  *
21689  * Return:
21690  *   true - if XRIs are successfully moved from the specified pbl_pool to the
21691  *          specified pvt_pool
21692  *   false - if the specified pbl_pool is empty or locked by someone else
21693  **/
21694 static bool
21695 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21696 			  struct lpfc_pbl_pool *pbl_pool,
21697 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
21698 {
21699 	struct lpfc_io_buf *lpfc_ncmd;
21700 	struct lpfc_io_buf *lpfc_ncmd_next;
21701 	unsigned long iflag;
21702 	int ret;
21703 
21704 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
21705 	if (ret) {
21706 		if (pbl_pool->count) {
21707 			/* Move a batch of XRIs from public to private pool */
21708 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
21709 			list_for_each_entry_safe(lpfc_ncmd,
21710 						 lpfc_ncmd_next,
21711 						 &pbl_pool->list,
21712 						 list) {
21713 				list_move_tail(&lpfc_ncmd->list,
21714 					       &pvt_pool->list);
21715 				pvt_pool->count++;
21716 				pbl_pool->count--;
21717 				count--;
21718 				if (count == 0)
21719 					break;
21720 			}
21721 
21722 			spin_unlock(&pvt_pool->lock);
21723 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21724 			return true;
21725 		}
21726 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21727 	}
21728 
21729 	return false;
21730 }
21731 
21732 /**
21733  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21734  * @phba: pointer to lpfc hba data structure.
21735  * @hwqid: belong to which HWQ.
21736  * @count: number of XRIs to move
21737  *
21738  * This routine tries to find some free common bufs in one of public pools with
21739  * Round Robin method. The search always starts from local hwqid, then the next
21740  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
21741  * a batch of free common bufs are moved to private pool on hwqid.
21742  * It might move less than count XRIs if there's not enough in public pool.
21743  **/
21744 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
21745 {
21746 	struct lpfc_multixri_pool *multixri_pool;
21747 	struct lpfc_multixri_pool *next_multixri_pool;
21748 	struct lpfc_pvt_pool *pvt_pool;
21749 	struct lpfc_pbl_pool *pbl_pool;
21750 	struct lpfc_sli4_hdw_queue *qp;
21751 	u32 next_hwqid;
21752 	u32 hwq_count;
21753 	int ret;
21754 
21755 	qp = &phba->sli4_hba.hdwq[hwqid];
21756 	multixri_pool = qp->p_multixri_pool;
21757 	pvt_pool = &multixri_pool->pvt_pool;
21758 	pbl_pool = &multixri_pool->pbl_pool;
21759 
21760 	/* Check if local pbl_pool is available */
21761 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
21762 	if (ret) {
21763 #ifdef LPFC_MXP_STAT
21764 		multixri_pool->local_pbl_hit_count++;
21765 #endif
21766 		return;
21767 	}
21768 
21769 	hwq_count = phba->cfg_hdw_queue;
21770 
21771 	/* Get the next hwqid which was found last time */
21772 	next_hwqid = multixri_pool->rrb_next_hwqid;
21773 
21774 	do {
21775 		/* Go to next hwq */
21776 		next_hwqid = (next_hwqid + 1) % hwq_count;
21777 
21778 		next_multixri_pool =
21779 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
21780 		pbl_pool = &next_multixri_pool->pbl_pool;
21781 
21782 		/* Check if the public free xri pool is available */
21783 		ret = _lpfc_move_xri_pbl_to_pvt(
21784 			phba, qp, pbl_pool, pvt_pool, count);
21785 
21786 		/* Exit while-loop if success or all hwqid are checked */
21787 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
21788 
21789 	/* Starting point for the next time */
21790 	multixri_pool->rrb_next_hwqid = next_hwqid;
21791 
21792 	if (!ret) {
21793 		/* stats: all public pools are empty*/
21794 		multixri_pool->pbl_empty_count++;
21795 	}
21796 
21797 #ifdef LPFC_MXP_STAT
21798 	if (ret) {
21799 		if (next_hwqid == hwqid)
21800 			multixri_pool->local_pbl_hit_count++;
21801 		else
21802 			multixri_pool->other_pbl_hit_count++;
21803 	}
21804 #endif
21805 }
21806 
21807 /**
21808  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
21809  * @phba: pointer to lpfc hba data structure.
21810  * @hwqid: belong to which HWQ.
21811  *
21812  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
21813  * low watermark.
21814  **/
21815 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
21816 {
21817 	struct lpfc_multixri_pool *multixri_pool;
21818 	struct lpfc_pvt_pool *pvt_pool;
21819 
21820 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21821 	pvt_pool = &multixri_pool->pvt_pool;
21822 
21823 	if (pvt_pool->count < pvt_pool->low_watermark)
21824 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21825 }
21826 
21827 /**
21828  * lpfc_release_io_buf - Return one IO buf back to free pool
21829  * @phba: pointer to lpfc hba data structure.
21830  * @lpfc_ncmd: IO buf to be returned.
21831  * @qp: belong to which HWQ.
21832  *
21833  * This routine returns one IO buf back to free pool. If this is an urgent IO,
21834  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
21835  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
21836  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
21837  * lpfc_io_buf_list_put.
21838  **/
21839 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
21840 			 struct lpfc_sli4_hdw_queue *qp)
21841 {
21842 	unsigned long iflag;
21843 	struct lpfc_pbl_pool *pbl_pool;
21844 	struct lpfc_pvt_pool *pvt_pool;
21845 	struct lpfc_epd_pool *epd_pool;
21846 	u32 txcmplq_cnt;
21847 	u32 xri_owned;
21848 	u32 xri_limit;
21849 	u32 abts_io_bufs;
21850 
21851 	/* MUST zero fields if buffer is reused by another protocol */
21852 	lpfc_ncmd->nvmeCmd = NULL;
21853 	lpfc_ncmd->cur_iocbq.wqe_cmpl = NULL;
21854 	lpfc_ncmd->cur_iocbq.iocb_cmpl = NULL;
21855 
21856 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
21857 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
21858 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
21859 
21860 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
21861 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
21862 
21863 	if (phba->cfg_xri_rebalancing) {
21864 		if (lpfc_ncmd->expedite) {
21865 			/* Return to expedite pool */
21866 			epd_pool = &phba->epd_pool;
21867 			spin_lock_irqsave(&epd_pool->lock, iflag);
21868 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21869 			epd_pool->count++;
21870 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
21871 			return;
21872 		}
21873 
21874 		/* Avoid invalid access if an IO sneaks in and is being rejected
21875 		 * just _after_ xri pools are destroyed in lpfc_offline.
21876 		 * Nothing much can be done at this point.
21877 		 */
21878 		if (!qp->p_multixri_pool)
21879 			return;
21880 
21881 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21882 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21883 
21884 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21885 		abts_io_bufs = qp->abts_scsi_io_bufs;
21886 		abts_io_bufs += qp->abts_nvme_io_bufs;
21887 
21888 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21889 		xri_limit = qp->p_multixri_pool->xri_limit;
21890 
21891 #ifdef LPFC_MXP_STAT
21892 		if (xri_owned <= xri_limit)
21893 			qp->p_multixri_pool->below_limit_count++;
21894 		else
21895 			qp->p_multixri_pool->above_limit_count++;
21896 #endif
21897 
21898 		/* XRI goes to either public or private free xri pool
21899 		 *     based on watermark and xri_limit
21900 		 */
21901 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
21902 		    (xri_owned < xri_limit &&
21903 		     pvt_pool->count < pvt_pool->high_watermark)) {
21904 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
21905 						  qp, free_pvt_pool);
21906 			list_add_tail(&lpfc_ncmd->list,
21907 				      &pvt_pool->list);
21908 			pvt_pool->count++;
21909 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21910 		} else {
21911 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
21912 						  qp, free_pub_pool);
21913 			list_add_tail(&lpfc_ncmd->list,
21914 				      &pbl_pool->list);
21915 			pbl_pool->count++;
21916 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21917 		}
21918 	} else {
21919 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
21920 					  qp, free_xri);
21921 		list_add_tail(&lpfc_ncmd->list,
21922 			      &qp->lpfc_io_buf_list_put);
21923 		qp->put_io_bufs++;
21924 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
21925 				       iflag);
21926 	}
21927 }
21928 
21929 /**
21930  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
21931  * @phba: pointer to lpfc hba data structure.
21932  * @qp: pointer to HDW queue
21933  * @pvt_pool: pointer to private pool data structure.
21934  * @ndlp: pointer to lpfc nodelist data structure.
21935  *
21936  * This routine tries to get one free IO buf from private pool.
21937  *
21938  * Return:
21939  *   pointer to one free IO buf - if private pool is not empty
21940  *   NULL - if private pool is empty
21941  **/
21942 static struct lpfc_io_buf *
21943 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
21944 				  struct lpfc_sli4_hdw_queue *qp,
21945 				  struct lpfc_pvt_pool *pvt_pool,
21946 				  struct lpfc_nodelist *ndlp)
21947 {
21948 	struct lpfc_io_buf *lpfc_ncmd;
21949 	struct lpfc_io_buf *lpfc_ncmd_next;
21950 	unsigned long iflag;
21951 
21952 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
21953 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21954 				 &pvt_pool->list, list) {
21955 		if (lpfc_test_rrq_active(
21956 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
21957 			continue;
21958 		list_del(&lpfc_ncmd->list);
21959 		pvt_pool->count--;
21960 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21961 		return lpfc_ncmd;
21962 	}
21963 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21964 
21965 	return NULL;
21966 }
21967 
21968 /**
21969  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
21970  * @phba: pointer to lpfc hba data structure.
21971  *
21972  * This routine tries to get one free IO buf from expedite pool.
21973  *
21974  * Return:
21975  *   pointer to one free IO buf - if expedite pool is not empty
21976  *   NULL - if expedite pool is empty
21977  **/
21978 static struct lpfc_io_buf *
21979 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
21980 {
21981 	struct lpfc_io_buf *lpfc_ncmd;
21982 	struct lpfc_io_buf *lpfc_ncmd_next;
21983 	unsigned long iflag;
21984 	struct lpfc_epd_pool *epd_pool;
21985 
21986 	epd_pool = &phba->epd_pool;
21987 	lpfc_ncmd = NULL;
21988 
21989 	spin_lock_irqsave(&epd_pool->lock, iflag);
21990 	if (epd_pool->count > 0) {
21991 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21992 					 &epd_pool->list, list) {
21993 			list_del(&lpfc_ncmd->list);
21994 			epd_pool->count--;
21995 			break;
21996 		}
21997 	}
21998 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
21999 
22000 	return lpfc_ncmd;
22001 }
22002 
22003 /**
22004  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
22005  * @phba: pointer to lpfc hba data structure.
22006  * @ndlp: pointer to lpfc nodelist data structure.
22007  * @hwqid: belong to which HWQ
22008  * @expedite: 1 means this request is urgent.
22009  *
22010  * This routine will do the following actions and then return a pointer to
22011  * one free IO buf.
22012  *
22013  * 1. If private free xri count is empty, move some XRIs from public to
22014  *    private pool.
22015  * 2. Get one XRI from private free xri pool.
22016  * 3. If we fail to get one from pvt_pool and this is an expedite request,
22017  *    get one free xri from expedite pool.
22018  *
22019  * Note: ndlp is only used on SCSI side for RRQ testing.
22020  *       The caller should pass NULL for ndlp on NVME side.
22021  *
22022  * Return:
22023  *   pointer to one free IO buf - if private pool is not empty
22024  *   NULL - if private pool is empty
22025  **/
22026 static struct lpfc_io_buf *
22027 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
22028 				    struct lpfc_nodelist *ndlp,
22029 				    int hwqid, int expedite)
22030 {
22031 	struct lpfc_sli4_hdw_queue *qp;
22032 	struct lpfc_multixri_pool *multixri_pool;
22033 	struct lpfc_pvt_pool *pvt_pool;
22034 	struct lpfc_io_buf *lpfc_ncmd;
22035 
22036 	qp = &phba->sli4_hba.hdwq[hwqid];
22037 	lpfc_ncmd = NULL;
22038 	if (!qp) {
22039 		lpfc_printf_log(phba, KERN_INFO,
22040 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22041 				"5556 NULL qp for hwqid  x%x\n", hwqid);
22042 		return lpfc_ncmd;
22043 	}
22044 	multixri_pool = qp->p_multixri_pool;
22045 	if (!multixri_pool) {
22046 		lpfc_printf_log(phba, KERN_INFO,
22047 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22048 				"5557 NULL multixri for hwqid  x%x\n", hwqid);
22049 		return lpfc_ncmd;
22050 	}
22051 	pvt_pool = &multixri_pool->pvt_pool;
22052 	if (!pvt_pool) {
22053 		lpfc_printf_log(phba, KERN_INFO,
22054 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22055 				"5558 NULL pvt_pool for hwqid  x%x\n", hwqid);
22056 		return lpfc_ncmd;
22057 	}
22058 	multixri_pool->io_req_count++;
22059 
22060 	/* If pvt_pool is empty, move some XRIs from public to private pool */
22061 	if (pvt_pool->count == 0)
22062 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
22063 
22064 	/* Get one XRI from private free xri pool */
22065 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
22066 
22067 	if (lpfc_ncmd) {
22068 		lpfc_ncmd->hdwq = qp;
22069 		lpfc_ncmd->hdwq_no = hwqid;
22070 	} else if (expedite) {
22071 		/* If we fail to get one from pvt_pool and this is an expedite
22072 		 * request, get one free xri from expedite pool.
22073 		 */
22074 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
22075 	}
22076 
22077 	return lpfc_ncmd;
22078 }
22079 
22080 static inline struct lpfc_io_buf *
22081 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
22082 {
22083 	struct lpfc_sli4_hdw_queue *qp;
22084 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
22085 
22086 	qp = &phba->sli4_hba.hdwq[idx];
22087 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
22088 				 &qp->lpfc_io_buf_list_get, list) {
22089 		if (lpfc_test_rrq_active(phba, ndlp,
22090 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
22091 			continue;
22092 
22093 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
22094 			continue;
22095 
22096 		list_del_init(&lpfc_cmd->list);
22097 		qp->get_io_bufs--;
22098 		lpfc_cmd->hdwq = qp;
22099 		lpfc_cmd->hdwq_no = idx;
22100 		return lpfc_cmd;
22101 	}
22102 	return NULL;
22103 }
22104 
22105 /**
22106  * lpfc_get_io_buf - Get one IO buffer from free pool
22107  * @phba: The HBA for which this call is being executed.
22108  * @ndlp: pointer to lpfc nodelist data structure.
22109  * @hwqid: belong to which HWQ
22110  * @expedite: 1 means this request is urgent.
22111  *
22112  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
22113  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
22114  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
22115  *
22116  * Note: ndlp is only used on SCSI side for RRQ testing.
22117  *       The caller should pass NULL for ndlp on NVME side.
22118  *
22119  * Return codes:
22120  *   NULL - Error
22121  *   Pointer to lpfc_io_buf - Success
22122  **/
22123 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
22124 				    struct lpfc_nodelist *ndlp,
22125 				    u32 hwqid, int expedite)
22126 {
22127 	struct lpfc_sli4_hdw_queue *qp;
22128 	unsigned long iflag;
22129 	struct lpfc_io_buf *lpfc_cmd;
22130 
22131 	qp = &phba->sli4_hba.hdwq[hwqid];
22132 	lpfc_cmd = NULL;
22133 	if (!qp) {
22134 		lpfc_printf_log(phba, KERN_WARNING,
22135 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22136 				"5555 NULL qp for hwqid  x%x\n", hwqid);
22137 		return lpfc_cmd;
22138 	}
22139 
22140 	if (phba->cfg_xri_rebalancing)
22141 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
22142 			phba, ndlp, hwqid, expedite);
22143 	else {
22144 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
22145 					  qp, alloc_xri_get);
22146 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
22147 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22148 		if (!lpfc_cmd) {
22149 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
22150 					  qp, alloc_xri_put);
22151 			list_splice(&qp->lpfc_io_buf_list_put,
22152 				    &qp->lpfc_io_buf_list_get);
22153 			qp->get_io_bufs += qp->put_io_bufs;
22154 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
22155 			qp->put_io_bufs = 0;
22156 			spin_unlock(&qp->io_buf_list_put_lock);
22157 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
22158 			    expedite)
22159 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22160 		}
22161 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
22162 	}
22163 
22164 	return lpfc_cmd;
22165 }
22166 
22167 /**
22168  * lpfc_read_object - Retrieve object data from HBA
22169  * @phba: The HBA for which this call is being executed.
22170  * @rdobject: Pathname of object data we want to read.
22171  * @datap: Pointer to where data will be copied to.
22172  * @datasz: size of data area
22173  *
22174  * This routine is limited to object sizes of LPFC_BPL_SIZE (1024) or less.
22175  * The data will be truncated if datasz is not large enough.
22176  * Version 1 is not supported with Embedded mbox cmd, so we must use version 0.
22177  * Returns the actual bytes read from the object.
22178  */
22179 int
22180 lpfc_read_object(struct lpfc_hba *phba, char *rdobject, uint32_t *datap,
22181 		 uint32_t datasz)
22182 {
22183 	struct lpfc_mbx_read_object *read_object;
22184 	LPFC_MBOXQ_t *mbox;
22185 	int rc, length, eof, j, byte_cnt = 0;
22186 	uint32_t shdr_status, shdr_add_status;
22187 	union lpfc_sli4_cfg_shdr *shdr;
22188 	struct lpfc_dmabuf *pcmd;
22189 
22190 	/* sanity check on queue memory */
22191 	if (!datap)
22192 		return -ENODEV;
22193 
22194 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
22195 	if (!mbox)
22196 		return -ENOMEM;
22197 	length = (sizeof(struct lpfc_mbx_read_object) -
22198 		  sizeof(struct lpfc_sli4_cfg_mhdr));
22199 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
22200 			 LPFC_MBOX_OPCODE_READ_OBJECT,
22201 			 length, LPFC_SLI4_MBX_EMBED);
22202 	read_object = &mbox->u.mqe.un.read_object;
22203 	shdr = (union lpfc_sli4_cfg_shdr *)&read_object->header.cfg_shdr;
22204 
22205 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_0);
22206 	bf_set(lpfc_mbx_rd_object_rlen, &read_object->u.request, datasz);
22207 	read_object->u.request.rd_object_offset = 0;
22208 	read_object->u.request.rd_object_cnt = 1;
22209 
22210 	memset((void *)read_object->u.request.rd_object_name, 0,
22211 	       LPFC_OBJ_NAME_SZ);
22212 	sprintf((uint8_t *)read_object->u.request.rd_object_name, rdobject);
22213 	for (j = 0; j < strlen(rdobject); j++)
22214 		read_object->u.request.rd_object_name[j] =
22215 			cpu_to_le32(read_object->u.request.rd_object_name[j]);
22216 
22217 	pcmd = kmalloc(sizeof(*pcmd), GFP_KERNEL);
22218 	if (pcmd)
22219 		pcmd->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &pcmd->phys);
22220 	if (!pcmd || !pcmd->virt) {
22221 		kfree(pcmd);
22222 		mempool_free(mbox, phba->mbox_mem_pool);
22223 		return -ENOMEM;
22224 	}
22225 	memset((void *)pcmd->virt, 0, LPFC_BPL_SIZE);
22226 	read_object->u.request.rd_object_hbuf[0].pa_lo =
22227 		putPaddrLow(pcmd->phys);
22228 	read_object->u.request.rd_object_hbuf[0].pa_hi =
22229 		putPaddrHigh(pcmd->phys);
22230 	read_object->u.request.rd_object_hbuf[0].length = LPFC_BPL_SIZE;
22231 
22232 	mbox->vport = phba->pport;
22233 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
22234 	mbox->ctx_buf = NULL;
22235 	mbox->ctx_ndlp = NULL;
22236 
22237 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
22238 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
22239 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
22240 
22241 	if (shdr_status == STATUS_FAILED &&
22242 	    shdr_add_status == ADD_STATUS_INVALID_OBJECT_NAME) {
22243 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22244 				"4674 No port cfg file in FW.\n");
22245 		byte_cnt = -ENOENT;
22246 	} else if (shdr_status || shdr_add_status || rc) {
22247 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22248 				"2625 READ_OBJECT mailbox failed with "
22249 				"status x%x add_status x%x, mbx status x%x\n",
22250 				shdr_status, shdr_add_status, rc);
22251 		byte_cnt = -ENXIO;
22252 	} else {
22253 		/* Success */
22254 		length = read_object->u.response.rd_object_actual_rlen;
22255 		eof = bf_get(lpfc_mbx_rd_object_eof, &read_object->u.response);
22256 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_CGN_MGMT,
22257 				"2626 READ_OBJECT Success len %d:%d, EOF %d\n",
22258 				length, datasz, eof);
22259 
22260 		/* Detect the port config file exists but is empty */
22261 		if (!length && eof) {
22262 			byte_cnt = 0;
22263 			goto exit;
22264 		}
22265 
22266 		byte_cnt = length;
22267 		lpfc_sli_pcimem_bcopy(pcmd->virt, datap, byte_cnt);
22268 	}
22269 
22270  exit:
22271 	lpfc_mbuf_free(phba, pcmd->virt, pcmd->phys);
22272 	kfree(pcmd);
22273 	mempool_free(mbox, phba->mbox_mem_pool);
22274 	return byte_cnt;
22275 }
22276 
22277 /**
22278  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
22279  * @phba: The HBA for which this call is being executed.
22280  * @lpfc_buf: IO buf structure to append the SGL chunk
22281  *
22282  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
22283  * and will allocate an SGL chunk if the pool is empty.
22284  *
22285  * Return codes:
22286  *   NULL - Error
22287  *   Pointer to sli4_hybrid_sgl - Success
22288  **/
22289 struct sli4_hybrid_sgl *
22290 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22291 {
22292 	struct sli4_hybrid_sgl *list_entry = NULL;
22293 	struct sli4_hybrid_sgl *tmp = NULL;
22294 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
22295 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22296 	struct list_head *buf_list = &hdwq->sgl_list;
22297 	unsigned long iflags;
22298 
22299 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22300 
22301 	if (likely(!list_empty(buf_list))) {
22302 		/* break off 1 chunk from the sgl_list */
22303 		list_for_each_entry_safe(list_entry, tmp,
22304 					 buf_list, list_node) {
22305 			list_move_tail(&list_entry->list_node,
22306 				       &lpfc_buf->dma_sgl_xtra_list);
22307 			break;
22308 		}
22309 	} else {
22310 		/* allocate more */
22311 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22312 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22313 				   cpu_to_node(hdwq->io_wq->chann));
22314 		if (!tmp) {
22315 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22316 					"8353 error kmalloc memory for HDWQ "
22317 					"%d %s\n",
22318 					lpfc_buf->hdwq_no, __func__);
22319 			return NULL;
22320 		}
22321 
22322 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
22323 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
22324 		if (!tmp->dma_sgl) {
22325 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22326 					"8354 error pool_alloc memory for HDWQ "
22327 					"%d %s\n",
22328 					lpfc_buf->hdwq_no, __func__);
22329 			kfree(tmp);
22330 			return NULL;
22331 		}
22332 
22333 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22334 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
22335 	}
22336 
22337 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
22338 					struct sli4_hybrid_sgl,
22339 					list_node);
22340 
22341 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22342 
22343 	return allocated_sgl;
22344 }
22345 
22346 /**
22347  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
22348  * @phba: The HBA for which this call is being executed.
22349  * @lpfc_buf: IO buf structure with the SGL chunk
22350  *
22351  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
22352  *
22353  * Return codes:
22354  *   0 - Success
22355  *   -EINVAL - Error
22356  **/
22357 int
22358 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22359 {
22360 	int rc = 0;
22361 	struct sli4_hybrid_sgl *list_entry = NULL;
22362 	struct sli4_hybrid_sgl *tmp = NULL;
22363 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22364 	struct list_head *buf_list = &hdwq->sgl_list;
22365 	unsigned long iflags;
22366 
22367 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22368 
22369 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
22370 		list_for_each_entry_safe(list_entry, tmp,
22371 					 &lpfc_buf->dma_sgl_xtra_list,
22372 					 list_node) {
22373 			list_move_tail(&list_entry->list_node,
22374 				       buf_list);
22375 		}
22376 	} else {
22377 		rc = -EINVAL;
22378 	}
22379 
22380 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22381 	return rc;
22382 }
22383 
22384 /**
22385  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
22386  * @phba: phba object
22387  * @hdwq: hdwq to cleanup sgl buff resources on
22388  *
22389  * This routine frees all SGL chunks of hdwq SGL chunk pool.
22390  *
22391  * Return codes:
22392  *   None
22393  **/
22394 void
22395 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
22396 		       struct lpfc_sli4_hdw_queue *hdwq)
22397 {
22398 	struct list_head *buf_list = &hdwq->sgl_list;
22399 	struct sli4_hybrid_sgl *list_entry = NULL;
22400 	struct sli4_hybrid_sgl *tmp = NULL;
22401 	unsigned long iflags;
22402 
22403 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22404 
22405 	/* Free sgl pool */
22406 	list_for_each_entry_safe(list_entry, tmp,
22407 				 buf_list, list_node) {
22408 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
22409 			      list_entry->dma_sgl,
22410 			      list_entry->dma_phys_sgl);
22411 		list_del(&list_entry->list_node);
22412 		kfree(list_entry);
22413 	}
22414 
22415 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22416 }
22417 
22418 /**
22419  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
22420  * @phba: The HBA for which this call is being executed.
22421  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
22422  *
22423  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
22424  * and will allocate an CMD/RSP buffer if the pool is empty.
22425  *
22426  * Return codes:
22427  *   NULL - Error
22428  *   Pointer to fcp_cmd_rsp_buf - Success
22429  **/
22430 struct fcp_cmd_rsp_buf *
22431 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22432 			      struct lpfc_io_buf *lpfc_buf)
22433 {
22434 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22435 	struct fcp_cmd_rsp_buf *tmp = NULL;
22436 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
22437 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22438 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22439 	unsigned long iflags;
22440 
22441 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22442 
22443 	if (likely(!list_empty(buf_list))) {
22444 		/* break off 1 chunk from the list */
22445 		list_for_each_entry_safe(list_entry, tmp,
22446 					 buf_list,
22447 					 list_node) {
22448 			list_move_tail(&list_entry->list_node,
22449 				       &lpfc_buf->dma_cmd_rsp_list);
22450 			break;
22451 		}
22452 	} else {
22453 		/* allocate more */
22454 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22455 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22456 				   cpu_to_node(hdwq->io_wq->chann));
22457 		if (!tmp) {
22458 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22459 					"8355 error kmalloc memory for HDWQ "
22460 					"%d %s\n",
22461 					lpfc_buf->hdwq_no, __func__);
22462 			return NULL;
22463 		}
22464 
22465 		tmp->fcp_cmnd = dma_pool_alloc(phba->lpfc_cmd_rsp_buf_pool,
22466 						GFP_ATOMIC,
22467 						&tmp->fcp_cmd_rsp_dma_handle);
22468 
22469 		if (!tmp->fcp_cmnd) {
22470 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22471 					"8356 error pool_alloc memory for HDWQ "
22472 					"%d %s\n",
22473 					lpfc_buf->hdwq_no, __func__);
22474 			kfree(tmp);
22475 			return NULL;
22476 		}
22477 
22478 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
22479 				sizeof(struct fcp_cmnd));
22480 
22481 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22482 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
22483 	}
22484 
22485 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
22486 					struct fcp_cmd_rsp_buf,
22487 					list_node);
22488 
22489 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22490 
22491 	return allocated_buf;
22492 }
22493 
22494 /**
22495  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
22496  * @phba: The HBA for which this call is being executed.
22497  * @lpfc_buf: IO buf structure with the CMD/RSP buf
22498  *
22499  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
22500  *
22501  * Return codes:
22502  *   0 - Success
22503  *   -EINVAL - Error
22504  **/
22505 int
22506 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22507 			      struct lpfc_io_buf *lpfc_buf)
22508 {
22509 	int rc = 0;
22510 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22511 	struct fcp_cmd_rsp_buf *tmp = NULL;
22512 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22513 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22514 	unsigned long iflags;
22515 
22516 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22517 
22518 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
22519 		list_for_each_entry_safe(list_entry, tmp,
22520 					 &lpfc_buf->dma_cmd_rsp_list,
22521 					 list_node) {
22522 			list_move_tail(&list_entry->list_node,
22523 				       buf_list);
22524 		}
22525 	} else {
22526 		rc = -EINVAL;
22527 	}
22528 
22529 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22530 	return rc;
22531 }
22532 
22533 /**
22534  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
22535  * @phba: phba object
22536  * @hdwq: hdwq to cleanup cmd rsp buff resources on
22537  *
22538  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
22539  *
22540  * Return codes:
22541  *   None
22542  **/
22543 void
22544 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22545 			       struct lpfc_sli4_hdw_queue *hdwq)
22546 {
22547 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22548 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22549 	struct fcp_cmd_rsp_buf *tmp = NULL;
22550 	unsigned long iflags;
22551 
22552 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22553 
22554 	/* Free cmd_rsp buf pool */
22555 	list_for_each_entry_safe(list_entry, tmp,
22556 				 buf_list,
22557 				 list_node) {
22558 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
22559 			      list_entry->fcp_cmnd,
22560 			      list_entry->fcp_cmd_rsp_dma_handle);
22561 		list_del(&list_entry->list_node);
22562 		kfree(list_entry);
22563 	}
22564 
22565 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22566 }
22567