xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision 69868c3b)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2021 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.     *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/pci.h>
26 #include <linux/interrupt.h>
27 #include <linux/delay.h>
28 #include <linux/slab.h>
29 #include <linux/lockdep.h>
30 
31 #include <scsi/scsi.h>
32 #include <scsi/scsi_cmnd.h>
33 #include <scsi/scsi_device.h>
34 #include <scsi/scsi_host.h>
35 #include <scsi/scsi_transport_fc.h>
36 #include <scsi/fc/fc_fs.h>
37 #include <linux/aer.h>
38 #include <linux/crash_dump.h>
39 #ifdef CONFIG_X86
40 #include <asm/set_memory.h>
41 #endif
42 
43 #include "lpfc_hw4.h"
44 #include "lpfc_hw.h"
45 #include "lpfc_sli.h"
46 #include "lpfc_sli4.h"
47 #include "lpfc_nl.h"
48 #include "lpfc_disc.h"
49 #include "lpfc.h"
50 #include "lpfc_scsi.h"
51 #include "lpfc_nvme.h"
52 #include "lpfc_crtn.h"
53 #include "lpfc_logmsg.h"
54 #include "lpfc_compat.h"
55 #include "lpfc_debugfs.h"
56 #include "lpfc_vport.h"
57 #include "lpfc_version.h"
58 
59 /* There are only four IOCB completion types. */
60 typedef enum _lpfc_iocb_type {
61 	LPFC_UNKNOWN_IOCB,
62 	LPFC_UNSOL_IOCB,
63 	LPFC_SOL_IOCB,
64 	LPFC_ABORT_IOCB
65 } lpfc_iocb_type;
66 
67 
68 /* Provide function prototypes local to this module. */
69 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
70 				  uint32_t);
71 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
72 			      uint8_t *, uint32_t *);
73 static struct lpfc_iocbq *lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *,
74 							 struct lpfc_iocbq *);
75 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
76 				      struct hbq_dmabuf *);
77 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
78 					  struct hbq_dmabuf *dmabuf);
79 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
80 				   struct lpfc_queue *cq, struct lpfc_cqe *cqe);
81 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
82 				       int);
83 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
84 				     struct lpfc_queue *eq,
85 				     struct lpfc_eqe *eqe);
86 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
87 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
88 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
89 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
90 				    struct lpfc_queue *cq,
91 				    struct lpfc_cqe *cqe);
92 
93 union lpfc_wqe128 lpfc_iread_cmd_template;
94 union lpfc_wqe128 lpfc_iwrite_cmd_template;
95 union lpfc_wqe128 lpfc_icmnd_cmd_template;
96 
97 static IOCB_t *
98 lpfc_get_iocb_from_iocbq(struct lpfc_iocbq *iocbq)
99 {
100 	return &iocbq->iocb;
101 }
102 
103 /* Setup WQE templates for IOs */
104 void lpfc_wqe_cmd_template(void)
105 {
106 	union lpfc_wqe128 *wqe;
107 
108 	/* IREAD template */
109 	wqe = &lpfc_iread_cmd_template;
110 	memset(wqe, 0, sizeof(union lpfc_wqe128));
111 
112 	/* Word 0, 1, 2 - BDE is variable */
113 
114 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
115 
116 	/* Word 4 - total_xfer_len is variable */
117 
118 	/* Word 5 - is zero */
119 
120 	/* Word 6 - ctxt_tag, xri_tag is variable */
121 
122 	/* Word 7 */
123 	bf_set(wqe_cmnd, &wqe->fcp_iread.wqe_com, CMD_FCP_IREAD64_WQE);
124 	bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, PARM_READ_CHECK);
125 	bf_set(wqe_class, &wqe->fcp_iread.wqe_com, CLASS3);
126 	bf_set(wqe_ct, &wqe->fcp_iread.wqe_com, SLI4_CT_RPI);
127 
128 	/* Word 8 - abort_tag is variable */
129 
130 	/* Word 9  - reqtag is variable */
131 
132 	/* Word 10 - dbde, wqes is variable */
133 	bf_set(wqe_qosd, &wqe->fcp_iread.wqe_com, 0);
134 	bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
135 	bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com, LPFC_WQE_LENLOC_WORD4);
136 	bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
137 	bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
138 
139 	/* Word 11 - pbde is variable */
140 	bf_set(wqe_cmd_type, &wqe->fcp_iread.wqe_com, COMMAND_DATA_IN);
141 	bf_set(wqe_cqid, &wqe->fcp_iread.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
142 	bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
143 
144 	/* Word 12 - is zero */
145 
146 	/* Word 13, 14, 15 - PBDE is variable */
147 
148 	/* IWRITE template */
149 	wqe = &lpfc_iwrite_cmd_template;
150 	memset(wqe, 0, sizeof(union lpfc_wqe128));
151 
152 	/* Word 0, 1, 2 - BDE is variable */
153 
154 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
155 
156 	/* Word 4 - total_xfer_len is variable */
157 
158 	/* Word 5 - initial_xfer_len is variable */
159 
160 	/* Word 6 - ctxt_tag, xri_tag is variable */
161 
162 	/* Word 7 */
163 	bf_set(wqe_cmnd, &wqe->fcp_iwrite.wqe_com, CMD_FCP_IWRITE64_WQE);
164 	bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, PARM_READ_CHECK);
165 	bf_set(wqe_class, &wqe->fcp_iwrite.wqe_com, CLASS3);
166 	bf_set(wqe_ct, &wqe->fcp_iwrite.wqe_com, SLI4_CT_RPI);
167 
168 	/* Word 8 - abort_tag is variable */
169 
170 	/* Word 9  - reqtag is variable */
171 
172 	/* Word 10 - dbde, wqes is variable */
173 	bf_set(wqe_qosd, &wqe->fcp_iwrite.wqe_com, 0);
174 	bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
175 	bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_LENLOC_WORD4);
176 	bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
177 	bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
178 
179 	/* Word 11 - pbde is variable */
180 	bf_set(wqe_cmd_type, &wqe->fcp_iwrite.wqe_com, COMMAND_DATA_OUT);
181 	bf_set(wqe_cqid, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
182 	bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
183 
184 	/* Word 12 - is zero */
185 
186 	/* Word 13, 14, 15 - PBDE is variable */
187 
188 	/* ICMND template */
189 	wqe = &lpfc_icmnd_cmd_template;
190 	memset(wqe, 0, sizeof(union lpfc_wqe128));
191 
192 	/* Word 0, 1, 2 - BDE is variable */
193 
194 	/* Word 3 - payload_offset_len is variable */
195 
196 	/* Word 4, 5 - is zero */
197 
198 	/* Word 6 - ctxt_tag, xri_tag is variable */
199 
200 	/* Word 7 */
201 	bf_set(wqe_cmnd, &wqe->fcp_icmd.wqe_com, CMD_FCP_ICMND64_WQE);
202 	bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
203 	bf_set(wqe_class, &wqe->fcp_icmd.wqe_com, CLASS3);
204 	bf_set(wqe_ct, &wqe->fcp_icmd.wqe_com, SLI4_CT_RPI);
205 
206 	/* Word 8 - abort_tag is variable */
207 
208 	/* Word 9  - reqtag is variable */
209 
210 	/* Word 10 - dbde, wqes is variable */
211 	bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
212 	bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_NONE);
213 	bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com, LPFC_WQE_LENLOC_NONE);
214 	bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
215 	bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
216 
217 	/* Word 11 */
218 	bf_set(wqe_cmd_type, &wqe->fcp_icmd.wqe_com, COMMAND_DATA_IN);
219 	bf_set(wqe_cqid, &wqe->fcp_icmd.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
220 	bf_set(wqe_pbde, &wqe->fcp_icmd.wqe_com, 0);
221 
222 	/* Word 12, 13, 14, 15 - is zero */
223 }
224 
225 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
226 /**
227  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
228  * @srcp: Source memory pointer.
229  * @destp: Destination memory pointer.
230  * @cnt: Number of words required to be copied.
231  *       Must be a multiple of sizeof(uint64_t)
232  *
233  * This function is used for copying data between driver memory
234  * and the SLI WQ. This function also changes the endianness
235  * of each word if native endianness is different from SLI
236  * endianness. This function can be called with or without
237  * lock.
238  **/
239 static void
240 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
241 {
242 	uint64_t *src = srcp;
243 	uint64_t *dest = destp;
244 	int i;
245 
246 	for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
247 		*dest++ = *src++;
248 }
249 #else
250 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
251 #endif
252 
253 /**
254  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
255  * @q: The Work Queue to operate on.
256  * @wqe: The work Queue Entry to put on the Work queue.
257  *
258  * This routine will copy the contents of @wqe to the next available entry on
259  * the @q. This function will then ring the Work Queue Doorbell to signal the
260  * HBA to start processing the Work Queue Entry. This function returns 0 if
261  * successful. If no entries are available on @q then this function will return
262  * -ENOMEM.
263  * The caller is expected to hold the hbalock when calling this routine.
264  **/
265 static int
266 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
267 {
268 	union lpfc_wqe *temp_wqe;
269 	struct lpfc_register doorbell;
270 	uint32_t host_index;
271 	uint32_t idx;
272 	uint32_t i = 0;
273 	uint8_t *tmp;
274 	u32 if_type;
275 
276 	/* sanity check on queue memory */
277 	if (unlikely(!q))
278 		return -ENOMEM;
279 
280 	temp_wqe = lpfc_sli4_qe(q, q->host_index);
281 
282 	/* If the host has not yet processed the next entry then we are done */
283 	idx = ((q->host_index + 1) % q->entry_count);
284 	if (idx == q->hba_index) {
285 		q->WQ_overflow++;
286 		return -EBUSY;
287 	}
288 	q->WQ_posted++;
289 	/* set consumption flag every once in a while */
290 	if (!((q->host_index + 1) % q->notify_interval))
291 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
292 	else
293 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
294 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
295 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
296 	lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
297 	if (q->dpp_enable && q->phba->cfg_enable_dpp) {
298 		/* write to DPP aperture taking advatage of Combined Writes */
299 		tmp = (uint8_t *)temp_wqe;
300 #ifdef __raw_writeq
301 		for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
302 			__raw_writeq(*((uint64_t *)(tmp + i)),
303 					q->dpp_regaddr + i);
304 #else
305 		for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
306 			__raw_writel(*((uint32_t *)(tmp + i)),
307 					q->dpp_regaddr + i);
308 #endif
309 	}
310 	/* ensure WQE bcopy and DPP flushed before doorbell write */
311 	wmb();
312 
313 	/* Update the host index before invoking device */
314 	host_index = q->host_index;
315 
316 	q->host_index = idx;
317 
318 	/* Ring Doorbell */
319 	doorbell.word0 = 0;
320 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
321 		if (q->dpp_enable && q->phba->cfg_enable_dpp) {
322 			bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
323 			bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
324 			bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
325 			    q->dpp_id);
326 			bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
327 			    q->queue_id);
328 		} else {
329 			bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
330 			bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
331 
332 			/* Leave bits <23:16> clear for if_type 6 dpp */
333 			if_type = bf_get(lpfc_sli_intf_if_type,
334 					 &q->phba->sli4_hba.sli_intf);
335 			if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
336 				bf_set(lpfc_wq_db_list_fm_index, &doorbell,
337 				       host_index);
338 		}
339 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
340 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
341 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
342 	} else {
343 		return -EINVAL;
344 	}
345 	writel(doorbell.word0, q->db_regaddr);
346 
347 	return 0;
348 }
349 
350 /**
351  * lpfc_sli4_wq_release - Updates internal hba index for WQ
352  * @q: The Work Queue to operate on.
353  * @index: The index to advance the hba index to.
354  *
355  * This routine will update the HBA index of a queue to reflect consumption of
356  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
357  * an entry the host calls this function to update the queue's internal
358  * pointers.
359  **/
360 static void
361 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
362 {
363 	/* sanity check on queue memory */
364 	if (unlikely(!q))
365 		return;
366 
367 	q->hba_index = index;
368 }
369 
370 /**
371  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
372  * @q: The Mailbox Queue to operate on.
373  * @mqe: The Mailbox Queue Entry to put on the Work queue.
374  *
375  * This routine will copy the contents of @mqe to the next available entry on
376  * the @q. This function will then ring the Work Queue Doorbell to signal the
377  * HBA to start processing the Work Queue Entry. This function returns 0 if
378  * successful. If no entries are available on @q then this function will return
379  * -ENOMEM.
380  * The caller is expected to hold the hbalock when calling this routine.
381  **/
382 static uint32_t
383 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
384 {
385 	struct lpfc_mqe *temp_mqe;
386 	struct lpfc_register doorbell;
387 
388 	/* sanity check on queue memory */
389 	if (unlikely(!q))
390 		return -ENOMEM;
391 	temp_mqe = lpfc_sli4_qe(q, q->host_index);
392 
393 	/* If the host has not yet processed the next entry then we are done */
394 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
395 		return -ENOMEM;
396 	lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
397 	/* Save off the mailbox pointer for completion */
398 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
399 
400 	/* Update the host index before invoking device */
401 	q->host_index = ((q->host_index + 1) % q->entry_count);
402 
403 	/* Ring Doorbell */
404 	doorbell.word0 = 0;
405 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
406 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
407 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
408 	return 0;
409 }
410 
411 /**
412  * lpfc_sli4_mq_release - Updates internal hba index for MQ
413  * @q: The Mailbox Queue to operate on.
414  *
415  * This routine will update the HBA index of a queue to reflect consumption of
416  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
417  * an entry the host calls this function to update the queue's internal
418  * pointers. This routine returns the number of entries that were consumed by
419  * the HBA.
420  **/
421 static uint32_t
422 lpfc_sli4_mq_release(struct lpfc_queue *q)
423 {
424 	/* sanity check on queue memory */
425 	if (unlikely(!q))
426 		return 0;
427 
428 	/* Clear the mailbox pointer for completion */
429 	q->phba->mbox = NULL;
430 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
431 	return 1;
432 }
433 
434 /**
435  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
436  * @q: The Event Queue to get the first valid EQE from
437  *
438  * This routine will get the first valid Event Queue Entry from @q, update
439  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
440  * the Queue (no more work to do), or the Queue is full of EQEs that have been
441  * processed, but not popped back to the HBA then this routine will return NULL.
442  **/
443 static struct lpfc_eqe *
444 lpfc_sli4_eq_get(struct lpfc_queue *q)
445 {
446 	struct lpfc_eqe *eqe;
447 
448 	/* sanity check on queue memory */
449 	if (unlikely(!q))
450 		return NULL;
451 	eqe = lpfc_sli4_qe(q, q->host_index);
452 
453 	/* If the next EQE is not valid then we are done */
454 	if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
455 		return NULL;
456 
457 	/*
458 	 * insert barrier for instruction interlock : data from the hardware
459 	 * must have the valid bit checked before it can be copied and acted
460 	 * upon. Speculative instructions were allowing a bcopy at the start
461 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
462 	 * after our return, to copy data before the valid bit check above
463 	 * was done. As such, some of the copied data was stale. The barrier
464 	 * ensures the check is before any data is copied.
465 	 */
466 	mb();
467 	return eqe;
468 }
469 
470 /**
471  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
472  * @q: The Event Queue to disable interrupts
473  *
474  **/
475 void
476 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
477 {
478 	struct lpfc_register doorbell;
479 
480 	doorbell.word0 = 0;
481 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
482 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
483 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
484 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
485 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
486 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
487 }
488 
489 /**
490  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
491  * @q: The Event Queue to disable interrupts
492  *
493  **/
494 void
495 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
496 {
497 	struct lpfc_register doorbell;
498 
499 	doorbell.word0 = 0;
500 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
501 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
502 }
503 
504 /**
505  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
506  * @phba: adapter with EQ
507  * @q: The Event Queue that the host has completed processing for.
508  * @count: Number of elements that have been consumed
509  * @arm: Indicates whether the host wants to arms this CQ.
510  *
511  * This routine will notify the HBA, by ringing the doorbell, that count
512  * number of EQEs have been processed. The @arm parameter indicates whether
513  * the queue should be rearmed when ringing the doorbell.
514  **/
515 void
516 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
517 		     uint32_t count, bool arm)
518 {
519 	struct lpfc_register doorbell;
520 
521 	/* sanity check on queue memory */
522 	if (unlikely(!q || (count == 0 && !arm)))
523 		return;
524 
525 	/* ring doorbell for number popped */
526 	doorbell.word0 = 0;
527 	if (arm) {
528 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
529 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
530 	}
531 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
532 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
533 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
534 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
535 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
536 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
537 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
538 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
539 		readl(q->phba->sli4_hba.EQDBregaddr);
540 }
541 
542 /**
543  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
544  * @phba: adapter with EQ
545  * @q: The Event Queue that the host has completed processing for.
546  * @count: Number of elements that have been consumed
547  * @arm: Indicates whether the host wants to arms this CQ.
548  *
549  * This routine will notify the HBA, by ringing the doorbell, that count
550  * number of EQEs have been processed. The @arm parameter indicates whether
551  * the queue should be rearmed when ringing the doorbell.
552  **/
553 void
554 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
555 			  uint32_t count, bool arm)
556 {
557 	struct lpfc_register doorbell;
558 
559 	/* sanity check on queue memory */
560 	if (unlikely(!q || (count == 0 && !arm)))
561 		return;
562 
563 	/* ring doorbell for number popped */
564 	doorbell.word0 = 0;
565 	if (arm)
566 		bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
567 	bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
568 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
569 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
570 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
571 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
572 		readl(q->phba->sli4_hba.EQDBregaddr);
573 }
574 
575 static void
576 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
577 			struct lpfc_eqe *eqe)
578 {
579 	if (!phba->sli4_hba.pc_sli4_params.eqav)
580 		bf_set_le32(lpfc_eqe_valid, eqe, 0);
581 
582 	eq->host_index = ((eq->host_index + 1) % eq->entry_count);
583 
584 	/* if the index wrapped around, toggle the valid bit */
585 	if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
586 		eq->qe_valid = (eq->qe_valid) ? 0 : 1;
587 }
588 
589 static void
590 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
591 {
592 	struct lpfc_eqe *eqe = NULL;
593 	u32 eq_count = 0, cq_count = 0;
594 	struct lpfc_cqe *cqe = NULL;
595 	struct lpfc_queue *cq = NULL, *childq = NULL;
596 	int cqid = 0;
597 
598 	/* walk all the EQ entries and drop on the floor */
599 	eqe = lpfc_sli4_eq_get(eq);
600 	while (eqe) {
601 		/* Get the reference to the corresponding CQ */
602 		cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
603 		cq = NULL;
604 
605 		list_for_each_entry(childq, &eq->child_list, list) {
606 			if (childq->queue_id == cqid) {
607 				cq = childq;
608 				break;
609 			}
610 		}
611 		/* If CQ is valid, iterate through it and drop all the CQEs */
612 		if (cq) {
613 			cqe = lpfc_sli4_cq_get(cq);
614 			while (cqe) {
615 				__lpfc_sli4_consume_cqe(phba, cq, cqe);
616 				cq_count++;
617 				cqe = lpfc_sli4_cq_get(cq);
618 			}
619 			/* Clear and re-arm the CQ */
620 			phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
621 			    LPFC_QUEUE_REARM);
622 			cq_count = 0;
623 		}
624 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
625 		eq_count++;
626 		eqe = lpfc_sli4_eq_get(eq);
627 	}
628 
629 	/* Clear and re-arm the EQ */
630 	phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
631 }
632 
633 static int
634 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
635 		     uint8_t rearm)
636 {
637 	struct lpfc_eqe *eqe;
638 	int count = 0, consumed = 0;
639 
640 	if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
641 		goto rearm_and_exit;
642 
643 	eqe = lpfc_sli4_eq_get(eq);
644 	while (eqe) {
645 		lpfc_sli4_hba_handle_eqe(phba, eq, eqe);
646 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
647 
648 		consumed++;
649 		if (!(++count % eq->max_proc_limit))
650 			break;
651 
652 		if (!(count % eq->notify_interval)) {
653 			phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
654 							LPFC_QUEUE_NOARM);
655 			consumed = 0;
656 		}
657 
658 		eqe = lpfc_sli4_eq_get(eq);
659 	}
660 	eq->EQ_processed += count;
661 
662 	/* Track the max number of EQEs processed in 1 intr */
663 	if (count > eq->EQ_max_eqe)
664 		eq->EQ_max_eqe = count;
665 
666 	xchg(&eq->queue_claimed, 0);
667 
668 rearm_and_exit:
669 	/* Always clear the EQ. */
670 	phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
671 
672 	return count;
673 }
674 
675 /**
676  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
677  * @q: The Completion Queue to get the first valid CQE from
678  *
679  * This routine will get the first valid Completion Queue Entry from @q, update
680  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
681  * the Queue (no more work to do), or the Queue is full of CQEs that have been
682  * processed, but not popped back to the HBA then this routine will return NULL.
683  **/
684 static struct lpfc_cqe *
685 lpfc_sli4_cq_get(struct lpfc_queue *q)
686 {
687 	struct lpfc_cqe *cqe;
688 
689 	/* sanity check on queue memory */
690 	if (unlikely(!q))
691 		return NULL;
692 	cqe = lpfc_sli4_qe(q, q->host_index);
693 
694 	/* If the next CQE is not valid then we are done */
695 	if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
696 		return NULL;
697 
698 	/*
699 	 * insert barrier for instruction interlock : data from the hardware
700 	 * must have the valid bit checked before it can be copied and acted
701 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
702 	 * instructions allowing action on content before valid bit checked,
703 	 * add barrier here as well. May not be needed as "content" is a
704 	 * single 32-bit entity here (vs multi word structure for cq's).
705 	 */
706 	mb();
707 	return cqe;
708 }
709 
710 static void
711 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
712 			struct lpfc_cqe *cqe)
713 {
714 	if (!phba->sli4_hba.pc_sli4_params.cqav)
715 		bf_set_le32(lpfc_cqe_valid, cqe, 0);
716 
717 	cq->host_index = ((cq->host_index + 1) % cq->entry_count);
718 
719 	/* if the index wrapped around, toggle the valid bit */
720 	if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
721 		cq->qe_valid = (cq->qe_valid) ? 0 : 1;
722 }
723 
724 /**
725  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
726  * @phba: the adapter with the CQ
727  * @q: The Completion Queue that the host has completed processing for.
728  * @count: the number of elements that were consumed
729  * @arm: Indicates whether the host wants to arms this CQ.
730  *
731  * This routine will notify the HBA, by ringing the doorbell, that the
732  * CQEs have been processed. The @arm parameter specifies whether the
733  * queue should be rearmed when ringing the doorbell.
734  **/
735 void
736 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
737 		     uint32_t count, bool arm)
738 {
739 	struct lpfc_register doorbell;
740 
741 	/* sanity check on queue memory */
742 	if (unlikely(!q || (count == 0 && !arm)))
743 		return;
744 
745 	/* ring doorbell for number popped */
746 	doorbell.word0 = 0;
747 	if (arm)
748 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
749 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
750 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
751 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
752 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
753 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
754 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
755 }
756 
757 /**
758  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
759  * @phba: the adapter with the CQ
760  * @q: The Completion Queue that the host has completed processing for.
761  * @count: the number of elements that were consumed
762  * @arm: Indicates whether the host wants to arms this CQ.
763  *
764  * This routine will notify the HBA, by ringing the doorbell, that the
765  * CQEs have been processed. The @arm parameter specifies whether the
766  * queue should be rearmed when ringing the doorbell.
767  **/
768 void
769 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
770 			 uint32_t count, bool arm)
771 {
772 	struct lpfc_register doorbell;
773 
774 	/* sanity check on queue memory */
775 	if (unlikely(!q || (count == 0 && !arm)))
776 		return;
777 
778 	/* ring doorbell for number popped */
779 	doorbell.word0 = 0;
780 	if (arm)
781 		bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
782 	bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
783 	bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
784 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
785 }
786 
787 /*
788  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
789  *
790  * This routine will copy the contents of @wqe to the next available entry on
791  * the @q. This function will then ring the Receive Queue Doorbell to signal the
792  * HBA to start processing the Receive Queue Entry. This function returns the
793  * index that the rqe was copied to if successful. If no entries are available
794  * on @q then this function will return -ENOMEM.
795  * The caller is expected to hold the hbalock when calling this routine.
796  **/
797 int
798 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
799 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
800 {
801 	struct lpfc_rqe *temp_hrqe;
802 	struct lpfc_rqe *temp_drqe;
803 	struct lpfc_register doorbell;
804 	int hq_put_index;
805 	int dq_put_index;
806 
807 	/* sanity check on queue memory */
808 	if (unlikely(!hq) || unlikely(!dq))
809 		return -ENOMEM;
810 	hq_put_index = hq->host_index;
811 	dq_put_index = dq->host_index;
812 	temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
813 	temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
814 
815 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
816 		return -EINVAL;
817 	if (hq_put_index != dq_put_index)
818 		return -EINVAL;
819 	/* If the host has not yet processed the next entry then we are done */
820 	if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
821 		return -EBUSY;
822 	lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
823 	lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
824 
825 	/* Update the host index to point to the next slot */
826 	hq->host_index = ((hq_put_index + 1) % hq->entry_count);
827 	dq->host_index = ((dq_put_index + 1) % dq->entry_count);
828 	hq->RQ_buf_posted++;
829 
830 	/* Ring The Header Receive Queue Doorbell */
831 	if (!(hq->host_index % hq->notify_interval)) {
832 		doorbell.word0 = 0;
833 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
834 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
835 			       hq->notify_interval);
836 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
837 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
838 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
839 			       hq->notify_interval);
840 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
841 			       hq->host_index);
842 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
843 		} else {
844 			return -EINVAL;
845 		}
846 		writel(doorbell.word0, hq->db_regaddr);
847 	}
848 	return hq_put_index;
849 }
850 
851 /*
852  * lpfc_sli4_rq_release - Updates internal hba index for RQ
853  *
854  * This routine will update the HBA index of a queue to reflect consumption of
855  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
856  * consumed an entry the host calls this function to update the queue's
857  * internal pointers. This routine returns the number of entries that were
858  * consumed by the HBA.
859  **/
860 static uint32_t
861 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
862 {
863 	/* sanity check on queue memory */
864 	if (unlikely(!hq) || unlikely(!dq))
865 		return 0;
866 
867 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
868 		return 0;
869 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
870 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
871 	return 1;
872 }
873 
874 /**
875  * lpfc_cmd_iocb - Get next command iocb entry in the ring
876  * @phba: Pointer to HBA context object.
877  * @pring: Pointer to driver SLI ring object.
878  *
879  * This function returns pointer to next command iocb entry
880  * in the command ring. The caller must hold hbalock to prevent
881  * other threads consume the next command iocb.
882  * SLI-2/SLI-3 provide different sized iocbs.
883  **/
884 static inline IOCB_t *
885 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
886 {
887 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
888 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
889 }
890 
891 /**
892  * lpfc_resp_iocb - Get next response iocb entry in the ring
893  * @phba: Pointer to HBA context object.
894  * @pring: Pointer to driver SLI ring object.
895  *
896  * This function returns pointer to next response iocb entry
897  * in the response ring. The caller must hold hbalock to make sure
898  * that no other thread consume the next response iocb.
899  * SLI-2/SLI-3 provide different sized iocbs.
900  **/
901 static inline IOCB_t *
902 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
903 {
904 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
905 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
906 }
907 
908 /**
909  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
910  * @phba: Pointer to HBA context object.
911  *
912  * This function is called with hbalock held. This function
913  * allocates a new driver iocb object from the iocb pool. If the
914  * allocation is successful, it returns pointer to the newly
915  * allocated iocb object else it returns NULL.
916  **/
917 struct lpfc_iocbq *
918 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
919 {
920 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
921 	struct lpfc_iocbq * iocbq = NULL;
922 
923 	lockdep_assert_held(&phba->hbalock);
924 
925 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
926 	if (iocbq)
927 		phba->iocb_cnt++;
928 	if (phba->iocb_cnt > phba->iocb_max)
929 		phba->iocb_max = phba->iocb_cnt;
930 	return iocbq;
931 }
932 
933 /**
934  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
935  * @phba: Pointer to HBA context object.
936  * @xritag: XRI value.
937  *
938  * This function clears the sglq pointer from the array of active
939  * sglq's. The xritag that is passed in is used to index into the
940  * array. Before the xritag can be used it needs to be adjusted
941  * by subtracting the xribase.
942  *
943  * Returns sglq ponter = success, NULL = Failure.
944  **/
945 struct lpfc_sglq *
946 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
947 {
948 	struct lpfc_sglq *sglq;
949 
950 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
951 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
952 	return sglq;
953 }
954 
955 /**
956  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
957  * @phba: Pointer to HBA context object.
958  * @xritag: XRI value.
959  *
960  * This function returns the sglq pointer from the array of active
961  * sglq's. The xritag that is passed in is used to index into the
962  * array. Before the xritag can be used it needs to be adjusted
963  * by subtracting the xribase.
964  *
965  * Returns sglq ponter = success, NULL = Failure.
966  **/
967 struct lpfc_sglq *
968 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
969 {
970 	struct lpfc_sglq *sglq;
971 
972 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
973 	return sglq;
974 }
975 
976 /**
977  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
978  * @phba: Pointer to HBA context object.
979  * @xritag: xri used in this exchange.
980  * @rrq: The RRQ to be cleared.
981  *
982  **/
983 void
984 lpfc_clr_rrq_active(struct lpfc_hba *phba,
985 		    uint16_t xritag,
986 		    struct lpfc_node_rrq *rrq)
987 {
988 	struct lpfc_nodelist *ndlp = NULL;
989 
990 	/* Lookup did to verify if did is still active on this vport */
991 	if (rrq->vport)
992 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
993 
994 	if (!ndlp)
995 		goto out;
996 
997 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
998 		rrq->send_rrq = 0;
999 		rrq->xritag = 0;
1000 		rrq->rrq_stop_time = 0;
1001 	}
1002 out:
1003 	mempool_free(rrq, phba->rrq_pool);
1004 }
1005 
1006 /**
1007  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
1008  * @phba: Pointer to HBA context object.
1009  *
1010  * This function is called with hbalock held. This function
1011  * Checks if stop_time (ratov from setting rrq active) has
1012  * been reached, if it has and the send_rrq flag is set then
1013  * it will call lpfc_send_rrq. If the send_rrq flag is not set
1014  * then it will just call the routine to clear the rrq and
1015  * free the rrq resource.
1016  * The timer is set to the next rrq that is going to expire before
1017  * leaving the routine.
1018  *
1019  **/
1020 void
1021 lpfc_handle_rrq_active(struct lpfc_hba *phba)
1022 {
1023 	struct lpfc_node_rrq *rrq;
1024 	struct lpfc_node_rrq *nextrrq;
1025 	unsigned long next_time;
1026 	unsigned long iflags;
1027 	LIST_HEAD(send_rrq);
1028 
1029 	spin_lock_irqsave(&phba->hbalock, iflags);
1030 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1031 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1032 	list_for_each_entry_safe(rrq, nextrrq,
1033 				 &phba->active_rrq_list, list) {
1034 		if (time_after(jiffies, rrq->rrq_stop_time))
1035 			list_move(&rrq->list, &send_rrq);
1036 		else if (time_before(rrq->rrq_stop_time, next_time))
1037 			next_time = rrq->rrq_stop_time;
1038 	}
1039 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1040 	if ((!list_empty(&phba->active_rrq_list)) &&
1041 	    (!(phba->pport->load_flag & FC_UNLOADING)))
1042 		mod_timer(&phba->rrq_tmr, next_time);
1043 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
1044 		list_del(&rrq->list);
1045 		if (!rrq->send_rrq) {
1046 			/* this call will free the rrq */
1047 			lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1048 		} else if (lpfc_send_rrq(phba, rrq)) {
1049 			/* if we send the rrq then the completion handler
1050 			*  will clear the bit in the xribitmap.
1051 			*/
1052 			lpfc_clr_rrq_active(phba, rrq->xritag,
1053 					    rrq);
1054 		}
1055 	}
1056 }
1057 
1058 /**
1059  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
1060  * @vport: Pointer to vport context object.
1061  * @xri: The xri used in the exchange.
1062  * @did: The targets DID for this exchange.
1063  *
1064  * returns NULL = rrq not found in the phba->active_rrq_list.
1065  *         rrq = rrq for this xri and target.
1066  **/
1067 struct lpfc_node_rrq *
1068 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
1069 {
1070 	struct lpfc_hba *phba = vport->phba;
1071 	struct lpfc_node_rrq *rrq;
1072 	struct lpfc_node_rrq *nextrrq;
1073 	unsigned long iflags;
1074 
1075 	if (phba->sli_rev != LPFC_SLI_REV4)
1076 		return NULL;
1077 	spin_lock_irqsave(&phba->hbalock, iflags);
1078 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1079 		if (rrq->vport == vport && rrq->xritag == xri &&
1080 				rrq->nlp_DID == did){
1081 			list_del(&rrq->list);
1082 			spin_unlock_irqrestore(&phba->hbalock, iflags);
1083 			return rrq;
1084 		}
1085 	}
1086 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1087 	return NULL;
1088 }
1089 
1090 /**
1091  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
1092  * @vport: Pointer to vport context object.
1093  * @ndlp: Pointer to the lpfc_node_list structure.
1094  * If ndlp is NULL Remove all active RRQs for this vport from the
1095  * phba->active_rrq_list and clear the rrq.
1096  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
1097  **/
1098 void
1099 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
1100 
1101 {
1102 	struct lpfc_hba *phba = vport->phba;
1103 	struct lpfc_node_rrq *rrq;
1104 	struct lpfc_node_rrq *nextrrq;
1105 	unsigned long iflags;
1106 	LIST_HEAD(rrq_list);
1107 
1108 	if (phba->sli_rev != LPFC_SLI_REV4)
1109 		return;
1110 	if (!ndlp) {
1111 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
1112 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
1113 	}
1114 	spin_lock_irqsave(&phba->hbalock, iflags);
1115 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1116 		if (rrq->vport != vport)
1117 			continue;
1118 
1119 		if (!ndlp || ndlp == lpfc_findnode_did(vport, rrq->nlp_DID))
1120 			list_move(&rrq->list, &rrq_list);
1121 
1122 	}
1123 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1124 
1125 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1126 		list_del(&rrq->list);
1127 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1128 	}
1129 }
1130 
1131 /**
1132  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1133  * @phba: Pointer to HBA context object.
1134  * @ndlp: Targets nodelist pointer for this exchange.
1135  * @xritag: the xri in the bitmap to test.
1136  *
1137  * This function returns:
1138  * 0 = rrq not active for this xri
1139  * 1 = rrq is valid for this xri.
1140  **/
1141 int
1142 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1143 			uint16_t  xritag)
1144 {
1145 	if (!ndlp)
1146 		return 0;
1147 	if (!ndlp->active_rrqs_xri_bitmap)
1148 		return 0;
1149 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1150 		return 1;
1151 	else
1152 		return 0;
1153 }
1154 
1155 /**
1156  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1157  * @phba: Pointer to HBA context object.
1158  * @ndlp: nodelist pointer for this target.
1159  * @xritag: xri used in this exchange.
1160  * @rxid: Remote Exchange ID.
1161  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1162  *
1163  * This function takes the hbalock.
1164  * The active bit is always set in the active rrq xri_bitmap even
1165  * if there is no slot avaiable for the other rrq information.
1166  *
1167  * returns 0 rrq actived for this xri
1168  *         < 0 No memory or invalid ndlp.
1169  **/
1170 int
1171 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1172 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1173 {
1174 	unsigned long iflags;
1175 	struct lpfc_node_rrq *rrq;
1176 	int empty;
1177 
1178 	if (!ndlp)
1179 		return -EINVAL;
1180 
1181 	if (!phba->cfg_enable_rrq)
1182 		return -EINVAL;
1183 
1184 	spin_lock_irqsave(&phba->hbalock, iflags);
1185 	if (phba->pport->load_flag & FC_UNLOADING) {
1186 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1187 		goto out;
1188 	}
1189 
1190 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
1191 		goto out;
1192 
1193 	if (!ndlp->active_rrqs_xri_bitmap)
1194 		goto out;
1195 
1196 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1197 		goto out;
1198 
1199 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1200 	rrq = mempool_alloc(phba->rrq_pool, GFP_ATOMIC);
1201 	if (!rrq) {
1202 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1203 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1204 				" DID:0x%x Send:%d\n",
1205 				xritag, rxid, ndlp->nlp_DID, send_rrq);
1206 		return -EINVAL;
1207 	}
1208 	if (phba->cfg_enable_rrq == 1)
1209 		rrq->send_rrq = send_rrq;
1210 	else
1211 		rrq->send_rrq = 0;
1212 	rrq->xritag = xritag;
1213 	rrq->rrq_stop_time = jiffies +
1214 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1215 	rrq->nlp_DID = ndlp->nlp_DID;
1216 	rrq->vport = ndlp->vport;
1217 	rrq->rxid = rxid;
1218 	spin_lock_irqsave(&phba->hbalock, iflags);
1219 	empty = list_empty(&phba->active_rrq_list);
1220 	list_add_tail(&rrq->list, &phba->active_rrq_list);
1221 	phba->hba_flag |= HBA_RRQ_ACTIVE;
1222 	if (empty)
1223 		lpfc_worker_wake_up(phba);
1224 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1225 	return 0;
1226 out:
1227 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1228 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1229 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
1230 			" DID:0x%x Send:%d\n",
1231 			xritag, rxid, ndlp->nlp_DID, send_rrq);
1232 	return -EINVAL;
1233 }
1234 
1235 /**
1236  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1237  * @phba: Pointer to HBA context object.
1238  * @piocbq: Pointer to the iocbq.
1239  *
1240  * The driver calls this function with either the nvme ls ring lock
1241  * or the fc els ring lock held depending on the iocb usage.  This function
1242  * gets a new driver sglq object from the sglq list. If the list is not empty
1243  * then it is successful, it returns pointer to the newly allocated sglq
1244  * object else it returns NULL.
1245  **/
1246 static struct lpfc_sglq *
1247 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1248 {
1249 	struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1250 	struct lpfc_sglq *sglq = NULL;
1251 	struct lpfc_sglq *start_sglq = NULL;
1252 	struct lpfc_io_buf *lpfc_cmd;
1253 	struct lpfc_nodelist *ndlp;
1254 	struct lpfc_sli_ring *pring = NULL;
1255 	int found = 0;
1256 
1257 	if (piocbq->iocb_flag & LPFC_IO_NVME_LS)
1258 		pring =  phba->sli4_hba.nvmels_wq->pring;
1259 	else
1260 		pring = lpfc_phba_elsring(phba);
1261 
1262 	lockdep_assert_held(&pring->ring_lock);
1263 
1264 	if (piocbq->iocb_flag &  LPFC_IO_FCP) {
1265 		lpfc_cmd = (struct lpfc_io_buf *) piocbq->context1;
1266 		ndlp = lpfc_cmd->rdata->pnode;
1267 	} else  if ((piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) &&
1268 			!(piocbq->iocb_flag & LPFC_IO_LIBDFC)) {
1269 		ndlp = piocbq->context_un.ndlp;
1270 	} else  if (piocbq->iocb_flag & LPFC_IO_LIBDFC) {
1271 		if (piocbq->iocb_flag & LPFC_IO_LOOPBACK)
1272 			ndlp = NULL;
1273 		else
1274 			ndlp = piocbq->context_un.ndlp;
1275 	} else {
1276 		ndlp = piocbq->context1;
1277 	}
1278 
1279 	spin_lock(&phba->sli4_hba.sgl_list_lock);
1280 	list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1281 	start_sglq = sglq;
1282 	while (!found) {
1283 		if (!sglq)
1284 			break;
1285 		if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1286 		    test_bit(sglq->sli4_lxritag,
1287 		    ndlp->active_rrqs_xri_bitmap)) {
1288 			/* This xri has an rrq outstanding for this DID.
1289 			 * put it back in the list and get another xri.
1290 			 */
1291 			list_add_tail(&sglq->list, lpfc_els_sgl_list);
1292 			sglq = NULL;
1293 			list_remove_head(lpfc_els_sgl_list, sglq,
1294 						struct lpfc_sglq, list);
1295 			if (sglq == start_sglq) {
1296 				list_add_tail(&sglq->list, lpfc_els_sgl_list);
1297 				sglq = NULL;
1298 				break;
1299 			} else
1300 				continue;
1301 		}
1302 		sglq->ndlp = ndlp;
1303 		found = 1;
1304 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1305 		sglq->state = SGL_ALLOCATED;
1306 	}
1307 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
1308 	return sglq;
1309 }
1310 
1311 /**
1312  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1313  * @phba: Pointer to HBA context object.
1314  * @piocbq: Pointer to the iocbq.
1315  *
1316  * This function is called with the sgl_list lock held. This function
1317  * gets a new driver sglq object from the sglq list. If the
1318  * list is not empty then it is successful, it returns pointer to the newly
1319  * allocated sglq object else it returns NULL.
1320  **/
1321 struct lpfc_sglq *
1322 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1323 {
1324 	struct list_head *lpfc_nvmet_sgl_list;
1325 	struct lpfc_sglq *sglq = NULL;
1326 
1327 	lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1328 
1329 	lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1330 
1331 	list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1332 	if (!sglq)
1333 		return NULL;
1334 	phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1335 	sglq->state = SGL_ALLOCATED;
1336 	return sglq;
1337 }
1338 
1339 /**
1340  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1341  * @phba: Pointer to HBA context object.
1342  *
1343  * This function is called with no lock held. This function
1344  * allocates a new driver iocb object from the iocb pool. If the
1345  * allocation is successful, it returns pointer to the newly
1346  * allocated iocb object else it returns NULL.
1347  **/
1348 struct lpfc_iocbq *
1349 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1350 {
1351 	struct lpfc_iocbq * iocbq = NULL;
1352 	unsigned long iflags;
1353 
1354 	spin_lock_irqsave(&phba->hbalock, iflags);
1355 	iocbq = __lpfc_sli_get_iocbq(phba);
1356 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1357 	return iocbq;
1358 }
1359 
1360 /**
1361  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1362  * @phba: Pointer to HBA context object.
1363  * @iocbq: Pointer to driver iocb object.
1364  *
1365  * This function is called to release the driver iocb object
1366  * to the iocb pool. The iotag in the iocb object
1367  * does not change for each use of the iocb object. This function
1368  * clears all other fields of the iocb object when it is freed.
1369  * The sqlq structure that holds the xritag and phys and virtual
1370  * mappings for the scatter gather list is retrieved from the
1371  * active array of sglq. The get of the sglq pointer also clears
1372  * the entry in the array. If the status of the IO indiactes that
1373  * this IO was aborted then the sglq entry it put on the
1374  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1375  * IO has good status or fails for any other reason then the sglq
1376  * entry is added to the free list (lpfc_els_sgl_list). The hbalock is
1377  *  asserted held in the code path calling this routine.
1378  **/
1379 static void
1380 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1381 {
1382 	struct lpfc_sglq *sglq;
1383 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1384 	unsigned long iflag = 0;
1385 	struct lpfc_sli_ring *pring;
1386 
1387 	if (iocbq->sli4_xritag == NO_XRI)
1388 		sglq = NULL;
1389 	else
1390 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1391 
1392 
1393 	if (sglq)  {
1394 		if (iocbq->iocb_flag & LPFC_IO_NVMET) {
1395 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1396 					  iflag);
1397 			sglq->state = SGL_FREED;
1398 			sglq->ndlp = NULL;
1399 			list_add_tail(&sglq->list,
1400 				      &phba->sli4_hba.lpfc_nvmet_sgl_list);
1401 			spin_unlock_irqrestore(
1402 				&phba->sli4_hba.sgl_list_lock, iflag);
1403 			goto out;
1404 		}
1405 
1406 		if ((iocbq->iocb_flag & LPFC_EXCHANGE_BUSY) &&
1407 			(sglq->state != SGL_XRI_ABORTED)) {
1408 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1409 					  iflag);
1410 
1411 			/* Check if we can get a reference on ndlp */
1412 			if (sglq->ndlp && !lpfc_nlp_get(sglq->ndlp))
1413 				sglq->ndlp = NULL;
1414 
1415 			list_add(&sglq->list,
1416 				 &phba->sli4_hba.lpfc_abts_els_sgl_list);
1417 			spin_unlock_irqrestore(
1418 				&phba->sli4_hba.sgl_list_lock, iflag);
1419 		} else {
1420 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1421 					  iflag);
1422 			sglq->state = SGL_FREED;
1423 			sglq->ndlp = NULL;
1424 			list_add_tail(&sglq->list,
1425 				      &phba->sli4_hba.lpfc_els_sgl_list);
1426 			spin_unlock_irqrestore(
1427 				&phba->sli4_hba.sgl_list_lock, iflag);
1428 			pring = lpfc_phba_elsring(phba);
1429 			/* Check if TXQ queue needs to be serviced */
1430 			if (pring && (!list_empty(&pring->txq)))
1431 				lpfc_worker_wake_up(phba);
1432 		}
1433 	}
1434 
1435 out:
1436 	/*
1437 	 * Clean all volatile data fields, preserve iotag and node struct.
1438 	 */
1439 	memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1440 	iocbq->sli4_lxritag = NO_XRI;
1441 	iocbq->sli4_xritag = NO_XRI;
1442 	iocbq->iocb_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET |
1443 			      LPFC_IO_NVME_LS);
1444 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1445 }
1446 
1447 
1448 /**
1449  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1450  * @phba: Pointer to HBA context object.
1451  * @iocbq: Pointer to driver iocb object.
1452  *
1453  * This function is called to release the driver iocb object to the
1454  * iocb pool. The iotag in the iocb object does not change for each
1455  * use of the iocb object. This function clears all other fields of
1456  * the iocb object when it is freed. The hbalock is asserted held in
1457  * the code path calling this routine.
1458  **/
1459 static void
1460 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1461 {
1462 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1463 
1464 	/*
1465 	 * Clean all volatile data fields, preserve iotag and node struct.
1466 	 */
1467 	memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1468 	iocbq->sli4_xritag = NO_XRI;
1469 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1470 }
1471 
1472 /**
1473  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1474  * @phba: Pointer to HBA context object.
1475  * @iocbq: Pointer to driver iocb object.
1476  *
1477  * This function is called with hbalock held to release driver
1478  * iocb object to the iocb pool. The iotag in the iocb object
1479  * does not change for each use of the iocb object. This function
1480  * clears all other fields of the iocb object when it is freed.
1481  **/
1482 static void
1483 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1484 {
1485 	lockdep_assert_held(&phba->hbalock);
1486 
1487 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1488 	phba->iocb_cnt--;
1489 }
1490 
1491 /**
1492  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1493  * @phba: Pointer to HBA context object.
1494  * @iocbq: Pointer to driver iocb object.
1495  *
1496  * This function is called with no lock held to release the iocb to
1497  * iocb pool.
1498  **/
1499 void
1500 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1501 {
1502 	unsigned long iflags;
1503 
1504 	/*
1505 	 * Clean all volatile data fields, preserve iotag and node struct.
1506 	 */
1507 	spin_lock_irqsave(&phba->hbalock, iflags);
1508 	__lpfc_sli_release_iocbq(phba, iocbq);
1509 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1510 }
1511 
1512 /**
1513  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1514  * @phba: Pointer to HBA context object.
1515  * @iocblist: List of IOCBs.
1516  * @ulpstatus: ULP status in IOCB command field.
1517  * @ulpWord4: ULP word-4 in IOCB command field.
1518  *
1519  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1520  * on the list by invoking the complete callback function associated with the
1521  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1522  * fields.
1523  **/
1524 void
1525 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1526 		      uint32_t ulpstatus, uint32_t ulpWord4)
1527 {
1528 	struct lpfc_iocbq *piocb;
1529 
1530 	while (!list_empty(iocblist)) {
1531 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1532 		if (piocb->wqe_cmpl) {
1533 			if (piocb->iocb_flag & LPFC_IO_NVME)
1534 				lpfc_nvme_cancel_iocb(phba, piocb,
1535 						      ulpstatus, ulpWord4);
1536 			else
1537 				lpfc_sli_release_iocbq(phba, piocb);
1538 
1539 		} else if (piocb->iocb_cmpl) {
1540 			piocb->iocb.ulpStatus = ulpstatus;
1541 			piocb->iocb.un.ulpWord[4] = ulpWord4;
1542 			(piocb->iocb_cmpl) (phba, piocb, piocb);
1543 		} else {
1544 			lpfc_sli_release_iocbq(phba, piocb);
1545 		}
1546 	}
1547 	return;
1548 }
1549 
1550 /**
1551  * lpfc_sli_iocb_cmd_type - Get the iocb type
1552  * @iocb_cmnd: iocb command code.
1553  *
1554  * This function is called by ring event handler function to get the iocb type.
1555  * This function translates the iocb command to an iocb command type used to
1556  * decide the final disposition of each completed IOCB.
1557  * The function returns
1558  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1559  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1560  * LPFC_ABORT_IOCB   if it is an abort iocb
1561  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1562  *
1563  * The caller is not required to hold any lock.
1564  **/
1565 static lpfc_iocb_type
1566 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1567 {
1568 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1569 
1570 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1571 		return 0;
1572 
1573 	switch (iocb_cmnd) {
1574 	case CMD_XMIT_SEQUENCE_CR:
1575 	case CMD_XMIT_SEQUENCE_CX:
1576 	case CMD_XMIT_BCAST_CN:
1577 	case CMD_XMIT_BCAST_CX:
1578 	case CMD_ELS_REQUEST_CR:
1579 	case CMD_ELS_REQUEST_CX:
1580 	case CMD_CREATE_XRI_CR:
1581 	case CMD_CREATE_XRI_CX:
1582 	case CMD_GET_RPI_CN:
1583 	case CMD_XMIT_ELS_RSP_CX:
1584 	case CMD_GET_RPI_CR:
1585 	case CMD_FCP_IWRITE_CR:
1586 	case CMD_FCP_IWRITE_CX:
1587 	case CMD_FCP_IREAD_CR:
1588 	case CMD_FCP_IREAD_CX:
1589 	case CMD_FCP_ICMND_CR:
1590 	case CMD_FCP_ICMND_CX:
1591 	case CMD_FCP_TSEND_CX:
1592 	case CMD_FCP_TRSP_CX:
1593 	case CMD_FCP_TRECEIVE_CX:
1594 	case CMD_FCP_AUTO_TRSP_CX:
1595 	case CMD_ADAPTER_MSG:
1596 	case CMD_ADAPTER_DUMP:
1597 	case CMD_XMIT_SEQUENCE64_CR:
1598 	case CMD_XMIT_SEQUENCE64_CX:
1599 	case CMD_XMIT_BCAST64_CN:
1600 	case CMD_XMIT_BCAST64_CX:
1601 	case CMD_ELS_REQUEST64_CR:
1602 	case CMD_ELS_REQUEST64_CX:
1603 	case CMD_FCP_IWRITE64_CR:
1604 	case CMD_FCP_IWRITE64_CX:
1605 	case CMD_FCP_IREAD64_CR:
1606 	case CMD_FCP_IREAD64_CX:
1607 	case CMD_FCP_ICMND64_CR:
1608 	case CMD_FCP_ICMND64_CX:
1609 	case CMD_FCP_TSEND64_CX:
1610 	case CMD_FCP_TRSP64_CX:
1611 	case CMD_FCP_TRECEIVE64_CX:
1612 	case CMD_GEN_REQUEST64_CR:
1613 	case CMD_GEN_REQUEST64_CX:
1614 	case CMD_XMIT_ELS_RSP64_CX:
1615 	case DSSCMD_IWRITE64_CR:
1616 	case DSSCMD_IWRITE64_CX:
1617 	case DSSCMD_IREAD64_CR:
1618 	case DSSCMD_IREAD64_CX:
1619 	case CMD_SEND_FRAME:
1620 		type = LPFC_SOL_IOCB;
1621 		break;
1622 	case CMD_ABORT_XRI_CN:
1623 	case CMD_ABORT_XRI_CX:
1624 	case CMD_CLOSE_XRI_CN:
1625 	case CMD_CLOSE_XRI_CX:
1626 	case CMD_XRI_ABORTED_CX:
1627 	case CMD_ABORT_MXRI64_CN:
1628 	case CMD_XMIT_BLS_RSP64_CX:
1629 		type = LPFC_ABORT_IOCB;
1630 		break;
1631 	case CMD_RCV_SEQUENCE_CX:
1632 	case CMD_RCV_ELS_REQ_CX:
1633 	case CMD_RCV_SEQUENCE64_CX:
1634 	case CMD_RCV_ELS_REQ64_CX:
1635 	case CMD_ASYNC_STATUS:
1636 	case CMD_IOCB_RCV_SEQ64_CX:
1637 	case CMD_IOCB_RCV_ELS64_CX:
1638 	case CMD_IOCB_RCV_CONT64_CX:
1639 	case CMD_IOCB_RET_XRI64_CX:
1640 		type = LPFC_UNSOL_IOCB;
1641 		break;
1642 	case CMD_IOCB_XMIT_MSEQ64_CR:
1643 	case CMD_IOCB_XMIT_MSEQ64_CX:
1644 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1645 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1646 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1647 	case CMD_IOCB_ABORT_EXTENDED_CN:
1648 	case CMD_IOCB_RET_HBQE64_CN:
1649 	case CMD_IOCB_FCP_IBIDIR64_CR:
1650 	case CMD_IOCB_FCP_IBIDIR64_CX:
1651 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1652 	case CMD_IOCB_LOGENTRY_CN:
1653 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1654 		printk("%s - Unhandled SLI-3 Command x%x\n",
1655 				__func__, iocb_cmnd);
1656 		type = LPFC_UNKNOWN_IOCB;
1657 		break;
1658 	default:
1659 		type = LPFC_UNKNOWN_IOCB;
1660 		break;
1661 	}
1662 
1663 	return type;
1664 }
1665 
1666 /**
1667  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1668  * @phba: Pointer to HBA context object.
1669  *
1670  * This function is called from SLI initialization code
1671  * to configure every ring of the HBA's SLI interface. The
1672  * caller is not required to hold any lock. This function issues
1673  * a config_ring mailbox command for each ring.
1674  * This function returns zero if successful else returns a negative
1675  * error code.
1676  **/
1677 static int
1678 lpfc_sli_ring_map(struct lpfc_hba *phba)
1679 {
1680 	struct lpfc_sli *psli = &phba->sli;
1681 	LPFC_MBOXQ_t *pmb;
1682 	MAILBOX_t *pmbox;
1683 	int i, rc, ret = 0;
1684 
1685 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1686 	if (!pmb)
1687 		return -ENOMEM;
1688 	pmbox = &pmb->u.mb;
1689 	phba->link_state = LPFC_INIT_MBX_CMDS;
1690 	for (i = 0; i < psli->num_rings; i++) {
1691 		lpfc_config_ring(phba, i, pmb);
1692 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1693 		if (rc != MBX_SUCCESS) {
1694 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1695 					"0446 Adapter failed to init (%d), "
1696 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1697 					"ring %d\n",
1698 					rc, pmbox->mbxCommand,
1699 					pmbox->mbxStatus, i);
1700 			phba->link_state = LPFC_HBA_ERROR;
1701 			ret = -ENXIO;
1702 			break;
1703 		}
1704 	}
1705 	mempool_free(pmb, phba->mbox_mem_pool);
1706 	return ret;
1707 }
1708 
1709 /**
1710  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1711  * @phba: Pointer to HBA context object.
1712  * @pring: Pointer to driver SLI ring object.
1713  * @piocb: Pointer to the driver iocb object.
1714  *
1715  * The driver calls this function with the hbalock held for SLI3 ports or
1716  * the ring lock held for SLI4 ports. The function adds the
1717  * new iocb to txcmplq of the given ring. This function always returns
1718  * 0. If this function is called for ELS ring, this function checks if
1719  * there is a vport associated with the ELS command. This function also
1720  * starts els_tmofunc timer if this is an ELS command.
1721  **/
1722 static int
1723 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1724 			struct lpfc_iocbq *piocb)
1725 {
1726 	if (phba->sli_rev == LPFC_SLI_REV4)
1727 		lockdep_assert_held(&pring->ring_lock);
1728 	else
1729 		lockdep_assert_held(&phba->hbalock);
1730 
1731 	BUG_ON(!piocb);
1732 
1733 	list_add_tail(&piocb->list, &pring->txcmplq);
1734 	piocb->iocb_flag |= LPFC_IO_ON_TXCMPLQ;
1735 	pring->txcmplq_cnt++;
1736 
1737 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1738 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
1739 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
1740 		BUG_ON(!piocb->vport);
1741 		if (!(piocb->vport->load_flag & FC_UNLOADING))
1742 			mod_timer(&piocb->vport->els_tmofunc,
1743 				  jiffies +
1744 				  msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1745 	}
1746 
1747 	return 0;
1748 }
1749 
1750 /**
1751  * lpfc_sli_ringtx_get - Get first element of the txq
1752  * @phba: Pointer to HBA context object.
1753  * @pring: Pointer to driver SLI ring object.
1754  *
1755  * This function is called with hbalock held to get next
1756  * iocb in txq of the given ring. If there is any iocb in
1757  * the txq, the function returns first iocb in the list after
1758  * removing the iocb from the list, else it returns NULL.
1759  **/
1760 struct lpfc_iocbq *
1761 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1762 {
1763 	struct lpfc_iocbq *cmd_iocb;
1764 
1765 	lockdep_assert_held(&phba->hbalock);
1766 
1767 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1768 	return cmd_iocb;
1769 }
1770 
1771 /**
1772  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
1773  * @phba: Pointer to HBA context object.
1774  * @pring: Pointer to driver SLI ring object.
1775  *
1776  * This function is called with hbalock held and the caller must post the
1777  * iocb without releasing the lock. If the caller releases the lock,
1778  * iocb slot returned by the function is not guaranteed to be available.
1779  * The function returns pointer to the next available iocb slot if there
1780  * is available slot in the ring, else it returns NULL.
1781  * If the get index of the ring is ahead of the put index, the function
1782  * will post an error attention event to the worker thread to take the
1783  * HBA to offline state.
1784  **/
1785 static IOCB_t *
1786 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1787 {
1788 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
1789 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
1790 
1791 	lockdep_assert_held(&phba->hbalock);
1792 
1793 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
1794 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
1795 		pring->sli.sli3.next_cmdidx = 0;
1796 
1797 	if (unlikely(pring->sli.sli3.local_getidx ==
1798 		pring->sli.sli3.next_cmdidx)) {
1799 
1800 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
1801 
1802 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
1803 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1804 					"0315 Ring %d issue: portCmdGet %d "
1805 					"is bigger than cmd ring %d\n",
1806 					pring->ringno,
1807 					pring->sli.sli3.local_getidx,
1808 					max_cmd_idx);
1809 
1810 			phba->link_state = LPFC_HBA_ERROR;
1811 			/*
1812 			 * All error attention handlers are posted to
1813 			 * worker thread
1814 			 */
1815 			phba->work_ha |= HA_ERATT;
1816 			phba->work_hs = HS_FFER3;
1817 
1818 			lpfc_worker_wake_up(phba);
1819 
1820 			return NULL;
1821 		}
1822 
1823 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
1824 			return NULL;
1825 	}
1826 
1827 	return lpfc_cmd_iocb(phba, pring);
1828 }
1829 
1830 /**
1831  * lpfc_sli_next_iotag - Get an iotag for the iocb
1832  * @phba: Pointer to HBA context object.
1833  * @iocbq: Pointer to driver iocb object.
1834  *
1835  * This function gets an iotag for the iocb. If there is no unused iotag and
1836  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
1837  * array and assigns a new iotag.
1838  * The function returns the allocated iotag if successful, else returns zero.
1839  * Zero is not a valid iotag.
1840  * The caller is not required to hold any lock.
1841  **/
1842 uint16_t
1843 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1844 {
1845 	struct lpfc_iocbq **new_arr;
1846 	struct lpfc_iocbq **old_arr;
1847 	size_t new_len;
1848 	struct lpfc_sli *psli = &phba->sli;
1849 	uint16_t iotag;
1850 
1851 	spin_lock_irq(&phba->hbalock);
1852 	iotag = psli->last_iotag;
1853 	if(++iotag < psli->iocbq_lookup_len) {
1854 		psli->last_iotag = iotag;
1855 		psli->iocbq_lookup[iotag] = iocbq;
1856 		spin_unlock_irq(&phba->hbalock);
1857 		iocbq->iotag = iotag;
1858 		return iotag;
1859 	} else if (psli->iocbq_lookup_len < (0xffff
1860 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
1861 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
1862 		spin_unlock_irq(&phba->hbalock);
1863 		new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
1864 				  GFP_KERNEL);
1865 		if (new_arr) {
1866 			spin_lock_irq(&phba->hbalock);
1867 			old_arr = psli->iocbq_lookup;
1868 			if (new_len <= psli->iocbq_lookup_len) {
1869 				/* highly unprobable case */
1870 				kfree(new_arr);
1871 				iotag = psli->last_iotag;
1872 				if(++iotag < psli->iocbq_lookup_len) {
1873 					psli->last_iotag = iotag;
1874 					psli->iocbq_lookup[iotag] = iocbq;
1875 					spin_unlock_irq(&phba->hbalock);
1876 					iocbq->iotag = iotag;
1877 					return iotag;
1878 				}
1879 				spin_unlock_irq(&phba->hbalock);
1880 				return 0;
1881 			}
1882 			if (psli->iocbq_lookup)
1883 				memcpy(new_arr, old_arr,
1884 				       ((psli->last_iotag  + 1) *
1885 					sizeof (struct lpfc_iocbq *)));
1886 			psli->iocbq_lookup = new_arr;
1887 			psli->iocbq_lookup_len = new_len;
1888 			psli->last_iotag = iotag;
1889 			psli->iocbq_lookup[iotag] = iocbq;
1890 			spin_unlock_irq(&phba->hbalock);
1891 			iocbq->iotag = iotag;
1892 			kfree(old_arr);
1893 			return iotag;
1894 		}
1895 	} else
1896 		spin_unlock_irq(&phba->hbalock);
1897 
1898 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
1899 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
1900 			psli->last_iotag);
1901 
1902 	return 0;
1903 }
1904 
1905 /**
1906  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
1907  * @phba: Pointer to HBA context object.
1908  * @pring: Pointer to driver SLI ring object.
1909  * @iocb: Pointer to iocb slot in the ring.
1910  * @nextiocb: Pointer to driver iocb object which need to be
1911  *            posted to firmware.
1912  *
1913  * This function is called to post a new iocb to the firmware. This
1914  * function copies the new iocb to ring iocb slot and updates the
1915  * ring pointers. It adds the new iocb to txcmplq if there is
1916  * a completion call back for this iocb else the function will free the
1917  * iocb object.  The hbalock is asserted held in the code path calling
1918  * this routine.
1919  **/
1920 static void
1921 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1922 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
1923 {
1924 	/*
1925 	 * Set up an iotag
1926 	 */
1927 	nextiocb->iocb.ulpIoTag = (nextiocb->iocb_cmpl) ? nextiocb->iotag : 0;
1928 
1929 
1930 	if (pring->ringno == LPFC_ELS_RING) {
1931 		lpfc_debugfs_slow_ring_trc(phba,
1932 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
1933 			*(((uint32_t *) &nextiocb->iocb) + 4),
1934 			*(((uint32_t *) &nextiocb->iocb) + 6),
1935 			*(((uint32_t *) &nextiocb->iocb) + 7));
1936 	}
1937 
1938 	/*
1939 	 * Issue iocb command to adapter
1940 	 */
1941 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
1942 	wmb();
1943 	pring->stats.iocb_cmd++;
1944 
1945 	/*
1946 	 * If there is no completion routine to call, we can release the
1947 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
1948 	 * that have no rsp ring completion, iocb_cmpl MUST be NULL.
1949 	 */
1950 	if (nextiocb->iocb_cmpl)
1951 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
1952 	else
1953 		__lpfc_sli_release_iocbq(phba, nextiocb);
1954 
1955 	/*
1956 	 * Let the HBA know what IOCB slot will be the next one the
1957 	 * driver will put a command into.
1958 	 */
1959 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
1960 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
1961 }
1962 
1963 /**
1964  * lpfc_sli_update_full_ring - Update the chip attention register
1965  * @phba: Pointer to HBA context object.
1966  * @pring: Pointer to driver SLI ring object.
1967  *
1968  * The caller is not required to hold any lock for calling this function.
1969  * This function updates the chip attention bits for the ring to inform firmware
1970  * that there are pending work to be done for this ring and requests an
1971  * interrupt when there is space available in the ring. This function is
1972  * called when the driver is unable to post more iocbs to the ring due
1973  * to unavailability of space in the ring.
1974  **/
1975 static void
1976 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1977 {
1978 	int ringno = pring->ringno;
1979 
1980 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
1981 
1982 	wmb();
1983 
1984 	/*
1985 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
1986 	 * The HBA will tell us when an IOCB entry is available.
1987 	 */
1988 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
1989 	readl(phba->CAregaddr); /* flush */
1990 
1991 	pring->stats.iocb_cmd_full++;
1992 }
1993 
1994 /**
1995  * lpfc_sli_update_ring - Update chip attention register
1996  * @phba: Pointer to HBA context object.
1997  * @pring: Pointer to driver SLI ring object.
1998  *
1999  * This function updates the chip attention register bit for the
2000  * given ring to inform HBA that there is more work to be done
2001  * in this ring. The caller is not required to hold any lock.
2002  **/
2003 static void
2004 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2005 {
2006 	int ringno = pring->ringno;
2007 
2008 	/*
2009 	 * Tell the HBA that there is work to do in this ring.
2010 	 */
2011 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
2012 		wmb();
2013 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
2014 		readl(phba->CAregaddr); /* flush */
2015 	}
2016 }
2017 
2018 /**
2019  * lpfc_sli_resume_iocb - Process iocbs in the txq
2020  * @phba: Pointer to HBA context object.
2021  * @pring: Pointer to driver SLI ring object.
2022  *
2023  * This function is called with hbalock held to post pending iocbs
2024  * in the txq to the firmware. This function is called when driver
2025  * detects space available in the ring.
2026  **/
2027 static void
2028 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2029 {
2030 	IOCB_t *iocb;
2031 	struct lpfc_iocbq *nextiocb;
2032 
2033 	lockdep_assert_held(&phba->hbalock);
2034 
2035 	/*
2036 	 * Check to see if:
2037 	 *  (a) there is anything on the txq to send
2038 	 *  (b) link is up
2039 	 *  (c) link attention events can be processed (fcp ring only)
2040 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
2041 	 */
2042 
2043 	if (lpfc_is_link_up(phba) &&
2044 	    (!list_empty(&pring->txq)) &&
2045 	    (pring->ringno != LPFC_FCP_RING ||
2046 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
2047 
2048 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
2049 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
2050 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
2051 
2052 		if (iocb)
2053 			lpfc_sli_update_ring(phba, pring);
2054 		else
2055 			lpfc_sli_update_full_ring(phba, pring);
2056 	}
2057 
2058 	return;
2059 }
2060 
2061 /**
2062  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
2063  * @phba: Pointer to HBA context object.
2064  * @hbqno: HBQ number.
2065  *
2066  * This function is called with hbalock held to get the next
2067  * available slot for the given HBQ. If there is free slot
2068  * available for the HBQ it will return pointer to the next available
2069  * HBQ entry else it will return NULL.
2070  **/
2071 static struct lpfc_hbq_entry *
2072 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
2073 {
2074 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
2075 
2076 	lockdep_assert_held(&phba->hbalock);
2077 
2078 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
2079 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
2080 		hbqp->next_hbqPutIdx = 0;
2081 
2082 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
2083 		uint32_t raw_index = phba->hbq_get[hbqno];
2084 		uint32_t getidx = le32_to_cpu(raw_index);
2085 
2086 		hbqp->local_hbqGetIdx = getidx;
2087 
2088 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
2089 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2090 					"1802 HBQ %d: local_hbqGetIdx "
2091 					"%u is > than hbqp->entry_count %u\n",
2092 					hbqno, hbqp->local_hbqGetIdx,
2093 					hbqp->entry_count);
2094 
2095 			phba->link_state = LPFC_HBA_ERROR;
2096 			return NULL;
2097 		}
2098 
2099 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
2100 			return NULL;
2101 	}
2102 
2103 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
2104 			hbqp->hbqPutIdx;
2105 }
2106 
2107 /**
2108  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
2109  * @phba: Pointer to HBA context object.
2110  *
2111  * This function is called with no lock held to free all the
2112  * hbq buffers while uninitializing the SLI interface. It also
2113  * frees the HBQ buffers returned by the firmware but not yet
2114  * processed by the upper layers.
2115  **/
2116 void
2117 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
2118 {
2119 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
2120 	struct hbq_dmabuf *hbq_buf;
2121 	unsigned long flags;
2122 	int i, hbq_count;
2123 
2124 	hbq_count = lpfc_sli_hbq_count();
2125 	/* Return all memory used by all HBQs */
2126 	spin_lock_irqsave(&phba->hbalock, flags);
2127 	for (i = 0; i < hbq_count; ++i) {
2128 		list_for_each_entry_safe(dmabuf, next_dmabuf,
2129 				&phba->hbqs[i].hbq_buffer_list, list) {
2130 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2131 			list_del(&hbq_buf->dbuf.list);
2132 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2133 		}
2134 		phba->hbqs[i].buffer_count = 0;
2135 	}
2136 
2137 	/* Mark the HBQs not in use */
2138 	phba->hbq_in_use = 0;
2139 	spin_unlock_irqrestore(&phba->hbalock, flags);
2140 }
2141 
2142 /**
2143  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2144  * @phba: Pointer to HBA context object.
2145  * @hbqno: HBQ number.
2146  * @hbq_buf: Pointer to HBQ buffer.
2147  *
2148  * This function is called with the hbalock held to post a
2149  * hbq buffer to the firmware. If the function finds an empty
2150  * slot in the HBQ, it will post the buffer. The function will return
2151  * pointer to the hbq entry if it successfully post the buffer
2152  * else it will return NULL.
2153  **/
2154 static int
2155 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2156 			 struct hbq_dmabuf *hbq_buf)
2157 {
2158 	lockdep_assert_held(&phba->hbalock);
2159 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2160 }
2161 
2162 /**
2163  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2164  * @phba: Pointer to HBA context object.
2165  * @hbqno: HBQ number.
2166  * @hbq_buf: Pointer to HBQ buffer.
2167  *
2168  * This function is called with the hbalock held to post a hbq buffer to the
2169  * firmware. If the function finds an empty slot in the HBQ, it will post the
2170  * buffer and place it on the hbq_buffer_list. The function will return zero if
2171  * it successfully post the buffer else it will return an error.
2172  **/
2173 static int
2174 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2175 			    struct hbq_dmabuf *hbq_buf)
2176 {
2177 	struct lpfc_hbq_entry *hbqe;
2178 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
2179 
2180 	lockdep_assert_held(&phba->hbalock);
2181 	/* Get next HBQ entry slot to use */
2182 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2183 	if (hbqe) {
2184 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
2185 
2186 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2187 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2188 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2189 		hbqe->bde.tus.f.bdeFlags = 0;
2190 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2191 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2192 				/* Sync SLIM */
2193 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2194 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2195 				/* flush */
2196 		readl(phba->hbq_put + hbqno);
2197 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2198 		return 0;
2199 	} else
2200 		return -ENOMEM;
2201 }
2202 
2203 /**
2204  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2205  * @phba: Pointer to HBA context object.
2206  * @hbqno: HBQ number.
2207  * @hbq_buf: Pointer to HBQ buffer.
2208  *
2209  * This function is called with the hbalock held to post an RQE to the SLI4
2210  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2211  * the hbq_buffer_list and return zero, otherwise it will return an error.
2212  **/
2213 static int
2214 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2215 			    struct hbq_dmabuf *hbq_buf)
2216 {
2217 	int rc;
2218 	struct lpfc_rqe hrqe;
2219 	struct lpfc_rqe drqe;
2220 	struct lpfc_queue *hrq;
2221 	struct lpfc_queue *drq;
2222 
2223 	if (hbqno != LPFC_ELS_HBQ)
2224 		return 1;
2225 	hrq = phba->sli4_hba.hdr_rq;
2226 	drq = phba->sli4_hba.dat_rq;
2227 
2228 	lockdep_assert_held(&phba->hbalock);
2229 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2230 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2231 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2232 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2233 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2234 	if (rc < 0)
2235 		return rc;
2236 	hbq_buf->tag = (rc | (hbqno << 16));
2237 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2238 	return 0;
2239 }
2240 
2241 /* HBQ for ELS and CT traffic. */
2242 static struct lpfc_hbq_init lpfc_els_hbq = {
2243 	.rn = 1,
2244 	.entry_count = 256,
2245 	.mask_count = 0,
2246 	.profile = 0,
2247 	.ring_mask = (1 << LPFC_ELS_RING),
2248 	.buffer_count = 0,
2249 	.init_count = 40,
2250 	.add_count = 40,
2251 };
2252 
2253 /* Array of HBQs */
2254 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2255 	&lpfc_els_hbq,
2256 };
2257 
2258 /**
2259  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2260  * @phba: Pointer to HBA context object.
2261  * @hbqno: HBQ number.
2262  * @count: Number of HBQ buffers to be posted.
2263  *
2264  * This function is called with no lock held to post more hbq buffers to the
2265  * given HBQ. The function returns the number of HBQ buffers successfully
2266  * posted.
2267  **/
2268 static int
2269 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2270 {
2271 	uint32_t i, posted = 0;
2272 	unsigned long flags;
2273 	struct hbq_dmabuf *hbq_buffer;
2274 	LIST_HEAD(hbq_buf_list);
2275 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2276 		return 0;
2277 
2278 	if ((phba->hbqs[hbqno].buffer_count + count) >
2279 	    lpfc_hbq_defs[hbqno]->entry_count)
2280 		count = lpfc_hbq_defs[hbqno]->entry_count -
2281 					phba->hbqs[hbqno].buffer_count;
2282 	if (!count)
2283 		return 0;
2284 	/* Allocate HBQ entries */
2285 	for (i = 0; i < count; i++) {
2286 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2287 		if (!hbq_buffer)
2288 			break;
2289 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2290 	}
2291 	/* Check whether HBQ is still in use */
2292 	spin_lock_irqsave(&phba->hbalock, flags);
2293 	if (!phba->hbq_in_use)
2294 		goto err;
2295 	while (!list_empty(&hbq_buf_list)) {
2296 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2297 				 dbuf.list);
2298 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2299 				      (hbqno << 16));
2300 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2301 			phba->hbqs[hbqno].buffer_count++;
2302 			posted++;
2303 		} else
2304 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2305 	}
2306 	spin_unlock_irqrestore(&phba->hbalock, flags);
2307 	return posted;
2308 err:
2309 	spin_unlock_irqrestore(&phba->hbalock, flags);
2310 	while (!list_empty(&hbq_buf_list)) {
2311 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2312 				 dbuf.list);
2313 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2314 	}
2315 	return 0;
2316 }
2317 
2318 /**
2319  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2320  * @phba: Pointer to HBA context object.
2321  * @qno: HBQ number.
2322  *
2323  * This function posts more buffers to the HBQ. This function
2324  * is called with no lock held. The function returns the number of HBQ entries
2325  * successfully allocated.
2326  **/
2327 int
2328 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2329 {
2330 	if (phba->sli_rev == LPFC_SLI_REV4)
2331 		return 0;
2332 	else
2333 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2334 					 lpfc_hbq_defs[qno]->add_count);
2335 }
2336 
2337 /**
2338  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2339  * @phba: Pointer to HBA context object.
2340  * @qno:  HBQ queue number.
2341  *
2342  * This function is called from SLI initialization code path with
2343  * no lock held to post initial HBQ buffers to firmware. The
2344  * function returns the number of HBQ entries successfully allocated.
2345  **/
2346 static int
2347 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2348 {
2349 	if (phba->sli_rev == LPFC_SLI_REV4)
2350 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2351 					lpfc_hbq_defs[qno]->entry_count);
2352 	else
2353 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2354 					 lpfc_hbq_defs[qno]->init_count);
2355 }
2356 
2357 /*
2358  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2359  *
2360  * This function removes the first hbq buffer on an hbq list and returns a
2361  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2362  **/
2363 static struct hbq_dmabuf *
2364 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2365 {
2366 	struct lpfc_dmabuf *d_buf;
2367 
2368 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2369 	if (!d_buf)
2370 		return NULL;
2371 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2372 }
2373 
2374 /**
2375  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2376  * @phba: Pointer to HBA context object.
2377  * @hrq: HBQ number.
2378  *
2379  * This function removes the first RQ buffer on an RQ buffer list and returns a
2380  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2381  **/
2382 static struct rqb_dmabuf *
2383 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2384 {
2385 	struct lpfc_dmabuf *h_buf;
2386 	struct lpfc_rqb *rqbp;
2387 
2388 	rqbp = hrq->rqbp;
2389 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2390 			 struct lpfc_dmabuf, list);
2391 	if (!h_buf)
2392 		return NULL;
2393 	rqbp->buffer_count--;
2394 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2395 }
2396 
2397 /**
2398  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2399  * @phba: Pointer to HBA context object.
2400  * @tag: Tag of the hbq buffer.
2401  *
2402  * This function searches for the hbq buffer associated with the given tag in
2403  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2404  * otherwise it returns NULL.
2405  **/
2406 static struct hbq_dmabuf *
2407 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2408 {
2409 	struct lpfc_dmabuf *d_buf;
2410 	struct hbq_dmabuf *hbq_buf;
2411 	uint32_t hbqno;
2412 
2413 	hbqno = tag >> 16;
2414 	if (hbqno >= LPFC_MAX_HBQS)
2415 		return NULL;
2416 
2417 	spin_lock_irq(&phba->hbalock);
2418 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2419 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2420 		if (hbq_buf->tag == tag) {
2421 			spin_unlock_irq(&phba->hbalock);
2422 			return hbq_buf;
2423 		}
2424 	}
2425 	spin_unlock_irq(&phba->hbalock);
2426 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2427 			"1803 Bad hbq tag. Data: x%x x%x\n",
2428 			tag, phba->hbqs[tag >> 16].buffer_count);
2429 	return NULL;
2430 }
2431 
2432 /**
2433  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2434  * @phba: Pointer to HBA context object.
2435  * @hbq_buffer: Pointer to HBQ buffer.
2436  *
2437  * This function is called with hbalock. This function gives back
2438  * the hbq buffer to firmware. If the HBQ does not have space to
2439  * post the buffer, it will free the buffer.
2440  **/
2441 void
2442 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2443 {
2444 	uint32_t hbqno;
2445 
2446 	if (hbq_buffer) {
2447 		hbqno = hbq_buffer->tag >> 16;
2448 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2449 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2450 	}
2451 }
2452 
2453 /**
2454  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2455  * @mbxCommand: mailbox command code.
2456  *
2457  * This function is called by the mailbox event handler function to verify
2458  * that the completed mailbox command is a legitimate mailbox command. If the
2459  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2460  * and the mailbox event handler will take the HBA offline.
2461  **/
2462 static int
2463 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2464 {
2465 	uint8_t ret;
2466 
2467 	switch (mbxCommand) {
2468 	case MBX_LOAD_SM:
2469 	case MBX_READ_NV:
2470 	case MBX_WRITE_NV:
2471 	case MBX_WRITE_VPARMS:
2472 	case MBX_RUN_BIU_DIAG:
2473 	case MBX_INIT_LINK:
2474 	case MBX_DOWN_LINK:
2475 	case MBX_CONFIG_LINK:
2476 	case MBX_CONFIG_RING:
2477 	case MBX_RESET_RING:
2478 	case MBX_READ_CONFIG:
2479 	case MBX_READ_RCONFIG:
2480 	case MBX_READ_SPARM:
2481 	case MBX_READ_STATUS:
2482 	case MBX_READ_RPI:
2483 	case MBX_READ_XRI:
2484 	case MBX_READ_REV:
2485 	case MBX_READ_LNK_STAT:
2486 	case MBX_REG_LOGIN:
2487 	case MBX_UNREG_LOGIN:
2488 	case MBX_CLEAR_LA:
2489 	case MBX_DUMP_MEMORY:
2490 	case MBX_DUMP_CONTEXT:
2491 	case MBX_RUN_DIAGS:
2492 	case MBX_RESTART:
2493 	case MBX_UPDATE_CFG:
2494 	case MBX_DOWN_LOAD:
2495 	case MBX_DEL_LD_ENTRY:
2496 	case MBX_RUN_PROGRAM:
2497 	case MBX_SET_MASK:
2498 	case MBX_SET_VARIABLE:
2499 	case MBX_UNREG_D_ID:
2500 	case MBX_KILL_BOARD:
2501 	case MBX_CONFIG_FARP:
2502 	case MBX_BEACON:
2503 	case MBX_LOAD_AREA:
2504 	case MBX_RUN_BIU_DIAG64:
2505 	case MBX_CONFIG_PORT:
2506 	case MBX_READ_SPARM64:
2507 	case MBX_READ_RPI64:
2508 	case MBX_REG_LOGIN64:
2509 	case MBX_READ_TOPOLOGY:
2510 	case MBX_WRITE_WWN:
2511 	case MBX_SET_DEBUG:
2512 	case MBX_LOAD_EXP_ROM:
2513 	case MBX_ASYNCEVT_ENABLE:
2514 	case MBX_REG_VPI:
2515 	case MBX_UNREG_VPI:
2516 	case MBX_HEARTBEAT:
2517 	case MBX_PORT_CAPABILITIES:
2518 	case MBX_PORT_IOV_CONTROL:
2519 	case MBX_SLI4_CONFIG:
2520 	case MBX_SLI4_REQ_FTRS:
2521 	case MBX_REG_FCFI:
2522 	case MBX_UNREG_FCFI:
2523 	case MBX_REG_VFI:
2524 	case MBX_UNREG_VFI:
2525 	case MBX_INIT_VPI:
2526 	case MBX_INIT_VFI:
2527 	case MBX_RESUME_RPI:
2528 	case MBX_READ_EVENT_LOG_STATUS:
2529 	case MBX_READ_EVENT_LOG:
2530 	case MBX_SECURITY_MGMT:
2531 	case MBX_AUTH_PORT:
2532 	case MBX_ACCESS_VDATA:
2533 		ret = mbxCommand;
2534 		break;
2535 	default:
2536 		ret = MBX_SHUTDOWN;
2537 		break;
2538 	}
2539 	return ret;
2540 }
2541 
2542 /**
2543  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2544  * @phba: Pointer to HBA context object.
2545  * @pmboxq: Pointer to mailbox command.
2546  *
2547  * This is completion handler function for mailbox commands issued from
2548  * lpfc_sli_issue_mbox_wait function. This function is called by the
2549  * mailbox event handler function with no lock held. This function
2550  * will wake up thread waiting on the wait queue pointed by context1
2551  * of the mailbox.
2552  **/
2553 void
2554 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2555 {
2556 	unsigned long drvr_flag;
2557 	struct completion *pmbox_done;
2558 
2559 	/*
2560 	 * If pmbox_done is empty, the driver thread gave up waiting and
2561 	 * continued running.
2562 	 */
2563 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2564 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2565 	pmbox_done = (struct completion *)pmboxq->context3;
2566 	if (pmbox_done)
2567 		complete(pmbox_done);
2568 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2569 	return;
2570 }
2571 
2572 static void
2573 __lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2574 {
2575 	unsigned long iflags;
2576 
2577 	if (ndlp->nlp_flag & NLP_RELEASE_RPI) {
2578 		lpfc_sli4_free_rpi(vport->phba, ndlp->nlp_rpi);
2579 		spin_lock_irqsave(&ndlp->lock, iflags);
2580 		ndlp->nlp_flag &= ~NLP_RELEASE_RPI;
2581 		ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
2582 		spin_unlock_irqrestore(&ndlp->lock, iflags);
2583 	}
2584 	ndlp->nlp_flag &= ~NLP_UNREG_INP;
2585 }
2586 
2587 /**
2588  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2589  * @phba: Pointer to HBA context object.
2590  * @pmb: Pointer to mailbox object.
2591  *
2592  * This function is the default mailbox completion handler. It
2593  * frees the memory resources associated with the completed mailbox
2594  * command. If the completed command is a REG_LOGIN mailbox command,
2595  * this function will issue a UREG_LOGIN to re-claim the RPI.
2596  **/
2597 void
2598 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2599 {
2600 	struct lpfc_vport  *vport = pmb->vport;
2601 	struct lpfc_dmabuf *mp;
2602 	struct lpfc_nodelist *ndlp;
2603 	struct Scsi_Host *shost;
2604 	uint16_t rpi, vpi;
2605 	int rc;
2606 
2607 	mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
2608 
2609 	if (mp) {
2610 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
2611 		kfree(mp);
2612 	}
2613 
2614 	/*
2615 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2616 	 * is in re-discovery driver need to cleanup the RPI.
2617 	 */
2618 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2619 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2620 	    !pmb->u.mb.mbxStatus) {
2621 		rpi = pmb->u.mb.un.varWords[0];
2622 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2623 		if (phba->sli_rev == LPFC_SLI_REV4)
2624 			vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2625 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2626 		pmb->vport = vport;
2627 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2628 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2629 		if (rc != MBX_NOT_FINISHED)
2630 			return;
2631 	}
2632 
2633 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2634 		!(phba->pport->load_flag & FC_UNLOADING) &&
2635 		!pmb->u.mb.mbxStatus) {
2636 		shost = lpfc_shost_from_vport(vport);
2637 		spin_lock_irq(shost->host_lock);
2638 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2639 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2640 		spin_unlock_irq(shost->host_lock);
2641 	}
2642 
2643 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2644 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2645 		lpfc_nlp_put(ndlp);
2646 		pmb->ctx_buf = NULL;
2647 		pmb->ctx_ndlp = NULL;
2648 	}
2649 
2650 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2651 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2652 
2653 		/* Check to see if there are any deferred events to process */
2654 		if (ndlp) {
2655 			lpfc_printf_vlog(
2656 				vport,
2657 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2658 				"1438 UNREG cmpl deferred mbox x%x "
2659 				"on NPort x%x Data: x%x x%x x%px x%x x%x\n",
2660 				ndlp->nlp_rpi, ndlp->nlp_DID,
2661 				ndlp->nlp_flag, ndlp->nlp_defer_did,
2662 				ndlp, vport->load_flag, kref_read(&ndlp->kref));
2663 
2664 			if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2665 			    (ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING)) {
2666 				ndlp->nlp_flag &= ~NLP_UNREG_INP;
2667 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2668 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2669 			} else {
2670 				__lpfc_sli_rpi_release(vport, ndlp);
2671 			}
2672 
2673 			/* The unreg_login mailbox is complete and had a
2674 			 * reference that has to be released.  The PLOGI
2675 			 * got its own ref.
2676 			 */
2677 			lpfc_nlp_put(ndlp);
2678 			pmb->ctx_ndlp = NULL;
2679 		}
2680 	}
2681 
2682 	/* This nlp_put pairs with lpfc_sli4_resume_rpi */
2683 	if (pmb->u.mb.mbxCommand == MBX_RESUME_RPI) {
2684 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2685 		lpfc_nlp_put(ndlp);
2686 	}
2687 
2688 	/* Check security permission status on INIT_LINK mailbox command */
2689 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2690 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2691 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2692 				"2860 SLI authentication is required "
2693 				"for INIT_LINK but has not done yet\n");
2694 
2695 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2696 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2697 	else
2698 		mempool_free(pmb, phba->mbox_mem_pool);
2699 }
2700  /**
2701  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2702  * @phba: Pointer to HBA context object.
2703  * @pmb: Pointer to mailbox object.
2704  *
2705  * This function is the unreg rpi mailbox completion handler. It
2706  * frees the memory resources associated with the completed mailbox
2707  * command. An additional reference is put on the ndlp to prevent
2708  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2709  * the unreg mailbox command completes, this routine puts the
2710  * reference back.
2711  *
2712  **/
2713 void
2714 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2715 {
2716 	struct lpfc_vport  *vport = pmb->vport;
2717 	struct lpfc_nodelist *ndlp;
2718 
2719 	ndlp = pmb->ctx_ndlp;
2720 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2721 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2722 		    (bf_get(lpfc_sli_intf_if_type,
2723 		     &phba->sli4_hba.sli_intf) >=
2724 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2725 			if (ndlp) {
2726 				lpfc_printf_vlog(
2727 					 vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2728 					 "0010 UNREG_LOGIN vpi:%x "
2729 					 "rpi:%x DID:%x defer x%x flg x%x "
2730 					 "x%px\n",
2731 					 vport->vpi, ndlp->nlp_rpi,
2732 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
2733 					 ndlp->nlp_flag,
2734 					 ndlp);
2735 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2736 
2737 				/* Check to see if there are any deferred
2738 				 * events to process
2739 				 */
2740 				if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2741 				    (ndlp->nlp_defer_did !=
2742 				    NLP_EVT_NOTHING_PENDING)) {
2743 					lpfc_printf_vlog(
2744 						vport, KERN_INFO, LOG_DISCOVERY,
2745 						"4111 UNREG cmpl deferred "
2746 						"clr x%x on "
2747 						"NPort x%x Data: x%x x%px\n",
2748 						ndlp->nlp_rpi, ndlp->nlp_DID,
2749 						ndlp->nlp_defer_did, ndlp);
2750 					ndlp->nlp_flag &= ~NLP_UNREG_INP;
2751 					ndlp->nlp_defer_did =
2752 						NLP_EVT_NOTHING_PENDING;
2753 					lpfc_issue_els_plogi(
2754 						vport, ndlp->nlp_DID, 0);
2755 				} else {
2756 					__lpfc_sli_rpi_release(vport, ndlp);
2757 				}
2758 				lpfc_nlp_put(ndlp);
2759 			}
2760 		}
2761 	}
2762 
2763 	mempool_free(pmb, phba->mbox_mem_pool);
2764 }
2765 
2766 /**
2767  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
2768  * @phba: Pointer to HBA context object.
2769  *
2770  * This function is called with no lock held. This function processes all
2771  * the completed mailbox commands and gives it to upper layers. The interrupt
2772  * service routine processes mailbox completion interrupt and adds completed
2773  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
2774  * Worker thread call lpfc_sli_handle_mb_event, which will return the
2775  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
2776  * function returns the mailbox commands to the upper layer by calling the
2777  * completion handler function of each mailbox.
2778  **/
2779 int
2780 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
2781 {
2782 	MAILBOX_t *pmbox;
2783 	LPFC_MBOXQ_t *pmb;
2784 	int rc;
2785 	LIST_HEAD(cmplq);
2786 
2787 	phba->sli.slistat.mbox_event++;
2788 
2789 	/* Get all completed mailboxe buffers into the cmplq */
2790 	spin_lock_irq(&phba->hbalock);
2791 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
2792 	spin_unlock_irq(&phba->hbalock);
2793 
2794 	/* Get a Mailbox buffer to setup mailbox commands for callback */
2795 	do {
2796 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
2797 		if (pmb == NULL)
2798 			break;
2799 
2800 		pmbox = &pmb->u.mb;
2801 
2802 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
2803 			if (pmb->vport) {
2804 				lpfc_debugfs_disc_trc(pmb->vport,
2805 					LPFC_DISC_TRC_MBOX_VPORT,
2806 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
2807 					(uint32_t)pmbox->mbxCommand,
2808 					pmbox->un.varWords[0],
2809 					pmbox->un.varWords[1]);
2810 			}
2811 			else {
2812 				lpfc_debugfs_disc_trc(phba->pport,
2813 					LPFC_DISC_TRC_MBOX,
2814 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
2815 					(uint32_t)pmbox->mbxCommand,
2816 					pmbox->un.varWords[0],
2817 					pmbox->un.varWords[1]);
2818 			}
2819 		}
2820 
2821 		/*
2822 		 * It is a fatal error if unknown mbox command completion.
2823 		 */
2824 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
2825 		    MBX_SHUTDOWN) {
2826 			/* Unknown mailbox command compl */
2827 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2828 					"(%d):0323 Unknown Mailbox command "
2829 					"x%x (x%x/x%x) Cmpl\n",
2830 					pmb->vport ? pmb->vport->vpi :
2831 					LPFC_VPORT_UNKNOWN,
2832 					pmbox->mbxCommand,
2833 					lpfc_sli_config_mbox_subsys_get(phba,
2834 									pmb),
2835 					lpfc_sli_config_mbox_opcode_get(phba,
2836 									pmb));
2837 			phba->link_state = LPFC_HBA_ERROR;
2838 			phba->work_hs = HS_FFER3;
2839 			lpfc_handle_eratt(phba);
2840 			continue;
2841 		}
2842 
2843 		if (pmbox->mbxStatus) {
2844 			phba->sli.slistat.mbox_stat_err++;
2845 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
2846 				/* Mbox cmd cmpl error - RETRYing */
2847 				lpfc_printf_log(phba, KERN_INFO,
2848 					LOG_MBOX | LOG_SLI,
2849 					"(%d):0305 Mbox cmd cmpl "
2850 					"error - RETRYing Data: x%x "
2851 					"(x%x/x%x) x%x x%x x%x\n",
2852 					pmb->vport ? pmb->vport->vpi :
2853 					LPFC_VPORT_UNKNOWN,
2854 					pmbox->mbxCommand,
2855 					lpfc_sli_config_mbox_subsys_get(phba,
2856 									pmb),
2857 					lpfc_sli_config_mbox_opcode_get(phba,
2858 									pmb),
2859 					pmbox->mbxStatus,
2860 					pmbox->un.varWords[0],
2861 					pmb->vport ? pmb->vport->port_state :
2862 					LPFC_VPORT_UNKNOWN);
2863 				pmbox->mbxStatus = 0;
2864 				pmbox->mbxOwner = OWN_HOST;
2865 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2866 				if (rc != MBX_NOT_FINISHED)
2867 					continue;
2868 			}
2869 		}
2870 
2871 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
2872 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
2873 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
2874 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
2875 				"x%x x%x x%x\n",
2876 				pmb->vport ? pmb->vport->vpi : 0,
2877 				pmbox->mbxCommand,
2878 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
2879 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
2880 				pmb->mbox_cmpl,
2881 				*((uint32_t *) pmbox),
2882 				pmbox->un.varWords[0],
2883 				pmbox->un.varWords[1],
2884 				pmbox->un.varWords[2],
2885 				pmbox->un.varWords[3],
2886 				pmbox->un.varWords[4],
2887 				pmbox->un.varWords[5],
2888 				pmbox->un.varWords[6],
2889 				pmbox->un.varWords[7],
2890 				pmbox->un.varWords[8],
2891 				pmbox->un.varWords[9],
2892 				pmbox->un.varWords[10]);
2893 
2894 		if (pmb->mbox_cmpl)
2895 			pmb->mbox_cmpl(phba,pmb);
2896 	} while (1);
2897 	return 0;
2898 }
2899 
2900 /**
2901  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
2902  * @phba: Pointer to HBA context object.
2903  * @pring: Pointer to driver SLI ring object.
2904  * @tag: buffer tag.
2905  *
2906  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
2907  * is set in the tag the buffer is posted for a particular exchange,
2908  * the function will return the buffer without replacing the buffer.
2909  * If the buffer is for unsolicited ELS or CT traffic, this function
2910  * returns the buffer and also posts another buffer to the firmware.
2911  **/
2912 static struct lpfc_dmabuf *
2913 lpfc_sli_get_buff(struct lpfc_hba *phba,
2914 		  struct lpfc_sli_ring *pring,
2915 		  uint32_t tag)
2916 {
2917 	struct hbq_dmabuf *hbq_entry;
2918 
2919 	if (tag & QUE_BUFTAG_BIT)
2920 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
2921 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
2922 	if (!hbq_entry)
2923 		return NULL;
2924 	return &hbq_entry->dbuf;
2925 }
2926 
2927 /**
2928  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
2929  *                              containing a NVME LS request.
2930  * @phba: pointer to lpfc hba data structure.
2931  * @piocb: pointer to the iocbq struct representing the sequence starting
2932  *        frame.
2933  *
2934  * This routine initially validates the NVME LS, validates there is a login
2935  * with the port that sent the LS, and then calls the appropriate nvme host
2936  * or target LS request handler.
2937  **/
2938 static void
2939 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
2940 {
2941 	struct lpfc_nodelist *ndlp;
2942 	struct lpfc_dmabuf *d_buf;
2943 	struct hbq_dmabuf *nvmebuf;
2944 	struct fc_frame_header *fc_hdr;
2945 	struct lpfc_async_xchg_ctx *axchg = NULL;
2946 	char *failwhy = NULL;
2947 	uint32_t oxid, sid, did, fctl, size;
2948 	int ret = 1;
2949 
2950 	d_buf = piocb->context2;
2951 
2952 	nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2953 	fc_hdr = nvmebuf->hbuf.virt;
2954 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
2955 	sid = sli4_sid_from_fc_hdr(fc_hdr);
2956 	did = sli4_did_from_fc_hdr(fc_hdr);
2957 	fctl = (fc_hdr->fh_f_ctl[0] << 16 |
2958 		fc_hdr->fh_f_ctl[1] << 8 |
2959 		fc_hdr->fh_f_ctl[2]);
2960 	size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
2961 
2962 	lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
2963 			 oxid, size, sid);
2964 
2965 	if (phba->pport->load_flag & FC_UNLOADING) {
2966 		failwhy = "Driver Unloading";
2967 	} else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
2968 		failwhy = "NVME FC4 Disabled";
2969 	} else if (!phba->nvmet_support && !phba->pport->localport) {
2970 		failwhy = "No Localport";
2971 	} else if (phba->nvmet_support && !phba->targetport) {
2972 		failwhy = "No Targetport";
2973 	} else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
2974 		failwhy = "Bad NVME LS R_CTL";
2975 	} else if (unlikely((fctl & 0x00FF0000) !=
2976 			(FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
2977 		failwhy = "Bad NVME LS F_CTL";
2978 	} else {
2979 		axchg = kzalloc(sizeof(*axchg), GFP_ATOMIC);
2980 		if (!axchg)
2981 			failwhy = "No CTX memory";
2982 	}
2983 
2984 	if (unlikely(failwhy)) {
2985 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2986 				"6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
2987 				sid, oxid, failwhy);
2988 		goto out_fail;
2989 	}
2990 
2991 	/* validate the source of the LS is logged in */
2992 	ndlp = lpfc_findnode_did(phba->pport, sid);
2993 	if (!ndlp ||
2994 	    ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
2995 	     (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
2996 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
2997 				"6216 NVME Unsol rcv: No ndlp: "
2998 				"NPort_ID x%x oxid x%x\n",
2999 				sid, oxid);
3000 		goto out_fail;
3001 	}
3002 
3003 	axchg->phba = phba;
3004 	axchg->ndlp = ndlp;
3005 	axchg->size = size;
3006 	axchg->oxid = oxid;
3007 	axchg->sid = sid;
3008 	axchg->wqeq = NULL;
3009 	axchg->state = LPFC_NVME_STE_LS_RCV;
3010 	axchg->entry_cnt = 1;
3011 	axchg->rqb_buffer = (void *)nvmebuf;
3012 	axchg->hdwq = &phba->sli4_hba.hdwq[0];
3013 	axchg->payload = nvmebuf->dbuf.virt;
3014 	INIT_LIST_HEAD(&axchg->list);
3015 
3016 	if (phba->nvmet_support) {
3017 		ret = lpfc_nvmet_handle_lsreq(phba, axchg);
3018 		spin_lock_irq(&ndlp->lock);
3019 		if (!ret && !(ndlp->fc4_xpt_flags & NLP_XPT_HAS_HH)) {
3020 			ndlp->fc4_xpt_flags |= NLP_XPT_HAS_HH;
3021 			spin_unlock_irq(&ndlp->lock);
3022 
3023 			/* This reference is a single occurrence to hold the
3024 			 * node valid until the nvmet transport calls
3025 			 * host_release.
3026 			 */
3027 			if (!lpfc_nlp_get(ndlp))
3028 				goto out_fail;
3029 
3030 			lpfc_printf_log(phba, KERN_ERR, LOG_NODE,
3031 					"6206 NVMET unsol ls_req ndlp x%px "
3032 					"DID x%x xflags x%x refcnt %d\n",
3033 					ndlp, ndlp->nlp_DID,
3034 					ndlp->fc4_xpt_flags,
3035 					kref_read(&ndlp->kref));
3036 		} else {
3037 			spin_unlock_irq(&ndlp->lock);
3038 		}
3039 	} else {
3040 		ret = lpfc_nvme_handle_lsreq(phba, axchg);
3041 	}
3042 
3043 	/* if zero, LS was successfully handled. If non-zero, LS not handled */
3044 	if (!ret)
3045 		return;
3046 
3047 out_fail:
3048 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3049 			"6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
3050 			"NVMe%s handler failed %d\n",
3051 			did, sid, oxid,
3052 			(phba->nvmet_support) ? "T" : "I", ret);
3053 
3054 	/* recycle receive buffer */
3055 	lpfc_in_buf_free(phba, &nvmebuf->dbuf);
3056 
3057 	/* If start of new exchange, abort it */
3058 	if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
3059 		ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
3060 
3061 	if (ret)
3062 		kfree(axchg);
3063 }
3064 
3065 /**
3066  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
3067  * @phba: Pointer to HBA context object.
3068  * @pring: Pointer to driver SLI ring object.
3069  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
3070  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
3071  * @fch_type: the type for the first frame of the sequence.
3072  *
3073  * This function is called with no lock held. This function uses the r_ctl and
3074  * type of the received sequence to find the correct callback function to call
3075  * to process the sequence.
3076  **/
3077 static int
3078 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3079 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
3080 			 uint32_t fch_type)
3081 {
3082 	int i;
3083 
3084 	switch (fch_type) {
3085 	case FC_TYPE_NVME:
3086 		lpfc_nvme_unsol_ls_handler(phba, saveq);
3087 		return 1;
3088 	default:
3089 		break;
3090 	}
3091 
3092 	/* unSolicited Responses */
3093 	if (pring->prt[0].profile) {
3094 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
3095 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
3096 									saveq);
3097 		return 1;
3098 	}
3099 	/* We must search, based on rctl / type
3100 	   for the right routine */
3101 	for (i = 0; i < pring->num_mask; i++) {
3102 		if ((pring->prt[i].rctl == fch_r_ctl) &&
3103 		    (pring->prt[i].type == fch_type)) {
3104 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
3105 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
3106 						(phba, pring, saveq);
3107 			return 1;
3108 		}
3109 	}
3110 	return 0;
3111 }
3112 
3113 /**
3114  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
3115  * @phba: Pointer to HBA context object.
3116  * @pring: Pointer to driver SLI ring object.
3117  * @saveq: Pointer to the unsolicited iocb.
3118  *
3119  * This function is called with no lock held by the ring event handler
3120  * when there is an unsolicited iocb posted to the response ring by the
3121  * firmware. This function gets the buffer associated with the iocbs
3122  * and calls the event handler for the ring. This function handles both
3123  * qring buffers and hbq buffers.
3124  * When the function returns 1 the caller can free the iocb object otherwise
3125  * upper layer functions will free the iocb objects.
3126  **/
3127 static int
3128 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3129 			    struct lpfc_iocbq *saveq)
3130 {
3131 	IOCB_t           * irsp;
3132 	WORD5            * w5p;
3133 	uint32_t           Rctl, Type;
3134 	struct lpfc_iocbq *iocbq;
3135 	struct lpfc_dmabuf *dmzbuf;
3136 
3137 	irsp = &(saveq->iocb);
3138 
3139 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
3140 		if (pring->lpfc_sli_rcv_async_status)
3141 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
3142 		else
3143 			lpfc_printf_log(phba,
3144 					KERN_WARNING,
3145 					LOG_SLI,
3146 					"0316 Ring %d handler: unexpected "
3147 					"ASYNC_STATUS iocb received evt_code "
3148 					"0x%x\n",
3149 					pring->ringno,
3150 					irsp->un.asyncstat.evt_code);
3151 		return 1;
3152 	}
3153 
3154 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3155 		(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3156 		if (irsp->ulpBdeCount > 0) {
3157 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3158 					irsp->un.ulpWord[3]);
3159 			lpfc_in_buf_free(phba, dmzbuf);
3160 		}
3161 
3162 		if (irsp->ulpBdeCount > 1) {
3163 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3164 					irsp->unsli3.sli3Words[3]);
3165 			lpfc_in_buf_free(phba, dmzbuf);
3166 		}
3167 
3168 		if (irsp->ulpBdeCount > 2) {
3169 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3170 				irsp->unsli3.sli3Words[7]);
3171 			lpfc_in_buf_free(phba, dmzbuf);
3172 		}
3173 
3174 		return 1;
3175 	}
3176 
3177 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3178 		if (irsp->ulpBdeCount != 0) {
3179 			saveq->context2 = lpfc_sli_get_buff(phba, pring,
3180 						irsp->un.ulpWord[3]);
3181 			if (!saveq->context2)
3182 				lpfc_printf_log(phba,
3183 					KERN_ERR,
3184 					LOG_SLI,
3185 					"0341 Ring %d Cannot find buffer for "
3186 					"an unsolicited iocb. tag 0x%x\n",
3187 					pring->ringno,
3188 					irsp->un.ulpWord[3]);
3189 		}
3190 		if (irsp->ulpBdeCount == 2) {
3191 			saveq->context3 = lpfc_sli_get_buff(phba, pring,
3192 						irsp->unsli3.sli3Words[7]);
3193 			if (!saveq->context3)
3194 				lpfc_printf_log(phba,
3195 					KERN_ERR,
3196 					LOG_SLI,
3197 					"0342 Ring %d Cannot find buffer for an"
3198 					" unsolicited iocb. tag 0x%x\n",
3199 					pring->ringno,
3200 					irsp->unsli3.sli3Words[7]);
3201 		}
3202 		list_for_each_entry(iocbq, &saveq->list, list) {
3203 			irsp = &(iocbq->iocb);
3204 			if (irsp->ulpBdeCount != 0) {
3205 				iocbq->context2 = lpfc_sli_get_buff(phba, pring,
3206 							irsp->un.ulpWord[3]);
3207 				if (!iocbq->context2)
3208 					lpfc_printf_log(phba,
3209 						KERN_ERR,
3210 						LOG_SLI,
3211 						"0343 Ring %d Cannot find "
3212 						"buffer for an unsolicited iocb"
3213 						". tag 0x%x\n", pring->ringno,
3214 						irsp->un.ulpWord[3]);
3215 			}
3216 			if (irsp->ulpBdeCount == 2) {
3217 				iocbq->context3 = lpfc_sli_get_buff(phba, pring,
3218 						irsp->unsli3.sli3Words[7]);
3219 				if (!iocbq->context3)
3220 					lpfc_printf_log(phba,
3221 						KERN_ERR,
3222 						LOG_SLI,
3223 						"0344 Ring %d Cannot find "
3224 						"buffer for an unsolicited "
3225 						"iocb. tag 0x%x\n",
3226 						pring->ringno,
3227 						irsp->unsli3.sli3Words[7]);
3228 			}
3229 		}
3230 	}
3231 	if (irsp->ulpBdeCount != 0 &&
3232 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3233 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3234 		int found = 0;
3235 
3236 		/* search continue save q for same XRI */
3237 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3238 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3239 				saveq->iocb.unsli3.rcvsli3.ox_id) {
3240 				list_add_tail(&saveq->list, &iocbq->list);
3241 				found = 1;
3242 				break;
3243 			}
3244 		}
3245 		if (!found)
3246 			list_add_tail(&saveq->clist,
3247 				      &pring->iocb_continue_saveq);
3248 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3249 			list_del_init(&iocbq->clist);
3250 			saveq = iocbq;
3251 			irsp = &(saveq->iocb);
3252 		} else
3253 			return 0;
3254 	}
3255 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3256 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3257 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3258 		Rctl = FC_RCTL_ELS_REQ;
3259 		Type = FC_TYPE_ELS;
3260 	} else {
3261 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3262 		Rctl = w5p->hcsw.Rctl;
3263 		Type = w5p->hcsw.Type;
3264 
3265 		/* Firmware Workaround */
3266 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3267 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3268 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3269 			Rctl = FC_RCTL_ELS_REQ;
3270 			Type = FC_TYPE_ELS;
3271 			w5p->hcsw.Rctl = Rctl;
3272 			w5p->hcsw.Type = Type;
3273 		}
3274 	}
3275 
3276 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3277 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3278 				"0313 Ring %d handler: unexpected Rctl x%x "
3279 				"Type x%x received\n",
3280 				pring->ringno, Rctl, Type);
3281 
3282 	return 1;
3283 }
3284 
3285 /**
3286  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3287  * @phba: Pointer to HBA context object.
3288  * @pring: Pointer to driver SLI ring object.
3289  * @prspiocb: Pointer to response iocb object.
3290  *
3291  * This function looks up the iocb_lookup table to get the command iocb
3292  * corresponding to the given response iocb using the iotag of the
3293  * response iocb. The driver calls this function with the hbalock held
3294  * for SLI3 ports or the ring lock held for SLI4 ports.
3295  * This function returns the command iocb object if it finds the command
3296  * iocb else returns NULL.
3297  **/
3298 static struct lpfc_iocbq *
3299 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3300 		      struct lpfc_sli_ring *pring,
3301 		      struct lpfc_iocbq *prspiocb)
3302 {
3303 	struct lpfc_iocbq *cmd_iocb = NULL;
3304 	uint16_t iotag;
3305 	spinlock_t *temp_lock = NULL;
3306 	unsigned long iflag = 0;
3307 
3308 	if (phba->sli_rev == LPFC_SLI_REV4)
3309 		temp_lock = &pring->ring_lock;
3310 	else
3311 		temp_lock = &phba->hbalock;
3312 
3313 	spin_lock_irqsave(temp_lock, iflag);
3314 	iotag = prspiocb->iocb.ulpIoTag;
3315 
3316 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3317 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3318 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3319 			/* remove from txcmpl queue list */
3320 			list_del_init(&cmd_iocb->list);
3321 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3322 			pring->txcmplq_cnt--;
3323 			spin_unlock_irqrestore(temp_lock, iflag);
3324 			return cmd_iocb;
3325 		}
3326 	}
3327 
3328 	spin_unlock_irqrestore(temp_lock, iflag);
3329 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3330 			"0317 iotag x%x is out of "
3331 			"range: max iotag x%x wd0 x%x\n",
3332 			iotag, phba->sli.last_iotag,
3333 			*(((uint32_t *) &prspiocb->iocb) + 7));
3334 	return NULL;
3335 }
3336 
3337 /**
3338  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3339  * @phba: Pointer to HBA context object.
3340  * @pring: Pointer to driver SLI ring object.
3341  * @iotag: IOCB tag.
3342  *
3343  * This function looks up the iocb_lookup table to get the command iocb
3344  * corresponding to the given iotag. The driver calls this function with
3345  * the ring lock held because this function is an SLI4 port only helper.
3346  * This function returns the command iocb object if it finds the command
3347  * iocb else returns NULL.
3348  **/
3349 static struct lpfc_iocbq *
3350 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3351 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3352 {
3353 	struct lpfc_iocbq *cmd_iocb = NULL;
3354 	spinlock_t *temp_lock = NULL;
3355 	unsigned long iflag = 0;
3356 
3357 	if (phba->sli_rev == LPFC_SLI_REV4)
3358 		temp_lock = &pring->ring_lock;
3359 	else
3360 		temp_lock = &phba->hbalock;
3361 
3362 	spin_lock_irqsave(temp_lock, iflag);
3363 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3364 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3365 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3366 			/* remove from txcmpl queue list */
3367 			list_del_init(&cmd_iocb->list);
3368 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3369 			pring->txcmplq_cnt--;
3370 			spin_unlock_irqrestore(temp_lock, iflag);
3371 			return cmd_iocb;
3372 		}
3373 	}
3374 
3375 	spin_unlock_irqrestore(temp_lock, iflag);
3376 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3377 			"0372 iotag x%x lookup error: max iotag (x%x) "
3378 			"iocb_flag x%x\n",
3379 			iotag, phba->sli.last_iotag,
3380 			cmd_iocb ? cmd_iocb->iocb_flag : 0xffff);
3381 	return NULL;
3382 }
3383 
3384 /**
3385  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3386  * @phba: Pointer to HBA context object.
3387  * @pring: Pointer to driver SLI ring object.
3388  * @saveq: Pointer to the response iocb to be processed.
3389  *
3390  * This function is called by the ring event handler for non-fcp
3391  * rings when there is a new response iocb in the response ring.
3392  * The caller is not required to hold any locks. This function
3393  * gets the command iocb associated with the response iocb and
3394  * calls the completion handler for the command iocb. If there
3395  * is no completion handler, the function will free the resources
3396  * associated with command iocb. If the response iocb is for
3397  * an already aborted command iocb, the status of the completion
3398  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3399  * This function always returns 1.
3400  **/
3401 static int
3402 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3403 			  struct lpfc_iocbq *saveq)
3404 {
3405 	struct lpfc_iocbq *cmdiocbp;
3406 	int rc = 1;
3407 	unsigned long iflag;
3408 
3409 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3410 	if (cmdiocbp) {
3411 		if (cmdiocbp->iocb_cmpl) {
3412 			/*
3413 			 * If an ELS command failed send an event to mgmt
3414 			 * application.
3415 			 */
3416 			if (saveq->iocb.ulpStatus &&
3417 			     (pring->ringno == LPFC_ELS_RING) &&
3418 			     (cmdiocbp->iocb.ulpCommand ==
3419 				CMD_ELS_REQUEST64_CR))
3420 				lpfc_send_els_failure_event(phba,
3421 					cmdiocbp, saveq);
3422 
3423 			/*
3424 			 * Post all ELS completions to the worker thread.
3425 			 * All other are passed to the completion callback.
3426 			 */
3427 			if (pring->ringno == LPFC_ELS_RING) {
3428 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3429 				    (cmdiocbp->iocb_flag &
3430 							LPFC_DRIVER_ABORTED)) {
3431 					spin_lock_irqsave(&phba->hbalock,
3432 							  iflag);
3433 					cmdiocbp->iocb_flag &=
3434 						~LPFC_DRIVER_ABORTED;
3435 					spin_unlock_irqrestore(&phba->hbalock,
3436 							       iflag);
3437 					saveq->iocb.ulpStatus =
3438 						IOSTAT_LOCAL_REJECT;
3439 					saveq->iocb.un.ulpWord[4] =
3440 						IOERR_SLI_ABORTED;
3441 
3442 					/* Firmware could still be in progress
3443 					 * of DMAing payload, so don't free data
3444 					 * buffer till after a hbeat.
3445 					 */
3446 					spin_lock_irqsave(&phba->hbalock,
3447 							  iflag);
3448 					saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
3449 					spin_unlock_irqrestore(&phba->hbalock,
3450 							       iflag);
3451 				}
3452 				if (phba->sli_rev == LPFC_SLI_REV4) {
3453 					if (saveq->iocb_flag &
3454 					    LPFC_EXCHANGE_BUSY) {
3455 						/* Set cmdiocb flag for the
3456 						 * exchange busy so sgl (xri)
3457 						 * will not be released until
3458 						 * the abort xri is received
3459 						 * from hba.
3460 						 */
3461 						spin_lock_irqsave(
3462 							&phba->hbalock, iflag);
3463 						cmdiocbp->iocb_flag |=
3464 							LPFC_EXCHANGE_BUSY;
3465 						spin_unlock_irqrestore(
3466 							&phba->hbalock, iflag);
3467 					}
3468 					if (cmdiocbp->iocb_flag &
3469 					    LPFC_DRIVER_ABORTED) {
3470 						/*
3471 						 * Clear LPFC_DRIVER_ABORTED
3472 						 * bit in case it was driver
3473 						 * initiated abort.
3474 						 */
3475 						spin_lock_irqsave(
3476 							&phba->hbalock, iflag);
3477 						cmdiocbp->iocb_flag &=
3478 							~LPFC_DRIVER_ABORTED;
3479 						spin_unlock_irqrestore(
3480 							&phba->hbalock, iflag);
3481 						cmdiocbp->iocb.ulpStatus =
3482 							IOSTAT_LOCAL_REJECT;
3483 						cmdiocbp->iocb.un.ulpWord[4] =
3484 							IOERR_ABORT_REQUESTED;
3485 						/*
3486 						 * For SLI4, irsiocb contains
3487 						 * NO_XRI in sli_xritag, it
3488 						 * shall not affect releasing
3489 						 * sgl (xri) process.
3490 						 */
3491 						saveq->iocb.ulpStatus =
3492 							IOSTAT_LOCAL_REJECT;
3493 						saveq->iocb.un.ulpWord[4] =
3494 							IOERR_SLI_ABORTED;
3495 						spin_lock_irqsave(
3496 							&phba->hbalock, iflag);
3497 						saveq->iocb_flag |=
3498 							LPFC_DELAY_MEM_FREE;
3499 						spin_unlock_irqrestore(
3500 							&phba->hbalock, iflag);
3501 					}
3502 				}
3503 			}
3504 			(cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
3505 		} else
3506 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3507 	} else {
3508 		/*
3509 		 * Unknown initiating command based on the response iotag.
3510 		 * This could be the case on the ELS ring because of
3511 		 * lpfc_els_abort().
3512 		 */
3513 		if (pring->ringno != LPFC_ELS_RING) {
3514 			/*
3515 			 * Ring <ringno> handler: unexpected completion IoTag
3516 			 * <IoTag>
3517 			 */
3518 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3519 					 "0322 Ring %d handler: "
3520 					 "unexpected completion IoTag x%x "
3521 					 "Data: x%x x%x x%x x%x\n",
3522 					 pring->ringno,
3523 					 saveq->iocb.ulpIoTag,
3524 					 saveq->iocb.ulpStatus,
3525 					 saveq->iocb.un.ulpWord[4],
3526 					 saveq->iocb.ulpCommand,
3527 					 saveq->iocb.ulpContext);
3528 		}
3529 	}
3530 
3531 	return rc;
3532 }
3533 
3534 /**
3535  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3536  * @phba: Pointer to HBA context object.
3537  * @pring: Pointer to driver SLI ring object.
3538  *
3539  * This function is called from the iocb ring event handlers when
3540  * put pointer is ahead of the get pointer for a ring. This function signal
3541  * an error attention condition to the worker thread and the worker
3542  * thread will transition the HBA to offline state.
3543  **/
3544 static void
3545 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3546 {
3547 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3548 	/*
3549 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3550 	 * rsp ring <portRspMax>
3551 	 */
3552 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3553 			"0312 Ring %d handler: portRspPut %d "
3554 			"is bigger than rsp ring %d\n",
3555 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3556 			pring->sli.sli3.numRiocb);
3557 
3558 	phba->link_state = LPFC_HBA_ERROR;
3559 
3560 	/*
3561 	 * All error attention handlers are posted to
3562 	 * worker thread
3563 	 */
3564 	phba->work_ha |= HA_ERATT;
3565 	phba->work_hs = HS_FFER3;
3566 
3567 	lpfc_worker_wake_up(phba);
3568 
3569 	return;
3570 }
3571 
3572 /**
3573  * lpfc_poll_eratt - Error attention polling timer timeout handler
3574  * @t: Context to fetch pointer to address of HBA context object from.
3575  *
3576  * This function is invoked by the Error Attention polling timer when the
3577  * timer times out. It will check the SLI Error Attention register for
3578  * possible attention events. If so, it will post an Error Attention event
3579  * and wake up worker thread to process it. Otherwise, it will set up the
3580  * Error Attention polling timer for the next poll.
3581  **/
3582 void lpfc_poll_eratt(struct timer_list *t)
3583 {
3584 	struct lpfc_hba *phba;
3585 	uint32_t eratt = 0;
3586 	uint64_t sli_intr, cnt;
3587 
3588 	phba = from_timer(phba, t, eratt_poll);
3589 
3590 	/* Here we will also keep track of interrupts per sec of the hba */
3591 	sli_intr = phba->sli.slistat.sli_intr;
3592 
3593 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3594 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3595 			sli_intr);
3596 	else
3597 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3598 
3599 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3600 	do_div(cnt, phba->eratt_poll_interval);
3601 	phba->sli.slistat.sli_ips = cnt;
3602 
3603 	phba->sli.slistat.sli_prev_intr = sli_intr;
3604 
3605 	/* Check chip HA register for error event */
3606 	eratt = lpfc_sli_check_eratt(phba);
3607 
3608 	if (eratt)
3609 		/* Tell the worker thread there is work to do */
3610 		lpfc_worker_wake_up(phba);
3611 	else
3612 		/* Restart the timer for next eratt poll */
3613 		mod_timer(&phba->eratt_poll,
3614 			  jiffies +
3615 			  msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3616 	return;
3617 }
3618 
3619 
3620 /**
3621  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3622  * @phba: Pointer to HBA context object.
3623  * @pring: Pointer to driver SLI ring object.
3624  * @mask: Host attention register mask for this ring.
3625  *
3626  * This function is called from the interrupt context when there is a ring
3627  * event for the fcp ring. The caller does not hold any lock.
3628  * The function processes each response iocb in the response ring until it
3629  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3630  * LE bit set. The function will call the completion handler of the command iocb
3631  * if the response iocb indicates a completion for a command iocb or it is
3632  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3633  * function if this is an unsolicited iocb.
3634  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3635  * to check it explicitly.
3636  */
3637 int
3638 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3639 				struct lpfc_sli_ring *pring, uint32_t mask)
3640 {
3641 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3642 	IOCB_t *irsp = NULL;
3643 	IOCB_t *entry = NULL;
3644 	struct lpfc_iocbq *cmdiocbq = NULL;
3645 	struct lpfc_iocbq rspiocbq;
3646 	uint32_t status;
3647 	uint32_t portRspPut, portRspMax;
3648 	int rc = 1;
3649 	lpfc_iocb_type type;
3650 	unsigned long iflag;
3651 	uint32_t rsp_cmpl = 0;
3652 
3653 	spin_lock_irqsave(&phba->hbalock, iflag);
3654 	pring->stats.iocb_event++;
3655 
3656 	/*
3657 	 * The next available response entry should never exceed the maximum
3658 	 * entries.  If it does, treat it as an adapter hardware error.
3659 	 */
3660 	portRspMax = pring->sli.sli3.numRiocb;
3661 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3662 	if (unlikely(portRspPut >= portRspMax)) {
3663 		lpfc_sli_rsp_pointers_error(phba, pring);
3664 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3665 		return 1;
3666 	}
3667 	if (phba->fcp_ring_in_use) {
3668 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3669 		return 1;
3670 	} else
3671 		phba->fcp_ring_in_use = 1;
3672 
3673 	rmb();
3674 	while (pring->sli.sli3.rspidx != portRspPut) {
3675 		/*
3676 		 * Fetch an entry off the ring and copy it into a local data
3677 		 * structure.  The copy involves a byte-swap since the
3678 		 * network byte order and pci byte orders are different.
3679 		 */
3680 		entry = lpfc_resp_iocb(phba, pring);
3681 		phba->last_completion_time = jiffies;
3682 
3683 		if (++pring->sli.sli3.rspidx >= portRspMax)
3684 			pring->sli.sli3.rspidx = 0;
3685 
3686 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3687 				      (uint32_t *) &rspiocbq.iocb,
3688 				      phba->iocb_rsp_size);
3689 		INIT_LIST_HEAD(&(rspiocbq.list));
3690 		irsp = &rspiocbq.iocb;
3691 
3692 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3693 		pring->stats.iocb_rsp++;
3694 		rsp_cmpl++;
3695 
3696 		if (unlikely(irsp->ulpStatus)) {
3697 			/*
3698 			 * If resource errors reported from HBA, reduce
3699 			 * queuedepths of the SCSI device.
3700 			 */
3701 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3702 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3703 			     IOERR_NO_RESOURCES)) {
3704 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3705 				phba->lpfc_rampdown_queue_depth(phba);
3706 				spin_lock_irqsave(&phba->hbalock, iflag);
3707 			}
3708 
3709 			/* Rsp ring <ringno> error: IOCB */
3710 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3711 					"0336 Rsp Ring %d error: IOCB Data: "
3712 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
3713 					pring->ringno,
3714 					irsp->un.ulpWord[0],
3715 					irsp->un.ulpWord[1],
3716 					irsp->un.ulpWord[2],
3717 					irsp->un.ulpWord[3],
3718 					irsp->un.ulpWord[4],
3719 					irsp->un.ulpWord[5],
3720 					*(uint32_t *)&irsp->un1,
3721 					*((uint32_t *)&irsp->un1 + 1));
3722 		}
3723 
3724 		switch (type) {
3725 		case LPFC_ABORT_IOCB:
3726 		case LPFC_SOL_IOCB:
3727 			/*
3728 			 * Idle exchange closed via ABTS from port.  No iocb
3729 			 * resources need to be recovered.
3730 			 */
3731 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3732 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3733 						"0333 IOCB cmd 0x%x"
3734 						" processed. Skipping"
3735 						" completion\n",
3736 						irsp->ulpCommand);
3737 				break;
3738 			}
3739 
3740 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3741 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3742 							 &rspiocbq);
3743 			spin_lock_irqsave(&phba->hbalock, iflag);
3744 			if (unlikely(!cmdiocbq))
3745 				break;
3746 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3747 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3748 			if (cmdiocbq->iocb_cmpl) {
3749 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3750 				(cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
3751 						      &rspiocbq);
3752 				spin_lock_irqsave(&phba->hbalock, iflag);
3753 			}
3754 			break;
3755 		case LPFC_UNSOL_IOCB:
3756 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3757 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
3758 			spin_lock_irqsave(&phba->hbalock, iflag);
3759 			break;
3760 		default:
3761 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3762 				char adaptermsg[LPFC_MAX_ADPTMSG];
3763 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3764 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
3765 				       MAX_MSG_DATA);
3766 				dev_warn(&((phba->pcidev)->dev),
3767 					 "lpfc%d: %s\n",
3768 					 phba->brd_no, adaptermsg);
3769 			} else {
3770 				/* Unknown IOCB command */
3771 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3772 						"0334 Unknown IOCB command "
3773 						"Data: x%x, x%x x%x x%x x%x\n",
3774 						type, irsp->ulpCommand,
3775 						irsp->ulpStatus,
3776 						irsp->ulpIoTag,
3777 						irsp->ulpContext);
3778 			}
3779 			break;
3780 		}
3781 
3782 		/*
3783 		 * The response IOCB has been processed.  Update the ring
3784 		 * pointer in SLIM.  If the port response put pointer has not
3785 		 * been updated, sync the pgp->rspPutInx and fetch the new port
3786 		 * response put pointer.
3787 		 */
3788 		writel(pring->sli.sli3.rspidx,
3789 			&phba->host_gp[pring->ringno].rspGetInx);
3790 
3791 		if (pring->sli.sli3.rspidx == portRspPut)
3792 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3793 	}
3794 
3795 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
3796 		pring->stats.iocb_rsp_full++;
3797 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3798 		writel(status, phba->CAregaddr);
3799 		readl(phba->CAregaddr);
3800 	}
3801 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3802 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3803 		pring->stats.iocb_cmd_empty++;
3804 
3805 		/* Force update of the local copy of cmdGetInx */
3806 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3807 		lpfc_sli_resume_iocb(phba, pring);
3808 
3809 		if ((pring->lpfc_sli_cmd_available))
3810 			(pring->lpfc_sli_cmd_available) (phba, pring);
3811 
3812 	}
3813 
3814 	phba->fcp_ring_in_use = 0;
3815 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3816 	return rc;
3817 }
3818 
3819 /**
3820  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
3821  * @phba: Pointer to HBA context object.
3822  * @pring: Pointer to driver SLI ring object.
3823  * @rspiocbp: Pointer to driver response IOCB object.
3824  *
3825  * This function is called from the worker thread when there is a slow-path
3826  * response IOCB to process. This function chains all the response iocbs until
3827  * seeing the iocb with the LE bit set. The function will call
3828  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
3829  * completion of a command iocb. The function will call the
3830  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
3831  * The function frees the resources or calls the completion handler if this
3832  * iocb is an abort completion. The function returns NULL when the response
3833  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
3834  * this function shall chain the iocb on to the iocb_continueq and return the
3835  * response iocb passed in.
3836  **/
3837 static struct lpfc_iocbq *
3838 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3839 			struct lpfc_iocbq *rspiocbp)
3840 {
3841 	struct lpfc_iocbq *saveq;
3842 	struct lpfc_iocbq *cmdiocbp;
3843 	struct lpfc_iocbq *next_iocb;
3844 	IOCB_t *irsp = NULL;
3845 	uint32_t free_saveq;
3846 	uint8_t iocb_cmd_type;
3847 	lpfc_iocb_type type;
3848 	unsigned long iflag;
3849 	int rc;
3850 
3851 	spin_lock_irqsave(&phba->hbalock, iflag);
3852 	/* First add the response iocb to the countinueq list */
3853 	list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
3854 	pring->iocb_continueq_cnt++;
3855 
3856 	/* Now, determine whether the list is completed for processing */
3857 	irsp = &rspiocbp->iocb;
3858 	if (irsp->ulpLe) {
3859 		/*
3860 		 * By default, the driver expects to free all resources
3861 		 * associated with this iocb completion.
3862 		 */
3863 		free_saveq = 1;
3864 		saveq = list_get_first(&pring->iocb_continueq,
3865 				       struct lpfc_iocbq, list);
3866 		irsp = &(saveq->iocb);
3867 		list_del_init(&pring->iocb_continueq);
3868 		pring->iocb_continueq_cnt = 0;
3869 
3870 		pring->stats.iocb_rsp++;
3871 
3872 		/*
3873 		 * If resource errors reported from HBA, reduce
3874 		 * queuedepths of the SCSI device.
3875 		 */
3876 		if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3877 		    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3878 		     IOERR_NO_RESOURCES)) {
3879 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3880 			phba->lpfc_rampdown_queue_depth(phba);
3881 			spin_lock_irqsave(&phba->hbalock, iflag);
3882 		}
3883 
3884 		if (irsp->ulpStatus) {
3885 			/* Rsp ring <ringno> error: IOCB */
3886 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3887 					"0328 Rsp Ring %d error: "
3888 					"IOCB Data: "
3889 					"x%x x%x x%x x%x "
3890 					"x%x x%x x%x x%x "
3891 					"x%x x%x x%x x%x "
3892 					"x%x x%x x%x x%x\n",
3893 					pring->ringno,
3894 					irsp->un.ulpWord[0],
3895 					irsp->un.ulpWord[1],
3896 					irsp->un.ulpWord[2],
3897 					irsp->un.ulpWord[3],
3898 					irsp->un.ulpWord[4],
3899 					irsp->un.ulpWord[5],
3900 					*(((uint32_t *) irsp) + 6),
3901 					*(((uint32_t *) irsp) + 7),
3902 					*(((uint32_t *) irsp) + 8),
3903 					*(((uint32_t *) irsp) + 9),
3904 					*(((uint32_t *) irsp) + 10),
3905 					*(((uint32_t *) irsp) + 11),
3906 					*(((uint32_t *) irsp) + 12),
3907 					*(((uint32_t *) irsp) + 13),
3908 					*(((uint32_t *) irsp) + 14),
3909 					*(((uint32_t *) irsp) + 15));
3910 		}
3911 
3912 		/*
3913 		 * Fetch the IOCB command type and call the correct completion
3914 		 * routine. Solicited and Unsolicited IOCBs on the ELS ring
3915 		 * get freed back to the lpfc_iocb_list by the discovery
3916 		 * kernel thread.
3917 		 */
3918 		iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
3919 		type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
3920 		switch (type) {
3921 		case LPFC_SOL_IOCB:
3922 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3923 			rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
3924 			spin_lock_irqsave(&phba->hbalock, iflag);
3925 			break;
3926 
3927 		case LPFC_UNSOL_IOCB:
3928 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3929 			rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
3930 			spin_lock_irqsave(&phba->hbalock, iflag);
3931 			if (!rc)
3932 				free_saveq = 0;
3933 			break;
3934 
3935 		case LPFC_ABORT_IOCB:
3936 			cmdiocbp = NULL;
3937 			if (irsp->ulpCommand != CMD_XRI_ABORTED_CX) {
3938 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3939 				cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
3940 								 saveq);
3941 				spin_lock_irqsave(&phba->hbalock, iflag);
3942 			}
3943 			if (cmdiocbp) {
3944 				/* Call the specified completion routine */
3945 				if (cmdiocbp->iocb_cmpl) {
3946 					spin_unlock_irqrestore(&phba->hbalock,
3947 							       iflag);
3948 					(cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
3949 							      saveq);
3950 					spin_lock_irqsave(&phba->hbalock,
3951 							  iflag);
3952 				} else
3953 					__lpfc_sli_release_iocbq(phba,
3954 								 cmdiocbp);
3955 			}
3956 			break;
3957 
3958 		case LPFC_UNKNOWN_IOCB:
3959 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3960 				char adaptermsg[LPFC_MAX_ADPTMSG];
3961 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3962 				memcpy(&adaptermsg[0], (uint8_t *)irsp,
3963 				       MAX_MSG_DATA);
3964 				dev_warn(&((phba->pcidev)->dev),
3965 					 "lpfc%d: %s\n",
3966 					 phba->brd_no, adaptermsg);
3967 			} else {
3968 				/* Unknown IOCB command */
3969 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3970 						"0335 Unknown IOCB "
3971 						"command Data: x%x "
3972 						"x%x x%x x%x\n",
3973 						irsp->ulpCommand,
3974 						irsp->ulpStatus,
3975 						irsp->ulpIoTag,
3976 						irsp->ulpContext);
3977 			}
3978 			break;
3979 		}
3980 
3981 		if (free_saveq) {
3982 			list_for_each_entry_safe(rspiocbp, next_iocb,
3983 						 &saveq->list, list) {
3984 				list_del_init(&rspiocbp->list);
3985 				__lpfc_sli_release_iocbq(phba, rspiocbp);
3986 			}
3987 			__lpfc_sli_release_iocbq(phba, saveq);
3988 		}
3989 		rspiocbp = NULL;
3990 	}
3991 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3992 	return rspiocbp;
3993 }
3994 
3995 /**
3996  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
3997  * @phba: Pointer to HBA context object.
3998  * @pring: Pointer to driver SLI ring object.
3999  * @mask: Host attention register mask for this ring.
4000  *
4001  * This routine wraps the actual slow_ring event process routine from the
4002  * API jump table function pointer from the lpfc_hba struct.
4003  **/
4004 void
4005 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
4006 				struct lpfc_sli_ring *pring, uint32_t mask)
4007 {
4008 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
4009 }
4010 
4011 /**
4012  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
4013  * @phba: Pointer to HBA context object.
4014  * @pring: Pointer to driver SLI ring object.
4015  * @mask: Host attention register mask for this ring.
4016  *
4017  * This function is called from the worker thread when there is a ring event
4018  * for non-fcp rings. The caller does not hold any lock. The function will
4019  * remove each response iocb in the response ring and calls the handle
4020  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4021  **/
4022 static void
4023 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
4024 				   struct lpfc_sli_ring *pring, uint32_t mask)
4025 {
4026 	struct lpfc_pgp *pgp;
4027 	IOCB_t *entry;
4028 	IOCB_t *irsp = NULL;
4029 	struct lpfc_iocbq *rspiocbp = NULL;
4030 	uint32_t portRspPut, portRspMax;
4031 	unsigned long iflag;
4032 	uint32_t status;
4033 
4034 	pgp = &phba->port_gp[pring->ringno];
4035 	spin_lock_irqsave(&phba->hbalock, iflag);
4036 	pring->stats.iocb_event++;
4037 
4038 	/*
4039 	 * The next available response entry should never exceed the maximum
4040 	 * entries.  If it does, treat it as an adapter hardware error.
4041 	 */
4042 	portRspMax = pring->sli.sli3.numRiocb;
4043 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4044 	if (portRspPut >= portRspMax) {
4045 		/*
4046 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
4047 		 * rsp ring <portRspMax>
4048 		 */
4049 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4050 				"0303 Ring %d handler: portRspPut %d "
4051 				"is bigger than rsp ring %d\n",
4052 				pring->ringno, portRspPut, portRspMax);
4053 
4054 		phba->link_state = LPFC_HBA_ERROR;
4055 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4056 
4057 		phba->work_hs = HS_FFER3;
4058 		lpfc_handle_eratt(phba);
4059 
4060 		return;
4061 	}
4062 
4063 	rmb();
4064 	while (pring->sli.sli3.rspidx != portRspPut) {
4065 		/*
4066 		 * Build a completion list and call the appropriate handler.
4067 		 * The process is to get the next available response iocb, get
4068 		 * a free iocb from the list, copy the response data into the
4069 		 * free iocb, insert to the continuation list, and update the
4070 		 * next response index to slim.  This process makes response
4071 		 * iocb's in the ring available to DMA as fast as possible but
4072 		 * pays a penalty for a copy operation.  Since the iocb is
4073 		 * only 32 bytes, this penalty is considered small relative to
4074 		 * the PCI reads for register values and a slim write.  When
4075 		 * the ulpLe field is set, the entire Command has been
4076 		 * received.
4077 		 */
4078 		entry = lpfc_resp_iocb(phba, pring);
4079 
4080 		phba->last_completion_time = jiffies;
4081 		rspiocbp = __lpfc_sli_get_iocbq(phba);
4082 		if (rspiocbp == NULL) {
4083 			printk(KERN_ERR "%s: out of buffers! Failing "
4084 			       "completion.\n", __func__);
4085 			break;
4086 		}
4087 
4088 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
4089 				      phba->iocb_rsp_size);
4090 		irsp = &rspiocbp->iocb;
4091 
4092 		if (++pring->sli.sli3.rspidx >= portRspMax)
4093 			pring->sli.sli3.rspidx = 0;
4094 
4095 		if (pring->ringno == LPFC_ELS_RING) {
4096 			lpfc_debugfs_slow_ring_trc(phba,
4097 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
4098 				*(((uint32_t *) irsp) + 4),
4099 				*(((uint32_t *) irsp) + 6),
4100 				*(((uint32_t *) irsp) + 7));
4101 		}
4102 
4103 		writel(pring->sli.sli3.rspidx,
4104 			&phba->host_gp[pring->ringno].rspGetInx);
4105 
4106 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4107 		/* Handle the response IOCB */
4108 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
4109 		spin_lock_irqsave(&phba->hbalock, iflag);
4110 
4111 		/*
4112 		 * If the port response put pointer has not been updated, sync
4113 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
4114 		 * response put pointer.
4115 		 */
4116 		if (pring->sli.sli3.rspidx == portRspPut) {
4117 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4118 		}
4119 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
4120 
4121 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
4122 		/* At least one response entry has been freed */
4123 		pring->stats.iocb_rsp_full++;
4124 		/* SET RxRE_RSP in Chip Att register */
4125 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4126 		writel(status, phba->CAregaddr);
4127 		readl(phba->CAregaddr); /* flush */
4128 	}
4129 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4130 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4131 		pring->stats.iocb_cmd_empty++;
4132 
4133 		/* Force update of the local copy of cmdGetInx */
4134 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4135 		lpfc_sli_resume_iocb(phba, pring);
4136 
4137 		if ((pring->lpfc_sli_cmd_available))
4138 			(pring->lpfc_sli_cmd_available) (phba, pring);
4139 
4140 	}
4141 
4142 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4143 	return;
4144 }
4145 
4146 /**
4147  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
4148  * @phba: Pointer to HBA context object.
4149  * @pring: Pointer to driver SLI ring object.
4150  * @mask: Host attention register mask for this ring.
4151  *
4152  * This function is called from the worker thread when there is a pending
4153  * ELS response iocb on the driver internal slow-path response iocb worker
4154  * queue. The caller does not hold any lock. The function will remove each
4155  * response iocb from the response worker queue and calls the handle
4156  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4157  **/
4158 static void
4159 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4160 				   struct lpfc_sli_ring *pring, uint32_t mask)
4161 {
4162 	struct lpfc_iocbq *irspiocbq;
4163 	struct hbq_dmabuf *dmabuf;
4164 	struct lpfc_cq_event *cq_event;
4165 	unsigned long iflag;
4166 	int count = 0;
4167 
4168 	spin_lock_irqsave(&phba->hbalock, iflag);
4169 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
4170 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4171 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4172 		/* Get the response iocb from the head of work queue */
4173 		spin_lock_irqsave(&phba->hbalock, iflag);
4174 		list_remove_head(&phba->sli4_hba.sp_queue_event,
4175 				 cq_event, struct lpfc_cq_event, list);
4176 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4177 
4178 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4179 		case CQE_CODE_COMPL_WQE:
4180 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4181 						 cq_event);
4182 			/* Translate ELS WCQE to response IOCBQ */
4183 			irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
4184 								   irspiocbq);
4185 			if (irspiocbq)
4186 				lpfc_sli_sp_handle_rspiocb(phba, pring,
4187 							   irspiocbq);
4188 			count++;
4189 			break;
4190 		case CQE_CODE_RECEIVE:
4191 		case CQE_CODE_RECEIVE_V1:
4192 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
4193 					      cq_event);
4194 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
4195 			count++;
4196 			break;
4197 		default:
4198 			break;
4199 		}
4200 
4201 		/* Limit the number of events to 64 to avoid soft lockups */
4202 		if (count == 64)
4203 			break;
4204 	}
4205 }
4206 
4207 /**
4208  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4209  * @phba: Pointer to HBA context object.
4210  * @pring: Pointer to driver SLI ring object.
4211  *
4212  * This function aborts all iocbs in the given ring and frees all the iocb
4213  * objects in txq. This function issues an abort iocb for all the iocb commands
4214  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4215  * the return of this function. The caller is not required to hold any locks.
4216  **/
4217 void
4218 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4219 {
4220 	LIST_HEAD(completions);
4221 	struct lpfc_iocbq *iocb, *next_iocb;
4222 
4223 	if (pring->ringno == LPFC_ELS_RING) {
4224 		lpfc_fabric_abort_hba(phba);
4225 	}
4226 
4227 	/* Error everything on txq and txcmplq
4228 	 * First do the txq.
4229 	 */
4230 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4231 		spin_lock_irq(&pring->ring_lock);
4232 		list_splice_init(&pring->txq, &completions);
4233 		pring->txq_cnt = 0;
4234 		spin_unlock_irq(&pring->ring_lock);
4235 
4236 		spin_lock_irq(&phba->hbalock);
4237 		/* Next issue ABTS for everything on the txcmplq */
4238 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4239 			lpfc_sli_issue_abort_iotag(phba, pring, iocb, NULL);
4240 		spin_unlock_irq(&phba->hbalock);
4241 	} else {
4242 		spin_lock_irq(&phba->hbalock);
4243 		list_splice_init(&pring->txq, &completions);
4244 		pring->txq_cnt = 0;
4245 
4246 		/* Next issue ABTS for everything on the txcmplq */
4247 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4248 			lpfc_sli_issue_abort_iotag(phba, pring, iocb, NULL);
4249 		spin_unlock_irq(&phba->hbalock);
4250 	}
4251 	/* Make sure HBA is alive */
4252 	lpfc_issue_hb_tmo(phba);
4253 
4254 	/* Cancel all the IOCBs from the completions list */
4255 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
4256 			      IOERR_SLI_ABORTED);
4257 }
4258 
4259 /**
4260  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4261  * @phba: Pointer to HBA context object.
4262  *
4263  * This function aborts all iocbs in FCP rings and frees all the iocb
4264  * objects in txq. This function issues an abort iocb for all the iocb commands
4265  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4266  * the return of this function. The caller is not required to hold any locks.
4267  **/
4268 void
4269 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4270 {
4271 	struct lpfc_sli *psli = &phba->sli;
4272 	struct lpfc_sli_ring  *pring;
4273 	uint32_t i;
4274 
4275 	/* Look on all the FCP Rings for the iotag */
4276 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4277 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4278 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4279 			lpfc_sli_abort_iocb_ring(phba, pring);
4280 		}
4281 	} else {
4282 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4283 		lpfc_sli_abort_iocb_ring(phba, pring);
4284 	}
4285 }
4286 
4287 /**
4288  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4289  * @phba: Pointer to HBA context object.
4290  *
4291  * This function flushes all iocbs in the IO ring and frees all the iocb
4292  * objects in txq and txcmplq. This function will not issue abort iocbs
4293  * for all the iocb commands in txcmplq, they will just be returned with
4294  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4295  * slot has been permanently disabled.
4296  **/
4297 void
4298 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4299 {
4300 	LIST_HEAD(txq);
4301 	LIST_HEAD(txcmplq);
4302 	struct lpfc_sli *psli = &phba->sli;
4303 	struct lpfc_sli_ring  *pring;
4304 	uint32_t i;
4305 	struct lpfc_iocbq *piocb, *next_iocb;
4306 
4307 	spin_lock_irq(&phba->hbalock);
4308 	if (phba->hba_flag & HBA_IOQ_FLUSH ||
4309 	    !phba->sli4_hba.hdwq) {
4310 		spin_unlock_irq(&phba->hbalock);
4311 		return;
4312 	}
4313 	/* Indicate the I/O queues are flushed */
4314 	phba->hba_flag |= HBA_IOQ_FLUSH;
4315 	spin_unlock_irq(&phba->hbalock);
4316 
4317 	/* Look on all the FCP Rings for the iotag */
4318 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4319 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4320 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4321 
4322 			spin_lock_irq(&pring->ring_lock);
4323 			/* Retrieve everything on txq */
4324 			list_splice_init(&pring->txq, &txq);
4325 			list_for_each_entry_safe(piocb, next_iocb,
4326 						 &pring->txcmplq, list)
4327 				piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4328 			/* Retrieve everything on the txcmplq */
4329 			list_splice_init(&pring->txcmplq, &txcmplq);
4330 			pring->txq_cnt = 0;
4331 			pring->txcmplq_cnt = 0;
4332 			spin_unlock_irq(&pring->ring_lock);
4333 
4334 			/* Flush the txq */
4335 			lpfc_sli_cancel_iocbs(phba, &txq,
4336 					      IOSTAT_LOCAL_REJECT,
4337 					      IOERR_SLI_DOWN);
4338 			/* Flush the txcmpq */
4339 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4340 					      IOSTAT_LOCAL_REJECT,
4341 					      IOERR_SLI_DOWN);
4342 		}
4343 	} else {
4344 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4345 
4346 		spin_lock_irq(&phba->hbalock);
4347 		/* Retrieve everything on txq */
4348 		list_splice_init(&pring->txq, &txq);
4349 		list_for_each_entry_safe(piocb, next_iocb,
4350 					 &pring->txcmplq, list)
4351 			piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4352 		/* Retrieve everything on the txcmplq */
4353 		list_splice_init(&pring->txcmplq, &txcmplq);
4354 		pring->txq_cnt = 0;
4355 		pring->txcmplq_cnt = 0;
4356 		spin_unlock_irq(&phba->hbalock);
4357 
4358 		/* Flush the txq */
4359 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4360 				      IOERR_SLI_DOWN);
4361 		/* Flush the txcmpq */
4362 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4363 				      IOERR_SLI_DOWN);
4364 	}
4365 }
4366 
4367 /**
4368  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4369  * @phba: Pointer to HBA context object.
4370  * @mask: Bit mask to be checked.
4371  *
4372  * This function reads the host status register and compares
4373  * with the provided bit mask to check if HBA completed
4374  * the restart. This function will wait in a loop for the
4375  * HBA to complete restart. If the HBA does not restart within
4376  * 15 iterations, the function will reset the HBA again. The
4377  * function returns 1 when HBA fail to restart otherwise returns
4378  * zero.
4379  **/
4380 static int
4381 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4382 {
4383 	uint32_t status;
4384 	int i = 0;
4385 	int retval = 0;
4386 
4387 	/* Read the HBA Host Status Register */
4388 	if (lpfc_readl(phba->HSregaddr, &status))
4389 		return 1;
4390 
4391 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4392 
4393 	/*
4394 	 * Check status register every 100ms for 5 retries, then every
4395 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4396 	 * every 2.5 sec for 4.
4397 	 * Break our of the loop if errors occurred during init.
4398 	 */
4399 	while (((status & mask) != mask) &&
4400 	       !(status & HS_FFERM) &&
4401 	       i++ < 20) {
4402 
4403 		if (i <= 5)
4404 			msleep(10);
4405 		else if (i <= 10)
4406 			msleep(500);
4407 		else
4408 			msleep(2500);
4409 
4410 		if (i == 15) {
4411 				/* Do post */
4412 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4413 			lpfc_sli_brdrestart(phba);
4414 		}
4415 		/* Read the HBA Host Status Register */
4416 		if (lpfc_readl(phba->HSregaddr, &status)) {
4417 			retval = 1;
4418 			break;
4419 		}
4420 	}
4421 
4422 	/* Check to see if any errors occurred during init */
4423 	if ((status & HS_FFERM) || (i >= 20)) {
4424 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4425 				"2751 Adapter failed to restart, "
4426 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4427 				status,
4428 				readl(phba->MBslimaddr + 0xa8),
4429 				readl(phba->MBslimaddr + 0xac));
4430 		phba->link_state = LPFC_HBA_ERROR;
4431 		retval = 1;
4432 	}
4433 
4434 	return retval;
4435 }
4436 
4437 /**
4438  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4439  * @phba: Pointer to HBA context object.
4440  * @mask: Bit mask to be checked.
4441  *
4442  * This function checks the host status register to check if HBA is
4443  * ready. This function will wait in a loop for the HBA to be ready
4444  * If the HBA is not ready , the function will will reset the HBA PCI
4445  * function again. The function returns 1 when HBA fail to be ready
4446  * otherwise returns zero.
4447  **/
4448 static int
4449 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4450 {
4451 	uint32_t status;
4452 	int retval = 0;
4453 
4454 	/* Read the HBA Host Status Register */
4455 	status = lpfc_sli4_post_status_check(phba);
4456 
4457 	if (status) {
4458 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4459 		lpfc_sli_brdrestart(phba);
4460 		status = lpfc_sli4_post_status_check(phba);
4461 	}
4462 
4463 	/* Check to see if any errors occurred during init */
4464 	if (status) {
4465 		phba->link_state = LPFC_HBA_ERROR;
4466 		retval = 1;
4467 	} else
4468 		phba->sli4_hba.intr_enable = 0;
4469 
4470 	return retval;
4471 }
4472 
4473 /**
4474  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4475  * @phba: Pointer to HBA context object.
4476  * @mask: Bit mask to be checked.
4477  *
4478  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4479  * from the API jump table function pointer from the lpfc_hba struct.
4480  **/
4481 int
4482 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4483 {
4484 	return phba->lpfc_sli_brdready(phba, mask);
4485 }
4486 
4487 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4488 
4489 /**
4490  * lpfc_reset_barrier - Make HBA ready for HBA reset
4491  * @phba: Pointer to HBA context object.
4492  *
4493  * This function is called before resetting an HBA. This function is called
4494  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4495  **/
4496 void lpfc_reset_barrier(struct lpfc_hba *phba)
4497 {
4498 	uint32_t __iomem *resp_buf;
4499 	uint32_t __iomem *mbox_buf;
4500 	volatile uint32_t mbox;
4501 	uint32_t hc_copy, ha_copy, resp_data;
4502 	int  i;
4503 	uint8_t hdrtype;
4504 
4505 	lockdep_assert_held(&phba->hbalock);
4506 
4507 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4508 	if (hdrtype != 0x80 ||
4509 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4510 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4511 		return;
4512 
4513 	/*
4514 	 * Tell the other part of the chip to suspend temporarily all
4515 	 * its DMA activity.
4516 	 */
4517 	resp_buf = phba->MBslimaddr;
4518 
4519 	/* Disable the error attention */
4520 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4521 		return;
4522 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4523 	readl(phba->HCregaddr); /* flush */
4524 	phba->link_flag |= LS_IGNORE_ERATT;
4525 
4526 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4527 		return;
4528 	if (ha_copy & HA_ERATT) {
4529 		/* Clear Chip error bit */
4530 		writel(HA_ERATT, phba->HAregaddr);
4531 		phba->pport->stopped = 1;
4532 	}
4533 
4534 	mbox = 0;
4535 	((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
4536 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
4537 
4538 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4539 	mbox_buf = phba->MBslimaddr;
4540 	writel(mbox, mbox_buf);
4541 
4542 	for (i = 0; i < 50; i++) {
4543 		if (lpfc_readl((resp_buf + 1), &resp_data))
4544 			return;
4545 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4546 			mdelay(1);
4547 		else
4548 			break;
4549 	}
4550 	resp_data = 0;
4551 	if (lpfc_readl((resp_buf + 1), &resp_data))
4552 		return;
4553 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4554 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4555 		    phba->pport->stopped)
4556 			goto restore_hc;
4557 		else
4558 			goto clear_errat;
4559 	}
4560 
4561 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
4562 	resp_data = 0;
4563 	for (i = 0; i < 500; i++) {
4564 		if (lpfc_readl(resp_buf, &resp_data))
4565 			return;
4566 		if (resp_data != mbox)
4567 			mdelay(1);
4568 		else
4569 			break;
4570 	}
4571 
4572 clear_errat:
4573 
4574 	while (++i < 500) {
4575 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4576 			return;
4577 		if (!(ha_copy & HA_ERATT))
4578 			mdelay(1);
4579 		else
4580 			break;
4581 	}
4582 
4583 	if (readl(phba->HAregaddr) & HA_ERATT) {
4584 		writel(HA_ERATT, phba->HAregaddr);
4585 		phba->pport->stopped = 1;
4586 	}
4587 
4588 restore_hc:
4589 	phba->link_flag &= ~LS_IGNORE_ERATT;
4590 	writel(hc_copy, phba->HCregaddr);
4591 	readl(phba->HCregaddr); /* flush */
4592 }
4593 
4594 /**
4595  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4596  * @phba: Pointer to HBA context object.
4597  *
4598  * This function issues a kill_board mailbox command and waits for
4599  * the error attention interrupt. This function is called for stopping
4600  * the firmware processing. The caller is not required to hold any
4601  * locks. This function calls lpfc_hba_down_post function to free
4602  * any pending commands after the kill. The function will return 1 when it
4603  * fails to kill the board else will return 0.
4604  **/
4605 int
4606 lpfc_sli_brdkill(struct lpfc_hba *phba)
4607 {
4608 	struct lpfc_sli *psli;
4609 	LPFC_MBOXQ_t *pmb;
4610 	uint32_t status;
4611 	uint32_t ha_copy;
4612 	int retval;
4613 	int i = 0;
4614 
4615 	psli = &phba->sli;
4616 
4617 	/* Kill HBA */
4618 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4619 			"0329 Kill HBA Data: x%x x%x\n",
4620 			phba->pport->port_state, psli->sli_flag);
4621 
4622 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4623 	if (!pmb)
4624 		return 1;
4625 
4626 	/* Disable the error attention */
4627 	spin_lock_irq(&phba->hbalock);
4628 	if (lpfc_readl(phba->HCregaddr, &status)) {
4629 		spin_unlock_irq(&phba->hbalock);
4630 		mempool_free(pmb, phba->mbox_mem_pool);
4631 		return 1;
4632 	}
4633 	status &= ~HC_ERINT_ENA;
4634 	writel(status, phba->HCregaddr);
4635 	readl(phba->HCregaddr); /* flush */
4636 	phba->link_flag |= LS_IGNORE_ERATT;
4637 	spin_unlock_irq(&phba->hbalock);
4638 
4639 	lpfc_kill_board(phba, pmb);
4640 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4641 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4642 
4643 	if (retval != MBX_SUCCESS) {
4644 		if (retval != MBX_BUSY)
4645 			mempool_free(pmb, phba->mbox_mem_pool);
4646 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4647 				"2752 KILL_BOARD command failed retval %d\n",
4648 				retval);
4649 		spin_lock_irq(&phba->hbalock);
4650 		phba->link_flag &= ~LS_IGNORE_ERATT;
4651 		spin_unlock_irq(&phba->hbalock);
4652 		return 1;
4653 	}
4654 
4655 	spin_lock_irq(&phba->hbalock);
4656 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
4657 	spin_unlock_irq(&phba->hbalock);
4658 
4659 	mempool_free(pmb, phba->mbox_mem_pool);
4660 
4661 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
4662 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
4663 	 * 3 seconds we still set HBA_ERROR state because the status of the
4664 	 * board is now undefined.
4665 	 */
4666 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4667 		return 1;
4668 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
4669 		mdelay(100);
4670 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4671 			return 1;
4672 	}
4673 
4674 	del_timer_sync(&psli->mbox_tmo);
4675 	if (ha_copy & HA_ERATT) {
4676 		writel(HA_ERATT, phba->HAregaddr);
4677 		phba->pport->stopped = 1;
4678 	}
4679 	spin_lock_irq(&phba->hbalock);
4680 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4681 	psli->mbox_active = NULL;
4682 	phba->link_flag &= ~LS_IGNORE_ERATT;
4683 	spin_unlock_irq(&phba->hbalock);
4684 
4685 	lpfc_hba_down_post(phba);
4686 	phba->link_state = LPFC_HBA_ERROR;
4687 
4688 	return ha_copy & HA_ERATT ? 0 : 1;
4689 }
4690 
4691 /**
4692  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
4693  * @phba: Pointer to HBA context object.
4694  *
4695  * This function resets the HBA by writing HC_INITFF to the control
4696  * register. After the HBA resets, this function resets all the iocb ring
4697  * indices. This function disables PCI layer parity checking during
4698  * the reset.
4699  * This function returns 0 always.
4700  * The caller is not required to hold any locks.
4701  **/
4702 int
4703 lpfc_sli_brdreset(struct lpfc_hba *phba)
4704 {
4705 	struct lpfc_sli *psli;
4706 	struct lpfc_sli_ring *pring;
4707 	uint16_t cfg_value;
4708 	int i;
4709 
4710 	psli = &phba->sli;
4711 
4712 	/* Reset HBA */
4713 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4714 			"0325 Reset HBA Data: x%x x%x\n",
4715 			(phba->pport) ? phba->pport->port_state : 0,
4716 			psli->sli_flag);
4717 
4718 	/* perform board reset */
4719 	phba->fc_eventTag = 0;
4720 	phba->link_events = 0;
4721 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4722 	if (phba->pport) {
4723 		phba->pport->fc_myDID = 0;
4724 		phba->pport->fc_prevDID = 0;
4725 	}
4726 
4727 	/* Turn off parity checking and serr during the physical reset */
4728 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
4729 		return -EIO;
4730 
4731 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
4732 			      (cfg_value &
4733 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4734 
4735 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4736 
4737 	/* Now toggle INITFF bit in the Host Control Register */
4738 	writel(HC_INITFF, phba->HCregaddr);
4739 	mdelay(1);
4740 	readl(phba->HCregaddr); /* flush */
4741 	writel(0, phba->HCregaddr);
4742 	readl(phba->HCregaddr); /* flush */
4743 
4744 	/* Restore PCI cmd register */
4745 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4746 
4747 	/* Initialize relevant SLI info */
4748 	for (i = 0; i < psli->num_rings; i++) {
4749 		pring = &psli->sli3_ring[i];
4750 		pring->flag = 0;
4751 		pring->sli.sli3.rspidx = 0;
4752 		pring->sli.sli3.next_cmdidx  = 0;
4753 		pring->sli.sli3.local_getidx = 0;
4754 		pring->sli.sli3.cmdidx = 0;
4755 		pring->missbufcnt = 0;
4756 	}
4757 
4758 	phba->link_state = LPFC_WARM_START;
4759 	return 0;
4760 }
4761 
4762 /**
4763  * lpfc_sli4_brdreset - Reset a sli-4 HBA
4764  * @phba: Pointer to HBA context object.
4765  *
4766  * This function resets a SLI4 HBA. This function disables PCI layer parity
4767  * checking during resets the device. The caller is not required to hold
4768  * any locks.
4769  *
4770  * This function returns 0 on success else returns negative error code.
4771  **/
4772 int
4773 lpfc_sli4_brdreset(struct lpfc_hba *phba)
4774 {
4775 	struct lpfc_sli *psli = &phba->sli;
4776 	uint16_t cfg_value;
4777 	int rc = 0;
4778 
4779 	/* Reset HBA */
4780 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4781 			"0295 Reset HBA Data: x%x x%x x%x\n",
4782 			phba->pport->port_state, psli->sli_flag,
4783 			phba->hba_flag);
4784 
4785 	/* perform board reset */
4786 	phba->fc_eventTag = 0;
4787 	phba->link_events = 0;
4788 	phba->pport->fc_myDID = 0;
4789 	phba->pport->fc_prevDID = 0;
4790 
4791 	spin_lock_irq(&phba->hbalock);
4792 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
4793 	phba->fcf.fcf_flag = 0;
4794 	spin_unlock_irq(&phba->hbalock);
4795 
4796 	/* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
4797 	if (phba->hba_flag & HBA_FW_DUMP_OP) {
4798 		phba->hba_flag &= ~HBA_FW_DUMP_OP;
4799 		return rc;
4800 	}
4801 
4802 	/* Now physically reset the device */
4803 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4804 			"0389 Performing PCI function reset!\n");
4805 
4806 	/* Turn off parity checking and serr during the physical reset */
4807 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
4808 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4809 				"3205 PCI read Config failed\n");
4810 		return -EIO;
4811 	}
4812 
4813 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
4814 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4815 
4816 	/* Perform FCoE PCI function reset before freeing queue memory */
4817 	rc = lpfc_pci_function_reset(phba);
4818 
4819 	/* Restore PCI cmd register */
4820 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4821 
4822 	return rc;
4823 }
4824 
4825 /**
4826  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
4827  * @phba: Pointer to HBA context object.
4828  *
4829  * This function is called in the SLI initialization code path to
4830  * restart the HBA. The caller is not required to hold any lock.
4831  * This function writes MBX_RESTART mailbox command to the SLIM and
4832  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
4833  * function to free any pending commands. The function enables
4834  * POST only during the first initialization. The function returns zero.
4835  * The function does not guarantee completion of MBX_RESTART mailbox
4836  * command before the return of this function.
4837  **/
4838 static int
4839 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
4840 {
4841 	MAILBOX_t *mb;
4842 	struct lpfc_sli *psli;
4843 	volatile uint32_t word0;
4844 	void __iomem *to_slim;
4845 	uint32_t hba_aer_enabled;
4846 
4847 	spin_lock_irq(&phba->hbalock);
4848 
4849 	/* Take PCIe device Advanced Error Reporting (AER) state */
4850 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4851 
4852 	psli = &phba->sli;
4853 
4854 	/* Restart HBA */
4855 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4856 			"0337 Restart HBA Data: x%x x%x\n",
4857 			(phba->pport) ? phba->pport->port_state : 0,
4858 			psli->sli_flag);
4859 
4860 	word0 = 0;
4861 	mb = (MAILBOX_t *) &word0;
4862 	mb->mbxCommand = MBX_RESTART;
4863 	mb->mbxHc = 1;
4864 
4865 	lpfc_reset_barrier(phba);
4866 
4867 	to_slim = phba->MBslimaddr;
4868 	writel(*(uint32_t *) mb, to_slim);
4869 	readl(to_slim); /* flush */
4870 
4871 	/* Only skip post after fc_ffinit is completed */
4872 	if (phba->pport && phba->pport->port_state)
4873 		word0 = 1;	/* This is really setting up word1 */
4874 	else
4875 		word0 = 0;	/* This is really setting up word1 */
4876 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
4877 	writel(*(uint32_t *) mb, to_slim);
4878 	readl(to_slim); /* flush */
4879 
4880 	lpfc_sli_brdreset(phba);
4881 	if (phba->pport)
4882 		phba->pport->stopped = 0;
4883 	phba->link_state = LPFC_INIT_START;
4884 	phba->hba_flag = 0;
4885 	spin_unlock_irq(&phba->hbalock);
4886 
4887 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4888 	psli->stats_start = ktime_get_seconds();
4889 
4890 	/* Give the INITFF and Post time to settle. */
4891 	mdelay(100);
4892 
4893 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4894 	if (hba_aer_enabled)
4895 		pci_disable_pcie_error_reporting(phba->pcidev);
4896 
4897 	lpfc_hba_down_post(phba);
4898 
4899 	return 0;
4900 }
4901 
4902 /**
4903  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
4904  * @phba: Pointer to HBA context object.
4905  *
4906  * This function is called in the SLI initialization code path to restart
4907  * a SLI4 HBA. The caller is not required to hold any lock.
4908  * At the end of the function, it calls lpfc_hba_down_post function to
4909  * free any pending commands.
4910  **/
4911 static int
4912 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
4913 {
4914 	struct lpfc_sli *psli = &phba->sli;
4915 	uint32_t hba_aer_enabled;
4916 	int rc;
4917 
4918 	/* Restart HBA */
4919 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4920 			"0296 Restart HBA Data: x%x x%x\n",
4921 			phba->pport->port_state, psli->sli_flag);
4922 
4923 	/* Take PCIe device Advanced Error Reporting (AER) state */
4924 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4925 
4926 	rc = lpfc_sli4_brdreset(phba);
4927 	if (rc) {
4928 		phba->link_state = LPFC_HBA_ERROR;
4929 		goto hba_down_queue;
4930 	}
4931 
4932 	spin_lock_irq(&phba->hbalock);
4933 	phba->pport->stopped = 0;
4934 	phba->link_state = LPFC_INIT_START;
4935 	phba->hba_flag = 0;
4936 	spin_unlock_irq(&phba->hbalock);
4937 
4938 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4939 	psli->stats_start = ktime_get_seconds();
4940 
4941 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4942 	if (hba_aer_enabled)
4943 		pci_disable_pcie_error_reporting(phba->pcidev);
4944 
4945 hba_down_queue:
4946 	lpfc_hba_down_post(phba);
4947 	lpfc_sli4_queue_destroy(phba);
4948 
4949 	return rc;
4950 }
4951 
4952 /**
4953  * lpfc_sli_brdrestart - Wrapper func for restarting hba
4954  * @phba: Pointer to HBA context object.
4955  *
4956  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
4957  * API jump table function pointer from the lpfc_hba struct.
4958 **/
4959 int
4960 lpfc_sli_brdrestart(struct lpfc_hba *phba)
4961 {
4962 	return phba->lpfc_sli_brdrestart(phba);
4963 }
4964 
4965 /**
4966  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
4967  * @phba: Pointer to HBA context object.
4968  *
4969  * This function is called after a HBA restart to wait for successful
4970  * restart of the HBA. Successful restart of the HBA is indicated by
4971  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
4972  * iteration, the function will restart the HBA again. The function returns
4973  * zero if HBA successfully restarted else returns negative error code.
4974  **/
4975 int
4976 lpfc_sli_chipset_init(struct lpfc_hba *phba)
4977 {
4978 	uint32_t status, i = 0;
4979 
4980 	/* Read the HBA Host Status Register */
4981 	if (lpfc_readl(phba->HSregaddr, &status))
4982 		return -EIO;
4983 
4984 	/* Check status register to see what current state is */
4985 	i = 0;
4986 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
4987 
4988 		/* Check every 10ms for 10 retries, then every 100ms for 90
4989 		 * retries, then every 1 sec for 50 retires for a total of
4990 		 * ~60 seconds before reset the board again and check every
4991 		 * 1 sec for 50 retries. The up to 60 seconds before the
4992 		 * board ready is required by the Falcon FIPS zeroization
4993 		 * complete, and any reset the board in between shall cause
4994 		 * restart of zeroization, further delay the board ready.
4995 		 */
4996 		if (i++ >= 200) {
4997 			/* Adapter failed to init, timeout, status reg
4998 			   <status> */
4999 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5000 					"0436 Adapter failed to init, "
5001 					"timeout, status reg x%x, "
5002 					"FW Data: A8 x%x AC x%x\n", status,
5003 					readl(phba->MBslimaddr + 0xa8),
5004 					readl(phba->MBslimaddr + 0xac));
5005 			phba->link_state = LPFC_HBA_ERROR;
5006 			return -ETIMEDOUT;
5007 		}
5008 
5009 		/* Check to see if any errors occurred during init */
5010 		if (status & HS_FFERM) {
5011 			/* ERROR: During chipset initialization */
5012 			/* Adapter failed to init, chipset, status reg
5013 			   <status> */
5014 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5015 					"0437 Adapter failed to init, "
5016 					"chipset, status reg x%x, "
5017 					"FW Data: A8 x%x AC x%x\n", status,
5018 					readl(phba->MBslimaddr + 0xa8),
5019 					readl(phba->MBslimaddr + 0xac));
5020 			phba->link_state = LPFC_HBA_ERROR;
5021 			return -EIO;
5022 		}
5023 
5024 		if (i <= 10)
5025 			msleep(10);
5026 		else if (i <= 100)
5027 			msleep(100);
5028 		else
5029 			msleep(1000);
5030 
5031 		if (i == 150) {
5032 			/* Do post */
5033 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5034 			lpfc_sli_brdrestart(phba);
5035 		}
5036 		/* Read the HBA Host Status Register */
5037 		if (lpfc_readl(phba->HSregaddr, &status))
5038 			return -EIO;
5039 	}
5040 
5041 	/* Check to see if any errors occurred during init */
5042 	if (status & HS_FFERM) {
5043 		/* ERROR: During chipset initialization */
5044 		/* Adapter failed to init, chipset, status reg <status> */
5045 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5046 				"0438 Adapter failed to init, chipset, "
5047 				"status reg x%x, "
5048 				"FW Data: A8 x%x AC x%x\n", status,
5049 				readl(phba->MBslimaddr + 0xa8),
5050 				readl(phba->MBslimaddr + 0xac));
5051 		phba->link_state = LPFC_HBA_ERROR;
5052 		return -EIO;
5053 	}
5054 
5055 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5056 
5057 	/* Clear all interrupt enable conditions */
5058 	writel(0, phba->HCregaddr);
5059 	readl(phba->HCregaddr); /* flush */
5060 
5061 	/* setup host attn register */
5062 	writel(0xffffffff, phba->HAregaddr);
5063 	readl(phba->HAregaddr); /* flush */
5064 	return 0;
5065 }
5066 
5067 /**
5068  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5069  *
5070  * This function calculates and returns the number of HBQs required to be
5071  * configured.
5072  **/
5073 int
5074 lpfc_sli_hbq_count(void)
5075 {
5076 	return ARRAY_SIZE(lpfc_hbq_defs);
5077 }
5078 
5079 /**
5080  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5081  *
5082  * This function adds the number of hbq entries in every HBQ to get
5083  * the total number of hbq entries required for the HBA and returns
5084  * the total count.
5085  **/
5086 static int
5087 lpfc_sli_hbq_entry_count(void)
5088 {
5089 	int  hbq_count = lpfc_sli_hbq_count();
5090 	int  count = 0;
5091 	int  i;
5092 
5093 	for (i = 0; i < hbq_count; ++i)
5094 		count += lpfc_hbq_defs[i]->entry_count;
5095 	return count;
5096 }
5097 
5098 /**
5099  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5100  *
5101  * This function calculates amount of memory required for all hbq entries
5102  * to be configured and returns the total memory required.
5103  **/
5104 int
5105 lpfc_sli_hbq_size(void)
5106 {
5107 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5108 }
5109 
5110 /**
5111  * lpfc_sli_hbq_setup - configure and initialize HBQs
5112  * @phba: Pointer to HBA context object.
5113  *
5114  * This function is called during the SLI initialization to configure
5115  * all the HBQs and post buffers to the HBQ. The caller is not
5116  * required to hold any locks. This function will return zero if successful
5117  * else it will return negative error code.
5118  **/
5119 static int
5120 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5121 {
5122 	int  hbq_count = lpfc_sli_hbq_count();
5123 	LPFC_MBOXQ_t *pmb;
5124 	MAILBOX_t *pmbox;
5125 	uint32_t hbqno;
5126 	uint32_t hbq_entry_index;
5127 
5128 				/* Get a Mailbox buffer to setup mailbox
5129 				 * commands for HBA initialization
5130 				 */
5131 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5132 
5133 	if (!pmb)
5134 		return -ENOMEM;
5135 
5136 	pmbox = &pmb->u.mb;
5137 
5138 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
5139 	phba->link_state = LPFC_INIT_MBX_CMDS;
5140 	phba->hbq_in_use = 1;
5141 
5142 	hbq_entry_index = 0;
5143 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5144 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
5145 		phba->hbqs[hbqno].hbqPutIdx      = 0;
5146 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5147 		phba->hbqs[hbqno].entry_count =
5148 			lpfc_hbq_defs[hbqno]->entry_count;
5149 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5150 			hbq_entry_index, pmb);
5151 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
5152 
5153 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5154 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5155 			   mbxStatus <status>, ring <num> */
5156 
5157 			lpfc_printf_log(phba, KERN_ERR,
5158 					LOG_SLI | LOG_VPORT,
5159 					"1805 Adapter failed to init. "
5160 					"Data: x%x x%x x%x\n",
5161 					pmbox->mbxCommand,
5162 					pmbox->mbxStatus, hbqno);
5163 
5164 			phba->link_state = LPFC_HBA_ERROR;
5165 			mempool_free(pmb, phba->mbox_mem_pool);
5166 			return -ENXIO;
5167 		}
5168 	}
5169 	phba->hbq_count = hbq_count;
5170 
5171 	mempool_free(pmb, phba->mbox_mem_pool);
5172 
5173 	/* Initially populate or replenish the HBQs */
5174 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5175 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5176 	return 0;
5177 }
5178 
5179 /**
5180  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5181  * @phba: Pointer to HBA context object.
5182  *
5183  * This function is called during the SLI initialization to configure
5184  * all the HBQs and post buffers to the HBQ. The caller is not
5185  * required to hold any locks. This function will return zero if successful
5186  * else it will return negative error code.
5187  **/
5188 static int
5189 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5190 {
5191 	phba->hbq_in_use = 1;
5192 	/**
5193 	 * Specific case when the MDS diagnostics is enabled and supported.
5194 	 * The receive buffer count is truncated to manage the incoming
5195 	 * traffic.
5196 	 **/
5197 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5198 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5199 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5200 	else
5201 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5202 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5203 	phba->hbq_count = 1;
5204 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5205 	/* Initially populate or replenish the HBQs */
5206 	return 0;
5207 }
5208 
5209 /**
5210  * lpfc_sli_config_port - Issue config port mailbox command
5211  * @phba: Pointer to HBA context object.
5212  * @sli_mode: sli mode - 2/3
5213  *
5214  * This function is called by the sli initialization code path
5215  * to issue config_port mailbox command. This function restarts the
5216  * HBA firmware and issues a config_port mailbox command to configure
5217  * the SLI interface in the sli mode specified by sli_mode
5218  * variable. The caller is not required to hold any locks.
5219  * The function returns 0 if successful, else returns negative error
5220  * code.
5221  **/
5222 int
5223 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5224 {
5225 	LPFC_MBOXQ_t *pmb;
5226 	uint32_t resetcount = 0, rc = 0, done = 0;
5227 
5228 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5229 	if (!pmb) {
5230 		phba->link_state = LPFC_HBA_ERROR;
5231 		return -ENOMEM;
5232 	}
5233 
5234 	phba->sli_rev = sli_mode;
5235 	while (resetcount < 2 && !done) {
5236 		spin_lock_irq(&phba->hbalock);
5237 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5238 		spin_unlock_irq(&phba->hbalock);
5239 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5240 		lpfc_sli_brdrestart(phba);
5241 		rc = lpfc_sli_chipset_init(phba);
5242 		if (rc)
5243 			break;
5244 
5245 		spin_lock_irq(&phba->hbalock);
5246 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5247 		spin_unlock_irq(&phba->hbalock);
5248 		resetcount++;
5249 
5250 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5251 		 * value of 0 means the call was successful.  Any other
5252 		 * nonzero value is a failure, but if ERESTART is returned,
5253 		 * the driver may reset the HBA and try again.
5254 		 */
5255 		rc = lpfc_config_port_prep(phba);
5256 		if (rc == -ERESTART) {
5257 			phba->link_state = LPFC_LINK_UNKNOWN;
5258 			continue;
5259 		} else if (rc)
5260 			break;
5261 
5262 		phba->link_state = LPFC_INIT_MBX_CMDS;
5263 		lpfc_config_port(phba, pmb);
5264 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5265 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5266 					LPFC_SLI3_HBQ_ENABLED |
5267 					LPFC_SLI3_CRP_ENABLED |
5268 					LPFC_SLI3_DSS_ENABLED);
5269 		if (rc != MBX_SUCCESS) {
5270 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5271 				"0442 Adapter failed to init, mbxCmd x%x "
5272 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5273 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5274 			spin_lock_irq(&phba->hbalock);
5275 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5276 			spin_unlock_irq(&phba->hbalock);
5277 			rc = -ENXIO;
5278 		} else {
5279 			/* Allow asynchronous mailbox command to go through */
5280 			spin_lock_irq(&phba->hbalock);
5281 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5282 			spin_unlock_irq(&phba->hbalock);
5283 			done = 1;
5284 
5285 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5286 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5287 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5288 					"3110 Port did not grant ASABT\n");
5289 		}
5290 	}
5291 	if (!done) {
5292 		rc = -EINVAL;
5293 		goto do_prep_failed;
5294 	}
5295 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5296 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5297 			rc = -ENXIO;
5298 			goto do_prep_failed;
5299 		}
5300 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5301 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5302 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5303 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5304 				phba->max_vpi : phba->max_vports;
5305 
5306 		} else
5307 			phba->max_vpi = 0;
5308 		if (pmb->u.mb.un.varCfgPort.gerbm)
5309 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5310 		if (pmb->u.mb.un.varCfgPort.gcrp)
5311 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5312 
5313 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5314 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5315 
5316 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5317 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5318 				phba->cfg_enable_bg = 0;
5319 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5320 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5321 						"0443 Adapter did not grant "
5322 						"BlockGuard\n");
5323 			}
5324 		}
5325 	} else {
5326 		phba->hbq_get = NULL;
5327 		phba->port_gp = phba->mbox->us.s2.port;
5328 		phba->max_vpi = 0;
5329 	}
5330 do_prep_failed:
5331 	mempool_free(pmb, phba->mbox_mem_pool);
5332 	return rc;
5333 }
5334 
5335 
5336 /**
5337  * lpfc_sli_hba_setup - SLI initialization function
5338  * @phba: Pointer to HBA context object.
5339  *
5340  * This function is the main SLI initialization function. This function
5341  * is called by the HBA initialization code, HBA reset code and HBA
5342  * error attention handler code. Caller is not required to hold any
5343  * locks. This function issues config_port mailbox command to configure
5344  * the SLI, setup iocb rings and HBQ rings. In the end the function
5345  * calls the config_port_post function to issue init_link mailbox
5346  * command and to start the discovery. The function will return zero
5347  * if successful, else it will return negative error code.
5348  **/
5349 int
5350 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5351 {
5352 	uint32_t rc;
5353 	int  i;
5354 	int longs;
5355 
5356 	/* Enable ISR already does config_port because of config_msi mbx */
5357 	if (phba->hba_flag & HBA_NEEDS_CFG_PORT) {
5358 		rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5359 		if (rc)
5360 			return -EIO;
5361 		phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
5362 	}
5363 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5364 
5365 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
5366 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
5367 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
5368 		if (!rc) {
5369 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5370 					"2709 This device supports "
5371 					"Advanced Error Reporting (AER)\n");
5372 			spin_lock_irq(&phba->hbalock);
5373 			phba->hba_flag |= HBA_AER_ENABLED;
5374 			spin_unlock_irq(&phba->hbalock);
5375 		} else {
5376 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5377 					"2708 This device does not support "
5378 					"Advanced Error Reporting (AER): %d\n",
5379 					rc);
5380 			phba->cfg_aer_support = 0;
5381 		}
5382 	}
5383 
5384 	if (phba->sli_rev == 3) {
5385 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5386 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5387 	} else {
5388 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5389 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5390 		phba->sli3_options = 0;
5391 	}
5392 
5393 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5394 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5395 			phba->sli_rev, phba->max_vpi);
5396 	rc = lpfc_sli_ring_map(phba);
5397 
5398 	if (rc)
5399 		goto lpfc_sli_hba_setup_error;
5400 
5401 	/* Initialize VPIs. */
5402 	if (phba->sli_rev == LPFC_SLI_REV3) {
5403 		/*
5404 		 * The VPI bitmask and physical ID array are allocated
5405 		 * and initialized once only - at driver load.  A port
5406 		 * reset doesn't need to reinitialize this memory.
5407 		 */
5408 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5409 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5410 			phba->vpi_bmask = kcalloc(longs,
5411 						  sizeof(unsigned long),
5412 						  GFP_KERNEL);
5413 			if (!phba->vpi_bmask) {
5414 				rc = -ENOMEM;
5415 				goto lpfc_sli_hba_setup_error;
5416 			}
5417 
5418 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5419 						sizeof(uint16_t),
5420 						GFP_KERNEL);
5421 			if (!phba->vpi_ids) {
5422 				kfree(phba->vpi_bmask);
5423 				rc = -ENOMEM;
5424 				goto lpfc_sli_hba_setup_error;
5425 			}
5426 			for (i = 0; i < phba->max_vpi; i++)
5427 				phba->vpi_ids[i] = i;
5428 		}
5429 	}
5430 
5431 	/* Init HBQs */
5432 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5433 		rc = lpfc_sli_hbq_setup(phba);
5434 		if (rc)
5435 			goto lpfc_sli_hba_setup_error;
5436 	}
5437 	spin_lock_irq(&phba->hbalock);
5438 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5439 	spin_unlock_irq(&phba->hbalock);
5440 
5441 	rc = lpfc_config_port_post(phba);
5442 	if (rc)
5443 		goto lpfc_sli_hba_setup_error;
5444 
5445 	return rc;
5446 
5447 lpfc_sli_hba_setup_error:
5448 	phba->link_state = LPFC_HBA_ERROR;
5449 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5450 			"0445 Firmware initialization failed\n");
5451 	return rc;
5452 }
5453 
5454 /**
5455  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5456  * @phba: Pointer to HBA context object.
5457  *
5458  * This function issue a dump mailbox command to read config region
5459  * 23 and parse the records in the region and populate driver
5460  * data structure.
5461  **/
5462 static int
5463 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5464 {
5465 	LPFC_MBOXQ_t *mboxq;
5466 	struct lpfc_dmabuf *mp;
5467 	struct lpfc_mqe *mqe;
5468 	uint32_t data_length;
5469 	int rc;
5470 
5471 	/* Program the default value of vlan_id and fc_map */
5472 	phba->valid_vlan = 0;
5473 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5474 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5475 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5476 
5477 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5478 	if (!mboxq)
5479 		return -ENOMEM;
5480 
5481 	mqe = &mboxq->u.mqe;
5482 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5483 		rc = -ENOMEM;
5484 		goto out_free_mboxq;
5485 	}
5486 
5487 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5488 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5489 
5490 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5491 			"(%d):2571 Mailbox cmd x%x Status x%x "
5492 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5493 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5494 			"CQ: x%x x%x x%x x%x\n",
5495 			mboxq->vport ? mboxq->vport->vpi : 0,
5496 			bf_get(lpfc_mqe_command, mqe),
5497 			bf_get(lpfc_mqe_status, mqe),
5498 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5499 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5500 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5501 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5502 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5503 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5504 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5505 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5506 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5507 			mboxq->mcqe.word0,
5508 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5509 			mboxq->mcqe.trailer);
5510 
5511 	if (rc) {
5512 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5513 		kfree(mp);
5514 		rc = -EIO;
5515 		goto out_free_mboxq;
5516 	}
5517 	data_length = mqe->un.mb_words[5];
5518 	if (data_length > DMP_RGN23_SIZE) {
5519 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5520 		kfree(mp);
5521 		rc = -EIO;
5522 		goto out_free_mboxq;
5523 	}
5524 
5525 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5526 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
5527 	kfree(mp);
5528 	rc = 0;
5529 
5530 out_free_mboxq:
5531 	mempool_free(mboxq, phba->mbox_mem_pool);
5532 	return rc;
5533 }
5534 
5535 /**
5536  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5537  * @phba: pointer to lpfc hba data structure.
5538  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5539  * @vpd: pointer to the memory to hold resulting port vpd data.
5540  * @vpd_size: On input, the number of bytes allocated to @vpd.
5541  *	      On output, the number of data bytes in @vpd.
5542  *
5543  * This routine executes a READ_REV SLI4 mailbox command.  In
5544  * addition, this routine gets the port vpd data.
5545  *
5546  * Return codes
5547  * 	0 - successful
5548  * 	-ENOMEM - could not allocated memory.
5549  **/
5550 static int
5551 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5552 		    uint8_t *vpd, uint32_t *vpd_size)
5553 {
5554 	int rc = 0;
5555 	uint32_t dma_size;
5556 	struct lpfc_dmabuf *dmabuf;
5557 	struct lpfc_mqe *mqe;
5558 
5559 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5560 	if (!dmabuf)
5561 		return -ENOMEM;
5562 
5563 	/*
5564 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5565 	 * mailbox command.
5566 	 */
5567 	dma_size = *vpd_size;
5568 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5569 					  &dmabuf->phys, GFP_KERNEL);
5570 	if (!dmabuf->virt) {
5571 		kfree(dmabuf);
5572 		return -ENOMEM;
5573 	}
5574 
5575 	/*
5576 	 * The SLI4 implementation of READ_REV conflicts at word1,
5577 	 * bits 31:16 and SLI4 adds vpd functionality not present
5578 	 * in SLI3.  This code corrects the conflicts.
5579 	 */
5580 	lpfc_read_rev(phba, mboxq);
5581 	mqe = &mboxq->u.mqe;
5582 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5583 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5584 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5585 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5586 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5587 
5588 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5589 	if (rc) {
5590 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5591 				  dmabuf->virt, dmabuf->phys);
5592 		kfree(dmabuf);
5593 		return -EIO;
5594 	}
5595 
5596 	/*
5597 	 * The available vpd length cannot be bigger than the
5598 	 * DMA buffer passed to the port.  Catch the less than
5599 	 * case and update the caller's size.
5600 	 */
5601 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5602 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5603 
5604 	memcpy(vpd, dmabuf->virt, *vpd_size);
5605 
5606 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5607 			  dmabuf->virt, dmabuf->phys);
5608 	kfree(dmabuf);
5609 	return 0;
5610 }
5611 
5612 /**
5613  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5614  * @phba: pointer to lpfc hba data structure.
5615  *
5616  * This routine retrieves SLI4 device physical port name this PCI function
5617  * is attached to.
5618  *
5619  * Return codes
5620  *      0 - successful
5621  *      otherwise - failed to retrieve controller attributes
5622  **/
5623 static int
5624 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5625 {
5626 	LPFC_MBOXQ_t *mboxq;
5627 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5628 	struct lpfc_controller_attribute *cntl_attr;
5629 	void *virtaddr = NULL;
5630 	uint32_t alloclen, reqlen;
5631 	uint32_t shdr_status, shdr_add_status;
5632 	union lpfc_sli4_cfg_shdr *shdr;
5633 	int rc;
5634 
5635 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5636 	if (!mboxq)
5637 		return -ENOMEM;
5638 
5639 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5640 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5641 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5642 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5643 			LPFC_SLI4_MBX_NEMBED);
5644 
5645 	if (alloclen < reqlen) {
5646 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5647 				"3084 Allocated DMA memory size (%d) is "
5648 				"less than the requested DMA memory size "
5649 				"(%d)\n", alloclen, reqlen);
5650 		rc = -ENOMEM;
5651 		goto out_free_mboxq;
5652 	}
5653 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5654 	virtaddr = mboxq->sge_array->addr[0];
5655 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5656 	shdr = &mbx_cntl_attr->cfg_shdr;
5657 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5658 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5659 	if (shdr_status || shdr_add_status || rc) {
5660 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5661 				"3085 Mailbox x%x (x%x/x%x) failed, "
5662 				"rc:x%x, status:x%x, add_status:x%x\n",
5663 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5664 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5665 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5666 				rc, shdr_status, shdr_add_status);
5667 		rc = -ENXIO;
5668 		goto out_free_mboxq;
5669 	}
5670 
5671 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5672 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5673 	phba->sli4_hba.lnk_info.lnk_tp =
5674 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5675 	phba->sli4_hba.lnk_info.lnk_no =
5676 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5677 	phba->sli4_hba.flash_id = bf_get(lpfc_cntl_attr_flash_id, cntl_attr);
5678 	phba->sli4_hba.asic_rev = bf_get(lpfc_cntl_attr_asic_rev, cntl_attr);
5679 
5680 	memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
5681 	strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
5682 		sizeof(phba->BIOSVersion));
5683 
5684 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5685 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s, "
5686 			"flash_id: x%02x, asic_rev: x%02x\n",
5687 			phba->sli4_hba.lnk_info.lnk_tp,
5688 			phba->sli4_hba.lnk_info.lnk_no,
5689 			phba->BIOSVersion, phba->sli4_hba.flash_id,
5690 			phba->sli4_hba.asic_rev);
5691 out_free_mboxq:
5692 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5693 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
5694 	else
5695 		mempool_free(mboxq, phba->mbox_mem_pool);
5696 	return rc;
5697 }
5698 
5699 /**
5700  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
5701  * @phba: pointer to lpfc hba data structure.
5702  *
5703  * This routine retrieves SLI4 device physical port name this PCI function
5704  * is attached to.
5705  *
5706  * Return codes
5707  *      0 - successful
5708  *      otherwise - failed to retrieve physical port name
5709  **/
5710 static int
5711 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
5712 {
5713 	LPFC_MBOXQ_t *mboxq;
5714 	struct lpfc_mbx_get_port_name *get_port_name;
5715 	uint32_t shdr_status, shdr_add_status;
5716 	union lpfc_sli4_cfg_shdr *shdr;
5717 	char cport_name = 0;
5718 	int rc;
5719 
5720 	/* We assume nothing at this point */
5721 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5722 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
5723 
5724 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5725 	if (!mboxq)
5726 		return -ENOMEM;
5727 	/* obtain link type and link number via READ_CONFIG */
5728 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5729 	lpfc_sli4_read_config(phba);
5730 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
5731 		goto retrieve_ppname;
5732 
5733 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
5734 	rc = lpfc_sli4_get_ctl_attr(phba);
5735 	if (rc)
5736 		goto out_free_mboxq;
5737 
5738 retrieve_ppname:
5739 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5740 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
5741 		sizeof(struct lpfc_mbx_get_port_name) -
5742 		sizeof(struct lpfc_sli4_cfg_mhdr),
5743 		LPFC_SLI4_MBX_EMBED);
5744 	get_port_name = &mboxq->u.mqe.un.get_port_name;
5745 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5746 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
5747 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
5748 		phba->sli4_hba.lnk_info.lnk_tp);
5749 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5750 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5751 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5752 	if (shdr_status || shdr_add_status || rc) {
5753 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5754 				"3087 Mailbox x%x (x%x/x%x) failed: "
5755 				"rc:x%x, status:x%x, add_status:x%x\n",
5756 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5757 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5758 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5759 				rc, shdr_status, shdr_add_status);
5760 		rc = -ENXIO;
5761 		goto out_free_mboxq;
5762 	}
5763 	switch (phba->sli4_hba.lnk_info.lnk_no) {
5764 	case LPFC_LINK_NUMBER_0:
5765 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
5766 				&get_port_name->u.response);
5767 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5768 		break;
5769 	case LPFC_LINK_NUMBER_1:
5770 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
5771 				&get_port_name->u.response);
5772 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5773 		break;
5774 	case LPFC_LINK_NUMBER_2:
5775 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
5776 				&get_port_name->u.response);
5777 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5778 		break;
5779 	case LPFC_LINK_NUMBER_3:
5780 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
5781 				&get_port_name->u.response);
5782 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5783 		break;
5784 	default:
5785 		break;
5786 	}
5787 
5788 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
5789 		phba->Port[0] = cport_name;
5790 		phba->Port[1] = '\0';
5791 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5792 				"3091 SLI get port name: %s\n", phba->Port);
5793 	}
5794 
5795 out_free_mboxq:
5796 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5797 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
5798 	else
5799 		mempool_free(mboxq, phba->mbox_mem_pool);
5800 	return rc;
5801 }
5802 
5803 /**
5804  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
5805  * @phba: pointer to lpfc hba data structure.
5806  *
5807  * This routine is called to explicitly arm the SLI4 device's completion and
5808  * event queues
5809  **/
5810 static void
5811 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
5812 {
5813 	int qidx;
5814 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
5815 	struct lpfc_sli4_hdw_queue *qp;
5816 	struct lpfc_queue *eq;
5817 
5818 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
5819 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
5820 	if (sli4_hba->nvmels_cq)
5821 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
5822 					   LPFC_QUEUE_REARM);
5823 
5824 	if (sli4_hba->hdwq) {
5825 		/* Loop thru all Hardware Queues */
5826 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
5827 			qp = &sli4_hba->hdwq[qidx];
5828 			/* ARM the corresponding CQ */
5829 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
5830 						LPFC_QUEUE_REARM);
5831 		}
5832 
5833 		/* Loop thru all IRQ vectors */
5834 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
5835 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
5836 			/* ARM the corresponding EQ */
5837 			sli4_hba->sli4_write_eq_db(phba, eq,
5838 						   0, LPFC_QUEUE_REARM);
5839 		}
5840 	}
5841 
5842 	if (phba->nvmet_support) {
5843 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
5844 			sli4_hba->sli4_write_cq_db(phba,
5845 				sli4_hba->nvmet_cqset[qidx], 0,
5846 				LPFC_QUEUE_REARM);
5847 		}
5848 	}
5849 }
5850 
5851 /**
5852  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
5853  * @phba: Pointer to HBA context object.
5854  * @type: The resource extent type.
5855  * @extnt_count: buffer to hold port available extent count.
5856  * @extnt_size: buffer to hold element count per extent.
5857  *
5858  * This function calls the port and retrievs the number of available
5859  * extents and their size for a particular extent type.
5860  *
5861  * Returns: 0 if successful.  Nonzero otherwise.
5862  **/
5863 int
5864 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
5865 			       uint16_t *extnt_count, uint16_t *extnt_size)
5866 {
5867 	int rc = 0;
5868 	uint32_t length;
5869 	uint32_t mbox_tmo;
5870 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
5871 	LPFC_MBOXQ_t *mbox;
5872 
5873 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5874 	if (!mbox)
5875 		return -ENOMEM;
5876 
5877 	/* Find out how many extents are available for this resource type */
5878 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
5879 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5880 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5881 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
5882 			 length, LPFC_SLI4_MBX_EMBED);
5883 
5884 	/* Send an extents count of 0 - the GET doesn't use it. */
5885 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5886 					LPFC_SLI4_MBX_EMBED);
5887 	if (unlikely(rc)) {
5888 		rc = -EIO;
5889 		goto err_exit;
5890 	}
5891 
5892 	if (!phba->sli4_hba.intr_enable)
5893 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5894 	else {
5895 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5896 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5897 	}
5898 	if (unlikely(rc)) {
5899 		rc = -EIO;
5900 		goto err_exit;
5901 	}
5902 
5903 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
5904 	if (bf_get(lpfc_mbox_hdr_status,
5905 		   &rsrc_info->header.cfg_shdr.response)) {
5906 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5907 				"2930 Failed to get resource extents "
5908 				"Status 0x%x Add'l Status 0x%x\n",
5909 				bf_get(lpfc_mbox_hdr_status,
5910 				       &rsrc_info->header.cfg_shdr.response),
5911 				bf_get(lpfc_mbox_hdr_add_status,
5912 				       &rsrc_info->header.cfg_shdr.response));
5913 		rc = -EIO;
5914 		goto err_exit;
5915 	}
5916 
5917 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
5918 			      &rsrc_info->u.rsp);
5919 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
5920 			     &rsrc_info->u.rsp);
5921 
5922 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5923 			"3162 Retrieved extents type-%d from port: count:%d, "
5924 			"size:%d\n", type, *extnt_count, *extnt_size);
5925 
5926 err_exit:
5927 	mempool_free(mbox, phba->mbox_mem_pool);
5928 	return rc;
5929 }
5930 
5931 /**
5932  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
5933  * @phba: Pointer to HBA context object.
5934  * @type: The extent type to check.
5935  *
5936  * This function reads the current available extents from the port and checks
5937  * if the extent count or extent size has changed since the last access.
5938  * Callers use this routine post port reset to understand if there is a
5939  * extent reprovisioning requirement.
5940  *
5941  * Returns:
5942  *   -Error: error indicates problem.
5943  *   1: Extent count or size has changed.
5944  *   0: No changes.
5945  **/
5946 static int
5947 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
5948 {
5949 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
5950 	uint16_t size_diff, rsrc_ext_size;
5951 	int rc = 0;
5952 	struct lpfc_rsrc_blks *rsrc_entry;
5953 	struct list_head *rsrc_blk_list = NULL;
5954 
5955 	size_diff = 0;
5956 	curr_ext_cnt = 0;
5957 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5958 					    &rsrc_ext_cnt,
5959 					    &rsrc_ext_size);
5960 	if (unlikely(rc))
5961 		return -EIO;
5962 
5963 	switch (type) {
5964 	case LPFC_RSC_TYPE_FCOE_RPI:
5965 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5966 		break;
5967 	case LPFC_RSC_TYPE_FCOE_VPI:
5968 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
5969 		break;
5970 	case LPFC_RSC_TYPE_FCOE_XRI:
5971 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5972 		break;
5973 	case LPFC_RSC_TYPE_FCOE_VFI:
5974 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5975 		break;
5976 	default:
5977 		break;
5978 	}
5979 
5980 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
5981 		curr_ext_cnt++;
5982 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
5983 			size_diff++;
5984 	}
5985 
5986 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
5987 		rc = 1;
5988 
5989 	return rc;
5990 }
5991 
5992 /**
5993  * lpfc_sli4_cfg_post_extnts -
5994  * @phba: Pointer to HBA context object.
5995  * @extnt_cnt: number of available extents.
5996  * @type: the extent type (rpi, xri, vfi, vpi).
5997  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
5998  * @mbox: pointer to the caller's allocated mailbox structure.
5999  *
6000  * This function executes the extents allocation request.  It also
6001  * takes care of the amount of memory needed to allocate or get the
6002  * allocated extents. It is the caller's responsibility to evaluate
6003  * the response.
6004  *
6005  * Returns:
6006  *   -Error:  Error value describes the condition found.
6007  *   0: if successful
6008  **/
6009 static int
6010 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6011 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6012 {
6013 	int rc = 0;
6014 	uint32_t req_len;
6015 	uint32_t emb_len;
6016 	uint32_t alloc_len, mbox_tmo;
6017 
6018 	/* Calculate the total requested length of the dma memory */
6019 	req_len = extnt_cnt * sizeof(uint16_t);
6020 
6021 	/*
6022 	 * Calculate the size of an embedded mailbox.  The uint32_t
6023 	 * accounts for extents-specific word.
6024 	 */
6025 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6026 		sizeof(uint32_t);
6027 
6028 	/*
6029 	 * Presume the allocation and response will fit into an embedded
6030 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6031 	 */
6032 	*emb = LPFC_SLI4_MBX_EMBED;
6033 	if (req_len > emb_len) {
6034 		req_len = extnt_cnt * sizeof(uint16_t) +
6035 			sizeof(union lpfc_sli4_cfg_shdr) +
6036 			sizeof(uint32_t);
6037 		*emb = LPFC_SLI4_MBX_NEMBED;
6038 	}
6039 
6040 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6041 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6042 				     req_len, *emb);
6043 	if (alloc_len < req_len) {
6044 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6045 			"2982 Allocated DMA memory size (x%x) is "
6046 			"less than the requested DMA memory "
6047 			"size (x%x)\n", alloc_len, req_len);
6048 		return -ENOMEM;
6049 	}
6050 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6051 	if (unlikely(rc))
6052 		return -EIO;
6053 
6054 	if (!phba->sli4_hba.intr_enable)
6055 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6056 	else {
6057 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6058 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6059 	}
6060 
6061 	if (unlikely(rc))
6062 		rc = -EIO;
6063 	return rc;
6064 }
6065 
6066 /**
6067  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6068  * @phba: Pointer to HBA context object.
6069  * @type:  The resource extent type to allocate.
6070  *
6071  * This function allocates the number of elements for the specified
6072  * resource type.
6073  **/
6074 static int
6075 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6076 {
6077 	bool emb = false;
6078 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6079 	uint16_t rsrc_id, rsrc_start, j, k;
6080 	uint16_t *ids;
6081 	int i, rc;
6082 	unsigned long longs;
6083 	unsigned long *bmask;
6084 	struct lpfc_rsrc_blks *rsrc_blks;
6085 	LPFC_MBOXQ_t *mbox;
6086 	uint32_t length;
6087 	struct lpfc_id_range *id_array = NULL;
6088 	void *virtaddr = NULL;
6089 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6090 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6091 	struct list_head *ext_blk_list;
6092 
6093 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6094 					    &rsrc_cnt,
6095 					    &rsrc_size);
6096 	if (unlikely(rc))
6097 		return -EIO;
6098 
6099 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6100 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6101 			"3009 No available Resource Extents "
6102 			"for resource type 0x%x: Count: 0x%x, "
6103 			"Size 0x%x\n", type, rsrc_cnt,
6104 			rsrc_size);
6105 		return -ENOMEM;
6106 	}
6107 
6108 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6109 			"2903 Post resource extents type-0x%x: "
6110 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6111 
6112 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6113 	if (!mbox)
6114 		return -ENOMEM;
6115 
6116 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6117 	if (unlikely(rc)) {
6118 		rc = -EIO;
6119 		goto err_exit;
6120 	}
6121 
6122 	/*
6123 	 * Figure out where the response is located.  Then get local pointers
6124 	 * to the response data.  The port does not guarantee to respond to
6125 	 * all extents counts request so update the local variable with the
6126 	 * allocated count from the port.
6127 	 */
6128 	if (emb == LPFC_SLI4_MBX_EMBED) {
6129 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6130 		id_array = &rsrc_ext->u.rsp.id[0];
6131 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6132 	} else {
6133 		virtaddr = mbox->sge_array->addr[0];
6134 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6135 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6136 		id_array = &n_rsrc->id;
6137 	}
6138 
6139 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6140 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6141 
6142 	/*
6143 	 * Based on the resource size and count, correct the base and max
6144 	 * resource values.
6145 	 */
6146 	length = sizeof(struct lpfc_rsrc_blks);
6147 	switch (type) {
6148 	case LPFC_RSC_TYPE_FCOE_RPI:
6149 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6150 						   sizeof(unsigned long),
6151 						   GFP_KERNEL);
6152 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6153 			rc = -ENOMEM;
6154 			goto err_exit;
6155 		}
6156 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6157 						 sizeof(uint16_t),
6158 						 GFP_KERNEL);
6159 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6160 			kfree(phba->sli4_hba.rpi_bmask);
6161 			rc = -ENOMEM;
6162 			goto err_exit;
6163 		}
6164 
6165 		/*
6166 		 * The next_rpi was initialized with the maximum available
6167 		 * count but the port may allocate a smaller number.  Catch
6168 		 * that case and update the next_rpi.
6169 		 */
6170 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6171 
6172 		/* Initialize local ptrs for common extent processing later. */
6173 		bmask = phba->sli4_hba.rpi_bmask;
6174 		ids = phba->sli4_hba.rpi_ids;
6175 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6176 		break;
6177 	case LPFC_RSC_TYPE_FCOE_VPI:
6178 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6179 					  GFP_KERNEL);
6180 		if (unlikely(!phba->vpi_bmask)) {
6181 			rc = -ENOMEM;
6182 			goto err_exit;
6183 		}
6184 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6185 					 GFP_KERNEL);
6186 		if (unlikely(!phba->vpi_ids)) {
6187 			kfree(phba->vpi_bmask);
6188 			rc = -ENOMEM;
6189 			goto err_exit;
6190 		}
6191 
6192 		/* Initialize local ptrs for common extent processing later. */
6193 		bmask = phba->vpi_bmask;
6194 		ids = phba->vpi_ids;
6195 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6196 		break;
6197 	case LPFC_RSC_TYPE_FCOE_XRI:
6198 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6199 						   sizeof(unsigned long),
6200 						   GFP_KERNEL);
6201 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6202 			rc = -ENOMEM;
6203 			goto err_exit;
6204 		}
6205 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6206 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6207 						 sizeof(uint16_t),
6208 						 GFP_KERNEL);
6209 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6210 			kfree(phba->sli4_hba.xri_bmask);
6211 			rc = -ENOMEM;
6212 			goto err_exit;
6213 		}
6214 
6215 		/* Initialize local ptrs for common extent processing later. */
6216 		bmask = phba->sli4_hba.xri_bmask;
6217 		ids = phba->sli4_hba.xri_ids;
6218 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6219 		break;
6220 	case LPFC_RSC_TYPE_FCOE_VFI:
6221 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6222 						   sizeof(unsigned long),
6223 						   GFP_KERNEL);
6224 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6225 			rc = -ENOMEM;
6226 			goto err_exit;
6227 		}
6228 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6229 						 sizeof(uint16_t),
6230 						 GFP_KERNEL);
6231 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6232 			kfree(phba->sli4_hba.vfi_bmask);
6233 			rc = -ENOMEM;
6234 			goto err_exit;
6235 		}
6236 
6237 		/* Initialize local ptrs for common extent processing later. */
6238 		bmask = phba->sli4_hba.vfi_bmask;
6239 		ids = phba->sli4_hba.vfi_ids;
6240 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6241 		break;
6242 	default:
6243 		/* Unsupported Opcode.  Fail call. */
6244 		id_array = NULL;
6245 		bmask = NULL;
6246 		ids = NULL;
6247 		ext_blk_list = NULL;
6248 		goto err_exit;
6249 	}
6250 
6251 	/*
6252 	 * Complete initializing the extent configuration with the
6253 	 * allocated ids assigned to this function.  The bitmask serves
6254 	 * as an index into the array and manages the available ids.  The
6255 	 * array just stores the ids communicated to the port via the wqes.
6256 	 */
6257 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6258 		if ((i % 2) == 0)
6259 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6260 					 &id_array[k]);
6261 		else
6262 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6263 					 &id_array[k]);
6264 
6265 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6266 		if (unlikely(!rsrc_blks)) {
6267 			rc = -ENOMEM;
6268 			kfree(bmask);
6269 			kfree(ids);
6270 			goto err_exit;
6271 		}
6272 		rsrc_blks->rsrc_start = rsrc_id;
6273 		rsrc_blks->rsrc_size = rsrc_size;
6274 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6275 		rsrc_start = rsrc_id;
6276 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6277 			phba->sli4_hba.io_xri_start = rsrc_start +
6278 				lpfc_sli4_get_iocb_cnt(phba);
6279 		}
6280 
6281 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6282 			ids[j] = rsrc_id;
6283 			rsrc_id++;
6284 			j++;
6285 		}
6286 		/* Entire word processed.  Get next word.*/
6287 		if ((i % 2) == 1)
6288 			k++;
6289 	}
6290  err_exit:
6291 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6292 	return rc;
6293 }
6294 
6295 
6296 
6297 /**
6298  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6299  * @phba: Pointer to HBA context object.
6300  * @type: the extent's type.
6301  *
6302  * This function deallocates all extents of a particular resource type.
6303  * SLI4 does not allow for deallocating a particular extent range.  It
6304  * is the caller's responsibility to release all kernel memory resources.
6305  **/
6306 static int
6307 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6308 {
6309 	int rc;
6310 	uint32_t length, mbox_tmo = 0;
6311 	LPFC_MBOXQ_t *mbox;
6312 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6313 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6314 
6315 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6316 	if (!mbox)
6317 		return -ENOMEM;
6318 
6319 	/*
6320 	 * This function sends an embedded mailbox because it only sends the
6321 	 * the resource type.  All extents of this type are released by the
6322 	 * port.
6323 	 */
6324 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6325 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6326 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6327 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6328 			 length, LPFC_SLI4_MBX_EMBED);
6329 
6330 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6331 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6332 					LPFC_SLI4_MBX_EMBED);
6333 	if (unlikely(rc)) {
6334 		rc = -EIO;
6335 		goto out_free_mbox;
6336 	}
6337 	if (!phba->sli4_hba.intr_enable)
6338 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6339 	else {
6340 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6341 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6342 	}
6343 	if (unlikely(rc)) {
6344 		rc = -EIO;
6345 		goto out_free_mbox;
6346 	}
6347 
6348 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6349 	if (bf_get(lpfc_mbox_hdr_status,
6350 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6351 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6352 				"2919 Failed to release resource extents "
6353 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6354 				"Resource memory not released.\n",
6355 				type,
6356 				bf_get(lpfc_mbox_hdr_status,
6357 				    &dealloc_rsrc->header.cfg_shdr.response),
6358 				bf_get(lpfc_mbox_hdr_add_status,
6359 				    &dealloc_rsrc->header.cfg_shdr.response));
6360 		rc = -EIO;
6361 		goto out_free_mbox;
6362 	}
6363 
6364 	/* Release kernel memory resources for the specific type. */
6365 	switch (type) {
6366 	case LPFC_RSC_TYPE_FCOE_VPI:
6367 		kfree(phba->vpi_bmask);
6368 		kfree(phba->vpi_ids);
6369 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6370 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6371 				    &phba->lpfc_vpi_blk_list, list) {
6372 			list_del_init(&rsrc_blk->list);
6373 			kfree(rsrc_blk);
6374 		}
6375 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6376 		break;
6377 	case LPFC_RSC_TYPE_FCOE_XRI:
6378 		kfree(phba->sli4_hba.xri_bmask);
6379 		kfree(phba->sli4_hba.xri_ids);
6380 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6381 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6382 			list_del_init(&rsrc_blk->list);
6383 			kfree(rsrc_blk);
6384 		}
6385 		break;
6386 	case LPFC_RSC_TYPE_FCOE_VFI:
6387 		kfree(phba->sli4_hba.vfi_bmask);
6388 		kfree(phba->sli4_hba.vfi_ids);
6389 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6390 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6391 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6392 			list_del_init(&rsrc_blk->list);
6393 			kfree(rsrc_blk);
6394 		}
6395 		break;
6396 	case LPFC_RSC_TYPE_FCOE_RPI:
6397 		/* RPI bitmask and physical id array are cleaned up earlier. */
6398 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6399 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6400 			list_del_init(&rsrc_blk->list);
6401 			kfree(rsrc_blk);
6402 		}
6403 		break;
6404 	default:
6405 		break;
6406 	}
6407 
6408 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6409 
6410  out_free_mbox:
6411 	mempool_free(mbox, phba->mbox_mem_pool);
6412 	return rc;
6413 }
6414 
6415 static void
6416 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6417 		  uint32_t feature)
6418 {
6419 	uint32_t len;
6420 
6421 	len = sizeof(struct lpfc_mbx_set_feature) -
6422 		sizeof(struct lpfc_sli4_cfg_mhdr);
6423 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6424 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6425 			 LPFC_SLI4_MBX_EMBED);
6426 
6427 	switch (feature) {
6428 	case LPFC_SET_UE_RECOVERY:
6429 		bf_set(lpfc_mbx_set_feature_UER,
6430 		       &mbox->u.mqe.un.set_feature, 1);
6431 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6432 		mbox->u.mqe.un.set_feature.param_len = 8;
6433 		break;
6434 	case LPFC_SET_MDS_DIAGS:
6435 		bf_set(lpfc_mbx_set_feature_mds,
6436 		       &mbox->u.mqe.un.set_feature, 1);
6437 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6438 		       &mbox->u.mqe.un.set_feature, 1);
6439 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6440 		mbox->u.mqe.un.set_feature.param_len = 8;
6441 		break;
6442 	case LPFC_SET_DUAL_DUMP:
6443 		bf_set(lpfc_mbx_set_feature_dd,
6444 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6445 		bf_set(lpfc_mbx_set_feature_ddquery,
6446 		       &mbox->u.mqe.un.set_feature, 0);
6447 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6448 		mbox->u.mqe.un.set_feature.param_len = 4;
6449 		break;
6450 	}
6451 
6452 	return;
6453 }
6454 
6455 /**
6456  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6457  * @phba: Pointer to HBA context object.
6458  *
6459  * Disable FW logging into host memory on the adapter. To
6460  * be done before reading logs from the host memory.
6461  **/
6462 void
6463 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6464 {
6465 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6466 
6467 	spin_lock_irq(&phba->hbalock);
6468 	ras_fwlog->state = INACTIVE;
6469 	spin_unlock_irq(&phba->hbalock);
6470 
6471 	/* Disable FW logging to host memory */
6472 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6473 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6474 
6475 	/* Wait 10ms for firmware to stop using DMA buffer */
6476 	usleep_range(10 * 1000, 20 * 1000);
6477 }
6478 
6479 /**
6480  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6481  * @phba: Pointer to HBA context object.
6482  *
6483  * This function is called to free memory allocated for RAS FW logging
6484  * support in the driver.
6485  **/
6486 void
6487 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6488 {
6489 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6490 	struct lpfc_dmabuf *dmabuf, *next;
6491 
6492 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6493 		list_for_each_entry_safe(dmabuf, next,
6494 				    &ras_fwlog->fwlog_buff_list,
6495 				    list) {
6496 			list_del(&dmabuf->list);
6497 			dma_free_coherent(&phba->pcidev->dev,
6498 					  LPFC_RAS_MAX_ENTRY_SIZE,
6499 					  dmabuf->virt, dmabuf->phys);
6500 			kfree(dmabuf);
6501 		}
6502 	}
6503 
6504 	if (ras_fwlog->lwpd.virt) {
6505 		dma_free_coherent(&phba->pcidev->dev,
6506 				  sizeof(uint32_t) * 2,
6507 				  ras_fwlog->lwpd.virt,
6508 				  ras_fwlog->lwpd.phys);
6509 		ras_fwlog->lwpd.virt = NULL;
6510 	}
6511 
6512 	spin_lock_irq(&phba->hbalock);
6513 	ras_fwlog->state = INACTIVE;
6514 	spin_unlock_irq(&phba->hbalock);
6515 }
6516 
6517 /**
6518  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6519  * @phba: Pointer to HBA context object.
6520  * @fwlog_buff_count: Count of buffers to be created.
6521  *
6522  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6523  * to update FW log is posted to the adapter.
6524  * Buffer count is calculated based on module param ras_fwlog_buffsize
6525  * Size of each buffer posted to FW is 64K.
6526  **/
6527 
6528 static int
6529 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6530 			uint32_t fwlog_buff_count)
6531 {
6532 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6533 	struct lpfc_dmabuf *dmabuf;
6534 	int rc = 0, i = 0;
6535 
6536 	/* Initialize List */
6537 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6538 
6539 	/* Allocate memory for the LWPD */
6540 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6541 					    sizeof(uint32_t) * 2,
6542 					    &ras_fwlog->lwpd.phys,
6543 					    GFP_KERNEL);
6544 	if (!ras_fwlog->lwpd.virt) {
6545 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6546 				"6185 LWPD Memory Alloc Failed\n");
6547 
6548 		return -ENOMEM;
6549 	}
6550 
6551 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6552 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6553 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6554 				 GFP_KERNEL);
6555 		if (!dmabuf) {
6556 			rc = -ENOMEM;
6557 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6558 					"6186 Memory Alloc failed FW logging");
6559 			goto free_mem;
6560 		}
6561 
6562 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6563 						  LPFC_RAS_MAX_ENTRY_SIZE,
6564 						  &dmabuf->phys, GFP_KERNEL);
6565 		if (!dmabuf->virt) {
6566 			kfree(dmabuf);
6567 			rc = -ENOMEM;
6568 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6569 					"6187 DMA Alloc Failed FW logging");
6570 			goto free_mem;
6571 		}
6572 		dmabuf->buffer_tag = i;
6573 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6574 	}
6575 
6576 free_mem:
6577 	if (rc)
6578 		lpfc_sli4_ras_dma_free(phba);
6579 
6580 	return rc;
6581 }
6582 
6583 /**
6584  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6585  * @phba: pointer to lpfc hba data structure.
6586  * @pmb: pointer to the driver internal queue element for mailbox command.
6587  *
6588  * Completion handler for driver's RAS MBX command to the device.
6589  **/
6590 static void
6591 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6592 {
6593 	MAILBOX_t *mb;
6594 	union lpfc_sli4_cfg_shdr *shdr;
6595 	uint32_t shdr_status, shdr_add_status;
6596 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6597 
6598 	mb = &pmb->u.mb;
6599 
6600 	shdr = (union lpfc_sli4_cfg_shdr *)
6601 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6602 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6603 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6604 
6605 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6606 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6607 				"6188 FW LOG mailbox "
6608 				"completed with status x%x add_status x%x,"
6609 				" mbx status x%x\n",
6610 				shdr_status, shdr_add_status, mb->mbxStatus);
6611 
6612 		ras_fwlog->ras_hwsupport = false;
6613 		goto disable_ras;
6614 	}
6615 
6616 	spin_lock_irq(&phba->hbalock);
6617 	ras_fwlog->state = ACTIVE;
6618 	spin_unlock_irq(&phba->hbalock);
6619 	mempool_free(pmb, phba->mbox_mem_pool);
6620 
6621 	return;
6622 
6623 disable_ras:
6624 	/* Free RAS DMA memory */
6625 	lpfc_sli4_ras_dma_free(phba);
6626 	mempool_free(pmb, phba->mbox_mem_pool);
6627 }
6628 
6629 /**
6630  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
6631  * @phba: pointer to lpfc hba data structure.
6632  * @fwlog_level: Logging verbosity level.
6633  * @fwlog_enable: Enable/Disable logging.
6634  *
6635  * Initialize memory and post mailbox command to enable FW logging in host
6636  * memory.
6637  **/
6638 int
6639 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
6640 			 uint32_t fwlog_level,
6641 			 uint32_t fwlog_enable)
6642 {
6643 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6644 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
6645 	struct lpfc_dmabuf *dmabuf;
6646 	LPFC_MBOXQ_t *mbox;
6647 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
6648 	int rc = 0;
6649 
6650 	spin_lock_irq(&phba->hbalock);
6651 	ras_fwlog->state = INACTIVE;
6652 	spin_unlock_irq(&phba->hbalock);
6653 
6654 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
6655 			  phba->cfg_ras_fwlog_buffsize);
6656 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
6657 
6658 	/*
6659 	 * If re-enabling FW logging support use earlier allocated
6660 	 * DMA buffers while posting MBX command.
6661 	 **/
6662 	if (!ras_fwlog->lwpd.virt) {
6663 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
6664 		if (rc) {
6665 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6666 					"6189 FW Log Memory Allocation Failed");
6667 			return rc;
6668 		}
6669 	}
6670 
6671 	/* Setup Mailbox command */
6672 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6673 	if (!mbox) {
6674 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6675 				"6190 RAS MBX Alloc Failed");
6676 		rc = -ENOMEM;
6677 		goto mem_free;
6678 	}
6679 
6680 	ras_fwlog->fw_loglevel = fwlog_level;
6681 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
6682 		sizeof(struct lpfc_sli4_cfg_mhdr));
6683 
6684 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
6685 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
6686 			 len, LPFC_SLI4_MBX_EMBED);
6687 
6688 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
6689 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
6690 	       fwlog_enable);
6691 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
6692 	       ras_fwlog->fw_loglevel);
6693 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
6694 	       ras_fwlog->fw_buffcount);
6695 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
6696 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
6697 
6698 	/* Update DMA buffer address */
6699 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
6700 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
6701 
6702 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
6703 			putPaddrLow(dmabuf->phys);
6704 
6705 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
6706 			putPaddrHigh(dmabuf->phys);
6707 	}
6708 
6709 	/* Update LPWD address */
6710 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
6711 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
6712 
6713 	spin_lock_irq(&phba->hbalock);
6714 	ras_fwlog->state = REG_INPROGRESS;
6715 	spin_unlock_irq(&phba->hbalock);
6716 	mbox->vport = phba->pport;
6717 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
6718 
6719 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
6720 
6721 	if (rc == MBX_NOT_FINISHED) {
6722 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6723 				"6191 FW-Log Mailbox failed. "
6724 				"status %d mbxStatus : x%x", rc,
6725 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
6726 		mempool_free(mbox, phba->mbox_mem_pool);
6727 		rc = -EIO;
6728 		goto mem_free;
6729 	} else
6730 		rc = 0;
6731 mem_free:
6732 	if (rc)
6733 		lpfc_sli4_ras_dma_free(phba);
6734 
6735 	return rc;
6736 }
6737 
6738 /**
6739  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
6740  * @phba: Pointer to HBA context object.
6741  *
6742  * Check if RAS is supported on the adapter and initialize it.
6743  **/
6744 void
6745 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
6746 {
6747 	/* Check RAS FW Log needs to be enabled or not */
6748 	if (lpfc_check_fwlog_support(phba))
6749 		return;
6750 
6751 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
6752 				 LPFC_RAS_ENABLE_LOGGING);
6753 }
6754 
6755 /**
6756  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
6757  * @phba: Pointer to HBA context object.
6758  *
6759  * This function allocates all SLI4 resource identifiers.
6760  **/
6761 int
6762 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
6763 {
6764 	int i, rc, error = 0;
6765 	uint16_t count, base;
6766 	unsigned long longs;
6767 
6768 	if (!phba->sli4_hba.rpi_hdrs_in_use)
6769 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
6770 	if (phba->sli4_hba.extents_in_use) {
6771 		/*
6772 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
6773 		 * resource extent count must be read and allocated before
6774 		 * provisioning the resource id arrays.
6775 		 */
6776 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6777 		    LPFC_IDX_RSRC_RDY) {
6778 			/*
6779 			 * Extent-based resources are set - the driver could
6780 			 * be in a port reset. Figure out if any corrective
6781 			 * actions need to be taken.
6782 			 */
6783 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6784 						 LPFC_RSC_TYPE_FCOE_VFI);
6785 			if (rc != 0)
6786 				error++;
6787 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6788 						 LPFC_RSC_TYPE_FCOE_VPI);
6789 			if (rc != 0)
6790 				error++;
6791 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6792 						 LPFC_RSC_TYPE_FCOE_XRI);
6793 			if (rc != 0)
6794 				error++;
6795 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6796 						 LPFC_RSC_TYPE_FCOE_RPI);
6797 			if (rc != 0)
6798 				error++;
6799 
6800 			/*
6801 			 * It's possible that the number of resources
6802 			 * provided to this port instance changed between
6803 			 * resets.  Detect this condition and reallocate
6804 			 * resources.  Otherwise, there is no action.
6805 			 */
6806 			if (error) {
6807 				lpfc_printf_log(phba, KERN_INFO,
6808 						LOG_MBOX | LOG_INIT,
6809 						"2931 Detected extent resource "
6810 						"change.  Reallocating all "
6811 						"extents.\n");
6812 				rc = lpfc_sli4_dealloc_extent(phba,
6813 						 LPFC_RSC_TYPE_FCOE_VFI);
6814 				rc = lpfc_sli4_dealloc_extent(phba,
6815 						 LPFC_RSC_TYPE_FCOE_VPI);
6816 				rc = lpfc_sli4_dealloc_extent(phba,
6817 						 LPFC_RSC_TYPE_FCOE_XRI);
6818 				rc = lpfc_sli4_dealloc_extent(phba,
6819 						 LPFC_RSC_TYPE_FCOE_RPI);
6820 			} else
6821 				return 0;
6822 		}
6823 
6824 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6825 		if (unlikely(rc))
6826 			goto err_exit;
6827 
6828 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6829 		if (unlikely(rc))
6830 			goto err_exit;
6831 
6832 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6833 		if (unlikely(rc))
6834 			goto err_exit;
6835 
6836 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6837 		if (unlikely(rc))
6838 			goto err_exit;
6839 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6840 		       LPFC_IDX_RSRC_RDY);
6841 		return rc;
6842 	} else {
6843 		/*
6844 		 * The port does not support resource extents.  The XRI, VPI,
6845 		 * VFI, RPI resource ids were determined from READ_CONFIG.
6846 		 * Just allocate the bitmasks and provision the resource id
6847 		 * arrays.  If a port reset is active, the resources don't
6848 		 * need any action - just exit.
6849 		 */
6850 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6851 		    LPFC_IDX_RSRC_RDY) {
6852 			lpfc_sli4_dealloc_resource_identifiers(phba);
6853 			lpfc_sli4_remove_rpis(phba);
6854 		}
6855 		/* RPIs. */
6856 		count = phba->sli4_hba.max_cfg_param.max_rpi;
6857 		if (count <= 0) {
6858 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6859 					"3279 Invalid provisioning of "
6860 					"rpi:%d\n", count);
6861 			rc = -EINVAL;
6862 			goto err_exit;
6863 		}
6864 		base = phba->sli4_hba.max_cfg_param.rpi_base;
6865 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6866 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6867 						   sizeof(unsigned long),
6868 						   GFP_KERNEL);
6869 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6870 			rc = -ENOMEM;
6871 			goto err_exit;
6872 		}
6873 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
6874 						 GFP_KERNEL);
6875 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6876 			rc = -ENOMEM;
6877 			goto free_rpi_bmask;
6878 		}
6879 
6880 		for (i = 0; i < count; i++)
6881 			phba->sli4_hba.rpi_ids[i] = base + i;
6882 
6883 		/* VPIs. */
6884 		count = phba->sli4_hba.max_cfg_param.max_vpi;
6885 		if (count <= 0) {
6886 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6887 					"3280 Invalid provisioning of "
6888 					"vpi:%d\n", count);
6889 			rc = -EINVAL;
6890 			goto free_rpi_ids;
6891 		}
6892 		base = phba->sli4_hba.max_cfg_param.vpi_base;
6893 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6894 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6895 					  GFP_KERNEL);
6896 		if (unlikely(!phba->vpi_bmask)) {
6897 			rc = -ENOMEM;
6898 			goto free_rpi_ids;
6899 		}
6900 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
6901 					GFP_KERNEL);
6902 		if (unlikely(!phba->vpi_ids)) {
6903 			rc = -ENOMEM;
6904 			goto free_vpi_bmask;
6905 		}
6906 
6907 		for (i = 0; i < count; i++)
6908 			phba->vpi_ids[i] = base + i;
6909 
6910 		/* XRIs. */
6911 		count = phba->sli4_hba.max_cfg_param.max_xri;
6912 		if (count <= 0) {
6913 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6914 					"3281 Invalid provisioning of "
6915 					"xri:%d\n", count);
6916 			rc = -EINVAL;
6917 			goto free_vpi_ids;
6918 		}
6919 		base = phba->sli4_hba.max_cfg_param.xri_base;
6920 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6921 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6922 						   sizeof(unsigned long),
6923 						   GFP_KERNEL);
6924 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6925 			rc = -ENOMEM;
6926 			goto free_vpi_ids;
6927 		}
6928 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6929 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
6930 						 GFP_KERNEL);
6931 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6932 			rc = -ENOMEM;
6933 			goto free_xri_bmask;
6934 		}
6935 
6936 		for (i = 0; i < count; i++)
6937 			phba->sli4_hba.xri_ids[i] = base + i;
6938 
6939 		/* VFIs. */
6940 		count = phba->sli4_hba.max_cfg_param.max_vfi;
6941 		if (count <= 0) {
6942 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6943 					"3282 Invalid provisioning of "
6944 					"vfi:%d\n", count);
6945 			rc = -EINVAL;
6946 			goto free_xri_ids;
6947 		}
6948 		base = phba->sli4_hba.max_cfg_param.vfi_base;
6949 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6950 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6951 						   sizeof(unsigned long),
6952 						   GFP_KERNEL);
6953 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6954 			rc = -ENOMEM;
6955 			goto free_xri_ids;
6956 		}
6957 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
6958 						 GFP_KERNEL);
6959 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6960 			rc = -ENOMEM;
6961 			goto free_vfi_bmask;
6962 		}
6963 
6964 		for (i = 0; i < count; i++)
6965 			phba->sli4_hba.vfi_ids[i] = base + i;
6966 
6967 		/*
6968 		 * Mark all resources ready.  An HBA reset doesn't need
6969 		 * to reset the initialization.
6970 		 */
6971 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6972 		       LPFC_IDX_RSRC_RDY);
6973 		return 0;
6974 	}
6975 
6976  free_vfi_bmask:
6977 	kfree(phba->sli4_hba.vfi_bmask);
6978 	phba->sli4_hba.vfi_bmask = NULL;
6979  free_xri_ids:
6980 	kfree(phba->sli4_hba.xri_ids);
6981 	phba->sli4_hba.xri_ids = NULL;
6982  free_xri_bmask:
6983 	kfree(phba->sli4_hba.xri_bmask);
6984 	phba->sli4_hba.xri_bmask = NULL;
6985  free_vpi_ids:
6986 	kfree(phba->vpi_ids);
6987 	phba->vpi_ids = NULL;
6988  free_vpi_bmask:
6989 	kfree(phba->vpi_bmask);
6990 	phba->vpi_bmask = NULL;
6991  free_rpi_ids:
6992 	kfree(phba->sli4_hba.rpi_ids);
6993 	phba->sli4_hba.rpi_ids = NULL;
6994  free_rpi_bmask:
6995 	kfree(phba->sli4_hba.rpi_bmask);
6996 	phba->sli4_hba.rpi_bmask = NULL;
6997  err_exit:
6998 	return rc;
6999 }
7000 
7001 /**
7002  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
7003  * @phba: Pointer to HBA context object.
7004  *
7005  * This function allocates the number of elements for the specified
7006  * resource type.
7007  **/
7008 int
7009 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7010 {
7011 	if (phba->sli4_hba.extents_in_use) {
7012 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7013 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7014 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7015 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7016 	} else {
7017 		kfree(phba->vpi_bmask);
7018 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
7019 		kfree(phba->vpi_ids);
7020 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7021 		kfree(phba->sli4_hba.xri_bmask);
7022 		kfree(phba->sli4_hba.xri_ids);
7023 		kfree(phba->sli4_hba.vfi_bmask);
7024 		kfree(phba->sli4_hba.vfi_ids);
7025 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7026 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7027 	}
7028 
7029 	return 0;
7030 }
7031 
7032 /**
7033  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7034  * @phba: Pointer to HBA context object.
7035  * @type: The resource extent type.
7036  * @extnt_cnt: buffer to hold port extent count response
7037  * @extnt_size: buffer to hold port extent size response.
7038  *
7039  * This function calls the port to read the host allocated extents
7040  * for a particular type.
7041  **/
7042 int
7043 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7044 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
7045 {
7046 	bool emb;
7047 	int rc = 0;
7048 	uint16_t curr_blks = 0;
7049 	uint32_t req_len, emb_len;
7050 	uint32_t alloc_len, mbox_tmo;
7051 	struct list_head *blk_list_head;
7052 	struct lpfc_rsrc_blks *rsrc_blk;
7053 	LPFC_MBOXQ_t *mbox;
7054 	void *virtaddr = NULL;
7055 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7056 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7057 	union  lpfc_sli4_cfg_shdr *shdr;
7058 
7059 	switch (type) {
7060 	case LPFC_RSC_TYPE_FCOE_VPI:
7061 		blk_list_head = &phba->lpfc_vpi_blk_list;
7062 		break;
7063 	case LPFC_RSC_TYPE_FCOE_XRI:
7064 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7065 		break;
7066 	case LPFC_RSC_TYPE_FCOE_VFI:
7067 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7068 		break;
7069 	case LPFC_RSC_TYPE_FCOE_RPI:
7070 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7071 		break;
7072 	default:
7073 		return -EIO;
7074 	}
7075 
7076 	/* Count the number of extents currently allocatd for this type. */
7077 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
7078 		if (curr_blks == 0) {
7079 			/*
7080 			 * The GET_ALLOCATED mailbox does not return the size,
7081 			 * just the count.  The size should be just the size
7082 			 * stored in the current allocated block and all sizes
7083 			 * for an extent type are the same so set the return
7084 			 * value now.
7085 			 */
7086 			*extnt_size = rsrc_blk->rsrc_size;
7087 		}
7088 		curr_blks++;
7089 	}
7090 
7091 	/*
7092 	 * Calculate the size of an embedded mailbox.  The uint32_t
7093 	 * accounts for extents-specific word.
7094 	 */
7095 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7096 		sizeof(uint32_t);
7097 
7098 	/*
7099 	 * Presume the allocation and response will fit into an embedded
7100 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7101 	 */
7102 	emb = LPFC_SLI4_MBX_EMBED;
7103 	req_len = emb_len;
7104 	if (req_len > emb_len) {
7105 		req_len = curr_blks * sizeof(uint16_t) +
7106 			sizeof(union lpfc_sli4_cfg_shdr) +
7107 			sizeof(uint32_t);
7108 		emb = LPFC_SLI4_MBX_NEMBED;
7109 	}
7110 
7111 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7112 	if (!mbox)
7113 		return -ENOMEM;
7114 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7115 
7116 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7117 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7118 				     req_len, emb);
7119 	if (alloc_len < req_len) {
7120 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7121 			"2983 Allocated DMA memory size (x%x) is "
7122 			"less than the requested DMA memory "
7123 			"size (x%x)\n", alloc_len, req_len);
7124 		rc = -ENOMEM;
7125 		goto err_exit;
7126 	}
7127 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7128 	if (unlikely(rc)) {
7129 		rc = -EIO;
7130 		goto err_exit;
7131 	}
7132 
7133 	if (!phba->sli4_hba.intr_enable)
7134 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7135 	else {
7136 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7137 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7138 	}
7139 
7140 	if (unlikely(rc)) {
7141 		rc = -EIO;
7142 		goto err_exit;
7143 	}
7144 
7145 	/*
7146 	 * Figure out where the response is located.  Then get local pointers
7147 	 * to the response data.  The port does not guarantee to respond to
7148 	 * all extents counts request so update the local variable with the
7149 	 * allocated count from the port.
7150 	 */
7151 	if (emb == LPFC_SLI4_MBX_EMBED) {
7152 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7153 		shdr = &rsrc_ext->header.cfg_shdr;
7154 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7155 	} else {
7156 		virtaddr = mbox->sge_array->addr[0];
7157 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7158 		shdr = &n_rsrc->cfg_shdr;
7159 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7160 	}
7161 
7162 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7163 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7164 			"2984 Failed to read allocated resources "
7165 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7166 			type,
7167 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7168 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7169 		rc = -EIO;
7170 		goto err_exit;
7171 	}
7172  err_exit:
7173 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7174 	return rc;
7175 }
7176 
7177 /**
7178  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7179  * @phba: pointer to lpfc hba data structure.
7180  * @sgl_list: linked link of sgl buffers to post
7181  * @cnt: number of linked list buffers
7182  *
7183  * This routine walks the list of buffers that have been allocated and
7184  * repost them to the port by using SGL block post. This is needed after a
7185  * pci_function_reset/warm_start or start. It attempts to construct blocks
7186  * of buffer sgls which contains contiguous xris and uses the non-embedded
7187  * SGL block post mailbox commands to post them to the port. For single
7188  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7189  * mailbox command for posting.
7190  *
7191  * Returns: 0 = success, non-zero failure.
7192  **/
7193 static int
7194 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7195 			  struct list_head *sgl_list, int cnt)
7196 {
7197 	struct lpfc_sglq *sglq_entry = NULL;
7198 	struct lpfc_sglq *sglq_entry_next = NULL;
7199 	struct lpfc_sglq *sglq_entry_first = NULL;
7200 	int status, total_cnt;
7201 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7202 	int last_xritag = NO_XRI;
7203 	LIST_HEAD(prep_sgl_list);
7204 	LIST_HEAD(blck_sgl_list);
7205 	LIST_HEAD(allc_sgl_list);
7206 	LIST_HEAD(post_sgl_list);
7207 	LIST_HEAD(free_sgl_list);
7208 
7209 	spin_lock_irq(&phba->hbalock);
7210 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7211 	list_splice_init(sgl_list, &allc_sgl_list);
7212 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7213 	spin_unlock_irq(&phba->hbalock);
7214 
7215 	total_cnt = cnt;
7216 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7217 				 &allc_sgl_list, list) {
7218 		list_del_init(&sglq_entry->list);
7219 		block_cnt++;
7220 		if ((last_xritag != NO_XRI) &&
7221 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7222 			/* a hole in xri block, form a sgl posting block */
7223 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7224 			post_cnt = block_cnt - 1;
7225 			/* prepare list for next posting block */
7226 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7227 			block_cnt = 1;
7228 		} else {
7229 			/* prepare list for next posting block */
7230 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7231 			/* enough sgls for non-embed sgl mbox command */
7232 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7233 				list_splice_init(&prep_sgl_list,
7234 						 &blck_sgl_list);
7235 				post_cnt = block_cnt;
7236 				block_cnt = 0;
7237 			}
7238 		}
7239 		num_posted++;
7240 
7241 		/* keep track of last sgl's xritag */
7242 		last_xritag = sglq_entry->sli4_xritag;
7243 
7244 		/* end of repost sgl list condition for buffers */
7245 		if (num_posted == total_cnt) {
7246 			if (post_cnt == 0) {
7247 				list_splice_init(&prep_sgl_list,
7248 						 &blck_sgl_list);
7249 				post_cnt = block_cnt;
7250 			} else if (block_cnt == 1) {
7251 				status = lpfc_sli4_post_sgl(phba,
7252 						sglq_entry->phys, 0,
7253 						sglq_entry->sli4_xritag);
7254 				if (!status) {
7255 					/* successful, put sgl to posted list */
7256 					list_add_tail(&sglq_entry->list,
7257 						      &post_sgl_list);
7258 				} else {
7259 					/* Failure, put sgl to free list */
7260 					lpfc_printf_log(phba, KERN_WARNING,
7261 						LOG_SLI,
7262 						"3159 Failed to post "
7263 						"sgl, xritag:x%x\n",
7264 						sglq_entry->sli4_xritag);
7265 					list_add_tail(&sglq_entry->list,
7266 						      &free_sgl_list);
7267 					total_cnt--;
7268 				}
7269 			}
7270 		}
7271 
7272 		/* continue until a nembed page worth of sgls */
7273 		if (post_cnt == 0)
7274 			continue;
7275 
7276 		/* post the buffer list sgls as a block */
7277 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7278 						 post_cnt);
7279 
7280 		if (!status) {
7281 			/* success, put sgl list to posted sgl list */
7282 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7283 		} else {
7284 			/* Failure, put sgl list to free sgl list */
7285 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7286 							    struct lpfc_sglq,
7287 							    list);
7288 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7289 					"3160 Failed to post sgl-list, "
7290 					"xritag:x%x-x%x\n",
7291 					sglq_entry_first->sli4_xritag,
7292 					(sglq_entry_first->sli4_xritag +
7293 					 post_cnt - 1));
7294 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7295 			total_cnt -= post_cnt;
7296 		}
7297 
7298 		/* don't reset xirtag due to hole in xri block */
7299 		if (block_cnt == 0)
7300 			last_xritag = NO_XRI;
7301 
7302 		/* reset sgl post count for next round of posting */
7303 		post_cnt = 0;
7304 	}
7305 
7306 	/* free the sgls failed to post */
7307 	lpfc_free_sgl_list(phba, &free_sgl_list);
7308 
7309 	/* push sgls posted to the available list */
7310 	if (!list_empty(&post_sgl_list)) {
7311 		spin_lock_irq(&phba->hbalock);
7312 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7313 		list_splice_init(&post_sgl_list, sgl_list);
7314 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7315 		spin_unlock_irq(&phba->hbalock);
7316 	} else {
7317 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7318 				"3161 Failure to post sgl to port.\n");
7319 		return -EIO;
7320 	}
7321 
7322 	/* return the number of XRIs actually posted */
7323 	return total_cnt;
7324 }
7325 
7326 /**
7327  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7328  * @phba: pointer to lpfc hba data structure.
7329  *
7330  * This routine walks the list of nvme buffers that have been allocated and
7331  * repost them to the port by using SGL block post. This is needed after a
7332  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7333  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7334  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7335  *
7336  * Returns: 0 = success, non-zero failure.
7337  **/
7338 static int
7339 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7340 {
7341 	LIST_HEAD(post_nblist);
7342 	int num_posted, rc = 0;
7343 
7344 	/* get all NVME buffers need to repost to a local list */
7345 	lpfc_io_buf_flush(phba, &post_nblist);
7346 
7347 	/* post the list of nvme buffer sgls to port if available */
7348 	if (!list_empty(&post_nblist)) {
7349 		num_posted = lpfc_sli4_post_io_sgl_list(
7350 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7351 		/* failed to post any nvme buffer, return error */
7352 		if (num_posted == 0)
7353 			rc = -EIO;
7354 	}
7355 	return rc;
7356 }
7357 
7358 static void
7359 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7360 {
7361 	uint32_t len;
7362 
7363 	len = sizeof(struct lpfc_mbx_set_host_data) -
7364 		sizeof(struct lpfc_sli4_cfg_mhdr);
7365 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7366 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7367 			 LPFC_SLI4_MBX_EMBED);
7368 
7369 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7370 	mbox->u.mqe.un.set_host_data.param_len =
7371 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7372 	snprintf(mbox->u.mqe.un.set_host_data.data,
7373 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7374 		 "Linux %s v"LPFC_DRIVER_VERSION,
7375 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7376 }
7377 
7378 int
7379 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7380 		    struct lpfc_queue *drq, int count, int idx)
7381 {
7382 	int rc, i;
7383 	struct lpfc_rqe hrqe;
7384 	struct lpfc_rqe drqe;
7385 	struct lpfc_rqb *rqbp;
7386 	unsigned long flags;
7387 	struct rqb_dmabuf *rqb_buffer;
7388 	LIST_HEAD(rqb_buf_list);
7389 
7390 	rqbp = hrq->rqbp;
7391 	for (i = 0; i < count; i++) {
7392 		spin_lock_irqsave(&phba->hbalock, flags);
7393 		/* IF RQ is already full, don't bother */
7394 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7395 			spin_unlock_irqrestore(&phba->hbalock, flags);
7396 			break;
7397 		}
7398 		spin_unlock_irqrestore(&phba->hbalock, flags);
7399 
7400 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7401 		if (!rqb_buffer)
7402 			break;
7403 		rqb_buffer->hrq = hrq;
7404 		rqb_buffer->drq = drq;
7405 		rqb_buffer->idx = idx;
7406 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7407 	}
7408 
7409 	spin_lock_irqsave(&phba->hbalock, flags);
7410 	while (!list_empty(&rqb_buf_list)) {
7411 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7412 				 hbuf.list);
7413 
7414 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7415 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7416 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7417 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7418 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7419 		if (rc < 0) {
7420 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7421 					"6421 Cannot post to HRQ %d: %x %x %x "
7422 					"DRQ %x %x\n",
7423 					hrq->queue_id,
7424 					hrq->host_index,
7425 					hrq->hba_index,
7426 					hrq->entry_count,
7427 					drq->host_index,
7428 					drq->hba_index);
7429 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7430 		} else {
7431 			list_add_tail(&rqb_buffer->hbuf.list,
7432 				      &rqbp->rqb_buffer_list);
7433 			rqbp->buffer_count++;
7434 		}
7435 	}
7436 	spin_unlock_irqrestore(&phba->hbalock, flags);
7437 	return 1;
7438 }
7439 
7440 /**
7441  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7442  * @phba: pointer to lpfc hba data structure.
7443  *
7444  * This routine initializes the per-cq idle_stat to dynamically dictate
7445  * polling decisions.
7446  *
7447  * Return codes:
7448  *   None
7449  **/
7450 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
7451 {
7452 	int i;
7453 	struct lpfc_sli4_hdw_queue *hdwq;
7454 	struct lpfc_queue *cq;
7455 	struct lpfc_idle_stat *idle_stat;
7456 	u64 wall;
7457 
7458 	for_each_present_cpu(i) {
7459 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
7460 		cq = hdwq->io_cq;
7461 
7462 		/* Skip if we've already handled this cq's primary CPU */
7463 		if (cq->chann != i)
7464 			continue;
7465 
7466 		idle_stat = &phba->sli4_hba.idle_stat[i];
7467 
7468 		idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
7469 		idle_stat->prev_wall = wall;
7470 
7471 		if (phba->nvmet_support)
7472 			cq->poll_mode = LPFC_QUEUE_WORK;
7473 		else
7474 			cq->poll_mode = LPFC_IRQ_POLL;
7475 	}
7476 
7477 	if (!phba->nvmet_support)
7478 		schedule_delayed_work(&phba->idle_stat_delay_work,
7479 				      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
7480 }
7481 
7482 static void lpfc_sli4_dip(struct lpfc_hba *phba)
7483 {
7484 	uint32_t if_type;
7485 
7486 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
7487 	if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
7488 	    if_type == LPFC_SLI_INTF_IF_TYPE_6) {
7489 		struct lpfc_register reg_data;
7490 
7491 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
7492 			       &reg_data.word0))
7493 			return;
7494 
7495 		if (bf_get(lpfc_sliport_status_dip, &reg_data))
7496 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7497 					"2904 Firmware Dump Image Present"
7498 					" on Adapter");
7499 	}
7500 }
7501 
7502 /**
7503  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
7504  * @phba: Pointer to HBA context object.
7505  *
7506  * This function is the main SLI4 device initialization PCI function. This
7507  * function is called by the HBA initialization code, HBA reset code and
7508  * HBA error attention handler code. Caller is not required to hold any
7509  * locks.
7510  **/
7511 int
7512 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
7513 {
7514 	int rc, i, cnt, len, dd;
7515 	LPFC_MBOXQ_t *mboxq;
7516 	struct lpfc_mqe *mqe;
7517 	uint8_t *vpd;
7518 	uint32_t vpd_size;
7519 	uint32_t ftr_rsp = 0;
7520 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
7521 	struct lpfc_vport *vport = phba->pport;
7522 	struct lpfc_dmabuf *mp;
7523 	struct lpfc_rqb *rqbp;
7524 
7525 	/* Perform a PCI function reset to start from clean */
7526 	rc = lpfc_pci_function_reset(phba);
7527 	if (unlikely(rc))
7528 		return -ENODEV;
7529 
7530 	/* Check the HBA Host Status Register for readyness */
7531 	rc = lpfc_sli4_post_status_check(phba);
7532 	if (unlikely(rc))
7533 		return -ENODEV;
7534 	else {
7535 		spin_lock_irq(&phba->hbalock);
7536 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
7537 		spin_unlock_irq(&phba->hbalock);
7538 	}
7539 
7540 	lpfc_sli4_dip(phba);
7541 
7542 	/*
7543 	 * Allocate a single mailbox container for initializing the
7544 	 * port.
7545 	 */
7546 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7547 	if (!mboxq)
7548 		return -ENOMEM;
7549 
7550 	/* Issue READ_REV to collect vpd and FW information. */
7551 	vpd_size = SLI4_PAGE_SIZE;
7552 	vpd = kzalloc(vpd_size, GFP_KERNEL);
7553 	if (!vpd) {
7554 		rc = -ENOMEM;
7555 		goto out_free_mbox;
7556 	}
7557 
7558 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
7559 	if (unlikely(rc)) {
7560 		kfree(vpd);
7561 		goto out_free_mbox;
7562 	}
7563 
7564 	mqe = &mboxq->u.mqe;
7565 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
7566 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
7567 		phba->hba_flag |= HBA_FCOE_MODE;
7568 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
7569 	} else {
7570 		phba->hba_flag &= ~HBA_FCOE_MODE;
7571 	}
7572 
7573 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
7574 		LPFC_DCBX_CEE_MODE)
7575 		phba->hba_flag |= HBA_FIP_SUPPORT;
7576 	else
7577 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
7578 
7579 	phba->hba_flag &= ~HBA_IOQ_FLUSH;
7580 
7581 	if (phba->sli_rev != LPFC_SLI_REV4) {
7582 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7583 			"0376 READ_REV Error. SLI Level %d "
7584 			"FCoE enabled %d\n",
7585 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
7586 		rc = -EIO;
7587 		kfree(vpd);
7588 		goto out_free_mbox;
7589 	}
7590 
7591 	/*
7592 	 * Continue initialization with default values even if driver failed
7593 	 * to read FCoE param config regions, only read parameters if the
7594 	 * board is FCoE
7595 	 */
7596 	if (phba->hba_flag & HBA_FCOE_MODE &&
7597 	    lpfc_sli4_read_fcoe_params(phba))
7598 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
7599 			"2570 Failed to read FCoE parameters\n");
7600 
7601 	/*
7602 	 * Retrieve sli4 device physical port name, failure of doing it
7603 	 * is considered as non-fatal.
7604 	 */
7605 	rc = lpfc_sli4_retrieve_pport_name(phba);
7606 	if (!rc)
7607 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7608 				"3080 Successful retrieving SLI4 device "
7609 				"physical port name: %s.\n", phba->Port);
7610 
7611 	rc = lpfc_sli4_get_ctl_attr(phba);
7612 	if (!rc)
7613 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7614 				"8351 Successful retrieving SLI4 device "
7615 				"CTL ATTR\n");
7616 
7617 	/*
7618 	 * Evaluate the read rev and vpd data. Populate the driver
7619 	 * state with the results. If this routine fails, the failure
7620 	 * is not fatal as the driver will use generic values.
7621 	 */
7622 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
7623 	if (unlikely(!rc)) {
7624 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7625 				"0377 Error %d parsing vpd. "
7626 				"Using defaults.\n", rc);
7627 		rc = 0;
7628 	}
7629 	kfree(vpd);
7630 
7631 	/* Save information as VPD data */
7632 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
7633 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
7634 
7635 	/*
7636 	 * This is because first G7 ASIC doesn't support the standard
7637 	 * 0x5a NVME cmd descriptor type/subtype
7638 	 */
7639 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7640 			LPFC_SLI_INTF_IF_TYPE_6) &&
7641 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
7642 	    (phba->vpd.rev.smRev == 0) &&
7643 	    (phba->cfg_nvme_embed_cmd == 1))
7644 		phba->cfg_nvme_embed_cmd = 0;
7645 
7646 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
7647 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
7648 					 &mqe->un.read_rev);
7649 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
7650 				       &mqe->un.read_rev);
7651 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
7652 					    &mqe->un.read_rev);
7653 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
7654 					   &mqe->un.read_rev);
7655 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
7656 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
7657 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
7658 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
7659 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
7660 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
7661 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7662 			"(%d):0380 READ_REV Status x%x "
7663 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
7664 			mboxq->vport ? mboxq->vport->vpi : 0,
7665 			bf_get(lpfc_mqe_status, mqe),
7666 			phba->vpd.rev.opFwName,
7667 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
7668 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
7669 
7670 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7671 	    LPFC_SLI_INTF_IF_TYPE_0) {
7672 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
7673 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7674 		if (rc == MBX_SUCCESS) {
7675 			phba->hba_flag |= HBA_RECOVERABLE_UE;
7676 			/* Set 1Sec interval to detect UE */
7677 			phba->eratt_poll_interval = 1;
7678 			phba->sli4_hba.ue_to_sr = bf_get(
7679 					lpfc_mbx_set_feature_UESR,
7680 					&mboxq->u.mqe.un.set_feature);
7681 			phba->sli4_hba.ue_to_rp = bf_get(
7682 					lpfc_mbx_set_feature_UERP,
7683 					&mboxq->u.mqe.un.set_feature);
7684 		}
7685 	}
7686 
7687 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
7688 		/* Enable MDS Diagnostics only if the SLI Port supports it */
7689 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
7690 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7691 		if (rc != MBX_SUCCESS)
7692 			phba->mds_diags_support = 0;
7693 	}
7694 
7695 	/*
7696 	 * Discover the port's supported feature set and match it against the
7697 	 * hosts requests.
7698 	 */
7699 	lpfc_request_features(phba, mboxq);
7700 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7701 	if (unlikely(rc)) {
7702 		rc = -EIO;
7703 		goto out_free_mbox;
7704 	}
7705 
7706 	/* Disable VMID if app header is not supported */
7707 	if (phba->cfg_vmid_app_header && !(bf_get(lpfc_mbx_rq_ftr_rsp_ashdr,
7708 						  &mqe->un.req_ftrs))) {
7709 		bf_set(lpfc_ftr_ashdr, &phba->sli4_hba.sli4_flags, 0);
7710 		phba->cfg_vmid_app_header = 0;
7711 		lpfc_printf_log(phba, KERN_DEBUG, LOG_SLI,
7712 				"1242 vmid feature not supported\n");
7713 	}
7714 
7715 	/*
7716 	 * The port must support FCP initiator mode as this is the
7717 	 * only mode running in the host.
7718 	 */
7719 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
7720 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7721 				"0378 No support for fcpi mode.\n");
7722 		ftr_rsp++;
7723 	}
7724 
7725 	/* Performance Hints are ONLY for FCoE */
7726 	if (phba->hba_flag & HBA_FCOE_MODE) {
7727 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
7728 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
7729 		else
7730 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
7731 	}
7732 
7733 	/*
7734 	 * If the port cannot support the host's requested features
7735 	 * then turn off the global config parameters to disable the
7736 	 * feature in the driver.  This is not a fatal error.
7737 	 */
7738 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
7739 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
7740 			phba->cfg_enable_bg = 0;
7741 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
7742 			ftr_rsp++;
7743 		}
7744 	}
7745 
7746 	if (phba->max_vpi && phba->cfg_enable_npiv &&
7747 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7748 		ftr_rsp++;
7749 
7750 	if (ftr_rsp) {
7751 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7752 				"0379 Feature Mismatch Data: x%08x %08x "
7753 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
7754 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
7755 				phba->cfg_enable_npiv, phba->max_vpi);
7756 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
7757 			phba->cfg_enable_bg = 0;
7758 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7759 			phba->cfg_enable_npiv = 0;
7760 	}
7761 
7762 	/* These SLI3 features are assumed in SLI4 */
7763 	spin_lock_irq(&phba->hbalock);
7764 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
7765 	spin_unlock_irq(&phba->hbalock);
7766 
7767 	/* Always try to enable dual dump feature if we can */
7768 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
7769 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7770 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
7771 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
7772 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7773 				"6448 Dual Dump is enabled\n");
7774 	else
7775 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
7776 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
7777 				"rc:x%x dd:x%x\n",
7778 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7779 				lpfc_sli_config_mbox_subsys_get(
7780 					phba, mboxq),
7781 				lpfc_sli_config_mbox_opcode_get(
7782 					phba, mboxq),
7783 				rc, dd);
7784 	/*
7785 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
7786 	 * calls depends on these resources to complete port setup.
7787 	 */
7788 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
7789 	if (rc) {
7790 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7791 				"2920 Failed to alloc Resource IDs "
7792 				"rc = x%x\n", rc);
7793 		goto out_free_mbox;
7794 	}
7795 
7796 	lpfc_set_host_data(phba, mboxq);
7797 
7798 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7799 	if (rc) {
7800 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7801 				"2134 Failed to set host os driver version %x",
7802 				rc);
7803 	}
7804 
7805 	/* Read the port's service parameters. */
7806 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
7807 	if (rc) {
7808 		phba->link_state = LPFC_HBA_ERROR;
7809 		rc = -ENOMEM;
7810 		goto out_free_mbox;
7811 	}
7812 
7813 	mboxq->vport = vport;
7814 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7815 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
7816 	if (rc == MBX_SUCCESS) {
7817 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
7818 		rc = 0;
7819 	}
7820 
7821 	/*
7822 	 * This memory was allocated by the lpfc_read_sparam routine. Release
7823 	 * it to the mbuf pool.
7824 	 */
7825 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
7826 	kfree(mp);
7827 	mboxq->ctx_buf = NULL;
7828 	if (unlikely(rc)) {
7829 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7830 				"0382 READ_SPARAM command failed "
7831 				"status %d, mbxStatus x%x\n",
7832 				rc, bf_get(lpfc_mqe_status, mqe));
7833 		phba->link_state = LPFC_HBA_ERROR;
7834 		rc = -EIO;
7835 		goto out_free_mbox;
7836 	}
7837 
7838 	lpfc_update_vport_wwn(vport);
7839 
7840 	/* Update the fc_host data structures with new wwn. */
7841 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
7842 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
7843 
7844 	/* Create all the SLI4 queues */
7845 	rc = lpfc_sli4_queue_create(phba);
7846 	if (rc) {
7847 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7848 				"3089 Failed to allocate queues\n");
7849 		rc = -ENODEV;
7850 		goto out_free_mbox;
7851 	}
7852 	/* Set up all the queues to the device */
7853 	rc = lpfc_sli4_queue_setup(phba);
7854 	if (unlikely(rc)) {
7855 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7856 				"0381 Error %d during queue setup.\n ", rc);
7857 		goto out_stop_timers;
7858 	}
7859 	/* Initialize the driver internal SLI layer lists. */
7860 	lpfc_sli4_setup(phba);
7861 	lpfc_sli4_queue_init(phba);
7862 
7863 	/* update host els xri-sgl sizes and mappings */
7864 	rc = lpfc_sli4_els_sgl_update(phba);
7865 	if (unlikely(rc)) {
7866 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7867 				"1400 Failed to update xri-sgl size and "
7868 				"mapping: %d\n", rc);
7869 		goto out_destroy_queue;
7870 	}
7871 
7872 	/* register the els sgl pool to the port */
7873 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
7874 				       phba->sli4_hba.els_xri_cnt);
7875 	if (unlikely(rc < 0)) {
7876 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7877 				"0582 Error %d during els sgl post "
7878 				"operation\n", rc);
7879 		rc = -ENODEV;
7880 		goto out_destroy_queue;
7881 	}
7882 	phba->sli4_hba.els_xri_cnt = rc;
7883 
7884 	if (phba->nvmet_support) {
7885 		/* update host nvmet xri-sgl sizes and mappings */
7886 		rc = lpfc_sli4_nvmet_sgl_update(phba);
7887 		if (unlikely(rc)) {
7888 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7889 					"6308 Failed to update nvmet-sgl size "
7890 					"and mapping: %d\n", rc);
7891 			goto out_destroy_queue;
7892 		}
7893 
7894 		/* register the nvmet sgl pool to the port */
7895 		rc = lpfc_sli4_repost_sgl_list(
7896 			phba,
7897 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
7898 			phba->sli4_hba.nvmet_xri_cnt);
7899 		if (unlikely(rc < 0)) {
7900 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7901 					"3117 Error %d during nvmet "
7902 					"sgl post\n", rc);
7903 			rc = -ENODEV;
7904 			goto out_destroy_queue;
7905 		}
7906 		phba->sli4_hba.nvmet_xri_cnt = rc;
7907 
7908 		/* We allocate an iocbq for every receive context SGL.
7909 		 * The additional allocation is for abort and ls handling.
7910 		 */
7911 		cnt = phba->sli4_hba.nvmet_xri_cnt +
7912 			phba->sli4_hba.max_cfg_param.max_xri;
7913 	} else {
7914 		/* update host common xri-sgl sizes and mappings */
7915 		rc = lpfc_sli4_io_sgl_update(phba);
7916 		if (unlikely(rc)) {
7917 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7918 					"6082 Failed to update nvme-sgl size "
7919 					"and mapping: %d\n", rc);
7920 			goto out_destroy_queue;
7921 		}
7922 
7923 		/* register the allocated common sgl pool to the port */
7924 		rc = lpfc_sli4_repost_io_sgl_list(phba);
7925 		if (unlikely(rc)) {
7926 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7927 					"6116 Error %d during nvme sgl post "
7928 					"operation\n", rc);
7929 			/* Some NVME buffers were moved to abort nvme list */
7930 			/* A pci function reset will repost them */
7931 			rc = -ENODEV;
7932 			goto out_destroy_queue;
7933 		}
7934 		/* Each lpfc_io_buf job structure has an iocbq element.
7935 		 * This cnt provides for abort, els, ct and ls requests.
7936 		 */
7937 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
7938 	}
7939 
7940 	if (!phba->sli.iocbq_lookup) {
7941 		/* Initialize and populate the iocb list per host */
7942 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7943 				"2821 initialize iocb list with %d entries\n",
7944 				cnt);
7945 		rc = lpfc_init_iocb_list(phba, cnt);
7946 		if (rc) {
7947 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7948 					"1413 Failed to init iocb list.\n");
7949 			goto out_destroy_queue;
7950 		}
7951 	}
7952 
7953 	if (phba->nvmet_support)
7954 		lpfc_nvmet_create_targetport(phba);
7955 
7956 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
7957 		/* Post initial buffers to all RQs created */
7958 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
7959 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
7960 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
7961 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
7962 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
7963 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
7964 			rqbp->buffer_count = 0;
7965 
7966 			lpfc_post_rq_buffer(
7967 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
7968 				phba->sli4_hba.nvmet_mrq_data[i],
7969 				phba->cfg_nvmet_mrq_post, i);
7970 		}
7971 	}
7972 
7973 	/* Post the rpi header region to the device. */
7974 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
7975 	if (unlikely(rc)) {
7976 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7977 				"0393 Error %d during rpi post operation\n",
7978 				rc);
7979 		rc = -ENODEV;
7980 		goto out_free_iocblist;
7981 	}
7982 	lpfc_sli4_node_prep(phba);
7983 
7984 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
7985 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
7986 			/*
7987 			 * The FC Port needs to register FCFI (index 0)
7988 			 */
7989 			lpfc_reg_fcfi(phba, mboxq);
7990 			mboxq->vport = phba->pport;
7991 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7992 			if (rc != MBX_SUCCESS)
7993 				goto out_unset_queue;
7994 			rc = 0;
7995 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
7996 						&mboxq->u.mqe.un.reg_fcfi);
7997 		} else {
7998 			/* We are a NVME Target mode with MRQ > 1 */
7999 
8000 			/* First register the FCFI */
8001 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
8002 			mboxq->vport = phba->pport;
8003 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8004 			if (rc != MBX_SUCCESS)
8005 				goto out_unset_queue;
8006 			rc = 0;
8007 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
8008 						&mboxq->u.mqe.un.reg_fcfi_mrq);
8009 
8010 			/* Next register the MRQs */
8011 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
8012 			mboxq->vport = phba->pport;
8013 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8014 			if (rc != MBX_SUCCESS)
8015 				goto out_unset_queue;
8016 			rc = 0;
8017 		}
8018 		/* Check if the port is configured to be disabled */
8019 		lpfc_sli_read_link_ste(phba);
8020 	}
8021 
8022 	/* Don't post more new bufs if repost already recovered
8023 	 * the nvme sgls.
8024 	 */
8025 	if (phba->nvmet_support == 0) {
8026 		if (phba->sli4_hba.io_xri_cnt == 0) {
8027 			len = lpfc_new_io_buf(
8028 					      phba, phba->sli4_hba.io_xri_max);
8029 			if (len == 0) {
8030 				rc = -ENOMEM;
8031 				goto out_unset_queue;
8032 			}
8033 
8034 			if (phba->cfg_xri_rebalancing)
8035 				lpfc_create_multixri_pools(phba);
8036 		}
8037 	} else {
8038 		phba->cfg_xri_rebalancing = 0;
8039 	}
8040 
8041 	/* Allow asynchronous mailbox command to go through */
8042 	spin_lock_irq(&phba->hbalock);
8043 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8044 	spin_unlock_irq(&phba->hbalock);
8045 
8046 	/* Post receive buffers to the device */
8047 	lpfc_sli4_rb_setup(phba);
8048 
8049 	/* Reset HBA FCF states after HBA reset */
8050 	phba->fcf.fcf_flag = 0;
8051 	phba->fcf.current_rec.flag = 0;
8052 
8053 	/* Start the ELS watchdog timer */
8054 	mod_timer(&vport->els_tmofunc,
8055 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
8056 
8057 	/* Start heart beat timer */
8058 	mod_timer(&phba->hb_tmofunc,
8059 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
8060 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
8061 	phba->last_completion_time = jiffies;
8062 
8063 	/* start eq_delay heartbeat */
8064 	if (phba->cfg_auto_imax)
8065 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
8066 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
8067 
8068 	/* start per phba idle_stat_delay heartbeat */
8069 	lpfc_init_idle_stat_hb(phba);
8070 
8071 	/* Start error attention (ERATT) polling timer */
8072 	mod_timer(&phba->eratt_poll,
8073 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
8074 
8075 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
8076 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
8077 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
8078 		if (!rc) {
8079 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8080 					"2829 This device supports "
8081 					"Advanced Error Reporting (AER)\n");
8082 			spin_lock_irq(&phba->hbalock);
8083 			phba->hba_flag |= HBA_AER_ENABLED;
8084 			spin_unlock_irq(&phba->hbalock);
8085 		} else {
8086 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8087 					"2830 This device does not support "
8088 					"Advanced Error Reporting (AER)\n");
8089 			phba->cfg_aer_support = 0;
8090 		}
8091 		rc = 0;
8092 	}
8093 
8094 	/*
8095 	 * The port is ready, set the host's link state to LINK_DOWN
8096 	 * in preparation for link interrupts.
8097 	 */
8098 	spin_lock_irq(&phba->hbalock);
8099 	phba->link_state = LPFC_LINK_DOWN;
8100 
8101 	/* Check if physical ports are trunked */
8102 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
8103 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
8104 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
8105 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
8106 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
8107 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
8108 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
8109 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
8110 	spin_unlock_irq(&phba->hbalock);
8111 
8112 	/* Arm the CQs and then EQs on device */
8113 	lpfc_sli4_arm_cqeq_intr(phba);
8114 
8115 	/* Indicate device interrupt mode */
8116 	phba->sli4_hba.intr_enable = 1;
8117 
8118 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
8119 	    (phba->hba_flag & LINK_DISABLED)) {
8120 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8121 				"3103 Adapter Link is disabled.\n");
8122 		lpfc_down_link(phba, mboxq);
8123 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8124 		if (rc != MBX_SUCCESS) {
8125 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8126 					"3104 Adapter failed to issue "
8127 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
8128 			goto out_io_buff_free;
8129 		}
8130 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
8131 		/* don't perform init_link on SLI4 FC port loopback test */
8132 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
8133 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
8134 			if (rc)
8135 				goto out_io_buff_free;
8136 		}
8137 	}
8138 	mempool_free(mboxq, phba->mbox_mem_pool);
8139 	return rc;
8140 out_io_buff_free:
8141 	/* Free allocated IO Buffers */
8142 	lpfc_io_free(phba);
8143 out_unset_queue:
8144 	/* Unset all the queues set up in this routine when error out */
8145 	lpfc_sli4_queue_unset(phba);
8146 out_free_iocblist:
8147 	lpfc_free_iocb_list(phba);
8148 out_destroy_queue:
8149 	lpfc_sli4_queue_destroy(phba);
8150 out_stop_timers:
8151 	lpfc_stop_hba_timers(phba);
8152 out_free_mbox:
8153 	mempool_free(mboxq, phba->mbox_mem_pool);
8154 	return rc;
8155 }
8156 
8157 /**
8158  * lpfc_mbox_timeout - Timeout call back function for mbox timer
8159  * @t: Context to fetch pointer to hba structure from.
8160  *
8161  * This is the callback function for mailbox timer. The mailbox
8162  * timer is armed when a new mailbox command is issued and the timer
8163  * is deleted when the mailbox complete. The function is called by
8164  * the kernel timer code when a mailbox does not complete within
8165  * expected time. This function wakes up the worker thread to
8166  * process the mailbox timeout and returns. All the processing is
8167  * done by the worker thread function lpfc_mbox_timeout_handler.
8168  **/
8169 void
8170 lpfc_mbox_timeout(struct timer_list *t)
8171 {
8172 	struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
8173 	unsigned long iflag;
8174 	uint32_t tmo_posted;
8175 
8176 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
8177 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
8178 	if (!tmo_posted)
8179 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
8180 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
8181 
8182 	if (!tmo_posted)
8183 		lpfc_worker_wake_up(phba);
8184 	return;
8185 }
8186 
8187 /**
8188  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
8189  *                                    are pending
8190  * @phba: Pointer to HBA context object.
8191  *
8192  * This function checks if any mailbox completions are present on the mailbox
8193  * completion queue.
8194  **/
8195 static bool
8196 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
8197 {
8198 
8199 	uint32_t idx;
8200 	struct lpfc_queue *mcq;
8201 	struct lpfc_mcqe *mcqe;
8202 	bool pending_completions = false;
8203 	uint8_t	qe_valid;
8204 
8205 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8206 		return false;
8207 
8208 	/* Check for completions on mailbox completion queue */
8209 
8210 	mcq = phba->sli4_hba.mbx_cq;
8211 	idx = mcq->hba_index;
8212 	qe_valid = mcq->qe_valid;
8213 	while (bf_get_le32(lpfc_cqe_valid,
8214 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
8215 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
8216 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
8217 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
8218 			pending_completions = true;
8219 			break;
8220 		}
8221 		idx = (idx + 1) % mcq->entry_count;
8222 		if (mcq->hba_index == idx)
8223 			break;
8224 
8225 		/* if the index wrapped around, toggle the valid bit */
8226 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
8227 			qe_valid = (qe_valid) ? 0 : 1;
8228 	}
8229 	return pending_completions;
8230 
8231 }
8232 
8233 /**
8234  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
8235  *					      that were missed.
8236  * @phba: Pointer to HBA context object.
8237  *
8238  * For sli4, it is possible to miss an interrupt. As such mbox completions
8239  * maybe missed causing erroneous mailbox timeouts to occur. This function
8240  * checks to see if mbox completions are on the mailbox completion queue
8241  * and will process all the completions associated with the eq for the
8242  * mailbox completion queue.
8243  **/
8244 static bool
8245 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
8246 {
8247 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
8248 	uint32_t eqidx;
8249 	struct lpfc_queue *fpeq = NULL;
8250 	struct lpfc_queue *eq;
8251 	bool mbox_pending;
8252 
8253 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8254 		return false;
8255 
8256 	/* Find the EQ associated with the mbox CQ */
8257 	if (sli4_hba->hdwq) {
8258 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
8259 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
8260 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
8261 				fpeq = eq;
8262 				break;
8263 			}
8264 		}
8265 	}
8266 	if (!fpeq)
8267 		return false;
8268 
8269 	/* Turn off interrupts from this EQ */
8270 
8271 	sli4_hba->sli4_eq_clr_intr(fpeq);
8272 
8273 	/* Check to see if a mbox completion is pending */
8274 
8275 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
8276 
8277 	/*
8278 	 * If a mbox completion is pending, process all the events on EQ
8279 	 * associated with the mbox completion queue (this could include
8280 	 * mailbox commands, async events, els commands, receive queue data
8281 	 * and fcp commands)
8282 	 */
8283 
8284 	if (mbox_pending)
8285 		/* process and rearm the EQ */
8286 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
8287 	else
8288 		/* Always clear and re-arm the EQ */
8289 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
8290 
8291 	return mbox_pending;
8292 
8293 }
8294 
8295 /**
8296  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
8297  * @phba: Pointer to HBA context object.
8298  *
8299  * This function is called from worker thread when a mailbox command times out.
8300  * The caller is not required to hold any locks. This function will reset the
8301  * HBA and recover all the pending commands.
8302  **/
8303 void
8304 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
8305 {
8306 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
8307 	MAILBOX_t *mb = NULL;
8308 
8309 	struct lpfc_sli *psli = &phba->sli;
8310 
8311 	/* If the mailbox completed, process the completion */
8312 	lpfc_sli4_process_missed_mbox_completions(phba);
8313 
8314 	if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
8315 		return;
8316 
8317 	if (pmbox != NULL)
8318 		mb = &pmbox->u.mb;
8319 	/* Check the pmbox pointer first.  There is a race condition
8320 	 * between the mbox timeout handler getting executed in the
8321 	 * worklist and the mailbox actually completing. When this
8322 	 * race condition occurs, the mbox_active will be NULL.
8323 	 */
8324 	spin_lock_irq(&phba->hbalock);
8325 	if (pmbox == NULL) {
8326 		lpfc_printf_log(phba, KERN_WARNING,
8327 				LOG_MBOX | LOG_SLI,
8328 				"0353 Active Mailbox cleared - mailbox timeout "
8329 				"exiting\n");
8330 		spin_unlock_irq(&phba->hbalock);
8331 		return;
8332 	}
8333 
8334 	/* Mbox cmd <mbxCommand> timeout */
8335 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8336 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
8337 			mb->mbxCommand,
8338 			phba->pport->port_state,
8339 			phba->sli.sli_flag,
8340 			phba->sli.mbox_active);
8341 	spin_unlock_irq(&phba->hbalock);
8342 
8343 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
8344 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
8345 	 * it to fail all outstanding SCSI IO.
8346 	 */
8347 	spin_lock_irq(&phba->pport->work_port_lock);
8348 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
8349 	spin_unlock_irq(&phba->pport->work_port_lock);
8350 	spin_lock_irq(&phba->hbalock);
8351 	phba->link_state = LPFC_LINK_UNKNOWN;
8352 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
8353 	spin_unlock_irq(&phba->hbalock);
8354 
8355 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8356 			"0345 Resetting board due to mailbox timeout\n");
8357 
8358 	/* Reset the HBA device */
8359 	lpfc_reset_hba(phba);
8360 }
8361 
8362 /**
8363  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
8364  * @phba: Pointer to HBA context object.
8365  * @pmbox: Pointer to mailbox object.
8366  * @flag: Flag indicating how the mailbox need to be processed.
8367  *
8368  * This function is called by discovery code and HBA management code
8369  * to submit a mailbox command to firmware with SLI-3 interface spec. This
8370  * function gets the hbalock to protect the data structures.
8371  * The mailbox command can be submitted in polling mode, in which case
8372  * this function will wait in a polling loop for the completion of the
8373  * mailbox.
8374  * If the mailbox is submitted in no_wait mode (not polling) the
8375  * function will submit the command and returns immediately without waiting
8376  * for the mailbox completion. The no_wait is supported only when HBA
8377  * is in SLI2/SLI3 mode - interrupts are enabled.
8378  * The SLI interface allows only one mailbox pending at a time. If the
8379  * mailbox is issued in polling mode and there is already a mailbox
8380  * pending, then the function will return an error. If the mailbox is issued
8381  * in NO_WAIT mode and there is a mailbox pending already, the function
8382  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
8383  * The sli layer owns the mailbox object until the completion of mailbox
8384  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
8385  * return codes the caller owns the mailbox command after the return of
8386  * the function.
8387  **/
8388 static int
8389 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
8390 		       uint32_t flag)
8391 {
8392 	MAILBOX_t *mbx;
8393 	struct lpfc_sli *psli = &phba->sli;
8394 	uint32_t status, evtctr;
8395 	uint32_t ha_copy, hc_copy;
8396 	int i;
8397 	unsigned long timeout;
8398 	unsigned long drvr_flag = 0;
8399 	uint32_t word0, ldata;
8400 	void __iomem *to_slim;
8401 	int processing_queue = 0;
8402 
8403 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
8404 	if (!pmbox) {
8405 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8406 		/* processing mbox queue from intr_handler */
8407 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8408 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8409 			return MBX_SUCCESS;
8410 		}
8411 		processing_queue = 1;
8412 		pmbox = lpfc_mbox_get(phba);
8413 		if (!pmbox) {
8414 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8415 			return MBX_SUCCESS;
8416 		}
8417 	}
8418 
8419 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
8420 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
8421 		if(!pmbox->vport) {
8422 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8423 			lpfc_printf_log(phba, KERN_ERR,
8424 					LOG_MBOX | LOG_VPORT,
8425 					"1806 Mbox x%x failed. No vport\n",
8426 					pmbox->u.mb.mbxCommand);
8427 			dump_stack();
8428 			goto out_not_finished;
8429 		}
8430 	}
8431 
8432 	/* If the PCI channel is in offline state, do not post mbox. */
8433 	if (unlikely(pci_channel_offline(phba->pcidev))) {
8434 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8435 		goto out_not_finished;
8436 	}
8437 
8438 	/* If HBA has a deferred error attention, fail the iocb. */
8439 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
8440 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8441 		goto out_not_finished;
8442 	}
8443 
8444 	psli = &phba->sli;
8445 
8446 	mbx = &pmbox->u.mb;
8447 	status = MBX_SUCCESS;
8448 
8449 	if (phba->link_state == LPFC_HBA_ERROR) {
8450 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8451 
8452 		/* Mbox command <mbxCommand> cannot issue */
8453 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8454 				"(%d):0311 Mailbox command x%x cannot "
8455 				"issue Data: x%x x%x\n",
8456 				pmbox->vport ? pmbox->vport->vpi : 0,
8457 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8458 		goto out_not_finished;
8459 	}
8460 
8461 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
8462 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
8463 			!(hc_copy & HC_MBINT_ENA)) {
8464 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8465 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8466 				"(%d):2528 Mailbox command x%x cannot "
8467 				"issue Data: x%x x%x\n",
8468 				pmbox->vport ? pmbox->vport->vpi : 0,
8469 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8470 			goto out_not_finished;
8471 		}
8472 	}
8473 
8474 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8475 		/* Polling for a mbox command when another one is already active
8476 		 * is not allowed in SLI. Also, the driver must have established
8477 		 * SLI2 mode to queue and process multiple mbox commands.
8478 		 */
8479 
8480 		if (flag & MBX_POLL) {
8481 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8482 
8483 			/* Mbox command <mbxCommand> cannot issue */
8484 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8485 					"(%d):2529 Mailbox command x%x "
8486 					"cannot issue Data: x%x x%x\n",
8487 					pmbox->vport ? pmbox->vport->vpi : 0,
8488 					pmbox->u.mb.mbxCommand,
8489 					psli->sli_flag, flag);
8490 			goto out_not_finished;
8491 		}
8492 
8493 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
8494 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8495 			/* Mbox command <mbxCommand> cannot issue */
8496 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8497 					"(%d):2530 Mailbox command x%x "
8498 					"cannot issue Data: x%x x%x\n",
8499 					pmbox->vport ? pmbox->vport->vpi : 0,
8500 					pmbox->u.mb.mbxCommand,
8501 					psli->sli_flag, flag);
8502 			goto out_not_finished;
8503 		}
8504 
8505 		/* Another mailbox command is still being processed, queue this
8506 		 * command to be processed later.
8507 		 */
8508 		lpfc_mbox_put(phba, pmbox);
8509 
8510 		/* Mbox cmd issue - BUSY */
8511 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8512 				"(%d):0308 Mbox cmd issue - BUSY Data: "
8513 				"x%x x%x x%x x%x\n",
8514 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
8515 				mbx->mbxCommand,
8516 				phba->pport ? phba->pport->port_state : 0xff,
8517 				psli->sli_flag, flag);
8518 
8519 		psli->slistat.mbox_busy++;
8520 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8521 
8522 		if (pmbox->vport) {
8523 			lpfc_debugfs_disc_trc(pmbox->vport,
8524 				LPFC_DISC_TRC_MBOX_VPORT,
8525 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
8526 				(uint32_t)mbx->mbxCommand,
8527 				mbx->un.varWords[0], mbx->un.varWords[1]);
8528 		}
8529 		else {
8530 			lpfc_debugfs_disc_trc(phba->pport,
8531 				LPFC_DISC_TRC_MBOX,
8532 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
8533 				(uint32_t)mbx->mbxCommand,
8534 				mbx->un.varWords[0], mbx->un.varWords[1]);
8535 		}
8536 
8537 		return MBX_BUSY;
8538 	}
8539 
8540 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8541 
8542 	/* If we are not polling, we MUST be in SLI2 mode */
8543 	if (flag != MBX_POLL) {
8544 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
8545 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
8546 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8547 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8548 			/* Mbox command <mbxCommand> cannot issue */
8549 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8550 					"(%d):2531 Mailbox command x%x "
8551 					"cannot issue Data: x%x x%x\n",
8552 					pmbox->vport ? pmbox->vport->vpi : 0,
8553 					pmbox->u.mb.mbxCommand,
8554 					psli->sli_flag, flag);
8555 			goto out_not_finished;
8556 		}
8557 		/* timeout active mbox command */
8558 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8559 					   1000);
8560 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
8561 	}
8562 
8563 	/* Mailbox cmd <cmd> issue */
8564 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8565 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
8566 			"x%x\n",
8567 			pmbox->vport ? pmbox->vport->vpi : 0,
8568 			mbx->mbxCommand,
8569 			phba->pport ? phba->pport->port_state : 0xff,
8570 			psli->sli_flag, flag);
8571 
8572 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
8573 		if (pmbox->vport) {
8574 			lpfc_debugfs_disc_trc(pmbox->vport,
8575 				LPFC_DISC_TRC_MBOX_VPORT,
8576 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
8577 				(uint32_t)mbx->mbxCommand,
8578 				mbx->un.varWords[0], mbx->un.varWords[1]);
8579 		}
8580 		else {
8581 			lpfc_debugfs_disc_trc(phba->pport,
8582 				LPFC_DISC_TRC_MBOX,
8583 				"MBOX Send:       cmd:x%x mb:x%x x%x",
8584 				(uint32_t)mbx->mbxCommand,
8585 				mbx->un.varWords[0], mbx->un.varWords[1]);
8586 		}
8587 	}
8588 
8589 	psli->slistat.mbox_cmd++;
8590 	evtctr = psli->slistat.mbox_event;
8591 
8592 	/* next set own bit for the adapter and copy over command word */
8593 	mbx->mbxOwner = OWN_CHIP;
8594 
8595 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8596 		/* Populate mbox extension offset word. */
8597 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
8598 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8599 				= (uint8_t *)phba->mbox_ext
8600 				  - (uint8_t *)phba->mbox;
8601 		}
8602 
8603 		/* Copy the mailbox extension data */
8604 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
8605 			lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
8606 					      (uint8_t *)phba->mbox_ext,
8607 					      pmbox->in_ext_byte_len);
8608 		}
8609 		/* Copy command data to host SLIM area */
8610 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
8611 	} else {
8612 		/* Populate mbox extension offset word. */
8613 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
8614 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8615 				= MAILBOX_HBA_EXT_OFFSET;
8616 
8617 		/* Copy the mailbox extension data */
8618 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
8619 			lpfc_memcpy_to_slim(phba->MBslimaddr +
8620 				MAILBOX_HBA_EXT_OFFSET,
8621 				pmbox->ctx_buf, pmbox->in_ext_byte_len);
8622 
8623 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8624 			/* copy command data into host mbox for cmpl */
8625 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
8626 					      MAILBOX_CMD_SIZE);
8627 
8628 		/* First copy mbox command data to HBA SLIM, skip past first
8629 		   word */
8630 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
8631 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
8632 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
8633 
8634 		/* Next copy over first word, with mbxOwner set */
8635 		ldata = *((uint32_t *)mbx);
8636 		to_slim = phba->MBslimaddr;
8637 		writel(ldata, to_slim);
8638 		readl(to_slim); /* flush */
8639 
8640 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8641 			/* switch over to host mailbox */
8642 			psli->sli_flag |= LPFC_SLI_ACTIVE;
8643 	}
8644 
8645 	wmb();
8646 
8647 	switch (flag) {
8648 	case MBX_NOWAIT:
8649 		/* Set up reference to mailbox command */
8650 		psli->mbox_active = pmbox;
8651 		/* Interrupt board to do it */
8652 		writel(CA_MBATT, phba->CAregaddr);
8653 		readl(phba->CAregaddr); /* flush */
8654 		/* Don't wait for it to finish, just return */
8655 		break;
8656 
8657 	case MBX_POLL:
8658 		/* Set up null reference to mailbox command */
8659 		psli->mbox_active = NULL;
8660 		/* Interrupt board to do it */
8661 		writel(CA_MBATT, phba->CAregaddr);
8662 		readl(phba->CAregaddr); /* flush */
8663 
8664 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8665 			/* First read mbox status word */
8666 			word0 = *((uint32_t *)phba->mbox);
8667 			word0 = le32_to_cpu(word0);
8668 		} else {
8669 			/* First read mbox status word */
8670 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
8671 				spin_unlock_irqrestore(&phba->hbalock,
8672 						       drvr_flag);
8673 				goto out_not_finished;
8674 			}
8675 		}
8676 
8677 		/* Read the HBA Host Attention Register */
8678 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8679 			spin_unlock_irqrestore(&phba->hbalock,
8680 						       drvr_flag);
8681 			goto out_not_finished;
8682 		}
8683 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8684 							1000) + jiffies;
8685 		i = 0;
8686 		/* Wait for command to complete */
8687 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
8688 		       (!(ha_copy & HA_MBATT) &&
8689 			(phba->link_state > LPFC_WARM_START))) {
8690 			if (time_after(jiffies, timeout)) {
8691 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8692 				spin_unlock_irqrestore(&phba->hbalock,
8693 						       drvr_flag);
8694 				goto out_not_finished;
8695 			}
8696 
8697 			/* Check if we took a mbox interrupt while we were
8698 			   polling */
8699 			if (((word0 & OWN_CHIP) != OWN_CHIP)
8700 			    && (evtctr != psli->slistat.mbox_event))
8701 				break;
8702 
8703 			if (i++ > 10) {
8704 				spin_unlock_irqrestore(&phba->hbalock,
8705 						       drvr_flag);
8706 				msleep(1);
8707 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
8708 			}
8709 
8710 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8711 				/* First copy command data */
8712 				word0 = *((uint32_t *)phba->mbox);
8713 				word0 = le32_to_cpu(word0);
8714 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
8715 					MAILBOX_t *slimmb;
8716 					uint32_t slimword0;
8717 					/* Check real SLIM for any errors */
8718 					slimword0 = readl(phba->MBslimaddr);
8719 					slimmb = (MAILBOX_t *) & slimword0;
8720 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
8721 					    && slimmb->mbxStatus) {
8722 						psli->sli_flag &=
8723 						    ~LPFC_SLI_ACTIVE;
8724 						word0 = slimword0;
8725 					}
8726 				}
8727 			} else {
8728 				/* First copy command data */
8729 				word0 = readl(phba->MBslimaddr);
8730 			}
8731 			/* Read the HBA Host Attention Register */
8732 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8733 				spin_unlock_irqrestore(&phba->hbalock,
8734 						       drvr_flag);
8735 				goto out_not_finished;
8736 			}
8737 		}
8738 
8739 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8740 			/* copy results back to user */
8741 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
8742 						MAILBOX_CMD_SIZE);
8743 			/* Copy the mailbox extension data */
8744 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8745 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
8746 						      pmbox->ctx_buf,
8747 						      pmbox->out_ext_byte_len);
8748 			}
8749 		} else {
8750 			/* First copy command data */
8751 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
8752 						MAILBOX_CMD_SIZE);
8753 			/* Copy the mailbox extension data */
8754 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8755 				lpfc_memcpy_from_slim(
8756 					pmbox->ctx_buf,
8757 					phba->MBslimaddr +
8758 					MAILBOX_HBA_EXT_OFFSET,
8759 					pmbox->out_ext_byte_len);
8760 			}
8761 		}
8762 
8763 		writel(HA_MBATT, phba->HAregaddr);
8764 		readl(phba->HAregaddr); /* flush */
8765 
8766 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8767 		status = mbx->mbxStatus;
8768 	}
8769 
8770 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8771 	return status;
8772 
8773 out_not_finished:
8774 	if (processing_queue) {
8775 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
8776 		lpfc_mbox_cmpl_put(phba, pmbox);
8777 	}
8778 	return MBX_NOT_FINISHED;
8779 }
8780 
8781 /**
8782  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
8783  * @phba: Pointer to HBA context object.
8784  *
8785  * The function blocks the posting of SLI4 asynchronous mailbox commands from
8786  * the driver internal pending mailbox queue. It will then try to wait out the
8787  * possible outstanding mailbox command before return.
8788  *
8789  * Returns:
8790  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
8791  * 	the outstanding mailbox command timed out.
8792  **/
8793 static int
8794 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
8795 {
8796 	struct lpfc_sli *psli = &phba->sli;
8797 	LPFC_MBOXQ_t *mboxq;
8798 	int rc = 0;
8799 	unsigned long timeout = 0;
8800 	u32 sli_flag;
8801 	u8 cmd, subsys, opcode;
8802 
8803 	/* Mark the asynchronous mailbox command posting as blocked */
8804 	spin_lock_irq(&phba->hbalock);
8805 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
8806 	/* Determine how long we might wait for the active mailbox
8807 	 * command to be gracefully completed by firmware.
8808 	 */
8809 	if (phba->sli.mbox_active)
8810 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
8811 						phba->sli.mbox_active) *
8812 						1000) + jiffies;
8813 	spin_unlock_irq(&phba->hbalock);
8814 
8815 	/* Make sure the mailbox is really active */
8816 	if (timeout)
8817 		lpfc_sli4_process_missed_mbox_completions(phba);
8818 
8819 	/* Wait for the outstanding mailbox command to complete */
8820 	while (phba->sli.mbox_active) {
8821 		/* Check active mailbox complete status every 2ms */
8822 		msleep(2);
8823 		if (time_after(jiffies, timeout)) {
8824 			/* Timeout, mark the outstanding cmd not complete */
8825 
8826 			/* Sanity check sli.mbox_active has not completed or
8827 			 * cancelled from another context during last 2ms sleep,
8828 			 * so take hbalock to be sure before logging.
8829 			 */
8830 			spin_lock_irq(&phba->hbalock);
8831 			if (phba->sli.mbox_active) {
8832 				mboxq = phba->sli.mbox_active;
8833 				cmd = mboxq->u.mb.mbxCommand;
8834 				subsys = lpfc_sli_config_mbox_subsys_get(phba,
8835 									 mboxq);
8836 				opcode = lpfc_sli_config_mbox_opcode_get(phba,
8837 									 mboxq);
8838 				sli_flag = psli->sli_flag;
8839 				spin_unlock_irq(&phba->hbalock);
8840 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8841 						"2352 Mailbox command x%x "
8842 						"(x%x/x%x) sli_flag x%x could "
8843 						"not complete\n",
8844 						cmd, subsys, opcode,
8845 						sli_flag);
8846 			} else {
8847 				spin_unlock_irq(&phba->hbalock);
8848 			}
8849 
8850 			rc = 1;
8851 			break;
8852 		}
8853 	}
8854 
8855 	/* Can not cleanly block async mailbox command, fails it */
8856 	if (rc) {
8857 		spin_lock_irq(&phba->hbalock);
8858 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8859 		spin_unlock_irq(&phba->hbalock);
8860 	}
8861 	return rc;
8862 }
8863 
8864 /**
8865  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
8866  * @phba: Pointer to HBA context object.
8867  *
8868  * The function unblocks and resume posting of SLI4 asynchronous mailbox
8869  * commands from the driver internal pending mailbox queue. It makes sure
8870  * that there is no outstanding mailbox command before resuming posting
8871  * asynchronous mailbox commands. If, for any reason, there is outstanding
8872  * mailbox command, it will try to wait it out before resuming asynchronous
8873  * mailbox command posting.
8874  **/
8875 static void
8876 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
8877 {
8878 	struct lpfc_sli *psli = &phba->sli;
8879 
8880 	spin_lock_irq(&phba->hbalock);
8881 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8882 		/* Asynchronous mailbox posting is not blocked, do nothing */
8883 		spin_unlock_irq(&phba->hbalock);
8884 		return;
8885 	}
8886 
8887 	/* Outstanding synchronous mailbox command is guaranteed to be done,
8888 	 * successful or timeout, after timing-out the outstanding mailbox
8889 	 * command shall always be removed, so just unblock posting async
8890 	 * mailbox command and resume
8891 	 */
8892 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8893 	spin_unlock_irq(&phba->hbalock);
8894 
8895 	/* wake up worker thread to post asynchronous mailbox command */
8896 	lpfc_worker_wake_up(phba);
8897 }
8898 
8899 /**
8900  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
8901  * @phba: Pointer to HBA context object.
8902  * @mboxq: Pointer to mailbox object.
8903  *
8904  * The function waits for the bootstrap mailbox register ready bit from
8905  * port for twice the regular mailbox command timeout value.
8906  *
8907  *      0 - no timeout on waiting for bootstrap mailbox register ready.
8908  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
8909  **/
8910 static int
8911 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8912 {
8913 	uint32_t db_ready;
8914 	unsigned long timeout;
8915 	struct lpfc_register bmbx_reg;
8916 
8917 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
8918 				   * 1000) + jiffies;
8919 
8920 	do {
8921 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
8922 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
8923 		if (!db_ready)
8924 			mdelay(2);
8925 
8926 		if (time_after(jiffies, timeout))
8927 			return MBXERR_ERROR;
8928 	} while (!db_ready);
8929 
8930 	return 0;
8931 }
8932 
8933 /**
8934  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
8935  * @phba: Pointer to HBA context object.
8936  * @mboxq: Pointer to mailbox object.
8937  *
8938  * The function posts a mailbox to the port.  The mailbox is expected
8939  * to be comletely filled in and ready for the port to operate on it.
8940  * This routine executes a synchronous completion operation on the
8941  * mailbox by polling for its completion.
8942  *
8943  * The caller must not be holding any locks when calling this routine.
8944  *
8945  * Returns:
8946  *	MBX_SUCCESS - mailbox posted successfully
8947  *	Any of the MBX error values.
8948  **/
8949 static int
8950 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8951 {
8952 	int rc = MBX_SUCCESS;
8953 	unsigned long iflag;
8954 	uint32_t mcqe_status;
8955 	uint32_t mbx_cmnd;
8956 	struct lpfc_sli *psli = &phba->sli;
8957 	struct lpfc_mqe *mb = &mboxq->u.mqe;
8958 	struct lpfc_bmbx_create *mbox_rgn;
8959 	struct dma_address *dma_address;
8960 
8961 	/*
8962 	 * Only one mailbox can be active to the bootstrap mailbox region
8963 	 * at a time and there is no queueing provided.
8964 	 */
8965 	spin_lock_irqsave(&phba->hbalock, iflag);
8966 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8967 		spin_unlock_irqrestore(&phba->hbalock, iflag);
8968 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8969 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
8970 				"cannot issue Data: x%x x%x\n",
8971 				mboxq->vport ? mboxq->vport->vpi : 0,
8972 				mboxq->u.mb.mbxCommand,
8973 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8974 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8975 				psli->sli_flag, MBX_POLL);
8976 		return MBXERR_ERROR;
8977 	}
8978 	/* The server grabs the token and owns it until release */
8979 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8980 	phba->sli.mbox_active = mboxq;
8981 	spin_unlock_irqrestore(&phba->hbalock, iflag);
8982 
8983 	/* wait for bootstrap mbox register for readyness */
8984 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8985 	if (rc)
8986 		goto exit;
8987 	/*
8988 	 * Initialize the bootstrap memory region to avoid stale data areas
8989 	 * in the mailbox post.  Then copy the caller's mailbox contents to
8990 	 * the bmbx mailbox region.
8991 	 */
8992 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
8993 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
8994 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
8995 			       sizeof(struct lpfc_mqe));
8996 
8997 	/* Post the high mailbox dma address to the port and wait for ready. */
8998 	dma_address = &phba->sli4_hba.bmbx.dma_address;
8999 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
9000 
9001 	/* wait for bootstrap mbox register for hi-address write done */
9002 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9003 	if (rc)
9004 		goto exit;
9005 
9006 	/* Post the low mailbox dma address to the port. */
9007 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
9008 
9009 	/* wait for bootstrap mbox register for low address write done */
9010 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9011 	if (rc)
9012 		goto exit;
9013 
9014 	/*
9015 	 * Read the CQ to ensure the mailbox has completed.
9016 	 * If so, update the mailbox status so that the upper layers
9017 	 * can complete the request normally.
9018 	 */
9019 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
9020 			       sizeof(struct lpfc_mqe));
9021 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
9022 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
9023 			       sizeof(struct lpfc_mcqe));
9024 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
9025 	/*
9026 	 * When the CQE status indicates a failure and the mailbox status
9027 	 * indicates success then copy the CQE status into the mailbox status
9028 	 * (and prefix it with x4000).
9029 	 */
9030 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
9031 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
9032 			bf_set(lpfc_mqe_status, mb,
9033 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
9034 		rc = MBXERR_ERROR;
9035 	} else
9036 		lpfc_sli4_swap_str(phba, mboxq);
9037 
9038 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9039 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
9040 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
9041 			" x%x x%x CQ: x%x x%x x%x x%x\n",
9042 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
9043 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9044 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9045 			bf_get(lpfc_mqe_status, mb),
9046 			mb->un.mb_words[0], mb->un.mb_words[1],
9047 			mb->un.mb_words[2], mb->un.mb_words[3],
9048 			mb->un.mb_words[4], mb->un.mb_words[5],
9049 			mb->un.mb_words[6], mb->un.mb_words[7],
9050 			mb->un.mb_words[8], mb->un.mb_words[9],
9051 			mb->un.mb_words[10], mb->un.mb_words[11],
9052 			mb->un.mb_words[12], mboxq->mcqe.word0,
9053 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
9054 			mboxq->mcqe.trailer);
9055 exit:
9056 	/* We are holding the token, no needed for lock when release */
9057 	spin_lock_irqsave(&phba->hbalock, iflag);
9058 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9059 	phba->sli.mbox_active = NULL;
9060 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9061 	return rc;
9062 }
9063 
9064 /**
9065  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
9066  * @phba: Pointer to HBA context object.
9067  * @mboxq: Pointer to mailbox object.
9068  * @flag: Flag indicating how the mailbox need to be processed.
9069  *
9070  * This function is called by discovery code and HBA management code to submit
9071  * a mailbox command to firmware with SLI-4 interface spec.
9072  *
9073  * Return codes the caller owns the mailbox command after the return of the
9074  * function.
9075  **/
9076 static int
9077 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
9078 		       uint32_t flag)
9079 {
9080 	struct lpfc_sli *psli = &phba->sli;
9081 	unsigned long iflags;
9082 	int rc;
9083 
9084 	/* dump from issue mailbox command if setup */
9085 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
9086 
9087 	rc = lpfc_mbox_dev_check(phba);
9088 	if (unlikely(rc)) {
9089 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9090 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
9091 				"cannot issue Data: x%x x%x\n",
9092 				mboxq->vport ? mboxq->vport->vpi : 0,
9093 				mboxq->u.mb.mbxCommand,
9094 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9095 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9096 				psli->sli_flag, flag);
9097 		goto out_not_finished;
9098 	}
9099 
9100 	/* Detect polling mode and jump to a handler */
9101 	if (!phba->sli4_hba.intr_enable) {
9102 		if (flag == MBX_POLL)
9103 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
9104 		else
9105 			rc = -EIO;
9106 		if (rc != MBX_SUCCESS)
9107 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
9108 					"(%d):2541 Mailbox command x%x "
9109 					"(x%x/x%x) failure: "
9110 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
9111 					"Data: x%x x%x\n,",
9112 					mboxq->vport ? mboxq->vport->vpi : 0,
9113 					mboxq->u.mb.mbxCommand,
9114 					lpfc_sli_config_mbox_subsys_get(phba,
9115 									mboxq),
9116 					lpfc_sli_config_mbox_opcode_get(phba,
9117 									mboxq),
9118 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
9119 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
9120 					bf_get(lpfc_mcqe_ext_status,
9121 					       &mboxq->mcqe),
9122 					psli->sli_flag, flag);
9123 		return rc;
9124 	} else if (flag == MBX_POLL) {
9125 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
9126 				"(%d):2542 Try to issue mailbox command "
9127 				"x%x (x%x/x%x) synchronously ahead of async "
9128 				"mailbox command queue: x%x x%x\n",
9129 				mboxq->vport ? mboxq->vport->vpi : 0,
9130 				mboxq->u.mb.mbxCommand,
9131 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9132 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9133 				psli->sli_flag, flag);
9134 		/* Try to block the asynchronous mailbox posting */
9135 		rc = lpfc_sli4_async_mbox_block(phba);
9136 		if (!rc) {
9137 			/* Successfully blocked, now issue sync mbox cmd */
9138 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
9139 			if (rc != MBX_SUCCESS)
9140 				lpfc_printf_log(phba, KERN_WARNING,
9141 					LOG_MBOX | LOG_SLI,
9142 					"(%d):2597 Sync Mailbox command "
9143 					"x%x (x%x/x%x) failure: "
9144 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
9145 					"Data: x%x x%x\n,",
9146 					mboxq->vport ? mboxq->vport->vpi : 0,
9147 					mboxq->u.mb.mbxCommand,
9148 					lpfc_sli_config_mbox_subsys_get(phba,
9149 									mboxq),
9150 					lpfc_sli_config_mbox_opcode_get(phba,
9151 									mboxq),
9152 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
9153 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
9154 					bf_get(lpfc_mcqe_ext_status,
9155 					       &mboxq->mcqe),
9156 					psli->sli_flag, flag);
9157 			/* Unblock the async mailbox posting afterward */
9158 			lpfc_sli4_async_mbox_unblock(phba);
9159 		}
9160 		return rc;
9161 	}
9162 
9163 	/* Now, interrupt mode asynchronous mailbox command */
9164 	rc = lpfc_mbox_cmd_check(phba, mboxq);
9165 	if (rc) {
9166 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9167 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
9168 				"cannot issue Data: x%x x%x\n",
9169 				mboxq->vport ? mboxq->vport->vpi : 0,
9170 				mboxq->u.mb.mbxCommand,
9171 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9172 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9173 				psli->sli_flag, flag);
9174 		goto out_not_finished;
9175 	}
9176 
9177 	/* Put the mailbox command to the driver internal FIFO */
9178 	psli->slistat.mbox_busy++;
9179 	spin_lock_irqsave(&phba->hbalock, iflags);
9180 	lpfc_mbox_put(phba, mboxq);
9181 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9182 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9183 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
9184 			"x%x (x%x/x%x) x%x x%x x%x\n",
9185 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
9186 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
9187 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9188 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9189 			phba->pport->port_state,
9190 			psli->sli_flag, MBX_NOWAIT);
9191 	/* Wake up worker thread to transport mailbox command from head */
9192 	lpfc_worker_wake_up(phba);
9193 
9194 	return MBX_BUSY;
9195 
9196 out_not_finished:
9197 	return MBX_NOT_FINISHED;
9198 }
9199 
9200 /**
9201  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
9202  * @phba: Pointer to HBA context object.
9203  *
9204  * This function is called by worker thread to send a mailbox command to
9205  * SLI4 HBA firmware.
9206  *
9207  **/
9208 int
9209 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
9210 {
9211 	struct lpfc_sli *psli = &phba->sli;
9212 	LPFC_MBOXQ_t *mboxq;
9213 	int rc = MBX_SUCCESS;
9214 	unsigned long iflags;
9215 	struct lpfc_mqe *mqe;
9216 	uint32_t mbx_cmnd;
9217 
9218 	/* Check interrupt mode before post async mailbox command */
9219 	if (unlikely(!phba->sli4_hba.intr_enable))
9220 		return MBX_NOT_FINISHED;
9221 
9222 	/* Check for mailbox command service token */
9223 	spin_lock_irqsave(&phba->hbalock, iflags);
9224 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9225 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9226 		return MBX_NOT_FINISHED;
9227 	}
9228 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9229 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9230 		return MBX_NOT_FINISHED;
9231 	}
9232 	if (unlikely(phba->sli.mbox_active)) {
9233 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9234 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9235 				"0384 There is pending active mailbox cmd\n");
9236 		return MBX_NOT_FINISHED;
9237 	}
9238 	/* Take the mailbox command service token */
9239 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9240 
9241 	/* Get the next mailbox command from head of queue */
9242 	mboxq = lpfc_mbox_get(phba);
9243 
9244 	/* If no more mailbox command waiting for post, we're done */
9245 	if (!mboxq) {
9246 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9247 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9248 		return MBX_SUCCESS;
9249 	}
9250 	phba->sli.mbox_active = mboxq;
9251 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9252 
9253 	/* Check device readiness for posting mailbox command */
9254 	rc = lpfc_mbox_dev_check(phba);
9255 	if (unlikely(rc))
9256 		/* Driver clean routine will clean up pending mailbox */
9257 		goto out_not_finished;
9258 
9259 	/* Prepare the mbox command to be posted */
9260 	mqe = &mboxq->u.mqe;
9261 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
9262 
9263 	/* Start timer for the mbox_tmo and log some mailbox post messages */
9264 	mod_timer(&psli->mbox_tmo, (jiffies +
9265 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
9266 
9267 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9268 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
9269 			"x%x x%x\n",
9270 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
9271 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9272 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9273 			phba->pport->port_state, psli->sli_flag);
9274 
9275 	if (mbx_cmnd != MBX_HEARTBEAT) {
9276 		if (mboxq->vport) {
9277 			lpfc_debugfs_disc_trc(mboxq->vport,
9278 				LPFC_DISC_TRC_MBOX_VPORT,
9279 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9280 				mbx_cmnd, mqe->un.mb_words[0],
9281 				mqe->un.mb_words[1]);
9282 		} else {
9283 			lpfc_debugfs_disc_trc(phba->pport,
9284 				LPFC_DISC_TRC_MBOX,
9285 				"MBOX Send: cmd:x%x mb:x%x x%x",
9286 				mbx_cmnd, mqe->un.mb_words[0],
9287 				mqe->un.mb_words[1]);
9288 		}
9289 	}
9290 	psli->slistat.mbox_cmd++;
9291 
9292 	/* Post the mailbox command to the port */
9293 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
9294 	if (rc != MBX_SUCCESS) {
9295 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9296 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
9297 				"cannot issue Data: x%x x%x\n",
9298 				mboxq->vport ? mboxq->vport->vpi : 0,
9299 				mboxq->u.mb.mbxCommand,
9300 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9301 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9302 				psli->sli_flag, MBX_NOWAIT);
9303 		goto out_not_finished;
9304 	}
9305 
9306 	return rc;
9307 
9308 out_not_finished:
9309 	spin_lock_irqsave(&phba->hbalock, iflags);
9310 	if (phba->sli.mbox_active) {
9311 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
9312 		__lpfc_mbox_cmpl_put(phba, mboxq);
9313 		/* Release the token */
9314 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9315 		phba->sli.mbox_active = NULL;
9316 	}
9317 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9318 
9319 	return MBX_NOT_FINISHED;
9320 }
9321 
9322 /**
9323  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
9324  * @phba: Pointer to HBA context object.
9325  * @pmbox: Pointer to mailbox object.
9326  * @flag: Flag indicating how the mailbox need to be processed.
9327  *
9328  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
9329  * the API jump table function pointer from the lpfc_hba struct.
9330  *
9331  * Return codes the caller owns the mailbox command after the return of the
9332  * function.
9333  **/
9334 int
9335 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
9336 {
9337 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
9338 }
9339 
9340 /**
9341  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
9342  * @phba: The hba struct for which this call is being executed.
9343  * @dev_grp: The HBA PCI-Device group number.
9344  *
9345  * This routine sets up the mbox interface API function jump table in @phba
9346  * struct.
9347  * Returns: 0 - success, -ENODEV - failure.
9348  **/
9349 int
9350 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
9351 {
9352 
9353 	switch (dev_grp) {
9354 	case LPFC_PCI_DEV_LP:
9355 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
9356 		phba->lpfc_sli_handle_slow_ring_event =
9357 				lpfc_sli_handle_slow_ring_event_s3;
9358 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
9359 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
9360 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
9361 		break;
9362 	case LPFC_PCI_DEV_OC:
9363 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
9364 		phba->lpfc_sli_handle_slow_ring_event =
9365 				lpfc_sli_handle_slow_ring_event_s4;
9366 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
9367 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
9368 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
9369 		break;
9370 	default:
9371 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9372 				"1420 Invalid HBA PCI-device group: 0x%x\n",
9373 				dev_grp);
9374 		return -ENODEV;
9375 	}
9376 	return 0;
9377 }
9378 
9379 /**
9380  * __lpfc_sli_ringtx_put - Add an iocb to the txq
9381  * @phba: Pointer to HBA context object.
9382  * @pring: Pointer to driver SLI ring object.
9383  * @piocb: Pointer to address of newly added command iocb.
9384  *
9385  * This function is called with hbalock held for SLI3 ports or
9386  * the ring lock held for SLI4 ports to add a command
9387  * iocb to the txq when SLI layer cannot submit the command iocb
9388  * to the ring.
9389  **/
9390 void
9391 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9392 		    struct lpfc_iocbq *piocb)
9393 {
9394 	if (phba->sli_rev == LPFC_SLI_REV4)
9395 		lockdep_assert_held(&pring->ring_lock);
9396 	else
9397 		lockdep_assert_held(&phba->hbalock);
9398 	/* Insert the caller's iocb in the txq tail for later processing. */
9399 	list_add_tail(&piocb->list, &pring->txq);
9400 }
9401 
9402 /**
9403  * lpfc_sli_next_iocb - Get the next iocb in the txq
9404  * @phba: Pointer to HBA context object.
9405  * @pring: Pointer to driver SLI ring object.
9406  * @piocb: Pointer to address of newly added command iocb.
9407  *
9408  * This function is called with hbalock held before a new
9409  * iocb is submitted to the firmware. This function checks
9410  * txq to flush the iocbs in txq to Firmware before
9411  * submitting new iocbs to the Firmware.
9412  * If there are iocbs in the txq which need to be submitted
9413  * to firmware, lpfc_sli_next_iocb returns the first element
9414  * of the txq after dequeuing it from txq.
9415  * If there is no iocb in the txq then the function will return
9416  * *piocb and *piocb is set to NULL. Caller needs to check
9417  * *piocb to find if there are more commands in the txq.
9418  **/
9419 static struct lpfc_iocbq *
9420 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9421 		   struct lpfc_iocbq **piocb)
9422 {
9423 	struct lpfc_iocbq * nextiocb;
9424 
9425 	lockdep_assert_held(&phba->hbalock);
9426 
9427 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
9428 	if (!nextiocb) {
9429 		nextiocb = *piocb;
9430 		*piocb = NULL;
9431 	}
9432 
9433 	return nextiocb;
9434 }
9435 
9436 /**
9437  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
9438  * @phba: Pointer to HBA context object.
9439  * @ring_number: SLI ring number to issue iocb on.
9440  * @piocb: Pointer to command iocb.
9441  * @flag: Flag indicating if this command can be put into txq.
9442  *
9443  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
9444  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
9445  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
9446  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
9447  * this function allows only iocbs for posting buffers. This function finds
9448  * next available slot in the command ring and posts the command to the
9449  * available slot and writes the port attention register to request HBA start
9450  * processing new iocb. If there is no slot available in the ring and
9451  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
9452  * the function returns IOCB_BUSY.
9453  *
9454  * This function is called with hbalock held. The function will return success
9455  * after it successfully submit the iocb to firmware or after adding to the
9456  * txq.
9457  **/
9458 static int
9459 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
9460 		    struct lpfc_iocbq *piocb, uint32_t flag)
9461 {
9462 	struct lpfc_iocbq *nextiocb;
9463 	IOCB_t *iocb;
9464 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
9465 
9466 	lockdep_assert_held(&phba->hbalock);
9467 
9468 	if (piocb->iocb_cmpl && (!piocb->vport) &&
9469 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
9470 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
9471 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9472 				"1807 IOCB x%x failed. No vport\n",
9473 				piocb->iocb.ulpCommand);
9474 		dump_stack();
9475 		return IOCB_ERROR;
9476 	}
9477 
9478 
9479 	/* If the PCI channel is in offline state, do not post iocbs. */
9480 	if (unlikely(pci_channel_offline(phba->pcidev)))
9481 		return IOCB_ERROR;
9482 
9483 	/* If HBA has a deferred error attention, fail the iocb. */
9484 	if (unlikely(phba->hba_flag & DEFER_ERATT))
9485 		return IOCB_ERROR;
9486 
9487 	/*
9488 	 * We should never get an IOCB if we are in a < LINK_DOWN state
9489 	 */
9490 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
9491 		return IOCB_ERROR;
9492 
9493 	/*
9494 	 * Check to see if we are blocking IOCB processing because of a
9495 	 * outstanding event.
9496 	 */
9497 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
9498 		goto iocb_busy;
9499 
9500 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
9501 		/*
9502 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
9503 		 * can be issued if the link is not up.
9504 		 */
9505 		switch (piocb->iocb.ulpCommand) {
9506 		case CMD_GEN_REQUEST64_CR:
9507 		case CMD_GEN_REQUEST64_CX:
9508 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
9509 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
9510 					FC_RCTL_DD_UNSOL_CMD) ||
9511 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
9512 					MENLO_TRANSPORT_TYPE))
9513 
9514 				goto iocb_busy;
9515 			break;
9516 		case CMD_QUE_RING_BUF_CN:
9517 		case CMD_QUE_RING_BUF64_CN:
9518 			/*
9519 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
9520 			 * completion, iocb_cmpl MUST be 0.
9521 			 */
9522 			if (piocb->iocb_cmpl)
9523 				piocb->iocb_cmpl = NULL;
9524 			fallthrough;
9525 		case CMD_CREATE_XRI_CR:
9526 		case CMD_CLOSE_XRI_CN:
9527 		case CMD_CLOSE_XRI_CX:
9528 			break;
9529 		default:
9530 			goto iocb_busy;
9531 		}
9532 
9533 	/*
9534 	 * For FCP commands, we must be in a state where we can process link
9535 	 * attention events.
9536 	 */
9537 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
9538 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
9539 		goto iocb_busy;
9540 	}
9541 
9542 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
9543 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
9544 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
9545 
9546 	if (iocb)
9547 		lpfc_sli_update_ring(phba, pring);
9548 	else
9549 		lpfc_sli_update_full_ring(phba, pring);
9550 
9551 	if (!piocb)
9552 		return IOCB_SUCCESS;
9553 
9554 	goto out_busy;
9555 
9556  iocb_busy:
9557 	pring->stats.iocb_cmd_delay++;
9558 
9559  out_busy:
9560 
9561 	if (!(flag & SLI_IOCB_RET_IOCB)) {
9562 		__lpfc_sli_ringtx_put(phba, pring, piocb);
9563 		return IOCB_SUCCESS;
9564 	}
9565 
9566 	return IOCB_BUSY;
9567 }
9568 
9569 /**
9570  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
9571  * @phba: Pointer to HBA context object.
9572  * @piocbq: Pointer to command iocb.
9573  * @sglq: Pointer to the scatter gather queue object.
9574  *
9575  * This routine converts the bpl or bde that is in the IOCB
9576  * to a sgl list for the sli4 hardware. The physical address
9577  * of the bpl/bde is converted back to a virtual address.
9578  * If the IOCB contains a BPL then the list of BDE's is
9579  * converted to sli4_sge's. If the IOCB contains a single
9580  * BDE then it is converted to a single sli_sge.
9581  * The IOCB is still in cpu endianess so the contents of
9582  * the bpl can be used without byte swapping.
9583  *
9584  * Returns valid XRI = Success, NO_XRI = Failure.
9585 **/
9586 static uint16_t
9587 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
9588 		struct lpfc_sglq *sglq)
9589 {
9590 	uint16_t xritag = NO_XRI;
9591 	struct ulp_bde64 *bpl = NULL;
9592 	struct ulp_bde64 bde;
9593 	struct sli4_sge *sgl  = NULL;
9594 	struct lpfc_dmabuf *dmabuf;
9595 	IOCB_t *icmd;
9596 	int numBdes = 0;
9597 	int i = 0;
9598 	uint32_t offset = 0; /* accumulated offset in the sg request list */
9599 	int inbound = 0; /* number of sg reply entries inbound from firmware */
9600 
9601 	if (!piocbq || !sglq)
9602 		return xritag;
9603 
9604 	sgl  = (struct sli4_sge *)sglq->sgl;
9605 	icmd = &piocbq->iocb;
9606 	if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
9607 		return sglq->sli4_xritag;
9608 	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9609 		numBdes = icmd->un.genreq64.bdl.bdeSize /
9610 				sizeof(struct ulp_bde64);
9611 		/* The addrHigh and addrLow fields within the IOCB
9612 		 * have not been byteswapped yet so there is no
9613 		 * need to swap them back.
9614 		 */
9615 		if (piocbq->context3)
9616 			dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
9617 		else
9618 			return xritag;
9619 
9620 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
9621 		if (!bpl)
9622 			return xritag;
9623 
9624 		for (i = 0; i < numBdes; i++) {
9625 			/* Should already be byte swapped. */
9626 			sgl->addr_hi = bpl->addrHigh;
9627 			sgl->addr_lo = bpl->addrLow;
9628 
9629 			sgl->word2 = le32_to_cpu(sgl->word2);
9630 			if ((i+1) == numBdes)
9631 				bf_set(lpfc_sli4_sge_last, sgl, 1);
9632 			else
9633 				bf_set(lpfc_sli4_sge_last, sgl, 0);
9634 			/* swap the size field back to the cpu so we
9635 			 * can assign it to the sgl.
9636 			 */
9637 			bde.tus.w = le32_to_cpu(bpl->tus.w);
9638 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
9639 			/* The offsets in the sgl need to be accumulated
9640 			 * separately for the request and reply lists.
9641 			 * The request is always first, the reply follows.
9642 			 */
9643 			if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
9644 				/* add up the reply sg entries */
9645 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
9646 					inbound++;
9647 				/* first inbound? reset the offset */
9648 				if (inbound == 1)
9649 					offset = 0;
9650 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
9651 				bf_set(lpfc_sli4_sge_type, sgl,
9652 					LPFC_SGE_TYPE_DATA);
9653 				offset += bde.tus.f.bdeSize;
9654 			}
9655 			sgl->word2 = cpu_to_le32(sgl->word2);
9656 			bpl++;
9657 			sgl++;
9658 		}
9659 	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
9660 			/* The addrHigh and addrLow fields of the BDE have not
9661 			 * been byteswapped yet so they need to be swapped
9662 			 * before putting them in the sgl.
9663 			 */
9664 			sgl->addr_hi =
9665 				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
9666 			sgl->addr_lo =
9667 				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
9668 			sgl->word2 = le32_to_cpu(sgl->word2);
9669 			bf_set(lpfc_sli4_sge_last, sgl, 1);
9670 			sgl->word2 = cpu_to_le32(sgl->word2);
9671 			sgl->sge_len =
9672 				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
9673 	}
9674 	return sglq->sli4_xritag;
9675 }
9676 
9677 /**
9678  * lpfc_sli4_iocb2wqe - Convert the IOCB to a work queue entry.
9679  * @phba: Pointer to HBA context object.
9680  * @iocbq: Pointer to command iocb.
9681  * @wqe: Pointer to the work queue entry.
9682  *
9683  * This routine converts the iocb command to its Work Queue Entry
9684  * equivalent. The wqe pointer should not have any fields set when
9685  * this routine is called because it will memcpy over them.
9686  * This routine does not set the CQ_ID or the WQEC bits in the
9687  * wqe.
9688  *
9689  * Returns: 0 = Success, IOCB_ERROR = Failure.
9690  **/
9691 static int
9692 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
9693 		union lpfc_wqe128 *wqe)
9694 {
9695 	uint32_t xmit_len = 0, total_len = 0;
9696 	uint8_t ct = 0;
9697 	uint32_t fip;
9698 	uint32_t abort_tag;
9699 	uint8_t command_type = ELS_COMMAND_NON_FIP;
9700 	uint8_t cmnd;
9701 	uint16_t xritag;
9702 	uint16_t abrt_iotag;
9703 	struct lpfc_iocbq *abrtiocbq;
9704 	struct ulp_bde64 *bpl = NULL;
9705 	uint32_t els_id = LPFC_ELS_ID_DEFAULT;
9706 	int numBdes, i;
9707 	struct ulp_bde64 bde;
9708 	struct lpfc_nodelist *ndlp;
9709 	uint32_t *pcmd;
9710 	uint32_t if_type;
9711 
9712 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
9713 	/* The fcp commands will set command type */
9714 	if (iocbq->iocb_flag &  LPFC_IO_FCP)
9715 		command_type = FCP_COMMAND;
9716 	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
9717 		command_type = ELS_COMMAND_FIP;
9718 	else
9719 		command_type = ELS_COMMAND_NON_FIP;
9720 
9721 	if (phba->fcp_embed_io)
9722 		memset(wqe, 0, sizeof(union lpfc_wqe128));
9723 	/* Some of the fields are in the right position already */
9724 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
9725 	/* The ct field has moved so reset */
9726 	wqe->generic.wqe_com.word7 = 0;
9727 	wqe->generic.wqe_com.word10 = 0;
9728 
9729 	abort_tag = (uint32_t) iocbq->iotag;
9730 	xritag = iocbq->sli4_xritag;
9731 	/* words0-2 bpl convert bde */
9732 	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9733 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
9734 				sizeof(struct ulp_bde64);
9735 		bpl  = (struct ulp_bde64 *)
9736 			((struct lpfc_dmabuf *)iocbq->context3)->virt;
9737 		if (!bpl)
9738 			return IOCB_ERROR;
9739 
9740 		/* Should already be byte swapped. */
9741 		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
9742 		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
9743 		/* swap the size field back to the cpu so we
9744 		 * can assign it to the sgl.
9745 		 */
9746 		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
9747 		xmit_len = wqe->generic.bde.tus.f.bdeSize;
9748 		total_len = 0;
9749 		for (i = 0; i < numBdes; i++) {
9750 			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
9751 			total_len += bde.tus.f.bdeSize;
9752 		}
9753 	} else
9754 		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
9755 
9756 	iocbq->iocb.ulpIoTag = iocbq->iotag;
9757 	cmnd = iocbq->iocb.ulpCommand;
9758 
9759 	switch (iocbq->iocb.ulpCommand) {
9760 	case CMD_ELS_REQUEST64_CR:
9761 		if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
9762 			ndlp = iocbq->context_un.ndlp;
9763 		else
9764 			ndlp = (struct lpfc_nodelist *)iocbq->context1;
9765 		if (!iocbq->iocb.ulpLe) {
9766 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9767 				"2007 Only Limited Edition cmd Format"
9768 				" supported 0x%x\n",
9769 				iocbq->iocb.ulpCommand);
9770 			return IOCB_ERROR;
9771 		}
9772 
9773 		wqe->els_req.payload_len = xmit_len;
9774 		/* Els_reguest64 has a TMO */
9775 		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
9776 			iocbq->iocb.ulpTimeout);
9777 		/* Need a VF for word 4 set the vf bit*/
9778 		bf_set(els_req64_vf, &wqe->els_req, 0);
9779 		/* And a VFID for word 12 */
9780 		bf_set(els_req64_vfid, &wqe->els_req, 0);
9781 		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
9782 		bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9783 		       iocbq->iocb.ulpContext);
9784 		bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
9785 		bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
9786 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
9787 		if (command_type == ELS_COMMAND_FIP)
9788 			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
9789 					>> LPFC_FIP_ELS_ID_SHIFT);
9790 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9791 					iocbq->context2)->virt);
9792 		if_type = bf_get(lpfc_sli_intf_if_type,
9793 					&phba->sli4_hba.sli_intf);
9794 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9795 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
9796 				*pcmd == ELS_CMD_SCR ||
9797 				*pcmd == ELS_CMD_RDF ||
9798 				*pcmd == ELS_CMD_RSCN_XMT ||
9799 				*pcmd == ELS_CMD_FDISC ||
9800 				*pcmd == ELS_CMD_LOGO ||
9801 				*pcmd == ELS_CMD_QFPA ||
9802 				*pcmd == ELS_CMD_UVEM ||
9803 				*pcmd == ELS_CMD_PLOGI)) {
9804 				bf_set(els_req64_sp, &wqe->els_req, 1);
9805 				bf_set(els_req64_sid, &wqe->els_req,
9806 					iocbq->vport->fc_myDID);
9807 				if ((*pcmd == ELS_CMD_FLOGI) &&
9808 					!(phba->fc_topology ==
9809 						LPFC_TOPOLOGY_LOOP))
9810 					bf_set(els_req64_sid, &wqe->els_req, 0);
9811 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
9812 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9813 					phba->vpi_ids[iocbq->vport->vpi]);
9814 			} else if (pcmd && iocbq->context1) {
9815 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
9816 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9817 					phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9818 			}
9819 		}
9820 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
9821 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9822 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
9823 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
9824 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
9825 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
9826 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
9827 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
9828 		wqe->els_req.max_response_payload_len = total_len - xmit_len;
9829 		break;
9830 	case CMD_XMIT_SEQUENCE64_CX:
9831 		bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
9832 		       iocbq->iocb.un.ulpWord[3]);
9833 		bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
9834 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
9835 		/* The entire sequence is transmitted for this IOCB */
9836 		xmit_len = total_len;
9837 		cmnd = CMD_XMIT_SEQUENCE64_CR;
9838 		if (phba->link_flag & LS_LOOPBACK_MODE)
9839 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
9840 		fallthrough;
9841 	case CMD_XMIT_SEQUENCE64_CR:
9842 		/* word3 iocb=io_tag32 wqe=reserved */
9843 		wqe->xmit_sequence.rsvd3 = 0;
9844 		/* word4 relative_offset memcpy */
9845 		/* word5 r_ctl/df_ctl memcpy */
9846 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
9847 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
9848 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
9849 		       LPFC_WQE_IOD_WRITE);
9850 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
9851 		       LPFC_WQE_LENLOC_WORD12);
9852 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
9853 		wqe->xmit_sequence.xmit_len = xmit_len;
9854 		command_type = OTHER_COMMAND;
9855 		break;
9856 	case CMD_XMIT_BCAST64_CN:
9857 		/* word3 iocb=iotag32 wqe=seq_payload_len */
9858 		wqe->xmit_bcast64.seq_payload_len = xmit_len;
9859 		/* word4 iocb=rsvd wqe=rsvd */
9860 		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
9861 		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
9862 		bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
9863 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9864 		bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
9865 		bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
9866 		bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
9867 		       LPFC_WQE_LENLOC_WORD3);
9868 		bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
9869 		break;
9870 	case CMD_FCP_IWRITE64_CR:
9871 		command_type = FCP_COMMAND_DATA_OUT;
9872 		/* word3 iocb=iotag wqe=payload_offset_len */
9873 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9874 		bf_set(payload_offset_len, &wqe->fcp_iwrite,
9875 		       xmit_len + sizeof(struct fcp_rsp));
9876 		bf_set(cmd_buff_len, &wqe->fcp_iwrite,
9877 		       0);
9878 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9879 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9880 		bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
9881 		       iocbq->iocb.ulpFCP2Rcvy);
9882 		bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
9883 		/* Always open the exchange */
9884 		bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
9885 		bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
9886 		       LPFC_WQE_LENLOC_WORD4);
9887 		bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
9888 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
9889 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9890 			bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
9891 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
9892 			if (iocbq->priority) {
9893 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9894 				       (iocbq->priority << 1));
9895 			} else {
9896 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9897 				       (phba->cfg_XLanePriority << 1));
9898 			}
9899 		}
9900 		/* Note, word 10 is already initialized to 0 */
9901 
9902 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9903 		if (phba->cfg_enable_pbde)
9904 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 1);
9905 		else
9906 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
9907 
9908 		if (phba->fcp_embed_io) {
9909 			struct lpfc_io_buf *lpfc_cmd;
9910 			struct sli4_sge *sgl;
9911 			struct fcp_cmnd *fcp_cmnd;
9912 			uint32_t *ptr;
9913 
9914 			/* 128 byte wqe support here */
9915 
9916 			lpfc_cmd = iocbq->context1;
9917 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9918 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9919 
9920 			/* Word 0-2 - FCP_CMND */
9921 			wqe->generic.bde.tus.f.bdeFlags =
9922 				BUFF_TYPE_BDE_IMMED;
9923 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9924 			wqe->generic.bde.addrHigh = 0;
9925 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9926 
9927 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
9928 			bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
9929 
9930 			/* Word 22-29  FCP CMND Payload */
9931 			ptr = &wqe->words[22];
9932 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9933 		}
9934 		break;
9935 	case CMD_FCP_IREAD64_CR:
9936 		/* word3 iocb=iotag wqe=payload_offset_len */
9937 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9938 		bf_set(payload_offset_len, &wqe->fcp_iread,
9939 		       xmit_len + sizeof(struct fcp_rsp));
9940 		bf_set(cmd_buff_len, &wqe->fcp_iread,
9941 		       0);
9942 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9943 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9944 		bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
9945 		       iocbq->iocb.ulpFCP2Rcvy);
9946 		bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
9947 		/* Always open the exchange */
9948 		bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
9949 		bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
9950 		       LPFC_WQE_LENLOC_WORD4);
9951 		bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
9952 		bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
9953 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9954 			bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
9955 			bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
9956 			if (iocbq->priority) {
9957 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9958 				       (iocbq->priority << 1));
9959 			} else {
9960 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9961 				       (phba->cfg_XLanePriority << 1));
9962 			}
9963 		}
9964 		/* Note, word 10 is already initialized to 0 */
9965 
9966 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9967 		if (phba->cfg_enable_pbde)
9968 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 1);
9969 		else
9970 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
9971 
9972 		if (phba->fcp_embed_io) {
9973 			struct lpfc_io_buf *lpfc_cmd;
9974 			struct sli4_sge *sgl;
9975 			struct fcp_cmnd *fcp_cmnd;
9976 			uint32_t *ptr;
9977 
9978 			/* 128 byte wqe support here */
9979 
9980 			lpfc_cmd = iocbq->context1;
9981 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9982 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9983 
9984 			/* Word 0-2 - FCP_CMND */
9985 			wqe->generic.bde.tus.f.bdeFlags =
9986 				BUFF_TYPE_BDE_IMMED;
9987 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9988 			wqe->generic.bde.addrHigh = 0;
9989 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9990 
9991 			bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
9992 			bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
9993 
9994 			/* Word 22-29  FCP CMND Payload */
9995 			ptr = &wqe->words[22];
9996 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9997 		}
9998 		break;
9999 	case CMD_FCP_ICMND64_CR:
10000 		/* word3 iocb=iotag wqe=payload_offset_len */
10001 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
10002 		bf_set(payload_offset_len, &wqe->fcp_icmd,
10003 		       xmit_len + sizeof(struct fcp_rsp));
10004 		bf_set(cmd_buff_len, &wqe->fcp_icmd,
10005 		       0);
10006 		/* word3 iocb=IO_TAG wqe=reserved */
10007 		bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
10008 		/* Always open the exchange */
10009 		bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
10010 		bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
10011 		bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
10012 		bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
10013 		       LPFC_WQE_LENLOC_NONE);
10014 		bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
10015 		       iocbq->iocb.ulpFCP2Rcvy);
10016 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
10017 			bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
10018 			bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
10019 			if (iocbq->priority) {
10020 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
10021 				       (iocbq->priority << 1));
10022 			} else {
10023 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
10024 				       (phba->cfg_XLanePriority << 1));
10025 			}
10026 		}
10027 		/* Note, word 10 is already initialized to 0 */
10028 
10029 		if (phba->fcp_embed_io) {
10030 			struct lpfc_io_buf *lpfc_cmd;
10031 			struct sli4_sge *sgl;
10032 			struct fcp_cmnd *fcp_cmnd;
10033 			uint32_t *ptr;
10034 
10035 			/* 128 byte wqe support here */
10036 
10037 			lpfc_cmd = iocbq->context1;
10038 			sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10039 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
10040 
10041 			/* Word 0-2 - FCP_CMND */
10042 			wqe->generic.bde.tus.f.bdeFlags =
10043 				BUFF_TYPE_BDE_IMMED;
10044 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10045 			wqe->generic.bde.addrHigh = 0;
10046 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
10047 
10048 			bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
10049 			bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
10050 
10051 			/* Word 22-29  FCP CMND Payload */
10052 			ptr = &wqe->words[22];
10053 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10054 		}
10055 		break;
10056 	case CMD_GEN_REQUEST64_CR:
10057 		/* For this command calculate the xmit length of the
10058 		 * request bde.
10059 		 */
10060 		xmit_len = 0;
10061 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
10062 			sizeof(struct ulp_bde64);
10063 		for (i = 0; i < numBdes; i++) {
10064 			bde.tus.w = le32_to_cpu(bpl[i].tus.w);
10065 			if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
10066 				break;
10067 			xmit_len += bde.tus.f.bdeSize;
10068 		}
10069 		/* word3 iocb=IO_TAG wqe=request_payload_len */
10070 		wqe->gen_req.request_payload_len = xmit_len;
10071 		/* word4 iocb=parameter wqe=relative_offset memcpy */
10072 		/* word5 [rctl, type, df_ctl, la] copied in memcpy */
10073 		/* word6 context tag copied in memcpy */
10074 		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
10075 			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
10076 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10077 				"2015 Invalid CT %x command 0x%x\n",
10078 				ct, iocbq->iocb.ulpCommand);
10079 			return IOCB_ERROR;
10080 		}
10081 		bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
10082 		bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
10083 		bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
10084 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
10085 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
10086 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
10087 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
10088 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
10089 		wqe->gen_req.max_response_payload_len = total_len - xmit_len;
10090 		command_type = OTHER_COMMAND;
10091 		break;
10092 	case CMD_XMIT_ELS_RSP64_CX:
10093 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
10094 		/* words0-2 BDE memcpy */
10095 		/* word3 iocb=iotag32 wqe=response_payload_len */
10096 		wqe->xmit_els_rsp.response_payload_len = xmit_len;
10097 		/* word4 */
10098 		wqe->xmit_els_rsp.word4 = 0;
10099 		/* word5 iocb=rsvd wge=did */
10100 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
10101 			 iocbq->iocb.un.xseq64.xmit_els_remoteID);
10102 
10103 		if_type = bf_get(lpfc_sli_intf_if_type,
10104 					&phba->sli4_hba.sli_intf);
10105 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10106 			if (iocbq->vport->fc_flag & FC_PT2PT) {
10107 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
10108 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
10109 					iocbq->vport->fc_myDID);
10110 				if (iocbq->vport->fc_myDID == Fabric_DID) {
10111 					bf_set(wqe_els_did,
10112 						&wqe->xmit_els_rsp.wqe_dest, 0);
10113 				}
10114 			}
10115 		}
10116 		bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
10117 		       ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
10118 		bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
10119 		bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
10120 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
10121 		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
10122 			bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
10123 			       phba->vpi_ids[iocbq->vport->vpi]);
10124 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
10125 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
10126 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
10127 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
10128 		       LPFC_WQE_LENLOC_WORD3);
10129 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
10130 		bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
10131 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
10132 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
10133 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
10134 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
10135 					iocbq->vport->fc_myDID);
10136 				bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
10137 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
10138 					phba->vpi_ids[phba->pport->vpi]);
10139 		}
10140 		command_type = OTHER_COMMAND;
10141 		break;
10142 	case CMD_CLOSE_XRI_CN:
10143 	case CMD_ABORT_XRI_CN:
10144 	case CMD_ABORT_XRI_CX:
10145 		/* words 0-2 memcpy should be 0 rserved */
10146 		/* port will send abts */
10147 		abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
10148 		if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
10149 			abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
10150 			fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
10151 		} else
10152 			fip = 0;
10153 
10154 		if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
10155 			/*
10156 			 * The link is down, or the command was ELS_FIP
10157 			 * so the fw does not need to send abts
10158 			 * on the wire.
10159 			 */
10160 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
10161 		else
10162 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
10163 		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
10164 		/* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
10165 		wqe->abort_cmd.rsrvd5 = 0;
10166 		bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
10167 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
10168 		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
10169 		/*
10170 		 * The abort handler will send us CMD_ABORT_XRI_CN or
10171 		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
10172 		 */
10173 		bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
10174 		bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
10175 		bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
10176 		       LPFC_WQE_LENLOC_NONE);
10177 		cmnd = CMD_ABORT_XRI_CX;
10178 		command_type = OTHER_COMMAND;
10179 		xritag = 0;
10180 		break;
10181 	case CMD_XMIT_BLS_RSP64_CX:
10182 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
10183 		/* As BLS ABTS RSP WQE is very different from other WQEs,
10184 		 * we re-construct this WQE here based on information in
10185 		 * iocbq from scratch.
10186 		 */
10187 		memset(wqe, 0, sizeof(*wqe));
10188 		/* OX_ID is invariable to who sent ABTS to CT exchange */
10189 		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
10190 		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
10191 		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
10192 		    LPFC_ABTS_UNSOL_INT) {
10193 			/* ABTS sent by initiator to CT exchange, the
10194 			 * RX_ID field will be filled with the newly
10195 			 * allocated responder XRI.
10196 			 */
10197 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10198 			       iocbq->sli4_xritag);
10199 		} else {
10200 			/* ABTS sent by responder to CT exchange, the
10201 			 * RX_ID field will be filled with the responder
10202 			 * RX_ID from ABTS.
10203 			 */
10204 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10205 			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
10206 		}
10207 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
10208 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
10209 
10210 		/* Use CT=VPI */
10211 		bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
10212 			ndlp->nlp_DID);
10213 		bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
10214 			iocbq->iocb.ulpContext);
10215 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
10216 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
10217 			phba->vpi_ids[phba->pport->vpi]);
10218 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
10219 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
10220 		       LPFC_WQE_LENLOC_NONE);
10221 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
10222 		command_type = OTHER_COMMAND;
10223 		if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
10224 			bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
10225 			       bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
10226 			bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
10227 			       bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
10228 			bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
10229 			       bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
10230 		}
10231 
10232 		break;
10233 	case CMD_SEND_FRAME:
10234 		bf_set(wqe_cmnd, &wqe->generic.wqe_com, CMD_SEND_FRAME);
10235 		bf_set(wqe_sof, &wqe->generic.wqe_com, 0x2E); /* SOF byte */
10236 		bf_set(wqe_eof, &wqe->generic.wqe_com, 0x41); /* EOF byte */
10237 		bf_set(wqe_lenloc, &wqe->generic.wqe_com, 1);
10238 		bf_set(wqe_xbl, &wqe->generic.wqe_com, 1);
10239 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10240 		bf_set(wqe_xc, &wqe->generic.wqe_com, 1);
10241 		bf_set(wqe_cmd_type, &wqe->generic.wqe_com, 0xA);
10242 		bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10243 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10244 		bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10245 		return 0;
10246 	case CMD_XRI_ABORTED_CX:
10247 	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
10248 	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
10249 	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
10250 	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
10251 	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
10252 	default:
10253 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10254 				"2014 Invalid command 0x%x\n",
10255 				iocbq->iocb.ulpCommand);
10256 		return IOCB_ERROR;
10257 	}
10258 
10259 	if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
10260 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
10261 	else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
10262 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
10263 	else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
10264 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
10265 	iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
10266 			      LPFC_IO_DIF_INSERT);
10267 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10268 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10269 	wqe->generic.wqe_com.abort_tag = abort_tag;
10270 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
10271 	bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
10272 	bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
10273 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10274 	return 0;
10275 }
10276 
10277 /**
10278  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10279  * @phba: Pointer to HBA context object.
10280  * @ring_number: SLI ring number to issue wqe on.
10281  * @piocb: Pointer to command iocb.
10282  * @flag: Flag indicating if this command can be put into txq.
10283  *
10284  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10285  * send  an iocb command to an HBA with SLI-4 interface spec.
10286  *
10287  * This function takes the hbalock before invoking the lockless version.
10288  * The function will return success after it successfully submit the wqe to
10289  * firmware or after adding to the txq.
10290  **/
10291 static int
10292 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10293 			   struct lpfc_iocbq *piocb, uint32_t flag)
10294 {
10295 	unsigned long iflags;
10296 	int rc;
10297 
10298 	spin_lock_irqsave(&phba->hbalock, iflags);
10299 	rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10300 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10301 
10302 	return rc;
10303 }
10304 
10305 /**
10306  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10307  * @phba: Pointer to HBA context object.
10308  * @ring_number: SLI ring number to issue wqe on.
10309  * @piocb: Pointer to command iocb.
10310  * @flag: Flag indicating if this command can be put into txq.
10311  *
10312  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10313  * an wqe command to an HBA with SLI-4 interface spec.
10314  *
10315  * This function is a lockless version. The function will return success
10316  * after it successfully submit the wqe to firmware or after adding to the
10317  * txq.
10318  **/
10319 static int
10320 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10321 			   struct lpfc_iocbq *piocb, uint32_t flag)
10322 {
10323 	int rc;
10324 	struct lpfc_io_buf *lpfc_cmd =
10325 		(struct lpfc_io_buf *)piocb->context1;
10326 	union lpfc_wqe128 *wqe = &piocb->wqe;
10327 	struct sli4_sge *sgl;
10328 
10329 	/* 128 byte wqe support here */
10330 	sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10331 
10332 	if (phba->fcp_embed_io) {
10333 		struct fcp_cmnd *fcp_cmnd;
10334 		u32 *ptr;
10335 
10336 		fcp_cmnd = lpfc_cmd->fcp_cmnd;
10337 
10338 		/* Word 0-2 - FCP_CMND */
10339 		wqe->generic.bde.tus.f.bdeFlags =
10340 			BUFF_TYPE_BDE_IMMED;
10341 		wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10342 		wqe->generic.bde.addrHigh = 0;
10343 		wqe->generic.bde.addrLow =  88;  /* Word 22 */
10344 
10345 		bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10346 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10347 
10348 		/* Word 22-29  FCP CMND Payload */
10349 		ptr = &wqe->words[22];
10350 		memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10351 	} else {
10352 		/* Word 0-2 - Inline BDE */
10353 		wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
10354 		wqe->generic.bde.tus.f.bdeSize = sizeof(struct fcp_cmnd);
10355 		wqe->generic.bde.addrHigh = sgl->addr_hi;
10356 		wqe->generic.bde.addrLow =  sgl->addr_lo;
10357 
10358 		/* Word 10 */
10359 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10360 		bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
10361 	}
10362 
10363 	/* add the VMID tags as per switch response */
10364 	if (unlikely(piocb->iocb_flag & LPFC_IO_VMID)) {
10365 		if (phba->pport->vmid_priority_tagging) {
10366 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
10367 			bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10368 					(piocb->vmid_tag.cs_ctl_vmid));
10369 		} else {
10370 			bf_set(wqe_appid, &wqe->fcp_iwrite.wqe_com, 1);
10371 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10372 			wqe->words[31] = piocb->vmid_tag.app_id;
10373 		}
10374 	}
10375 	rc = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
10376 	return rc;
10377 }
10378 
10379 /**
10380  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10381  * @phba: Pointer to HBA context object.
10382  * @ring_number: SLI ring number to issue iocb on.
10383  * @piocb: Pointer to command iocb.
10384  * @flag: Flag indicating if this command can be put into txq.
10385  *
10386  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10387  * an iocb command to an HBA with SLI-4 interface spec.
10388  *
10389  * This function is called with ringlock held. The function will return success
10390  * after it successfully submit the iocb to firmware or after adding to the
10391  * txq.
10392  **/
10393 static int
10394 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10395 			 struct lpfc_iocbq *piocb, uint32_t flag)
10396 {
10397 	struct lpfc_sglq *sglq;
10398 	union lpfc_wqe128 wqe;
10399 	struct lpfc_queue *wq;
10400 	struct lpfc_sli_ring *pring;
10401 
10402 	/* Get the WQ */
10403 	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
10404 	    (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
10405 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10406 	} else {
10407 		wq = phba->sli4_hba.els_wq;
10408 	}
10409 
10410 	/* Get corresponding ring */
10411 	pring = wq->pring;
10412 
10413 	/*
10414 	 * The WQE can be either 64 or 128 bytes,
10415 	 */
10416 
10417 	lockdep_assert_held(&pring->ring_lock);
10418 
10419 	if (piocb->sli4_xritag == NO_XRI) {
10420 		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
10421 		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
10422 			sglq = NULL;
10423 		else {
10424 			if (!list_empty(&pring->txq)) {
10425 				if (!(flag & SLI_IOCB_RET_IOCB)) {
10426 					__lpfc_sli_ringtx_put(phba,
10427 						pring, piocb);
10428 					return IOCB_SUCCESS;
10429 				} else {
10430 					return IOCB_BUSY;
10431 				}
10432 			} else {
10433 				sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10434 				if (!sglq) {
10435 					if (!(flag & SLI_IOCB_RET_IOCB)) {
10436 						__lpfc_sli_ringtx_put(phba,
10437 								pring,
10438 								piocb);
10439 						return IOCB_SUCCESS;
10440 					} else
10441 						return IOCB_BUSY;
10442 				}
10443 			}
10444 		}
10445 	} else if (piocb->iocb_flag &  LPFC_IO_FCP) {
10446 		/* These IO's already have an XRI and a mapped sgl. */
10447 		sglq = NULL;
10448 	}
10449 	else {
10450 		/*
10451 		 * This is a continuation of a commandi,(CX) so this
10452 		 * sglq is on the active list
10453 		 */
10454 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10455 		if (!sglq)
10456 			return IOCB_ERROR;
10457 	}
10458 
10459 	if (sglq) {
10460 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10461 		piocb->sli4_xritag = sglq->sli4_xritag;
10462 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
10463 			return IOCB_ERROR;
10464 	}
10465 
10466 	if (lpfc_sli4_iocb2wqe(phba, piocb, &wqe))
10467 		return IOCB_ERROR;
10468 
10469 	if (lpfc_sli4_wq_put(wq, &wqe))
10470 		return IOCB_ERROR;
10471 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10472 
10473 	return 0;
10474 }
10475 
10476 /*
10477  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
10478  *
10479  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
10480  * or IOCB for sli-3  function.
10481  * pointer from the lpfc_hba struct.
10482  *
10483  * Return codes:
10484  * IOCB_ERROR - Error
10485  * IOCB_SUCCESS - Success
10486  * IOCB_BUSY - Busy
10487  **/
10488 int
10489 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
10490 		      struct lpfc_iocbq *piocb, uint32_t flag)
10491 {
10492 	return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
10493 }
10494 
10495 /*
10496  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10497  *
10498  * This routine wraps the actual lockless version for issusing IOCB function
10499  * pointer from the lpfc_hba struct.
10500  *
10501  * Return codes:
10502  * IOCB_ERROR - Error
10503  * IOCB_SUCCESS - Success
10504  * IOCB_BUSY - Busy
10505  **/
10506 int
10507 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10508 		struct lpfc_iocbq *piocb, uint32_t flag)
10509 {
10510 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10511 }
10512 
10513 /**
10514  * lpfc_sli_api_table_setup - Set up sli api function jump table
10515  * @phba: The hba struct for which this call is being executed.
10516  * @dev_grp: The HBA PCI-Device group number.
10517  *
10518  * This routine sets up the SLI interface API function jump table in @phba
10519  * struct.
10520  * Returns: 0 - success, -ENODEV - failure.
10521  **/
10522 int
10523 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10524 {
10525 
10526 	switch (dev_grp) {
10527 	case LPFC_PCI_DEV_LP:
10528 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
10529 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
10530 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
10531 		break;
10532 	case LPFC_PCI_DEV_OC:
10533 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
10534 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
10535 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
10536 		break;
10537 	default:
10538 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10539 				"1419 Invalid HBA PCI-device group: 0x%x\n",
10540 				dev_grp);
10541 		return -ENODEV;
10542 	}
10543 	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
10544 	return 0;
10545 }
10546 
10547 /**
10548  * lpfc_sli4_calc_ring - Calculates which ring to use
10549  * @phba: Pointer to HBA context object.
10550  * @piocb: Pointer to command iocb.
10551  *
10552  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
10553  * hba_wqidx, thus we need to calculate the corresponding ring.
10554  * Since ABORTS must go on the same WQ of the command they are
10555  * aborting, we use command's hba_wqidx.
10556  */
10557 struct lpfc_sli_ring *
10558 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
10559 {
10560 	struct lpfc_io_buf *lpfc_cmd;
10561 
10562 	if (piocb->iocb_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
10563 		if (unlikely(!phba->sli4_hba.hdwq))
10564 			return NULL;
10565 		/*
10566 		 * for abort iocb hba_wqidx should already
10567 		 * be setup based on what work queue we used.
10568 		 */
10569 		if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
10570 			lpfc_cmd = (struct lpfc_io_buf *)piocb->context1;
10571 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
10572 		}
10573 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
10574 	} else {
10575 		if (unlikely(!phba->sli4_hba.els_wq))
10576 			return NULL;
10577 		piocb->hba_wqidx = 0;
10578 		return phba->sli4_hba.els_wq->pring;
10579 	}
10580 }
10581 
10582 /**
10583  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
10584  * @phba: Pointer to HBA context object.
10585  * @ring_number: Ring number
10586  * @piocb: Pointer to command iocb.
10587  * @flag: Flag indicating if this command can be put into txq.
10588  *
10589  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
10590  * function. This function gets the hbalock and calls
10591  * __lpfc_sli_issue_iocb function and will return the error returned
10592  * by __lpfc_sli_issue_iocb function. This wrapper is used by
10593  * functions which do not hold hbalock.
10594  **/
10595 int
10596 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10597 		    struct lpfc_iocbq *piocb, uint32_t flag)
10598 {
10599 	struct lpfc_sli_ring *pring;
10600 	struct lpfc_queue *eq;
10601 	unsigned long iflags;
10602 	int rc;
10603 
10604 	if (phba->sli_rev == LPFC_SLI_REV4) {
10605 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
10606 
10607 		pring = lpfc_sli4_calc_ring(phba, piocb);
10608 		if (unlikely(pring == NULL))
10609 			return IOCB_ERROR;
10610 
10611 		spin_lock_irqsave(&pring->ring_lock, iflags);
10612 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10613 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
10614 
10615 		lpfc_sli4_poll_eq(eq, LPFC_POLL_FASTPATH);
10616 	} else {
10617 		/* For now, SLI2/3 will still use hbalock */
10618 		spin_lock_irqsave(&phba->hbalock, iflags);
10619 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10620 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10621 	}
10622 	return rc;
10623 }
10624 
10625 /**
10626  * lpfc_extra_ring_setup - Extra ring setup function
10627  * @phba: Pointer to HBA context object.
10628  *
10629  * This function is called while driver attaches with the
10630  * HBA to setup the extra ring. The extra ring is used
10631  * only when driver needs to support target mode functionality
10632  * or IP over FC functionalities.
10633  *
10634  * This function is called with no lock held. SLI3 only.
10635  **/
10636 static int
10637 lpfc_extra_ring_setup( struct lpfc_hba *phba)
10638 {
10639 	struct lpfc_sli *psli;
10640 	struct lpfc_sli_ring *pring;
10641 
10642 	psli = &phba->sli;
10643 
10644 	/* Adjust cmd/rsp ring iocb entries more evenly */
10645 
10646 	/* Take some away from the FCP ring */
10647 	pring = &psli->sli3_ring[LPFC_FCP_RING];
10648 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10649 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10650 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10651 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10652 
10653 	/* and give them to the extra ring */
10654 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
10655 
10656 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10657 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10658 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10659 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10660 
10661 	/* Setup default profile for this ring */
10662 	pring->iotag_max = 4096;
10663 	pring->num_mask = 1;
10664 	pring->prt[0].profile = 0;      /* Mask 0 */
10665 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
10666 	pring->prt[0].type = phba->cfg_multi_ring_type;
10667 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
10668 	return 0;
10669 }
10670 
10671 static void
10672 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
10673 			     struct lpfc_nodelist *ndlp)
10674 {
10675 	unsigned long iflags;
10676 	struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
10677 
10678 	spin_lock_irqsave(&phba->hbalock, iflags);
10679 	if (!list_empty(&evtp->evt_listp)) {
10680 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10681 		return;
10682 	}
10683 
10684 	/* Incrementing the reference count until the queued work is done. */
10685 	evtp->evt_arg1  = lpfc_nlp_get(ndlp);
10686 	if (!evtp->evt_arg1) {
10687 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10688 		return;
10689 	}
10690 	evtp->evt = LPFC_EVT_RECOVER_PORT;
10691 	list_add_tail(&evtp->evt_listp, &phba->work_list);
10692 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10693 
10694 	lpfc_worker_wake_up(phba);
10695 }
10696 
10697 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
10698  * @phba: Pointer to HBA context object.
10699  * @iocbq: Pointer to iocb object.
10700  *
10701  * The async_event handler calls this routine when it receives
10702  * an ASYNC_STATUS_CN event from the port.  The port generates
10703  * this event when an Abort Sequence request to an rport fails
10704  * twice in succession.  The abort could be originated by the
10705  * driver or by the port.  The ABTS could have been for an ELS
10706  * or FCP IO.  The port only generates this event when an ABTS
10707  * fails to complete after one retry.
10708  */
10709 static void
10710 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
10711 			  struct lpfc_iocbq *iocbq)
10712 {
10713 	struct lpfc_nodelist *ndlp = NULL;
10714 	uint16_t rpi = 0, vpi = 0;
10715 	struct lpfc_vport *vport = NULL;
10716 
10717 	/* The rpi in the ulpContext is vport-sensitive. */
10718 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
10719 	rpi = iocbq->iocb.ulpContext;
10720 
10721 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10722 			"3092 Port generated ABTS async event "
10723 			"on vpi %d rpi %d status 0x%x\n",
10724 			vpi, rpi, iocbq->iocb.ulpStatus);
10725 
10726 	vport = lpfc_find_vport_by_vpid(phba, vpi);
10727 	if (!vport)
10728 		goto err_exit;
10729 	ndlp = lpfc_findnode_rpi(vport, rpi);
10730 	if (!ndlp)
10731 		goto err_exit;
10732 
10733 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
10734 		lpfc_sli_abts_recover_port(vport, ndlp);
10735 	return;
10736 
10737  err_exit:
10738 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10739 			"3095 Event Context not found, no "
10740 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
10741 			iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
10742 			vpi, rpi);
10743 }
10744 
10745 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
10746  * @phba: pointer to HBA context object.
10747  * @ndlp: nodelist pointer for the impacted rport.
10748  * @axri: pointer to the wcqe containing the failed exchange.
10749  *
10750  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
10751  * port.  The port generates this event when an abort exchange request to an
10752  * rport fails twice in succession with no reply.  The abort could be originated
10753  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
10754  */
10755 void
10756 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
10757 			   struct lpfc_nodelist *ndlp,
10758 			   struct sli4_wcqe_xri_aborted *axri)
10759 {
10760 	uint32_t ext_status = 0;
10761 
10762 	if (!ndlp) {
10763 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10764 				"3115 Node Context not found, driver "
10765 				"ignoring abts err event\n");
10766 		return;
10767 	}
10768 
10769 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10770 			"3116 Port generated FCP XRI ABORT event on "
10771 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
10772 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
10773 			bf_get(lpfc_wcqe_xa_xri, axri),
10774 			bf_get(lpfc_wcqe_xa_status, axri),
10775 			axri->parameter);
10776 
10777 	/*
10778 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
10779 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
10780 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
10781 	 */
10782 	ext_status = axri->parameter & IOERR_PARAM_MASK;
10783 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
10784 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
10785 		lpfc_sli_post_recovery_event(phba, ndlp);
10786 }
10787 
10788 /**
10789  * lpfc_sli_async_event_handler - ASYNC iocb handler function
10790  * @phba: Pointer to HBA context object.
10791  * @pring: Pointer to driver SLI ring object.
10792  * @iocbq: Pointer to iocb object.
10793  *
10794  * This function is called by the slow ring event handler
10795  * function when there is an ASYNC event iocb in the ring.
10796  * This function is called with no lock held.
10797  * Currently this function handles only temperature related
10798  * ASYNC events. The function decodes the temperature sensor
10799  * event message and posts events for the management applications.
10800  **/
10801 static void
10802 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
10803 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
10804 {
10805 	IOCB_t *icmd;
10806 	uint16_t evt_code;
10807 	struct temp_event temp_event_data;
10808 	struct Scsi_Host *shost;
10809 	uint32_t *iocb_w;
10810 
10811 	icmd = &iocbq->iocb;
10812 	evt_code = icmd->un.asyncstat.evt_code;
10813 
10814 	switch (evt_code) {
10815 	case ASYNC_TEMP_WARN:
10816 	case ASYNC_TEMP_SAFE:
10817 		temp_event_data.data = (uint32_t) icmd->ulpContext;
10818 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
10819 		if (evt_code == ASYNC_TEMP_WARN) {
10820 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
10821 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10822 				"0347 Adapter is very hot, please take "
10823 				"corrective action. temperature : %d Celsius\n",
10824 				(uint32_t) icmd->ulpContext);
10825 		} else {
10826 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
10827 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10828 				"0340 Adapter temperature is OK now. "
10829 				"temperature : %d Celsius\n",
10830 				(uint32_t) icmd->ulpContext);
10831 		}
10832 
10833 		/* Send temperature change event to applications */
10834 		shost = lpfc_shost_from_vport(phba->pport);
10835 		fc_host_post_vendor_event(shost, fc_get_event_number(),
10836 			sizeof(temp_event_data), (char *) &temp_event_data,
10837 			LPFC_NL_VENDOR_ID);
10838 		break;
10839 	case ASYNC_STATUS_CN:
10840 		lpfc_sli_abts_err_handler(phba, iocbq);
10841 		break;
10842 	default:
10843 		iocb_w = (uint32_t *) icmd;
10844 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10845 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
10846 			" evt_code 0x%x\n"
10847 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
10848 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
10849 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
10850 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
10851 			pring->ringno, icmd->un.asyncstat.evt_code,
10852 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
10853 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
10854 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
10855 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
10856 
10857 		break;
10858 	}
10859 }
10860 
10861 
10862 /**
10863  * lpfc_sli4_setup - SLI ring setup function
10864  * @phba: Pointer to HBA context object.
10865  *
10866  * lpfc_sli_setup sets up rings of the SLI interface with
10867  * number of iocbs per ring and iotags. This function is
10868  * called while driver attach to the HBA and before the
10869  * interrupts are enabled. So there is no need for locking.
10870  *
10871  * This function always returns 0.
10872  **/
10873 int
10874 lpfc_sli4_setup(struct lpfc_hba *phba)
10875 {
10876 	struct lpfc_sli_ring *pring;
10877 
10878 	pring = phba->sli4_hba.els_wq->pring;
10879 	pring->num_mask = LPFC_MAX_RING_MASK;
10880 	pring->prt[0].profile = 0;	/* Mask 0 */
10881 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10882 	pring->prt[0].type = FC_TYPE_ELS;
10883 	pring->prt[0].lpfc_sli_rcv_unsol_event =
10884 	    lpfc_els_unsol_event;
10885 	pring->prt[1].profile = 0;	/* Mask 1 */
10886 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
10887 	pring->prt[1].type = FC_TYPE_ELS;
10888 	pring->prt[1].lpfc_sli_rcv_unsol_event =
10889 	    lpfc_els_unsol_event;
10890 	pring->prt[2].profile = 0;	/* Mask 2 */
10891 	/* NameServer Inquiry */
10892 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10893 	/* NameServer */
10894 	pring->prt[2].type = FC_TYPE_CT;
10895 	pring->prt[2].lpfc_sli_rcv_unsol_event =
10896 	    lpfc_ct_unsol_event;
10897 	pring->prt[3].profile = 0;	/* Mask 3 */
10898 	/* NameServer response */
10899 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10900 	/* NameServer */
10901 	pring->prt[3].type = FC_TYPE_CT;
10902 	pring->prt[3].lpfc_sli_rcv_unsol_event =
10903 	    lpfc_ct_unsol_event;
10904 	return 0;
10905 }
10906 
10907 /**
10908  * lpfc_sli_setup - SLI ring setup function
10909  * @phba: Pointer to HBA context object.
10910  *
10911  * lpfc_sli_setup sets up rings of the SLI interface with
10912  * number of iocbs per ring and iotags. This function is
10913  * called while driver attach to the HBA and before the
10914  * interrupts are enabled. So there is no need for locking.
10915  *
10916  * This function always returns 0. SLI3 only.
10917  **/
10918 int
10919 lpfc_sli_setup(struct lpfc_hba *phba)
10920 {
10921 	int i, totiocbsize = 0;
10922 	struct lpfc_sli *psli = &phba->sli;
10923 	struct lpfc_sli_ring *pring;
10924 
10925 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
10926 	psli->sli_flag = 0;
10927 
10928 	psli->iocbq_lookup = NULL;
10929 	psli->iocbq_lookup_len = 0;
10930 	psli->last_iotag = 0;
10931 
10932 	for (i = 0; i < psli->num_rings; i++) {
10933 		pring = &psli->sli3_ring[i];
10934 		switch (i) {
10935 		case LPFC_FCP_RING:	/* ring 0 - FCP */
10936 			/* numCiocb and numRiocb are used in config_port */
10937 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
10938 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
10939 			pring->sli.sli3.numCiocb +=
10940 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10941 			pring->sli.sli3.numRiocb +=
10942 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10943 			pring->sli.sli3.numCiocb +=
10944 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10945 			pring->sli.sli3.numRiocb +=
10946 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10947 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10948 							SLI3_IOCB_CMD_SIZE :
10949 							SLI2_IOCB_CMD_SIZE;
10950 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10951 							SLI3_IOCB_RSP_SIZE :
10952 							SLI2_IOCB_RSP_SIZE;
10953 			pring->iotag_ctr = 0;
10954 			pring->iotag_max =
10955 			    (phba->cfg_hba_queue_depth * 2);
10956 			pring->fast_iotag = pring->iotag_max;
10957 			pring->num_mask = 0;
10958 			break;
10959 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
10960 			/* numCiocb and numRiocb are used in config_port */
10961 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
10962 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
10963 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10964 							SLI3_IOCB_CMD_SIZE :
10965 							SLI2_IOCB_CMD_SIZE;
10966 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10967 							SLI3_IOCB_RSP_SIZE :
10968 							SLI2_IOCB_RSP_SIZE;
10969 			pring->iotag_max = phba->cfg_hba_queue_depth;
10970 			pring->num_mask = 0;
10971 			break;
10972 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
10973 			/* numCiocb and numRiocb are used in config_port */
10974 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
10975 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
10976 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10977 							SLI3_IOCB_CMD_SIZE :
10978 							SLI2_IOCB_CMD_SIZE;
10979 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10980 							SLI3_IOCB_RSP_SIZE :
10981 							SLI2_IOCB_RSP_SIZE;
10982 			pring->fast_iotag = 0;
10983 			pring->iotag_ctr = 0;
10984 			pring->iotag_max = 4096;
10985 			pring->lpfc_sli_rcv_async_status =
10986 				lpfc_sli_async_event_handler;
10987 			pring->num_mask = LPFC_MAX_RING_MASK;
10988 			pring->prt[0].profile = 0;	/* Mask 0 */
10989 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10990 			pring->prt[0].type = FC_TYPE_ELS;
10991 			pring->prt[0].lpfc_sli_rcv_unsol_event =
10992 			    lpfc_els_unsol_event;
10993 			pring->prt[1].profile = 0;	/* Mask 1 */
10994 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
10995 			pring->prt[1].type = FC_TYPE_ELS;
10996 			pring->prt[1].lpfc_sli_rcv_unsol_event =
10997 			    lpfc_els_unsol_event;
10998 			pring->prt[2].profile = 0;	/* Mask 2 */
10999 			/* NameServer Inquiry */
11000 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11001 			/* NameServer */
11002 			pring->prt[2].type = FC_TYPE_CT;
11003 			pring->prt[2].lpfc_sli_rcv_unsol_event =
11004 			    lpfc_ct_unsol_event;
11005 			pring->prt[3].profile = 0;	/* Mask 3 */
11006 			/* NameServer response */
11007 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11008 			/* NameServer */
11009 			pring->prt[3].type = FC_TYPE_CT;
11010 			pring->prt[3].lpfc_sli_rcv_unsol_event =
11011 			    lpfc_ct_unsol_event;
11012 			break;
11013 		}
11014 		totiocbsize += (pring->sli.sli3.numCiocb *
11015 			pring->sli.sli3.sizeCiocb) +
11016 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
11017 	}
11018 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
11019 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
11020 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
11021 		       "SLI2 SLIM Data: x%x x%lx\n",
11022 		       phba->brd_no, totiocbsize,
11023 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
11024 	}
11025 	if (phba->cfg_multi_ring_support == 2)
11026 		lpfc_extra_ring_setup(phba);
11027 
11028 	return 0;
11029 }
11030 
11031 /**
11032  * lpfc_sli4_queue_init - Queue initialization function
11033  * @phba: Pointer to HBA context object.
11034  *
11035  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
11036  * ring. This function also initializes ring indices of each ring.
11037  * This function is called during the initialization of the SLI
11038  * interface of an HBA.
11039  * This function is called with no lock held and always returns
11040  * 1.
11041  **/
11042 void
11043 lpfc_sli4_queue_init(struct lpfc_hba *phba)
11044 {
11045 	struct lpfc_sli *psli;
11046 	struct lpfc_sli_ring *pring;
11047 	int i;
11048 
11049 	psli = &phba->sli;
11050 	spin_lock_irq(&phba->hbalock);
11051 	INIT_LIST_HEAD(&psli->mboxq);
11052 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11053 	/* Initialize list headers for txq and txcmplq as double linked lists */
11054 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
11055 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
11056 		pring->flag = 0;
11057 		pring->ringno = LPFC_FCP_RING;
11058 		pring->txcmplq_cnt = 0;
11059 		INIT_LIST_HEAD(&pring->txq);
11060 		INIT_LIST_HEAD(&pring->txcmplq);
11061 		INIT_LIST_HEAD(&pring->iocb_continueq);
11062 		spin_lock_init(&pring->ring_lock);
11063 	}
11064 	pring = phba->sli4_hba.els_wq->pring;
11065 	pring->flag = 0;
11066 	pring->ringno = LPFC_ELS_RING;
11067 	pring->txcmplq_cnt = 0;
11068 	INIT_LIST_HEAD(&pring->txq);
11069 	INIT_LIST_HEAD(&pring->txcmplq);
11070 	INIT_LIST_HEAD(&pring->iocb_continueq);
11071 	spin_lock_init(&pring->ring_lock);
11072 
11073 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11074 		pring = phba->sli4_hba.nvmels_wq->pring;
11075 		pring->flag = 0;
11076 		pring->ringno = LPFC_ELS_RING;
11077 		pring->txcmplq_cnt = 0;
11078 		INIT_LIST_HEAD(&pring->txq);
11079 		INIT_LIST_HEAD(&pring->txcmplq);
11080 		INIT_LIST_HEAD(&pring->iocb_continueq);
11081 		spin_lock_init(&pring->ring_lock);
11082 	}
11083 
11084 	spin_unlock_irq(&phba->hbalock);
11085 }
11086 
11087 /**
11088  * lpfc_sli_queue_init - Queue initialization function
11089  * @phba: Pointer to HBA context object.
11090  *
11091  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11092  * ring. This function also initializes ring indices of each ring.
11093  * This function is called during the initialization of the SLI
11094  * interface of an HBA.
11095  * This function is called with no lock held and always returns
11096  * 1.
11097  **/
11098 void
11099 lpfc_sli_queue_init(struct lpfc_hba *phba)
11100 {
11101 	struct lpfc_sli *psli;
11102 	struct lpfc_sli_ring *pring;
11103 	int i;
11104 
11105 	psli = &phba->sli;
11106 	spin_lock_irq(&phba->hbalock);
11107 	INIT_LIST_HEAD(&psli->mboxq);
11108 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11109 	/* Initialize list headers for txq and txcmplq as double linked lists */
11110 	for (i = 0; i < psli->num_rings; i++) {
11111 		pring = &psli->sli3_ring[i];
11112 		pring->ringno = i;
11113 		pring->sli.sli3.next_cmdidx  = 0;
11114 		pring->sli.sli3.local_getidx = 0;
11115 		pring->sli.sli3.cmdidx = 0;
11116 		INIT_LIST_HEAD(&pring->iocb_continueq);
11117 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11118 		INIT_LIST_HEAD(&pring->postbufq);
11119 		pring->flag = 0;
11120 		INIT_LIST_HEAD(&pring->txq);
11121 		INIT_LIST_HEAD(&pring->txcmplq);
11122 		spin_lock_init(&pring->ring_lock);
11123 	}
11124 	spin_unlock_irq(&phba->hbalock);
11125 }
11126 
11127 /**
11128  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11129  * @phba: Pointer to HBA context object.
11130  *
11131  * This routine flushes the mailbox command subsystem. It will unconditionally
11132  * flush all the mailbox commands in the three possible stages in the mailbox
11133  * command sub-system: pending mailbox command queue; the outstanding mailbox
11134  * command; and completed mailbox command queue. It is caller's responsibility
11135  * to make sure that the driver is in the proper state to flush the mailbox
11136  * command sub-system. Namely, the posting of mailbox commands into the
11137  * pending mailbox command queue from the various clients must be stopped;
11138  * either the HBA is in a state that it will never works on the outstanding
11139  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11140  * mailbox command has been completed.
11141  **/
11142 static void
11143 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11144 {
11145 	LIST_HEAD(completions);
11146 	struct lpfc_sli *psli = &phba->sli;
11147 	LPFC_MBOXQ_t *pmb;
11148 	unsigned long iflag;
11149 
11150 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11151 	local_bh_disable();
11152 
11153 	/* Flush all the mailbox commands in the mbox system */
11154 	spin_lock_irqsave(&phba->hbalock, iflag);
11155 
11156 	/* The pending mailbox command queue */
11157 	list_splice_init(&phba->sli.mboxq, &completions);
11158 	/* The outstanding active mailbox command */
11159 	if (psli->mbox_active) {
11160 		list_add_tail(&psli->mbox_active->list, &completions);
11161 		psli->mbox_active = NULL;
11162 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11163 	}
11164 	/* The completed mailbox command queue */
11165 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11166 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11167 
11168 	/* Enable softirqs again, done with phba->hbalock */
11169 	local_bh_enable();
11170 
11171 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11172 	while (!list_empty(&completions)) {
11173 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11174 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11175 		if (pmb->mbox_cmpl)
11176 			pmb->mbox_cmpl(phba, pmb);
11177 	}
11178 }
11179 
11180 /**
11181  * lpfc_sli_host_down - Vport cleanup function
11182  * @vport: Pointer to virtual port object.
11183  *
11184  * lpfc_sli_host_down is called to clean up the resources
11185  * associated with a vport before destroying virtual
11186  * port data structures.
11187  * This function does following operations:
11188  * - Free discovery resources associated with this virtual
11189  *   port.
11190  * - Free iocbs associated with this virtual port in
11191  *   the txq.
11192  * - Send abort for all iocb commands associated with this
11193  *   vport in txcmplq.
11194  *
11195  * This function is called with no lock held and always returns 1.
11196  **/
11197 int
11198 lpfc_sli_host_down(struct lpfc_vport *vport)
11199 {
11200 	LIST_HEAD(completions);
11201 	struct lpfc_hba *phba = vport->phba;
11202 	struct lpfc_sli *psli = &phba->sli;
11203 	struct lpfc_queue *qp = NULL;
11204 	struct lpfc_sli_ring *pring;
11205 	struct lpfc_iocbq *iocb, *next_iocb;
11206 	int i;
11207 	unsigned long flags = 0;
11208 	uint16_t prev_pring_flag;
11209 
11210 	lpfc_cleanup_discovery_resources(vport);
11211 
11212 	spin_lock_irqsave(&phba->hbalock, flags);
11213 
11214 	/*
11215 	 * Error everything on the txq since these iocbs
11216 	 * have not been given to the FW yet.
11217 	 * Also issue ABTS for everything on the txcmplq
11218 	 */
11219 	if (phba->sli_rev != LPFC_SLI_REV4) {
11220 		for (i = 0; i < psli->num_rings; i++) {
11221 			pring = &psli->sli3_ring[i];
11222 			prev_pring_flag = pring->flag;
11223 			/* Only slow rings */
11224 			if (pring->ringno == LPFC_ELS_RING) {
11225 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11226 				/* Set the lpfc data pending flag */
11227 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11228 			}
11229 			list_for_each_entry_safe(iocb, next_iocb,
11230 						 &pring->txq, list) {
11231 				if (iocb->vport != vport)
11232 					continue;
11233 				list_move_tail(&iocb->list, &completions);
11234 			}
11235 			list_for_each_entry_safe(iocb, next_iocb,
11236 						 &pring->txcmplq, list) {
11237 				if (iocb->vport != vport)
11238 					continue;
11239 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11240 							   NULL);
11241 			}
11242 			pring->flag = prev_pring_flag;
11243 		}
11244 	} else {
11245 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11246 			pring = qp->pring;
11247 			if (!pring)
11248 				continue;
11249 			if (pring == phba->sli4_hba.els_wq->pring) {
11250 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11251 				/* Set the lpfc data pending flag */
11252 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11253 			}
11254 			prev_pring_flag = pring->flag;
11255 			spin_lock(&pring->ring_lock);
11256 			list_for_each_entry_safe(iocb, next_iocb,
11257 						 &pring->txq, list) {
11258 				if (iocb->vport != vport)
11259 					continue;
11260 				list_move_tail(&iocb->list, &completions);
11261 			}
11262 			spin_unlock(&pring->ring_lock);
11263 			list_for_each_entry_safe(iocb, next_iocb,
11264 						 &pring->txcmplq, list) {
11265 				if (iocb->vport != vport)
11266 					continue;
11267 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11268 							   NULL);
11269 			}
11270 			pring->flag = prev_pring_flag;
11271 		}
11272 	}
11273 	spin_unlock_irqrestore(&phba->hbalock, flags);
11274 
11275 	/* Make sure HBA is alive */
11276 	lpfc_issue_hb_tmo(phba);
11277 
11278 	/* Cancel all the IOCBs from the completions list */
11279 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11280 			      IOERR_SLI_DOWN);
11281 	return 1;
11282 }
11283 
11284 /**
11285  * lpfc_sli_hba_down - Resource cleanup function for the HBA
11286  * @phba: Pointer to HBA context object.
11287  *
11288  * This function cleans up all iocb, buffers, mailbox commands
11289  * while shutting down the HBA. This function is called with no
11290  * lock held and always returns 1.
11291  * This function does the following to cleanup driver resources:
11292  * - Free discovery resources for each virtual port
11293  * - Cleanup any pending fabric iocbs
11294  * - Iterate through the iocb txq and free each entry
11295  *   in the list.
11296  * - Free up any buffer posted to the HBA
11297  * - Free mailbox commands in the mailbox queue.
11298  **/
11299 int
11300 lpfc_sli_hba_down(struct lpfc_hba *phba)
11301 {
11302 	LIST_HEAD(completions);
11303 	struct lpfc_sli *psli = &phba->sli;
11304 	struct lpfc_queue *qp = NULL;
11305 	struct lpfc_sli_ring *pring;
11306 	struct lpfc_dmabuf *buf_ptr;
11307 	unsigned long flags = 0;
11308 	int i;
11309 
11310 	/* Shutdown the mailbox command sub-system */
11311 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
11312 
11313 	lpfc_hba_down_prep(phba);
11314 
11315 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11316 	local_bh_disable();
11317 
11318 	lpfc_fabric_abort_hba(phba);
11319 
11320 	spin_lock_irqsave(&phba->hbalock, flags);
11321 
11322 	/*
11323 	 * Error everything on the txq since these iocbs
11324 	 * have not been given to the FW yet.
11325 	 */
11326 	if (phba->sli_rev != LPFC_SLI_REV4) {
11327 		for (i = 0; i < psli->num_rings; i++) {
11328 			pring = &psli->sli3_ring[i];
11329 			/* Only slow rings */
11330 			if (pring->ringno == LPFC_ELS_RING) {
11331 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11332 				/* Set the lpfc data pending flag */
11333 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11334 			}
11335 			list_splice_init(&pring->txq, &completions);
11336 		}
11337 	} else {
11338 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11339 			pring = qp->pring;
11340 			if (!pring)
11341 				continue;
11342 			spin_lock(&pring->ring_lock);
11343 			list_splice_init(&pring->txq, &completions);
11344 			spin_unlock(&pring->ring_lock);
11345 			if (pring == phba->sli4_hba.els_wq->pring) {
11346 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11347 				/* Set the lpfc data pending flag */
11348 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11349 			}
11350 		}
11351 	}
11352 	spin_unlock_irqrestore(&phba->hbalock, flags);
11353 
11354 	/* Cancel all the IOCBs from the completions list */
11355 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11356 			      IOERR_SLI_DOWN);
11357 
11358 	spin_lock_irqsave(&phba->hbalock, flags);
11359 	list_splice_init(&phba->elsbuf, &completions);
11360 	phba->elsbuf_cnt = 0;
11361 	phba->elsbuf_prev_cnt = 0;
11362 	spin_unlock_irqrestore(&phba->hbalock, flags);
11363 
11364 	while (!list_empty(&completions)) {
11365 		list_remove_head(&completions, buf_ptr,
11366 			struct lpfc_dmabuf, list);
11367 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
11368 		kfree(buf_ptr);
11369 	}
11370 
11371 	/* Enable softirqs again, done with phba->hbalock */
11372 	local_bh_enable();
11373 
11374 	/* Return any active mbox cmds */
11375 	del_timer_sync(&psli->mbox_tmo);
11376 
11377 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
11378 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
11379 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
11380 
11381 	return 1;
11382 }
11383 
11384 /**
11385  * lpfc_sli_pcimem_bcopy - SLI memory copy function
11386  * @srcp: Source memory pointer.
11387  * @destp: Destination memory pointer.
11388  * @cnt: Number of words required to be copied.
11389  *
11390  * This function is used for copying data between driver memory
11391  * and the SLI memory. This function also changes the endianness
11392  * of each word if native endianness is different from SLI
11393  * endianness. This function can be called with or without
11394  * lock.
11395  **/
11396 void
11397 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
11398 {
11399 	uint32_t *src = srcp;
11400 	uint32_t *dest = destp;
11401 	uint32_t ldata;
11402 	int i;
11403 
11404 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
11405 		ldata = *src;
11406 		ldata = le32_to_cpu(ldata);
11407 		*dest = ldata;
11408 		src++;
11409 		dest++;
11410 	}
11411 }
11412 
11413 
11414 /**
11415  * lpfc_sli_bemem_bcopy - SLI memory copy function
11416  * @srcp: Source memory pointer.
11417  * @destp: Destination memory pointer.
11418  * @cnt: Number of words required to be copied.
11419  *
11420  * This function is used for copying data between a data structure
11421  * with big endian representation to local endianness.
11422  * This function can be called with or without lock.
11423  **/
11424 void
11425 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
11426 {
11427 	uint32_t *src = srcp;
11428 	uint32_t *dest = destp;
11429 	uint32_t ldata;
11430 	int i;
11431 
11432 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
11433 		ldata = *src;
11434 		ldata = be32_to_cpu(ldata);
11435 		*dest = ldata;
11436 		src++;
11437 		dest++;
11438 	}
11439 }
11440 
11441 /**
11442  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
11443  * @phba: Pointer to HBA context object.
11444  * @pring: Pointer to driver SLI ring object.
11445  * @mp: Pointer to driver buffer object.
11446  *
11447  * This function is called with no lock held.
11448  * It always return zero after adding the buffer to the postbufq
11449  * buffer list.
11450  **/
11451 int
11452 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11453 			 struct lpfc_dmabuf *mp)
11454 {
11455 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
11456 	   later */
11457 	spin_lock_irq(&phba->hbalock);
11458 	list_add_tail(&mp->list, &pring->postbufq);
11459 	pring->postbufq_cnt++;
11460 	spin_unlock_irq(&phba->hbalock);
11461 	return 0;
11462 }
11463 
11464 /**
11465  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
11466  * @phba: Pointer to HBA context object.
11467  *
11468  * When HBQ is enabled, buffers are searched based on tags. This function
11469  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
11470  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
11471  * does not conflict with tags of buffer posted for unsolicited events.
11472  * The function returns the allocated tag. The function is called with
11473  * no locks held.
11474  **/
11475 uint32_t
11476 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
11477 {
11478 	spin_lock_irq(&phba->hbalock);
11479 	phba->buffer_tag_count++;
11480 	/*
11481 	 * Always set the QUE_BUFTAG_BIT to distiguish between
11482 	 * a tag assigned by HBQ.
11483 	 */
11484 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
11485 	spin_unlock_irq(&phba->hbalock);
11486 	return phba->buffer_tag_count;
11487 }
11488 
11489 /**
11490  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
11491  * @phba: Pointer to HBA context object.
11492  * @pring: Pointer to driver SLI ring object.
11493  * @tag: Buffer tag.
11494  *
11495  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
11496  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
11497  * iocb is posted to the response ring with the tag of the buffer.
11498  * This function searches the pring->postbufq list using the tag
11499  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
11500  * iocb. If the buffer is found then lpfc_dmabuf object of the
11501  * buffer is returned to the caller else NULL is returned.
11502  * This function is called with no lock held.
11503  **/
11504 struct lpfc_dmabuf *
11505 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11506 			uint32_t tag)
11507 {
11508 	struct lpfc_dmabuf *mp, *next_mp;
11509 	struct list_head *slp = &pring->postbufq;
11510 
11511 	/* Search postbufq, from the beginning, looking for a match on tag */
11512 	spin_lock_irq(&phba->hbalock);
11513 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11514 		if (mp->buffer_tag == tag) {
11515 			list_del_init(&mp->list);
11516 			pring->postbufq_cnt--;
11517 			spin_unlock_irq(&phba->hbalock);
11518 			return mp;
11519 		}
11520 	}
11521 
11522 	spin_unlock_irq(&phba->hbalock);
11523 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11524 			"0402 Cannot find virtual addr for buffer tag on "
11525 			"ring %d Data x%lx x%px x%px x%x\n",
11526 			pring->ringno, (unsigned long) tag,
11527 			slp->next, slp->prev, pring->postbufq_cnt);
11528 
11529 	return NULL;
11530 }
11531 
11532 /**
11533  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
11534  * @phba: Pointer to HBA context object.
11535  * @pring: Pointer to driver SLI ring object.
11536  * @phys: DMA address of the buffer.
11537  *
11538  * This function searches the buffer list using the dma_address
11539  * of unsolicited event to find the driver's lpfc_dmabuf object
11540  * corresponding to the dma_address. The function returns the
11541  * lpfc_dmabuf object if a buffer is found else it returns NULL.
11542  * This function is called by the ct and els unsolicited event
11543  * handlers to get the buffer associated with the unsolicited
11544  * event.
11545  *
11546  * This function is called with no lock held.
11547  **/
11548 struct lpfc_dmabuf *
11549 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11550 			 dma_addr_t phys)
11551 {
11552 	struct lpfc_dmabuf *mp, *next_mp;
11553 	struct list_head *slp = &pring->postbufq;
11554 
11555 	/* Search postbufq, from the beginning, looking for a match on phys */
11556 	spin_lock_irq(&phba->hbalock);
11557 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11558 		if (mp->phys == phys) {
11559 			list_del_init(&mp->list);
11560 			pring->postbufq_cnt--;
11561 			spin_unlock_irq(&phba->hbalock);
11562 			return mp;
11563 		}
11564 	}
11565 
11566 	spin_unlock_irq(&phba->hbalock);
11567 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11568 			"0410 Cannot find virtual addr for mapped buf on "
11569 			"ring %d Data x%llx x%px x%px x%x\n",
11570 			pring->ringno, (unsigned long long)phys,
11571 			slp->next, slp->prev, pring->postbufq_cnt);
11572 	return NULL;
11573 }
11574 
11575 /**
11576  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
11577  * @phba: Pointer to HBA context object.
11578  * @cmdiocb: Pointer to driver command iocb object.
11579  * @rspiocb: Pointer to driver response iocb object.
11580  *
11581  * This function is the completion handler for the abort iocbs for
11582  * ELS commands. This function is called from the ELS ring event
11583  * handler with no lock held. This function frees memory resources
11584  * associated with the abort iocb.
11585  **/
11586 static void
11587 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11588 			struct lpfc_iocbq *rspiocb)
11589 {
11590 	IOCB_t *irsp = &rspiocb->iocb;
11591 	uint16_t abort_iotag, abort_context;
11592 	struct lpfc_iocbq *abort_iocb = NULL;
11593 
11594 	if (irsp->ulpStatus) {
11595 
11596 		/*
11597 		 * Assume that the port already completed and returned, or
11598 		 * will return the iocb. Just Log the message.
11599 		 */
11600 		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
11601 		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
11602 
11603 		spin_lock_irq(&phba->hbalock);
11604 		if (phba->sli_rev < LPFC_SLI_REV4) {
11605 			if (irsp->ulpCommand == CMD_ABORT_XRI_CX &&
11606 			    irsp->ulpStatus == IOSTAT_LOCAL_REJECT &&
11607 			    irsp->un.ulpWord[4] == IOERR_ABORT_REQUESTED) {
11608 				spin_unlock_irq(&phba->hbalock);
11609 				goto release_iocb;
11610 			}
11611 			if (abort_iotag != 0 &&
11612 				abort_iotag <= phba->sli.last_iotag)
11613 				abort_iocb =
11614 					phba->sli.iocbq_lookup[abort_iotag];
11615 		} else
11616 			/* For sli4 the abort_tag is the XRI,
11617 			 * so the abort routine puts the iotag  of the iocb
11618 			 * being aborted in the context field of the abort
11619 			 * IOCB.
11620 			 */
11621 			abort_iocb = phba->sli.iocbq_lookup[abort_context];
11622 
11623 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
11624 				"0327 Cannot abort els iocb x%px "
11625 				"with tag %x context %x, abort status %x, "
11626 				"abort code %x\n",
11627 				abort_iocb, abort_iotag, abort_context,
11628 				irsp->ulpStatus, irsp->un.ulpWord[4]);
11629 
11630 		spin_unlock_irq(&phba->hbalock);
11631 	}
11632 release_iocb:
11633 	lpfc_sli_release_iocbq(phba, cmdiocb);
11634 	return;
11635 }
11636 
11637 /**
11638  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
11639  * @phba: Pointer to HBA context object.
11640  * @cmdiocb: Pointer to driver command iocb object.
11641  * @rspiocb: Pointer to driver response iocb object.
11642  *
11643  * The function is called from SLI ring event handler with no
11644  * lock held. This function is the completion handler for ELS commands
11645  * which are aborted. The function frees memory resources used for
11646  * the aborted ELS commands.
11647  **/
11648 void
11649 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11650 		     struct lpfc_iocbq *rspiocb)
11651 {
11652 	struct lpfc_nodelist *ndlp = (struct lpfc_nodelist *) cmdiocb->context1;
11653 	IOCB_t *irsp = &rspiocb->iocb;
11654 
11655 	/* ELS cmd tag <ulpIoTag> completes */
11656 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
11657 			"0139 Ignoring ELS cmd tag x%x completion Data: "
11658 			"x%x x%x x%x\n",
11659 			irsp->ulpIoTag, irsp->ulpStatus,
11660 			irsp->un.ulpWord[4], irsp->ulpTimeout);
11661 	/*
11662 	 * Deref the ndlp after free_iocb. sli_release_iocb will access the ndlp
11663 	 * if exchange is busy.
11664 	 */
11665 	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
11666 		lpfc_ct_free_iocb(phba, cmdiocb);
11667 	else
11668 		lpfc_els_free_iocb(phba, cmdiocb);
11669 
11670 	lpfc_nlp_put(ndlp);
11671 }
11672 
11673 /**
11674  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
11675  * @phba: Pointer to HBA context object.
11676  * @pring: Pointer to driver SLI ring object.
11677  * @cmdiocb: Pointer to driver command iocb object.
11678  * @cmpl: completion function.
11679  *
11680  * This function issues an abort iocb for the provided command iocb. In case
11681  * of unloading, the abort iocb will not be issued to commands on the ELS
11682  * ring. Instead, the callback function shall be changed to those commands
11683  * so that nothing happens when them finishes. This function is called with
11684  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
11685  * when the command iocb is an abort request.
11686  *
11687  **/
11688 int
11689 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11690 			   struct lpfc_iocbq *cmdiocb, void *cmpl)
11691 {
11692 	struct lpfc_vport *vport = cmdiocb->vport;
11693 	struct lpfc_iocbq *abtsiocbp;
11694 	IOCB_t *icmd = NULL;
11695 	IOCB_t *iabt = NULL;
11696 	int retval = IOCB_ERROR;
11697 	unsigned long iflags;
11698 	struct lpfc_nodelist *ndlp;
11699 
11700 	/*
11701 	 * There are certain command types we don't want to abort.  And we
11702 	 * don't want to abort commands that are already in the process of
11703 	 * being aborted.
11704 	 */
11705 	icmd = &cmdiocb->iocb;
11706 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11707 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
11708 	    cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED)
11709 		return IOCB_ABORTING;
11710 
11711 	if (!pring) {
11712 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11713 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11714 		else
11715 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11716 		return retval;
11717 	}
11718 
11719 	/*
11720 	 * If we're unloading, don't abort iocb on the ELS ring, but change
11721 	 * the callback so that nothing happens when it finishes.
11722 	 */
11723 	if ((vport->load_flag & FC_UNLOADING) &&
11724 	    pring->ringno == LPFC_ELS_RING) {
11725 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11726 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11727 		else
11728 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11729 		return retval;
11730 	}
11731 
11732 	/* issue ABTS for this IOCB based on iotag */
11733 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
11734 	if (abtsiocbp == NULL)
11735 		return IOCB_NORESOURCE;
11736 
11737 	/* This signals the response to set the correct status
11738 	 * before calling the completion handler
11739 	 */
11740 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
11741 
11742 	iabt = &abtsiocbp->iocb;
11743 	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
11744 	iabt->un.acxri.abortContextTag = icmd->ulpContext;
11745 	if (phba->sli_rev == LPFC_SLI_REV4) {
11746 		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
11747 		if (pring->ringno == LPFC_ELS_RING)
11748 			iabt->un.acxri.abortContextTag = cmdiocb->iotag;
11749 	} else {
11750 		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
11751 		if (pring->ringno == LPFC_ELS_RING) {
11752 			ndlp = (struct lpfc_nodelist *)(cmdiocb->context1);
11753 			iabt->un.acxri.abortContextTag = ndlp->nlp_rpi;
11754 		}
11755 	}
11756 	iabt->ulpLe = 1;
11757 	iabt->ulpClass = icmd->ulpClass;
11758 
11759 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11760 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
11761 	if (cmdiocb->iocb_flag & LPFC_IO_FCP) {
11762 		abtsiocbp->iocb_flag |= LPFC_IO_FCP;
11763 		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
11764 	}
11765 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
11766 		abtsiocbp->iocb_flag |= LPFC_IO_FOF;
11767 
11768 	if (phba->link_state >= LPFC_LINK_UP)
11769 		iabt->ulpCommand = CMD_ABORT_XRI_CN;
11770 	else
11771 		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
11772 
11773 	if (cmpl)
11774 		abtsiocbp->iocb_cmpl = cmpl;
11775 	else
11776 		abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
11777 	abtsiocbp->vport = vport;
11778 
11779 	if (phba->sli_rev == LPFC_SLI_REV4) {
11780 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
11781 		if (unlikely(pring == NULL))
11782 			goto abort_iotag_exit;
11783 		/* Note: both hbalock and ring_lock need to be set here */
11784 		spin_lock_irqsave(&pring->ring_lock, iflags);
11785 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11786 			abtsiocbp, 0);
11787 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11788 	} else {
11789 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11790 			abtsiocbp, 0);
11791 	}
11792 
11793 abort_iotag_exit:
11794 
11795 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
11796 			 "0339 Abort xri x%x, original iotag x%x, "
11797 			 "abort cmd iotag x%x retval x%x\n",
11798 			 iabt->un.acxri.abortIoTag,
11799 			 iabt->un.acxri.abortContextTag,
11800 			 abtsiocbp->iotag, retval);
11801 
11802 	if (retval) {
11803 		cmdiocb->iocb_flag &= ~LPFC_DRIVER_ABORTED;
11804 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
11805 	}
11806 
11807 	/*
11808 	 * Caller to this routine should check for IOCB_ERROR
11809 	 * and handle it properly.  This routine no longer removes
11810 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
11811 	 */
11812 	return retval;
11813 }
11814 
11815 /**
11816  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
11817  * @phba: pointer to lpfc HBA data structure.
11818  *
11819  * This routine will abort all pending and outstanding iocbs to an HBA.
11820  **/
11821 void
11822 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
11823 {
11824 	struct lpfc_sli *psli = &phba->sli;
11825 	struct lpfc_sli_ring *pring;
11826 	struct lpfc_queue *qp = NULL;
11827 	int i;
11828 
11829 	if (phba->sli_rev != LPFC_SLI_REV4) {
11830 		for (i = 0; i < psli->num_rings; i++) {
11831 			pring = &psli->sli3_ring[i];
11832 			lpfc_sli_abort_iocb_ring(phba, pring);
11833 		}
11834 		return;
11835 	}
11836 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11837 		pring = qp->pring;
11838 		if (!pring)
11839 			continue;
11840 		lpfc_sli_abort_iocb_ring(phba, pring);
11841 	}
11842 }
11843 
11844 /**
11845  * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
11846  * @iocbq: Pointer to driver iocb object.
11847  * @vport: Pointer to driver virtual port object.
11848  * @tgt_id: SCSI ID of the target.
11849  * @lun_id: LUN ID of the scsi device.
11850  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
11851  *
11852  * This function acts as an iocb filter for functions which abort or count
11853  * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
11854  * 0 if the filtering criteria is met for the given iocb and will return
11855  * 1 if the filtering criteria is not met.
11856  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
11857  * given iocb is for the SCSI device specified by vport, tgt_id and
11858  * lun_id parameter.
11859  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
11860  * given iocb is for the SCSI target specified by vport and tgt_id
11861  * parameters.
11862  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
11863  * given iocb is for the SCSI host associated with the given vport.
11864  * This function is called with no locks held.
11865  **/
11866 static int
11867 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
11868 			   uint16_t tgt_id, uint64_t lun_id,
11869 			   lpfc_ctx_cmd ctx_cmd)
11870 {
11871 	struct lpfc_io_buf *lpfc_cmd;
11872 	IOCB_t *icmd = NULL;
11873 	int rc = 1;
11874 
11875 	if (!iocbq || iocbq->vport != vport)
11876 		return rc;
11877 
11878 	if (!(iocbq->iocb_flag & LPFC_IO_FCP) ||
11879 	    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ) ||
11880 	      iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
11881 		return rc;
11882 
11883 	icmd = &iocbq->iocb;
11884 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11885 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN)
11886 		return rc;
11887 
11888 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
11889 
11890 	if (lpfc_cmd->pCmd == NULL)
11891 		return rc;
11892 
11893 	switch (ctx_cmd) {
11894 	case LPFC_CTX_LUN:
11895 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11896 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
11897 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
11898 			rc = 0;
11899 		break;
11900 	case LPFC_CTX_TGT:
11901 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11902 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
11903 			rc = 0;
11904 		break;
11905 	case LPFC_CTX_HOST:
11906 		rc = 0;
11907 		break;
11908 	default:
11909 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
11910 			__func__, ctx_cmd);
11911 		break;
11912 	}
11913 
11914 	return rc;
11915 }
11916 
11917 /**
11918  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
11919  * @vport: Pointer to virtual port.
11920  * @tgt_id: SCSI ID of the target.
11921  * @lun_id: LUN ID of the scsi device.
11922  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11923  *
11924  * This function returns number of FCP commands pending for the vport.
11925  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
11926  * commands pending on the vport associated with SCSI device specified
11927  * by tgt_id and lun_id parameters.
11928  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
11929  * commands pending on the vport associated with SCSI target specified
11930  * by tgt_id parameter.
11931  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
11932  * commands pending on the vport.
11933  * This function returns the number of iocbs which satisfy the filter.
11934  * This function is called without any lock held.
11935  **/
11936 int
11937 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
11938 		  lpfc_ctx_cmd ctx_cmd)
11939 {
11940 	struct lpfc_hba *phba = vport->phba;
11941 	struct lpfc_iocbq *iocbq;
11942 	int sum, i;
11943 
11944 	spin_lock_irq(&phba->hbalock);
11945 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
11946 		iocbq = phba->sli.iocbq_lookup[i];
11947 
11948 		if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
11949 						ctx_cmd) == 0)
11950 			sum++;
11951 	}
11952 	spin_unlock_irq(&phba->hbalock);
11953 
11954 	return sum;
11955 }
11956 
11957 /**
11958  * lpfc_sli4_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
11959  * @phba: Pointer to HBA context object
11960  * @cmdiocb: Pointer to command iocb object.
11961  * @wcqe: pointer to the complete wcqe
11962  *
11963  * This function is called when an aborted FCP iocb completes. This
11964  * function is called by the ring event handler with no lock held.
11965  * This function frees the iocb. It is called for sli-4 adapters.
11966  **/
11967 void
11968 lpfc_sli4_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11969 			 struct lpfc_wcqe_complete *wcqe)
11970 {
11971 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11972 			"3017 ABORT_XRI_CN completing on rpi x%x "
11973 			"original iotag x%x, abort cmd iotag x%x "
11974 			"status 0x%x, reason 0x%x\n",
11975 			cmdiocb->iocb.un.acxri.abortContextTag,
11976 			cmdiocb->iocb.un.acxri.abortIoTag,
11977 			cmdiocb->iotag,
11978 			(bf_get(lpfc_wcqe_c_status, wcqe)
11979 			& LPFC_IOCB_STATUS_MASK),
11980 			wcqe->parameter);
11981 	lpfc_sli_release_iocbq(phba, cmdiocb);
11982 }
11983 
11984 /**
11985  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
11986  * @phba: Pointer to HBA context object
11987  * @cmdiocb: Pointer to command iocb object.
11988  * @rspiocb: Pointer to response iocb object.
11989  *
11990  * This function is called when an aborted FCP iocb completes. This
11991  * function is called by the ring event handler with no lock held.
11992  * This function frees the iocb.
11993  **/
11994 void
11995 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11996 			struct lpfc_iocbq *rspiocb)
11997 {
11998 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11999 			"3096 ABORT_XRI_CN completing on rpi x%x "
12000 			"original iotag x%x, abort cmd iotag x%x "
12001 			"status 0x%x, reason 0x%x\n",
12002 			cmdiocb->iocb.un.acxri.abortContextTag,
12003 			cmdiocb->iocb.un.acxri.abortIoTag,
12004 			cmdiocb->iotag, rspiocb->iocb.ulpStatus,
12005 			rspiocb->iocb.un.ulpWord[4]);
12006 	lpfc_sli_release_iocbq(phba, cmdiocb);
12007 	return;
12008 }
12009 
12010 /**
12011  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
12012  * @vport: Pointer to virtual port.
12013  * @tgt_id: SCSI ID of the target.
12014  * @lun_id: LUN ID of the scsi device.
12015  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12016  *
12017  * This function sends an abort command for every SCSI command
12018  * associated with the given virtual port pending on the ring
12019  * filtered by lpfc_sli_validate_fcp_iocb function.
12020  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
12021  * FCP iocbs associated with lun specified by tgt_id and lun_id
12022  * parameters
12023  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
12024  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12025  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
12026  * FCP iocbs associated with virtual port.
12027  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
12028  * lpfc_sli4_calc_ring is used.
12029  * This function returns number of iocbs it failed to abort.
12030  * This function is called with no locks held.
12031  **/
12032 int
12033 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
12034 		    lpfc_ctx_cmd abort_cmd)
12035 {
12036 	struct lpfc_hba *phba = vport->phba;
12037 	struct lpfc_sli_ring *pring = NULL;
12038 	struct lpfc_iocbq *iocbq;
12039 	int errcnt = 0, ret_val = 0;
12040 	unsigned long iflags;
12041 	int i;
12042 	void *fcp_cmpl = NULL;
12043 
12044 	/* all I/Os are in process of being flushed */
12045 	if (phba->hba_flag & HBA_IOQ_FLUSH)
12046 		return errcnt;
12047 
12048 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12049 		iocbq = phba->sli.iocbq_lookup[i];
12050 
12051 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12052 					       abort_cmd) != 0)
12053 			continue;
12054 
12055 		spin_lock_irqsave(&phba->hbalock, iflags);
12056 		if (phba->sli_rev == LPFC_SLI_REV3) {
12057 			pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12058 			fcp_cmpl = lpfc_sli_abort_fcp_cmpl;
12059 		} else if (phba->sli_rev == LPFC_SLI_REV4) {
12060 			pring = lpfc_sli4_calc_ring(phba, iocbq);
12061 			fcp_cmpl = lpfc_sli4_abort_fcp_cmpl;
12062 		}
12063 		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
12064 						     fcp_cmpl);
12065 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12066 		if (ret_val != IOCB_SUCCESS)
12067 			errcnt++;
12068 	}
12069 
12070 	return errcnt;
12071 }
12072 
12073 /**
12074  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12075  * @vport: Pointer to virtual port.
12076  * @pring: Pointer to driver SLI ring object.
12077  * @tgt_id: SCSI ID of the target.
12078  * @lun_id: LUN ID of the scsi device.
12079  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12080  *
12081  * This function sends an abort command for every SCSI command
12082  * associated with the given virtual port pending on the ring
12083  * filtered by lpfc_sli_validate_fcp_iocb function.
12084  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12085  * FCP iocbs associated with lun specified by tgt_id and lun_id
12086  * parameters
12087  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12088  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12089  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12090  * FCP iocbs associated with virtual port.
12091  * This function returns number of iocbs it aborted .
12092  * This function is called with no locks held right after a taskmgmt
12093  * command is sent.
12094  **/
12095 int
12096 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12097 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12098 {
12099 	struct lpfc_hba *phba = vport->phba;
12100 	struct lpfc_io_buf *lpfc_cmd;
12101 	struct lpfc_iocbq *abtsiocbq;
12102 	struct lpfc_nodelist *ndlp;
12103 	struct lpfc_iocbq *iocbq;
12104 	IOCB_t *icmd;
12105 	int sum, i, ret_val;
12106 	unsigned long iflags;
12107 	struct lpfc_sli_ring *pring_s4 = NULL;
12108 
12109 	spin_lock_irqsave(&phba->hbalock, iflags);
12110 
12111 	/* all I/Os are in process of being flushed */
12112 	if (phba->hba_flag & HBA_IOQ_FLUSH) {
12113 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12114 		return 0;
12115 	}
12116 	sum = 0;
12117 
12118 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12119 		iocbq = phba->sli.iocbq_lookup[i];
12120 
12121 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12122 					       cmd) != 0)
12123 			continue;
12124 
12125 		/* Guard against IO completion being called at same time */
12126 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12127 		spin_lock(&lpfc_cmd->buf_lock);
12128 
12129 		if (!lpfc_cmd->pCmd) {
12130 			spin_unlock(&lpfc_cmd->buf_lock);
12131 			continue;
12132 		}
12133 
12134 		if (phba->sli_rev == LPFC_SLI_REV4) {
12135 			pring_s4 =
12136 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12137 			if (!pring_s4) {
12138 				spin_unlock(&lpfc_cmd->buf_lock);
12139 				continue;
12140 			}
12141 			/* Note: both hbalock and ring_lock must be set here */
12142 			spin_lock(&pring_s4->ring_lock);
12143 		}
12144 
12145 		/*
12146 		 * If the iocbq is already being aborted, don't take a second
12147 		 * action, but do count it.
12148 		 */
12149 		if ((iocbq->iocb_flag & LPFC_DRIVER_ABORTED) ||
12150 		    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ)) {
12151 			if (phba->sli_rev == LPFC_SLI_REV4)
12152 				spin_unlock(&pring_s4->ring_lock);
12153 			spin_unlock(&lpfc_cmd->buf_lock);
12154 			continue;
12155 		}
12156 
12157 		/* issue ABTS for this IOCB based on iotag */
12158 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
12159 		if (!abtsiocbq) {
12160 			if (phba->sli_rev == LPFC_SLI_REV4)
12161 				spin_unlock(&pring_s4->ring_lock);
12162 			spin_unlock(&lpfc_cmd->buf_lock);
12163 			continue;
12164 		}
12165 
12166 		icmd = &iocbq->iocb;
12167 		abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
12168 		abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
12169 		if (phba->sli_rev == LPFC_SLI_REV4)
12170 			abtsiocbq->iocb.un.acxri.abortIoTag =
12171 							 iocbq->sli4_xritag;
12172 		else
12173 			abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
12174 		abtsiocbq->iocb.ulpLe = 1;
12175 		abtsiocbq->iocb.ulpClass = icmd->ulpClass;
12176 		abtsiocbq->vport = vport;
12177 
12178 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12179 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12180 		if (iocbq->iocb_flag & LPFC_IO_FCP)
12181 			abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
12182 		if (iocbq->iocb_flag & LPFC_IO_FOF)
12183 			abtsiocbq->iocb_flag |= LPFC_IO_FOF;
12184 
12185 		ndlp = lpfc_cmd->rdata->pnode;
12186 
12187 		if (lpfc_is_link_up(phba) &&
12188 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
12189 			abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
12190 		else
12191 			abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
12192 
12193 		/* Setup callback routine and issue the command. */
12194 		abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
12195 
12196 		/*
12197 		 * Indicate the IO is being aborted by the driver and set
12198 		 * the caller's flag into the aborted IO.
12199 		 */
12200 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
12201 
12202 		if (phba->sli_rev == LPFC_SLI_REV4) {
12203 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
12204 							abtsiocbq, 0);
12205 			spin_unlock(&pring_s4->ring_lock);
12206 		} else {
12207 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
12208 							abtsiocbq, 0);
12209 		}
12210 
12211 		spin_unlock(&lpfc_cmd->buf_lock);
12212 
12213 		if (ret_val == IOCB_ERROR)
12214 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
12215 		else
12216 			sum++;
12217 	}
12218 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12219 	return sum;
12220 }
12221 
12222 /**
12223  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
12224  * @phba: Pointer to HBA context object.
12225  * @cmdiocbq: Pointer to command iocb.
12226  * @rspiocbq: Pointer to response iocb.
12227  *
12228  * This function is the completion handler for iocbs issued using
12229  * lpfc_sli_issue_iocb_wait function. This function is called by the
12230  * ring event handler function without any lock held. This function
12231  * can be called from both worker thread context and interrupt
12232  * context. This function also can be called from other thread which
12233  * cleans up the SLI layer objects.
12234  * This function copy the contents of the response iocb to the
12235  * response iocb memory object provided by the caller of
12236  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
12237  * sleeps for the iocb completion.
12238  **/
12239 static void
12240 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
12241 			struct lpfc_iocbq *cmdiocbq,
12242 			struct lpfc_iocbq *rspiocbq)
12243 {
12244 	wait_queue_head_t *pdone_q;
12245 	unsigned long iflags;
12246 	struct lpfc_io_buf *lpfc_cmd;
12247 
12248 	spin_lock_irqsave(&phba->hbalock, iflags);
12249 	if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
12250 
12251 		/*
12252 		 * A time out has occurred for the iocb.  If a time out
12253 		 * completion handler has been supplied, call it.  Otherwise,
12254 		 * just free the iocbq.
12255 		 */
12256 
12257 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12258 		cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
12259 		cmdiocbq->wait_iocb_cmpl = NULL;
12260 		if (cmdiocbq->iocb_cmpl)
12261 			(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
12262 		else
12263 			lpfc_sli_release_iocbq(phba, cmdiocbq);
12264 		return;
12265 	}
12266 
12267 	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
12268 	if (cmdiocbq->context2 && rspiocbq)
12269 		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
12270 		       &rspiocbq->iocb, sizeof(IOCB_t));
12271 
12272 	/* Set the exchange busy flag for task management commands */
12273 	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
12274 		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
12275 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
12276 			cur_iocbq);
12277 		if (rspiocbq && (rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY))
12278 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
12279 		else
12280 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
12281 	}
12282 
12283 	pdone_q = cmdiocbq->context_un.wait_queue;
12284 	if (pdone_q)
12285 		wake_up(pdone_q);
12286 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12287 	return;
12288 }
12289 
12290 /**
12291  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
12292  * @phba: Pointer to HBA context object..
12293  * @piocbq: Pointer to command iocb.
12294  * @flag: Flag to test.
12295  *
12296  * This routine grabs the hbalock and then test the iocb_flag to
12297  * see if the passed in flag is set.
12298  * Returns:
12299  * 1 if flag is set.
12300  * 0 if flag is not set.
12301  **/
12302 static int
12303 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
12304 		 struct lpfc_iocbq *piocbq, uint32_t flag)
12305 {
12306 	unsigned long iflags;
12307 	int ret;
12308 
12309 	spin_lock_irqsave(&phba->hbalock, iflags);
12310 	ret = piocbq->iocb_flag & flag;
12311 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12312 	return ret;
12313 
12314 }
12315 
12316 /**
12317  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
12318  * @phba: Pointer to HBA context object..
12319  * @ring_number: Ring number
12320  * @piocb: Pointer to command iocb.
12321  * @prspiocbq: Pointer to response iocb.
12322  * @timeout: Timeout in number of seconds.
12323  *
12324  * This function issues the iocb to firmware and waits for the
12325  * iocb to complete. The iocb_cmpl field of the shall be used
12326  * to handle iocbs which time out. If the field is NULL, the
12327  * function shall free the iocbq structure.  If more clean up is
12328  * needed, the caller is expected to provide a completion function
12329  * that will provide the needed clean up.  If the iocb command is
12330  * not completed within timeout seconds, the function will either
12331  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
12332  * completion function set in the iocb_cmpl field and then return
12333  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
12334  * resources if this function returns IOCB_TIMEDOUT.
12335  * The function waits for the iocb completion using an
12336  * non-interruptible wait.
12337  * This function will sleep while waiting for iocb completion.
12338  * So, this function should not be called from any context which
12339  * does not allow sleeping. Due to the same reason, this function
12340  * cannot be called with interrupt disabled.
12341  * This function assumes that the iocb completions occur while
12342  * this function sleep. So, this function cannot be called from
12343  * the thread which process iocb completion for this ring.
12344  * This function clears the iocb_flag of the iocb object before
12345  * issuing the iocb and the iocb completion handler sets this
12346  * flag and wakes this thread when the iocb completes.
12347  * The contents of the response iocb will be copied to prspiocbq
12348  * by the completion handler when the command completes.
12349  * This function returns IOCB_SUCCESS when success.
12350  * This function is called with no lock held.
12351  **/
12352 int
12353 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
12354 			 uint32_t ring_number,
12355 			 struct lpfc_iocbq *piocb,
12356 			 struct lpfc_iocbq *prspiocbq,
12357 			 uint32_t timeout)
12358 {
12359 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
12360 	long timeleft, timeout_req = 0;
12361 	int retval = IOCB_SUCCESS;
12362 	uint32_t creg_val;
12363 	struct lpfc_iocbq *iocb;
12364 	int txq_cnt = 0;
12365 	int txcmplq_cnt = 0;
12366 	struct lpfc_sli_ring *pring;
12367 	unsigned long iflags;
12368 	bool iocb_completed = true;
12369 
12370 	if (phba->sli_rev >= LPFC_SLI_REV4)
12371 		pring = lpfc_sli4_calc_ring(phba, piocb);
12372 	else
12373 		pring = &phba->sli.sli3_ring[ring_number];
12374 	/*
12375 	 * If the caller has provided a response iocbq buffer, then context2
12376 	 * is NULL or its an error.
12377 	 */
12378 	if (prspiocbq) {
12379 		if (piocb->context2)
12380 			return IOCB_ERROR;
12381 		piocb->context2 = prspiocbq;
12382 	}
12383 
12384 	piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
12385 	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
12386 	piocb->context_un.wait_queue = &done_q;
12387 	piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
12388 
12389 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12390 		if (lpfc_readl(phba->HCregaddr, &creg_val))
12391 			return IOCB_ERROR;
12392 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
12393 		writel(creg_val, phba->HCregaddr);
12394 		readl(phba->HCregaddr); /* flush */
12395 	}
12396 
12397 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
12398 				     SLI_IOCB_RET_IOCB);
12399 	if (retval == IOCB_SUCCESS) {
12400 		timeout_req = msecs_to_jiffies(timeout * 1000);
12401 		timeleft = wait_event_timeout(done_q,
12402 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
12403 				timeout_req);
12404 		spin_lock_irqsave(&phba->hbalock, iflags);
12405 		if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
12406 
12407 			/*
12408 			 * IOCB timed out.  Inform the wake iocb wait
12409 			 * completion function and set local status
12410 			 */
12411 
12412 			iocb_completed = false;
12413 			piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
12414 		}
12415 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12416 		if (iocb_completed) {
12417 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12418 					"0331 IOCB wake signaled\n");
12419 			/* Note: we are not indicating if the IOCB has a success
12420 			 * status or not - that's for the caller to check.
12421 			 * IOCB_SUCCESS means just that the command was sent and
12422 			 * completed. Not that it completed successfully.
12423 			 * */
12424 		} else if (timeleft == 0) {
12425 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12426 					"0338 IOCB wait timeout error - no "
12427 					"wake response Data x%x\n", timeout);
12428 			retval = IOCB_TIMEDOUT;
12429 		} else {
12430 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12431 					"0330 IOCB wake NOT set, "
12432 					"Data x%x x%lx\n",
12433 					timeout, (timeleft / jiffies));
12434 			retval = IOCB_TIMEDOUT;
12435 		}
12436 	} else if (retval == IOCB_BUSY) {
12437 		if (phba->cfg_log_verbose & LOG_SLI) {
12438 			list_for_each_entry(iocb, &pring->txq, list) {
12439 				txq_cnt++;
12440 			}
12441 			list_for_each_entry(iocb, &pring->txcmplq, list) {
12442 				txcmplq_cnt++;
12443 			}
12444 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12445 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
12446 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
12447 		}
12448 		return retval;
12449 	} else {
12450 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12451 				"0332 IOCB wait issue failed, Data x%x\n",
12452 				retval);
12453 		retval = IOCB_ERROR;
12454 	}
12455 
12456 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12457 		if (lpfc_readl(phba->HCregaddr, &creg_val))
12458 			return IOCB_ERROR;
12459 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
12460 		writel(creg_val, phba->HCregaddr);
12461 		readl(phba->HCregaddr); /* flush */
12462 	}
12463 
12464 	if (prspiocbq)
12465 		piocb->context2 = NULL;
12466 
12467 	piocb->context_un.wait_queue = NULL;
12468 	piocb->iocb_cmpl = NULL;
12469 	return retval;
12470 }
12471 
12472 /**
12473  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
12474  * @phba: Pointer to HBA context object.
12475  * @pmboxq: Pointer to driver mailbox object.
12476  * @timeout: Timeout in number of seconds.
12477  *
12478  * This function issues the mailbox to firmware and waits for the
12479  * mailbox command to complete. If the mailbox command is not
12480  * completed within timeout seconds, it returns MBX_TIMEOUT.
12481  * The function waits for the mailbox completion using an
12482  * interruptible wait. If the thread is woken up due to a
12483  * signal, MBX_TIMEOUT error is returned to the caller. Caller
12484  * should not free the mailbox resources, if this function returns
12485  * MBX_TIMEOUT.
12486  * This function will sleep while waiting for mailbox completion.
12487  * So, this function should not be called from any context which
12488  * does not allow sleeping. Due to the same reason, this function
12489  * cannot be called with interrupt disabled.
12490  * This function assumes that the mailbox completion occurs while
12491  * this function sleep. So, this function cannot be called from
12492  * the worker thread which processes mailbox completion.
12493  * This function is called in the context of HBA management
12494  * applications.
12495  * This function returns MBX_SUCCESS when successful.
12496  * This function is called with no lock held.
12497  **/
12498 int
12499 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
12500 			 uint32_t timeout)
12501 {
12502 	struct completion mbox_done;
12503 	int retval;
12504 	unsigned long flag;
12505 
12506 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
12507 	/* setup wake call as IOCB callback */
12508 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
12509 
12510 	/* setup context3 field to pass wait_queue pointer to wake function  */
12511 	init_completion(&mbox_done);
12512 	pmboxq->context3 = &mbox_done;
12513 	/* now issue the command */
12514 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
12515 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
12516 		wait_for_completion_timeout(&mbox_done,
12517 					    msecs_to_jiffies(timeout * 1000));
12518 
12519 		spin_lock_irqsave(&phba->hbalock, flag);
12520 		pmboxq->context3 = NULL;
12521 		/*
12522 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
12523 		 * else do not free the resources.
12524 		 */
12525 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
12526 			retval = MBX_SUCCESS;
12527 		} else {
12528 			retval = MBX_TIMEOUT;
12529 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
12530 		}
12531 		spin_unlock_irqrestore(&phba->hbalock, flag);
12532 	}
12533 	return retval;
12534 }
12535 
12536 /**
12537  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
12538  * @phba: Pointer to HBA context.
12539  * @mbx_action: Mailbox shutdown options.
12540  *
12541  * This function is called to shutdown the driver's mailbox sub-system.
12542  * It first marks the mailbox sub-system is in a block state to prevent
12543  * the asynchronous mailbox command from issued off the pending mailbox
12544  * command queue. If the mailbox command sub-system shutdown is due to
12545  * HBA error conditions such as EEH or ERATT, this routine shall invoke
12546  * the mailbox sub-system flush routine to forcefully bring down the
12547  * mailbox sub-system. Otherwise, if it is due to normal condition (such
12548  * as with offline or HBA function reset), this routine will wait for the
12549  * outstanding mailbox command to complete before invoking the mailbox
12550  * sub-system flush routine to gracefully bring down mailbox sub-system.
12551  **/
12552 void
12553 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
12554 {
12555 	struct lpfc_sli *psli = &phba->sli;
12556 	unsigned long timeout;
12557 
12558 	if (mbx_action == LPFC_MBX_NO_WAIT) {
12559 		/* delay 100ms for port state */
12560 		msleep(100);
12561 		lpfc_sli_mbox_sys_flush(phba);
12562 		return;
12563 	}
12564 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
12565 
12566 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12567 	local_bh_disable();
12568 
12569 	spin_lock_irq(&phba->hbalock);
12570 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
12571 
12572 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
12573 		/* Determine how long we might wait for the active mailbox
12574 		 * command to be gracefully completed by firmware.
12575 		 */
12576 		if (phba->sli.mbox_active)
12577 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
12578 						phba->sli.mbox_active) *
12579 						1000) + jiffies;
12580 		spin_unlock_irq(&phba->hbalock);
12581 
12582 		/* Enable softirqs again, done with phba->hbalock */
12583 		local_bh_enable();
12584 
12585 		while (phba->sli.mbox_active) {
12586 			/* Check active mailbox complete status every 2ms */
12587 			msleep(2);
12588 			if (time_after(jiffies, timeout))
12589 				/* Timeout, let the mailbox flush routine to
12590 				 * forcefully release active mailbox command
12591 				 */
12592 				break;
12593 		}
12594 	} else {
12595 		spin_unlock_irq(&phba->hbalock);
12596 
12597 		/* Enable softirqs again, done with phba->hbalock */
12598 		local_bh_enable();
12599 	}
12600 
12601 	lpfc_sli_mbox_sys_flush(phba);
12602 }
12603 
12604 /**
12605  * lpfc_sli_eratt_read - read sli-3 error attention events
12606  * @phba: Pointer to HBA context.
12607  *
12608  * This function is called to read the SLI3 device error attention registers
12609  * for possible error attention events. The caller must hold the hostlock
12610  * with spin_lock_irq().
12611  *
12612  * This function returns 1 when there is Error Attention in the Host Attention
12613  * Register and returns 0 otherwise.
12614  **/
12615 static int
12616 lpfc_sli_eratt_read(struct lpfc_hba *phba)
12617 {
12618 	uint32_t ha_copy;
12619 
12620 	/* Read chip Host Attention (HA) register */
12621 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
12622 		goto unplug_err;
12623 
12624 	if (ha_copy & HA_ERATT) {
12625 		/* Read host status register to retrieve error event */
12626 		if (lpfc_sli_read_hs(phba))
12627 			goto unplug_err;
12628 
12629 		/* Check if there is a deferred error condition is active */
12630 		if ((HS_FFER1 & phba->work_hs) &&
12631 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12632 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
12633 			phba->hba_flag |= DEFER_ERATT;
12634 			/* Clear all interrupt enable conditions */
12635 			writel(0, phba->HCregaddr);
12636 			readl(phba->HCregaddr);
12637 		}
12638 
12639 		/* Set the driver HA work bitmap */
12640 		phba->work_ha |= HA_ERATT;
12641 		/* Indicate polling handles this ERATT */
12642 		phba->hba_flag |= HBA_ERATT_HANDLED;
12643 		return 1;
12644 	}
12645 	return 0;
12646 
12647 unplug_err:
12648 	/* Set the driver HS work bitmap */
12649 	phba->work_hs |= UNPLUG_ERR;
12650 	/* Set the driver HA work bitmap */
12651 	phba->work_ha |= HA_ERATT;
12652 	/* Indicate polling handles this ERATT */
12653 	phba->hba_flag |= HBA_ERATT_HANDLED;
12654 	return 1;
12655 }
12656 
12657 /**
12658  * lpfc_sli4_eratt_read - read sli-4 error attention events
12659  * @phba: Pointer to HBA context.
12660  *
12661  * This function is called to read the SLI4 device error attention registers
12662  * for possible error attention events. The caller must hold the hostlock
12663  * with spin_lock_irq().
12664  *
12665  * This function returns 1 when there is Error Attention in the Host Attention
12666  * Register and returns 0 otherwise.
12667  **/
12668 static int
12669 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
12670 {
12671 	uint32_t uerr_sta_hi, uerr_sta_lo;
12672 	uint32_t if_type, portsmphr;
12673 	struct lpfc_register portstat_reg;
12674 
12675 	/*
12676 	 * For now, use the SLI4 device internal unrecoverable error
12677 	 * registers for error attention. This can be changed later.
12678 	 */
12679 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12680 	switch (if_type) {
12681 	case LPFC_SLI_INTF_IF_TYPE_0:
12682 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
12683 			&uerr_sta_lo) ||
12684 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
12685 			&uerr_sta_hi)) {
12686 			phba->work_hs |= UNPLUG_ERR;
12687 			phba->work_ha |= HA_ERATT;
12688 			phba->hba_flag |= HBA_ERATT_HANDLED;
12689 			return 1;
12690 		}
12691 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
12692 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
12693 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12694 					"1423 HBA Unrecoverable error: "
12695 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
12696 					"ue_mask_lo_reg=0x%x, "
12697 					"ue_mask_hi_reg=0x%x\n",
12698 					uerr_sta_lo, uerr_sta_hi,
12699 					phba->sli4_hba.ue_mask_lo,
12700 					phba->sli4_hba.ue_mask_hi);
12701 			phba->work_status[0] = uerr_sta_lo;
12702 			phba->work_status[1] = uerr_sta_hi;
12703 			phba->work_ha |= HA_ERATT;
12704 			phba->hba_flag |= HBA_ERATT_HANDLED;
12705 			return 1;
12706 		}
12707 		break;
12708 	case LPFC_SLI_INTF_IF_TYPE_2:
12709 	case LPFC_SLI_INTF_IF_TYPE_6:
12710 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
12711 			&portstat_reg.word0) ||
12712 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
12713 			&portsmphr)){
12714 			phba->work_hs |= UNPLUG_ERR;
12715 			phba->work_ha |= HA_ERATT;
12716 			phba->hba_flag |= HBA_ERATT_HANDLED;
12717 			return 1;
12718 		}
12719 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
12720 			phba->work_status[0] =
12721 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
12722 			phba->work_status[1] =
12723 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
12724 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12725 					"2885 Port Status Event: "
12726 					"port status reg 0x%x, "
12727 					"port smphr reg 0x%x, "
12728 					"error 1=0x%x, error 2=0x%x\n",
12729 					portstat_reg.word0,
12730 					portsmphr,
12731 					phba->work_status[0],
12732 					phba->work_status[1]);
12733 			phba->work_ha |= HA_ERATT;
12734 			phba->hba_flag |= HBA_ERATT_HANDLED;
12735 			return 1;
12736 		}
12737 		break;
12738 	case LPFC_SLI_INTF_IF_TYPE_1:
12739 	default:
12740 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12741 				"2886 HBA Error Attention on unsupported "
12742 				"if type %d.", if_type);
12743 		return 1;
12744 	}
12745 
12746 	return 0;
12747 }
12748 
12749 /**
12750  * lpfc_sli_check_eratt - check error attention events
12751  * @phba: Pointer to HBA context.
12752  *
12753  * This function is called from timer soft interrupt context to check HBA's
12754  * error attention register bit for error attention events.
12755  *
12756  * This function returns 1 when there is Error Attention in the Host Attention
12757  * Register and returns 0 otherwise.
12758  **/
12759 int
12760 lpfc_sli_check_eratt(struct lpfc_hba *phba)
12761 {
12762 	uint32_t ha_copy;
12763 
12764 	/* If somebody is waiting to handle an eratt, don't process it
12765 	 * here. The brdkill function will do this.
12766 	 */
12767 	if (phba->link_flag & LS_IGNORE_ERATT)
12768 		return 0;
12769 
12770 	/* Check if interrupt handler handles this ERATT */
12771 	spin_lock_irq(&phba->hbalock);
12772 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
12773 		/* Interrupt handler has handled ERATT */
12774 		spin_unlock_irq(&phba->hbalock);
12775 		return 0;
12776 	}
12777 
12778 	/*
12779 	 * If there is deferred error attention, do not check for error
12780 	 * attention
12781 	 */
12782 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12783 		spin_unlock_irq(&phba->hbalock);
12784 		return 0;
12785 	}
12786 
12787 	/* If PCI channel is offline, don't process it */
12788 	if (unlikely(pci_channel_offline(phba->pcidev))) {
12789 		spin_unlock_irq(&phba->hbalock);
12790 		return 0;
12791 	}
12792 
12793 	switch (phba->sli_rev) {
12794 	case LPFC_SLI_REV2:
12795 	case LPFC_SLI_REV3:
12796 		/* Read chip Host Attention (HA) register */
12797 		ha_copy = lpfc_sli_eratt_read(phba);
12798 		break;
12799 	case LPFC_SLI_REV4:
12800 		/* Read device Uncoverable Error (UERR) registers */
12801 		ha_copy = lpfc_sli4_eratt_read(phba);
12802 		break;
12803 	default:
12804 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12805 				"0299 Invalid SLI revision (%d)\n",
12806 				phba->sli_rev);
12807 		ha_copy = 0;
12808 		break;
12809 	}
12810 	spin_unlock_irq(&phba->hbalock);
12811 
12812 	return ha_copy;
12813 }
12814 
12815 /**
12816  * lpfc_intr_state_check - Check device state for interrupt handling
12817  * @phba: Pointer to HBA context.
12818  *
12819  * This inline routine checks whether a device or its PCI slot is in a state
12820  * that the interrupt should be handled.
12821  *
12822  * This function returns 0 if the device or the PCI slot is in a state that
12823  * interrupt should be handled, otherwise -EIO.
12824  */
12825 static inline int
12826 lpfc_intr_state_check(struct lpfc_hba *phba)
12827 {
12828 	/* If the pci channel is offline, ignore all the interrupts */
12829 	if (unlikely(pci_channel_offline(phba->pcidev)))
12830 		return -EIO;
12831 
12832 	/* Update device level interrupt statistics */
12833 	phba->sli.slistat.sli_intr++;
12834 
12835 	/* Ignore all interrupts during initialization. */
12836 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
12837 		return -EIO;
12838 
12839 	return 0;
12840 }
12841 
12842 /**
12843  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
12844  * @irq: Interrupt number.
12845  * @dev_id: The device context pointer.
12846  *
12847  * This function is directly called from the PCI layer as an interrupt
12848  * service routine when device with SLI-3 interface spec is enabled with
12849  * MSI-X multi-message interrupt mode and there are slow-path events in
12850  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
12851  * interrupt mode, this function is called as part of the device-level
12852  * interrupt handler. When the PCI slot is in error recovery or the HBA
12853  * is undergoing initialization, the interrupt handler will not process
12854  * the interrupt. The link attention and ELS ring attention events are
12855  * handled by the worker thread. The interrupt handler signals the worker
12856  * thread and returns for these events. This function is called without
12857  * any lock held. It gets the hbalock to access and update SLI data
12858  * structures.
12859  *
12860  * This function returns IRQ_HANDLED when interrupt is handled else it
12861  * returns IRQ_NONE.
12862  **/
12863 irqreturn_t
12864 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
12865 {
12866 	struct lpfc_hba  *phba;
12867 	uint32_t ha_copy, hc_copy;
12868 	uint32_t work_ha_copy;
12869 	unsigned long status;
12870 	unsigned long iflag;
12871 	uint32_t control;
12872 
12873 	MAILBOX_t *mbox, *pmbox;
12874 	struct lpfc_vport *vport;
12875 	struct lpfc_nodelist *ndlp;
12876 	struct lpfc_dmabuf *mp;
12877 	LPFC_MBOXQ_t *pmb;
12878 	int rc;
12879 
12880 	/*
12881 	 * Get the driver's phba structure from the dev_id and
12882 	 * assume the HBA is not interrupting.
12883 	 */
12884 	phba = (struct lpfc_hba *)dev_id;
12885 
12886 	if (unlikely(!phba))
12887 		return IRQ_NONE;
12888 
12889 	/*
12890 	 * Stuff needs to be attented to when this function is invoked as an
12891 	 * individual interrupt handler in MSI-X multi-message interrupt mode
12892 	 */
12893 	if (phba->intr_type == MSIX) {
12894 		/* Check device state for handling interrupt */
12895 		if (lpfc_intr_state_check(phba))
12896 			return IRQ_NONE;
12897 		/* Need to read HA REG for slow-path events */
12898 		spin_lock_irqsave(&phba->hbalock, iflag);
12899 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
12900 			goto unplug_error;
12901 		/* If somebody is waiting to handle an eratt don't process it
12902 		 * here. The brdkill function will do this.
12903 		 */
12904 		if (phba->link_flag & LS_IGNORE_ERATT)
12905 			ha_copy &= ~HA_ERATT;
12906 		/* Check the need for handling ERATT in interrupt handler */
12907 		if (ha_copy & HA_ERATT) {
12908 			if (phba->hba_flag & HBA_ERATT_HANDLED)
12909 				/* ERATT polling has handled ERATT */
12910 				ha_copy &= ~HA_ERATT;
12911 			else
12912 				/* Indicate interrupt handler handles ERATT */
12913 				phba->hba_flag |= HBA_ERATT_HANDLED;
12914 		}
12915 
12916 		/*
12917 		 * If there is deferred error attention, do not check for any
12918 		 * interrupt.
12919 		 */
12920 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12921 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12922 			return IRQ_NONE;
12923 		}
12924 
12925 		/* Clear up only attention source related to slow-path */
12926 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
12927 			goto unplug_error;
12928 
12929 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
12930 			HC_LAINT_ENA | HC_ERINT_ENA),
12931 			phba->HCregaddr);
12932 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
12933 			phba->HAregaddr);
12934 		writel(hc_copy, phba->HCregaddr);
12935 		readl(phba->HAregaddr); /* flush */
12936 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12937 	} else
12938 		ha_copy = phba->ha_copy;
12939 
12940 	work_ha_copy = ha_copy & phba->work_ha_mask;
12941 
12942 	if (work_ha_copy) {
12943 		if (work_ha_copy & HA_LATT) {
12944 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
12945 				/*
12946 				 * Turn off Link Attention interrupts
12947 				 * until CLEAR_LA done
12948 				 */
12949 				spin_lock_irqsave(&phba->hbalock, iflag);
12950 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
12951 				if (lpfc_readl(phba->HCregaddr, &control))
12952 					goto unplug_error;
12953 				control &= ~HC_LAINT_ENA;
12954 				writel(control, phba->HCregaddr);
12955 				readl(phba->HCregaddr); /* flush */
12956 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12957 			}
12958 			else
12959 				work_ha_copy &= ~HA_LATT;
12960 		}
12961 
12962 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
12963 			/*
12964 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
12965 			 * the only slow ring.
12966 			 */
12967 			status = (work_ha_copy &
12968 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
12969 			status >>= (4*LPFC_ELS_RING);
12970 			if (status & HA_RXMASK) {
12971 				spin_lock_irqsave(&phba->hbalock, iflag);
12972 				if (lpfc_readl(phba->HCregaddr, &control))
12973 					goto unplug_error;
12974 
12975 				lpfc_debugfs_slow_ring_trc(phba,
12976 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
12977 				control, status,
12978 				(uint32_t)phba->sli.slistat.sli_intr);
12979 
12980 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
12981 					lpfc_debugfs_slow_ring_trc(phba,
12982 						"ISR Disable ring:"
12983 						"pwork:x%x hawork:x%x wait:x%x",
12984 						phba->work_ha, work_ha_copy,
12985 						(uint32_t)((unsigned long)
12986 						&phba->work_waitq));
12987 
12988 					control &=
12989 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
12990 					writel(control, phba->HCregaddr);
12991 					readl(phba->HCregaddr); /* flush */
12992 				}
12993 				else {
12994 					lpfc_debugfs_slow_ring_trc(phba,
12995 						"ISR slow ring:   pwork:"
12996 						"x%x hawork:x%x wait:x%x",
12997 						phba->work_ha, work_ha_copy,
12998 						(uint32_t)((unsigned long)
12999 						&phba->work_waitq));
13000 				}
13001 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13002 			}
13003 		}
13004 		spin_lock_irqsave(&phba->hbalock, iflag);
13005 		if (work_ha_copy & HA_ERATT) {
13006 			if (lpfc_sli_read_hs(phba))
13007 				goto unplug_error;
13008 			/*
13009 			 * Check if there is a deferred error condition
13010 			 * is active
13011 			 */
13012 			if ((HS_FFER1 & phba->work_hs) &&
13013 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13014 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
13015 				  phba->work_hs)) {
13016 				phba->hba_flag |= DEFER_ERATT;
13017 				/* Clear all interrupt enable conditions */
13018 				writel(0, phba->HCregaddr);
13019 				readl(phba->HCregaddr);
13020 			}
13021 		}
13022 
13023 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
13024 			pmb = phba->sli.mbox_active;
13025 			pmbox = &pmb->u.mb;
13026 			mbox = phba->mbox;
13027 			vport = pmb->vport;
13028 
13029 			/* First check out the status word */
13030 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
13031 			if (pmbox->mbxOwner != OWN_HOST) {
13032 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13033 				/*
13034 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
13035 				 * mbxStatus <status>
13036 				 */
13037 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13038 						"(%d):0304 Stray Mailbox "
13039 						"Interrupt mbxCommand x%x "
13040 						"mbxStatus x%x\n",
13041 						(vport ? vport->vpi : 0),
13042 						pmbox->mbxCommand,
13043 						pmbox->mbxStatus);
13044 				/* clear mailbox attention bit */
13045 				work_ha_copy &= ~HA_MBATT;
13046 			} else {
13047 				phba->sli.mbox_active = NULL;
13048 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13049 				phba->last_completion_time = jiffies;
13050 				del_timer(&phba->sli.mbox_tmo);
13051 				if (pmb->mbox_cmpl) {
13052 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
13053 							MAILBOX_CMD_SIZE);
13054 					if (pmb->out_ext_byte_len &&
13055 						pmb->ctx_buf)
13056 						lpfc_sli_pcimem_bcopy(
13057 						phba->mbox_ext,
13058 						pmb->ctx_buf,
13059 						pmb->out_ext_byte_len);
13060 				}
13061 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13062 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13063 
13064 					lpfc_debugfs_disc_trc(vport,
13065 						LPFC_DISC_TRC_MBOX_VPORT,
13066 						"MBOX dflt rpi: : "
13067 						"status:x%x rpi:x%x",
13068 						(uint32_t)pmbox->mbxStatus,
13069 						pmbox->un.varWords[0], 0);
13070 
13071 					if (!pmbox->mbxStatus) {
13072 						mp = (struct lpfc_dmabuf *)
13073 							(pmb->ctx_buf);
13074 						ndlp = (struct lpfc_nodelist *)
13075 							pmb->ctx_ndlp;
13076 
13077 						/* Reg_LOGIN of dflt RPI was
13078 						 * successful. new lets get
13079 						 * rid of the RPI using the
13080 						 * same mbox buffer.
13081 						 */
13082 						lpfc_unreg_login(phba,
13083 							vport->vpi,
13084 							pmbox->un.varWords[0],
13085 							pmb);
13086 						pmb->mbox_cmpl =
13087 							lpfc_mbx_cmpl_dflt_rpi;
13088 						pmb->ctx_buf = mp;
13089 						pmb->ctx_ndlp = ndlp;
13090 						pmb->vport = vport;
13091 						rc = lpfc_sli_issue_mbox(phba,
13092 								pmb,
13093 								MBX_NOWAIT);
13094 						if (rc != MBX_BUSY)
13095 							lpfc_printf_log(phba,
13096 							KERN_ERR,
13097 							LOG_TRACE_EVENT,
13098 							"0350 rc should have"
13099 							"been MBX_BUSY\n");
13100 						if (rc != MBX_NOT_FINISHED)
13101 							goto send_current_mbox;
13102 					}
13103 				}
13104 				spin_lock_irqsave(
13105 						&phba->pport->work_port_lock,
13106 						iflag);
13107 				phba->pport->work_port_events &=
13108 					~WORKER_MBOX_TMO;
13109 				spin_unlock_irqrestore(
13110 						&phba->pport->work_port_lock,
13111 						iflag);
13112 
13113 				/* Do NOT queue MBX_HEARTBEAT to the worker
13114 				 * thread for processing.
13115 				 */
13116 				if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13117 					/* Process mbox now */
13118 					phba->sli.mbox_active = NULL;
13119 					phba->sli.sli_flag &=
13120 						~LPFC_SLI_MBOX_ACTIVE;
13121 					if (pmb->mbox_cmpl)
13122 						pmb->mbox_cmpl(phba, pmb);
13123 				} else {
13124 					/* Queue to worker thread to process */
13125 					lpfc_mbox_cmpl_put(phba, pmb);
13126 				}
13127 			}
13128 		} else
13129 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13130 
13131 		if ((work_ha_copy & HA_MBATT) &&
13132 		    (phba->sli.mbox_active == NULL)) {
13133 send_current_mbox:
13134 			/* Process next mailbox command if there is one */
13135 			do {
13136 				rc = lpfc_sli_issue_mbox(phba, NULL,
13137 							 MBX_NOWAIT);
13138 			} while (rc == MBX_NOT_FINISHED);
13139 			if (rc != MBX_SUCCESS)
13140 				lpfc_printf_log(phba, KERN_ERR,
13141 						LOG_TRACE_EVENT,
13142 						"0349 rc should be "
13143 						"MBX_SUCCESS\n");
13144 		}
13145 
13146 		spin_lock_irqsave(&phba->hbalock, iflag);
13147 		phba->work_ha |= work_ha_copy;
13148 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13149 		lpfc_worker_wake_up(phba);
13150 	}
13151 	return IRQ_HANDLED;
13152 unplug_error:
13153 	spin_unlock_irqrestore(&phba->hbalock, iflag);
13154 	return IRQ_HANDLED;
13155 
13156 } /* lpfc_sli_sp_intr_handler */
13157 
13158 /**
13159  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13160  * @irq: Interrupt number.
13161  * @dev_id: The device context pointer.
13162  *
13163  * This function is directly called from the PCI layer as an interrupt
13164  * service routine when device with SLI-3 interface spec is enabled with
13165  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13166  * ring event in the HBA. However, when the device is enabled with either
13167  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13168  * device-level interrupt handler. When the PCI slot is in error recovery
13169  * or the HBA is undergoing initialization, the interrupt handler will not
13170  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13171  * the intrrupt context. This function is called without any lock held.
13172  * It gets the hbalock to access and update SLI data structures.
13173  *
13174  * This function returns IRQ_HANDLED when interrupt is handled else it
13175  * returns IRQ_NONE.
13176  **/
13177 irqreturn_t
13178 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13179 {
13180 	struct lpfc_hba  *phba;
13181 	uint32_t ha_copy;
13182 	unsigned long status;
13183 	unsigned long iflag;
13184 	struct lpfc_sli_ring *pring;
13185 
13186 	/* Get the driver's phba structure from the dev_id and
13187 	 * assume the HBA is not interrupting.
13188 	 */
13189 	phba = (struct lpfc_hba *) dev_id;
13190 
13191 	if (unlikely(!phba))
13192 		return IRQ_NONE;
13193 
13194 	/*
13195 	 * Stuff needs to be attented to when this function is invoked as an
13196 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13197 	 */
13198 	if (phba->intr_type == MSIX) {
13199 		/* Check device state for handling interrupt */
13200 		if (lpfc_intr_state_check(phba))
13201 			return IRQ_NONE;
13202 		/* Need to read HA REG for FCP ring and other ring events */
13203 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13204 			return IRQ_HANDLED;
13205 		/* Clear up only attention source related to fast-path */
13206 		spin_lock_irqsave(&phba->hbalock, iflag);
13207 		/*
13208 		 * If there is deferred error attention, do not check for
13209 		 * any interrupt.
13210 		 */
13211 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13212 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13213 			return IRQ_NONE;
13214 		}
13215 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
13216 			phba->HAregaddr);
13217 		readl(phba->HAregaddr); /* flush */
13218 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13219 	} else
13220 		ha_copy = phba->ha_copy;
13221 
13222 	/*
13223 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
13224 	 */
13225 	ha_copy &= ~(phba->work_ha_mask);
13226 
13227 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13228 	status >>= (4*LPFC_FCP_RING);
13229 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
13230 	if (status & HA_RXMASK)
13231 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
13232 
13233 	if (phba->cfg_multi_ring_support == 2) {
13234 		/*
13235 		 * Process all events on extra ring. Take the optimized path
13236 		 * for extra ring IO.
13237 		 */
13238 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13239 		status >>= (4*LPFC_EXTRA_RING);
13240 		if (status & HA_RXMASK) {
13241 			lpfc_sli_handle_fast_ring_event(phba,
13242 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
13243 					status);
13244 		}
13245 	}
13246 	return IRQ_HANDLED;
13247 }  /* lpfc_sli_fp_intr_handler */
13248 
13249 /**
13250  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
13251  * @irq: Interrupt number.
13252  * @dev_id: The device context pointer.
13253  *
13254  * This function is the HBA device-level interrupt handler to device with
13255  * SLI-3 interface spec, called from the PCI layer when either MSI or
13256  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
13257  * requires driver attention. This function invokes the slow-path interrupt
13258  * attention handling function and fast-path interrupt attention handling
13259  * function in turn to process the relevant HBA attention events. This
13260  * function is called without any lock held. It gets the hbalock to access
13261  * and update SLI data structures.
13262  *
13263  * This function returns IRQ_HANDLED when interrupt is handled, else it
13264  * returns IRQ_NONE.
13265  **/
13266 irqreturn_t
13267 lpfc_sli_intr_handler(int irq, void *dev_id)
13268 {
13269 	struct lpfc_hba  *phba;
13270 	irqreturn_t sp_irq_rc, fp_irq_rc;
13271 	unsigned long status1, status2;
13272 	uint32_t hc_copy;
13273 
13274 	/*
13275 	 * Get the driver's phba structure from the dev_id and
13276 	 * assume the HBA is not interrupting.
13277 	 */
13278 	phba = (struct lpfc_hba *) dev_id;
13279 
13280 	if (unlikely(!phba))
13281 		return IRQ_NONE;
13282 
13283 	/* Check device state for handling interrupt */
13284 	if (lpfc_intr_state_check(phba))
13285 		return IRQ_NONE;
13286 
13287 	spin_lock(&phba->hbalock);
13288 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
13289 		spin_unlock(&phba->hbalock);
13290 		return IRQ_HANDLED;
13291 	}
13292 
13293 	if (unlikely(!phba->ha_copy)) {
13294 		spin_unlock(&phba->hbalock);
13295 		return IRQ_NONE;
13296 	} else if (phba->ha_copy & HA_ERATT) {
13297 		if (phba->hba_flag & HBA_ERATT_HANDLED)
13298 			/* ERATT polling has handled ERATT */
13299 			phba->ha_copy &= ~HA_ERATT;
13300 		else
13301 			/* Indicate interrupt handler handles ERATT */
13302 			phba->hba_flag |= HBA_ERATT_HANDLED;
13303 	}
13304 
13305 	/*
13306 	 * If there is deferred error attention, do not check for any interrupt.
13307 	 */
13308 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13309 		spin_unlock(&phba->hbalock);
13310 		return IRQ_NONE;
13311 	}
13312 
13313 	/* Clear attention sources except link and error attentions */
13314 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
13315 		spin_unlock(&phba->hbalock);
13316 		return IRQ_HANDLED;
13317 	}
13318 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
13319 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
13320 		phba->HCregaddr);
13321 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
13322 	writel(hc_copy, phba->HCregaddr);
13323 	readl(phba->HAregaddr); /* flush */
13324 	spin_unlock(&phba->hbalock);
13325 
13326 	/*
13327 	 * Invokes slow-path host attention interrupt handling as appropriate.
13328 	 */
13329 
13330 	/* status of events with mailbox and link attention */
13331 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
13332 
13333 	/* status of events with ELS ring */
13334 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
13335 	status2 >>= (4*LPFC_ELS_RING);
13336 
13337 	if (status1 || (status2 & HA_RXMASK))
13338 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
13339 	else
13340 		sp_irq_rc = IRQ_NONE;
13341 
13342 	/*
13343 	 * Invoke fast-path host attention interrupt handling as appropriate.
13344 	 */
13345 
13346 	/* status of events with FCP ring */
13347 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13348 	status1 >>= (4*LPFC_FCP_RING);
13349 
13350 	/* status of events with extra ring */
13351 	if (phba->cfg_multi_ring_support == 2) {
13352 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13353 		status2 >>= (4*LPFC_EXTRA_RING);
13354 	} else
13355 		status2 = 0;
13356 
13357 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
13358 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
13359 	else
13360 		fp_irq_rc = IRQ_NONE;
13361 
13362 	/* Return device-level interrupt handling status */
13363 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
13364 }  /* lpfc_sli_intr_handler */
13365 
13366 /**
13367  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
13368  * @phba: pointer to lpfc hba data structure.
13369  *
13370  * This routine is invoked by the worker thread to process all the pending
13371  * SLI4 els abort xri events.
13372  **/
13373 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
13374 {
13375 	struct lpfc_cq_event *cq_event;
13376 	unsigned long iflags;
13377 
13378 	/* First, declare the els xri abort event has been handled */
13379 	spin_lock_irqsave(&phba->hbalock, iflags);
13380 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
13381 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13382 
13383 	/* Now, handle all the els xri abort events */
13384 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
13385 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
13386 		/* Get the first event from the head of the event queue */
13387 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
13388 				 cq_event, struct lpfc_cq_event, list);
13389 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
13390 				       iflags);
13391 		/* Notify aborted XRI for ELS work queue */
13392 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
13393 
13394 		/* Free the event processed back to the free pool */
13395 		lpfc_sli4_cq_event_release(phba, cq_event);
13396 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
13397 				  iflags);
13398 	}
13399 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
13400 }
13401 
13402 /**
13403  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
13404  * @phba: pointer to lpfc hba data structure
13405  * @pIocbIn: pointer to the rspiocbq
13406  * @pIocbOut: pointer to the cmdiocbq
13407  * @wcqe: pointer to the complete wcqe
13408  *
13409  * This routine transfers the fields of a command iocbq to a response iocbq
13410  * by copying all the IOCB fields from command iocbq and transferring the
13411  * completion status information from the complete wcqe.
13412  **/
13413 static void
13414 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
13415 			      struct lpfc_iocbq *pIocbIn,
13416 			      struct lpfc_iocbq *pIocbOut,
13417 			      struct lpfc_wcqe_complete *wcqe)
13418 {
13419 	int numBdes, i;
13420 	unsigned long iflags;
13421 	uint32_t status, max_response;
13422 	struct lpfc_dmabuf *dmabuf;
13423 	struct ulp_bde64 *bpl, bde;
13424 	size_t offset = offsetof(struct lpfc_iocbq, iocb);
13425 
13426 	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
13427 	       sizeof(struct lpfc_iocbq) - offset);
13428 	/* Map WCQE parameters into irspiocb parameters */
13429 	status = bf_get(lpfc_wcqe_c_status, wcqe);
13430 	pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
13431 	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
13432 		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
13433 			pIocbIn->iocb.un.fcpi.fcpi_parm =
13434 					pIocbOut->iocb.un.fcpi.fcpi_parm -
13435 					wcqe->total_data_placed;
13436 		else
13437 			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
13438 	else {
13439 		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
13440 		switch (pIocbOut->iocb.ulpCommand) {
13441 		case CMD_ELS_REQUEST64_CR:
13442 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
13443 			bpl  = (struct ulp_bde64 *)dmabuf->virt;
13444 			bde.tus.w = le32_to_cpu(bpl[1].tus.w);
13445 			max_response = bde.tus.f.bdeSize;
13446 			break;
13447 		case CMD_GEN_REQUEST64_CR:
13448 			max_response = 0;
13449 			if (!pIocbOut->context3)
13450 				break;
13451 			numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
13452 					sizeof(struct ulp_bde64);
13453 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
13454 			bpl = (struct ulp_bde64 *)dmabuf->virt;
13455 			for (i = 0; i < numBdes; i++) {
13456 				bde.tus.w = le32_to_cpu(bpl[i].tus.w);
13457 				if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
13458 					max_response += bde.tus.f.bdeSize;
13459 			}
13460 			break;
13461 		default:
13462 			max_response = wcqe->total_data_placed;
13463 			break;
13464 		}
13465 		if (max_response < wcqe->total_data_placed)
13466 			pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
13467 		else
13468 			pIocbIn->iocb.un.genreq64.bdl.bdeSize =
13469 				wcqe->total_data_placed;
13470 	}
13471 
13472 	/* Convert BG errors for completion status */
13473 	if (status == CQE_STATUS_DI_ERROR) {
13474 		pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
13475 
13476 		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
13477 			pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
13478 		else
13479 			pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
13480 
13481 		pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
13482 		if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
13483 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13484 				BGS_GUARD_ERR_MASK;
13485 		if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
13486 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13487 				BGS_APPTAG_ERR_MASK;
13488 		if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
13489 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13490 				BGS_REFTAG_ERR_MASK;
13491 
13492 		/* Check to see if there was any good data before the error */
13493 		if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
13494 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13495 				BGS_HI_WATER_MARK_PRESENT_MASK;
13496 			pIocbIn->iocb.unsli3.sli3_bg.bghm =
13497 				wcqe->total_data_placed;
13498 		}
13499 
13500 		/*
13501 		* Set ALL the error bits to indicate we don't know what
13502 		* type of error it is.
13503 		*/
13504 		if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
13505 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13506 				(BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
13507 				BGS_GUARD_ERR_MASK);
13508 	}
13509 
13510 	/* Pick up HBA exchange busy condition */
13511 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
13512 		spin_lock_irqsave(&phba->hbalock, iflags);
13513 		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
13514 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13515 	}
13516 }
13517 
13518 /**
13519  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
13520  * @phba: Pointer to HBA context object.
13521  * @irspiocbq: Pointer to work-queue completion queue entry.
13522  *
13523  * This routine handles an ELS work-queue completion event and construct
13524  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
13525  * discovery engine to handle.
13526  *
13527  * Return: Pointer to the receive IOCBQ, NULL otherwise.
13528  **/
13529 static struct lpfc_iocbq *
13530 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
13531 			       struct lpfc_iocbq *irspiocbq)
13532 {
13533 	struct lpfc_sli_ring *pring;
13534 	struct lpfc_iocbq *cmdiocbq;
13535 	struct lpfc_wcqe_complete *wcqe;
13536 	unsigned long iflags;
13537 
13538 	pring = lpfc_phba_elsring(phba);
13539 	if (unlikely(!pring))
13540 		return NULL;
13541 
13542 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
13543 	pring->stats.iocb_event++;
13544 	/* Look up the ELS command IOCB and create pseudo response IOCB */
13545 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
13546 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13547 	if (unlikely(!cmdiocbq)) {
13548 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13549 				"0386 ELS complete with no corresponding "
13550 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
13551 				wcqe->word0, wcqe->total_data_placed,
13552 				wcqe->parameter, wcqe->word3);
13553 		lpfc_sli_release_iocbq(phba, irspiocbq);
13554 		return NULL;
13555 	}
13556 
13557 	spin_lock_irqsave(&pring->ring_lock, iflags);
13558 	/* Put the iocb back on the txcmplq */
13559 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
13560 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
13561 
13562 	/* Fake the irspiocbq and copy necessary response information */
13563 	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
13564 
13565 	return irspiocbq;
13566 }
13567 
13568 inline struct lpfc_cq_event *
13569 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
13570 {
13571 	struct lpfc_cq_event *cq_event;
13572 
13573 	/* Allocate a new internal CQ_EVENT entry */
13574 	cq_event = lpfc_sli4_cq_event_alloc(phba);
13575 	if (!cq_event) {
13576 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13577 				"0602 Failed to alloc CQ_EVENT entry\n");
13578 		return NULL;
13579 	}
13580 
13581 	/* Move the CQE into the event */
13582 	memcpy(&cq_event->cqe, entry, size);
13583 	return cq_event;
13584 }
13585 
13586 /**
13587  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
13588  * @phba: Pointer to HBA context object.
13589  * @mcqe: Pointer to mailbox completion queue entry.
13590  *
13591  * This routine process a mailbox completion queue entry with asynchronous
13592  * event.
13593  *
13594  * Return: true if work posted to worker thread, otherwise false.
13595  **/
13596 static bool
13597 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13598 {
13599 	struct lpfc_cq_event *cq_event;
13600 	unsigned long iflags;
13601 
13602 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13603 			"0392 Async Event: word0:x%x, word1:x%x, "
13604 			"word2:x%x, word3:x%x\n", mcqe->word0,
13605 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
13606 
13607 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
13608 	if (!cq_event)
13609 		return false;
13610 
13611 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
13612 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
13613 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
13614 
13615 	/* Set the async event flag */
13616 	spin_lock_irqsave(&phba->hbalock, iflags);
13617 	phba->hba_flag |= ASYNC_EVENT;
13618 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13619 
13620 	return true;
13621 }
13622 
13623 /**
13624  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
13625  * @phba: Pointer to HBA context object.
13626  * @mcqe: Pointer to mailbox completion queue entry.
13627  *
13628  * This routine process a mailbox completion queue entry with mailbox
13629  * completion event.
13630  *
13631  * Return: true if work posted to worker thread, otherwise false.
13632  **/
13633 static bool
13634 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13635 {
13636 	uint32_t mcqe_status;
13637 	MAILBOX_t *mbox, *pmbox;
13638 	struct lpfc_mqe *mqe;
13639 	struct lpfc_vport *vport;
13640 	struct lpfc_nodelist *ndlp;
13641 	struct lpfc_dmabuf *mp;
13642 	unsigned long iflags;
13643 	LPFC_MBOXQ_t *pmb;
13644 	bool workposted = false;
13645 	int rc;
13646 
13647 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
13648 	if (!bf_get(lpfc_trailer_completed, mcqe))
13649 		goto out_no_mqe_complete;
13650 
13651 	/* Get the reference to the active mbox command */
13652 	spin_lock_irqsave(&phba->hbalock, iflags);
13653 	pmb = phba->sli.mbox_active;
13654 	if (unlikely(!pmb)) {
13655 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13656 				"1832 No pending MBOX command to handle\n");
13657 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13658 		goto out_no_mqe_complete;
13659 	}
13660 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13661 	mqe = &pmb->u.mqe;
13662 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
13663 	mbox = phba->mbox;
13664 	vport = pmb->vport;
13665 
13666 	/* Reset heartbeat timer */
13667 	phba->last_completion_time = jiffies;
13668 	del_timer(&phba->sli.mbox_tmo);
13669 
13670 	/* Move mbox data to caller's mailbox region, do endian swapping */
13671 	if (pmb->mbox_cmpl && mbox)
13672 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
13673 
13674 	/*
13675 	 * For mcqe errors, conditionally move a modified error code to
13676 	 * the mbox so that the error will not be missed.
13677 	 */
13678 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
13679 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
13680 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
13681 			bf_set(lpfc_mqe_status, mqe,
13682 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
13683 	}
13684 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13685 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13686 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
13687 				      "MBOX dflt rpi: status:x%x rpi:x%x",
13688 				      mcqe_status,
13689 				      pmbox->un.varWords[0], 0);
13690 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
13691 			mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
13692 			ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
13693 
13694 			/* Reg_LOGIN of dflt RPI was successful. Mark the
13695 			 * node as having an UNREG_LOGIN in progress to stop
13696 			 * an unsolicited PLOGI from the same NPortId from
13697 			 * starting another mailbox transaction.
13698 			 */
13699 			spin_lock_irqsave(&ndlp->lock, iflags);
13700 			ndlp->nlp_flag |= NLP_UNREG_INP;
13701 			spin_unlock_irqrestore(&ndlp->lock, iflags);
13702 			lpfc_unreg_login(phba, vport->vpi,
13703 					 pmbox->un.varWords[0], pmb);
13704 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
13705 			pmb->ctx_buf = mp;
13706 
13707 			/* No reference taken here.  This is a default
13708 			 * RPI reg/immediate unreg cycle. The reference was
13709 			 * taken in the reg rpi path and is released when
13710 			 * this mailbox completes.
13711 			 */
13712 			pmb->ctx_ndlp = ndlp;
13713 			pmb->vport = vport;
13714 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
13715 			if (rc != MBX_BUSY)
13716 				lpfc_printf_log(phba, KERN_ERR,
13717 						LOG_TRACE_EVENT,
13718 						"0385 rc should "
13719 						"have been MBX_BUSY\n");
13720 			if (rc != MBX_NOT_FINISHED)
13721 				goto send_current_mbox;
13722 		}
13723 	}
13724 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
13725 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
13726 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
13727 
13728 	/* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
13729 	if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13730 		spin_lock_irqsave(&phba->hbalock, iflags);
13731 		/* Release the mailbox command posting token */
13732 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13733 		phba->sli.mbox_active = NULL;
13734 		if (bf_get(lpfc_trailer_consumed, mcqe))
13735 			lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13736 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13737 
13738 		/* Post the next mbox command, if there is one */
13739 		lpfc_sli4_post_async_mbox(phba);
13740 
13741 		/* Process cmpl now */
13742 		if (pmb->mbox_cmpl)
13743 			pmb->mbox_cmpl(phba, pmb);
13744 		return false;
13745 	}
13746 
13747 	/* There is mailbox completion work to queue to the worker thread */
13748 	spin_lock_irqsave(&phba->hbalock, iflags);
13749 	__lpfc_mbox_cmpl_put(phba, pmb);
13750 	phba->work_ha |= HA_MBATT;
13751 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13752 	workposted = true;
13753 
13754 send_current_mbox:
13755 	spin_lock_irqsave(&phba->hbalock, iflags);
13756 	/* Release the mailbox command posting token */
13757 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13758 	/* Setting active mailbox pointer need to be in sync to flag clear */
13759 	phba->sli.mbox_active = NULL;
13760 	if (bf_get(lpfc_trailer_consumed, mcqe))
13761 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13762 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13763 	/* Wake up worker thread to post the next pending mailbox command */
13764 	lpfc_worker_wake_up(phba);
13765 	return workposted;
13766 
13767 out_no_mqe_complete:
13768 	spin_lock_irqsave(&phba->hbalock, iflags);
13769 	if (bf_get(lpfc_trailer_consumed, mcqe))
13770 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13771 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13772 	return false;
13773 }
13774 
13775 /**
13776  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
13777  * @phba: Pointer to HBA context object.
13778  * @cq: Pointer to associated CQ
13779  * @cqe: Pointer to mailbox completion queue entry.
13780  *
13781  * This routine process a mailbox completion queue entry, it invokes the
13782  * proper mailbox complete handling or asynchronous event handling routine
13783  * according to the MCQE's async bit.
13784  *
13785  * Return: true if work posted to worker thread, otherwise false.
13786  **/
13787 static bool
13788 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13789 			 struct lpfc_cqe *cqe)
13790 {
13791 	struct lpfc_mcqe mcqe;
13792 	bool workposted;
13793 
13794 	cq->CQ_mbox++;
13795 
13796 	/* Copy the mailbox MCQE and convert endian order as needed */
13797 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
13798 
13799 	/* Invoke the proper event handling routine */
13800 	if (!bf_get(lpfc_trailer_async, &mcqe))
13801 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
13802 	else
13803 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
13804 	return workposted;
13805 }
13806 
13807 /**
13808  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
13809  * @phba: Pointer to HBA context object.
13810  * @cq: Pointer to associated CQ
13811  * @wcqe: Pointer to work-queue completion queue entry.
13812  *
13813  * This routine handles an ELS work-queue completion event.
13814  *
13815  * Return: true if work posted to worker thread, otherwise false.
13816  **/
13817 static bool
13818 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13819 			     struct lpfc_wcqe_complete *wcqe)
13820 {
13821 	struct lpfc_iocbq *irspiocbq;
13822 	unsigned long iflags;
13823 	struct lpfc_sli_ring *pring = cq->pring;
13824 	int txq_cnt = 0;
13825 	int txcmplq_cnt = 0;
13826 
13827 	/* Check for response status */
13828 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
13829 		/* Log the error status */
13830 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13831 				"0357 ELS CQE error: status=x%x: "
13832 				"CQE: %08x %08x %08x %08x\n",
13833 				bf_get(lpfc_wcqe_c_status, wcqe),
13834 				wcqe->word0, wcqe->total_data_placed,
13835 				wcqe->parameter, wcqe->word3);
13836 	}
13837 
13838 	/* Get an irspiocbq for later ELS response processing use */
13839 	irspiocbq = lpfc_sli_get_iocbq(phba);
13840 	if (!irspiocbq) {
13841 		if (!list_empty(&pring->txq))
13842 			txq_cnt++;
13843 		if (!list_empty(&pring->txcmplq))
13844 			txcmplq_cnt++;
13845 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13846 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
13847 			"els_txcmplq_cnt=%d\n",
13848 			txq_cnt, phba->iocb_cnt,
13849 			txcmplq_cnt);
13850 		return false;
13851 	}
13852 
13853 	/* Save off the slow-path queue event for work thread to process */
13854 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
13855 	spin_lock_irqsave(&phba->hbalock, iflags);
13856 	list_add_tail(&irspiocbq->cq_event.list,
13857 		      &phba->sli4_hba.sp_queue_event);
13858 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
13859 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13860 
13861 	return true;
13862 }
13863 
13864 /**
13865  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
13866  * @phba: Pointer to HBA context object.
13867  * @wcqe: Pointer to work-queue completion queue entry.
13868  *
13869  * This routine handles slow-path WQ entry consumed event by invoking the
13870  * proper WQ release routine to the slow-path WQ.
13871  **/
13872 static void
13873 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
13874 			     struct lpfc_wcqe_release *wcqe)
13875 {
13876 	/* sanity check on queue memory */
13877 	if (unlikely(!phba->sli4_hba.els_wq))
13878 		return;
13879 	/* Check for the slow-path ELS work queue */
13880 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
13881 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
13882 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
13883 	else
13884 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13885 				"2579 Slow-path wqe consume event carries "
13886 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
13887 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
13888 				phba->sli4_hba.els_wq->queue_id);
13889 }
13890 
13891 /**
13892  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
13893  * @phba: Pointer to HBA context object.
13894  * @cq: Pointer to a WQ completion queue.
13895  * @wcqe: Pointer to work-queue completion queue entry.
13896  *
13897  * This routine handles an XRI abort event.
13898  *
13899  * Return: true if work posted to worker thread, otherwise false.
13900  **/
13901 static bool
13902 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
13903 				   struct lpfc_queue *cq,
13904 				   struct sli4_wcqe_xri_aborted *wcqe)
13905 {
13906 	bool workposted = false;
13907 	struct lpfc_cq_event *cq_event;
13908 	unsigned long iflags;
13909 
13910 	switch (cq->subtype) {
13911 	case LPFC_IO:
13912 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
13913 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13914 			/* Notify aborted XRI for NVME work queue */
13915 			if (phba->nvmet_support)
13916 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
13917 		}
13918 		workposted = false;
13919 		break;
13920 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
13921 	case LPFC_ELS:
13922 		cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
13923 		if (!cq_event) {
13924 			workposted = false;
13925 			break;
13926 		}
13927 		cq_event->hdwq = cq->hdwq;
13928 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
13929 				  iflags);
13930 		list_add_tail(&cq_event->list,
13931 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
13932 		/* Set the els xri abort event flag */
13933 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
13934 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
13935 				       iflags);
13936 		workposted = true;
13937 		break;
13938 	default:
13939 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13940 				"0603 Invalid CQ subtype %d: "
13941 				"%08x %08x %08x %08x\n",
13942 				cq->subtype, wcqe->word0, wcqe->parameter,
13943 				wcqe->word2, wcqe->word3);
13944 		workposted = false;
13945 		break;
13946 	}
13947 	return workposted;
13948 }
13949 
13950 #define FC_RCTL_MDS_DIAGS	0xF4
13951 
13952 /**
13953  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
13954  * @phba: Pointer to HBA context object.
13955  * @rcqe: Pointer to receive-queue completion queue entry.
13956  *
13957  * This routine process a receive-queue completion queue entry.
13958  *
13959  * Return: true if work posted to worker thread, otherwise false.
13960  **/
13961 static bool
13962 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
13963 {
13964 	bool workposted = false;
13965 	struct fc_frame_header *fc_hdr;
13966 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
13967 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
13968 	struct lpfc_nvmet_tgtport *tgtp;
13969 	struct hbq_dmabuf *dma_buf;
13970 	uint32_t status, rq_id;
13971 	unsigned long iflags;
13972 
13973 	/* sanity check on queue memory */
13974 	if (unlikely(!hrq) || unlikely(!drq))
13975 		return workposted;
13976 
13977 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
13978 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
13979 	else
13980 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
13981 	if (rq_id != hrq->queue_id)
13982 		goto out;
13983 
13984 	status = bf_get(lpfc_rcqe_status, rcqe);
13985 	switch (status) {
13986 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
13987 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13988 				"2537 Receive Frame Truncated!!\n");
13989 		fallthrough;
13990 	case FC_STATUS_RQ_SUCCESS:
13991 		spin_lock_irqsave(&phba->hbalock, iflags);
13992 		lpfc_sli4_rq_release(hrq, drq);
13993 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
13994 		if (!dma_buf) {
13995 			hrq->RQ_no_buf_found++;
13996 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13997 			goto out;
13998 		}
13999 		hrq->RQ_rcv_buf++;
14000 		hrq->RQ_buf_posted--;
14001 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
14002 
14003 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14004 
14005 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
14006 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
14007 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14008 			/* Handle MDS Loopback frames */
14009 			if  (!(phba->pport->load_flag & FC_UNLOADING))
14010 				lpfc_sli4_handle_mds_loopback(phba->pport,
14011 							      dma_buf);
14012 			else
14013 				lpfc_in_buf_free(phba, &dma_buf->dbuf);
14014 			break;
14015 		}
14016 
14017 		/* save off the frame for the work thread to process */
14018 		list_add_tail(&dma_buf->cq_event.list,
14019 			      &phba->sli4_hba.sp_queue_event);
14020 		/* Frame received */
14021 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
14022 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14023 		workposted = true;
14024 		break;
14025 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14026 		if (phba->nvmet_support) {
14027 			tgtp = phba->targetport->private;
14028 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14029 					"6402 RQE Error x%x, posted %d err_cnt "
14030 					"%d: %x %x %x\n",
14031 					status, hrq->RQ_buf_posted,
14032 					hrq->RQ_no_posted_buf,
14033 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14034 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14035 					atomic_read(&tgtp->xmt_fcp_release));
14036 		}
14037 		fallthrough;
14038 
14039 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14040 		hrq->RQ_no_posted_buf++;
14041 		/* Post more buffers if possible */
14042 		spin_lock_irqsave(&phba->hbalock, iflags);
14043 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
14044 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14045 		workposted = true;
14046 		break;
14047 	}
14048 out:
14049 	return workposted;
14050 }
14051 
14052 /**
14053  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
14054  * @phba: Pointer to HBA context object.
14055  * @cq: Pointer to the completion queue.
14056  * @cqe: Pointer to a completion queue entry.
14057  *
14058  * This routine process a slow-path work-queue or receive queue completion queue
14059  * entry.
14060  *
14061  * Return: true if work posted to worker thread, otherwise false.
14062  **/
14063 static bool
14064 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14065 			 struct lpfc_cqe *cqe)
14066 {
14067 	struct lpfc_cqe cqevt;
14068 	bool workposted = false;
14069 
14070 	/* Copy the work queue CQE and convert endian order if needed */
14071 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14072 
14073 	/* Check and process for different type of WCQE and dispatch */
14074 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
14075 	case CQE_CODE_COMPL_WQE:
14076 		/* Process the WQ/RQ complete event */
14077 		phba->last_completion_time = jiffies;
14078 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14079 				(struct lpfc_wcqe_complete *)&cqevt);
14080 		break;
14081 	case CQE_CODE_RELEASE_WQE:
14082 		/* Process the WQ release event */
14083 		lpfc_sli4_sp_handle_rel_wcqe(phba,
14084 				(struct lpfc_wcqe_release *)&cqevt);
14085 		break;
14086 	case CQE_CODE_XRI_ABORTED:
14087 		/* Process the WQ XRI abort event */
14088 		phba->last_completion_time = jiffies;
14089 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14090 				(struct sli4_wcqe_xri_aborted *)&cqevt);
14091 		break;
14092 	case CQE_CODE_RECEIVE:
14093 	case CQE_CODE_RECEIVE_V1:
14094 		/* Process the RQ event */
14095 		phba->last_completion_time = jiffies;
14096 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
14097 				(struct lpfc_rcqe *)&cqevt);
14098 		break;
14099 	default:
14100 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14101 				"0388 Not a valid WCQE code: x%x\n",
14102 				bf_get(lpfc_cqe_code, &cqevt));
14103 		break;
14104 	}
14105 	return workposted;
14106 }
14107 
14108 /**
14109  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14110  * @phba: Pointer to HBA context object.
14111  * @eqe: Pointer to fast-path event queue entry.
14112  * @speq: Pointer to slow-path event queue.
14113  *
14114  * This routine process a event queue entry from the slow-path event queue.
14115  * It will check the MajorCode and MinorCode to determine this is for a
14116  * completion event on a completion queue, if not, an error shall be logged
14117  * and just return. Otherwise, it will get to the corresponding completion
14118  * queue and process all the entries on that completion queue, rearm the
14119  * completion queue, and then return.
14120  *
14121  **/
14122 static void
14123 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14124 	struct lpfc_queue *speq)
14125 {
14126 	struct lpfc_queue *cq = NULL, *childq;
14127 	uint16_t cqid;
14128 	int ret = 0;
14129 
14130 	/* Get the reference to the corresponding CQ */
14131 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14132 
14133 	list_for_each_entry(childq, &speq->child_list, list) {
14134 		if (childq->queue_id == cqid) {
14135 			cq = childq;
14136 			break;
14137 		}
14138 	}
14139 	if (unlikely(!cq)) {
14140 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14141 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14142 					"0365 Slow-path CQ identifier "
14143 					"(%d) does not exist\n", cqid);
14144 		return;
14145 	}
14146 
14147 	/* Save EQ associated with this CQ */
14148 	cq->assoc_qp = speq;
14149 
14150 	if (is_kdump_kernel())
14151 		ret = queue_work(phba->wq, &cq->spwork);
14152 	else
14153 		ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14154 
14155 	if (!ret)
14156 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14157 				"0390 Cannot schedule queue work "
14158 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14159 				cqid, cq->queue_id, raw_smp_processor_id());
14160 }
14161 
14162 /**
14163  * __lpfc_sli4_process_cq - Process elements of a CQ
14164  * @phba: Pointer to HBA context object.
14165  * @cq: Pointer to CQ to be processed
14166  * @handler: Routine to process each cqe
14167  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14168  * @poll_mode: Polling mode we were called from
14169  *
14170  * This routine processes completion queue entries in a CQ. While a valid
14171  * queue element is found, the handler is called. During processing checks
14172  * are made for periodic doorbell writes to let the hardware know of
14173  * element consumption.
14174  *
14175  * If the max limit on cqes to process is hit, or there are no more valid
14176  * entries, the loop stops. If we processed a sufficient number of elements,
14177  * meaning there is sufficient load, rather than rearming and generating
14178  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14179  * indicates no rescheduling.
14180  *
14181  * Returns True if work scheduled, False otherwise.
14182  **/
14183 static bool
14184 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14185 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14186 			struct lpfc_cqe *), unsigned long *delay,
14187 			enum lpfc_poll_mode poll_mode)
14188 {
14189 	struct lpfc_cqe *cqe;
14190 	bool workposted = false;
14191 	int count = 0, consumed = 0;
14192 	bool arm = true;
14193 
14194 	/* default - no reschedule */
14195 	*delay = 0;
14196 
14197 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14198 		goto rearm_and_exit;
14199 
14200 	/* Process all the entries to the CQ */
14201 	cq->q_flag = 0;
14202 	cqe = lpfc_sli4_cq_get(cq);
14203 	while (cqe) {
14204 		workposted |= handler(phba, cq, cqe);
14205 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
14206 
14207 		consumed++;
14208 		if (!(++count % cq->max_proc_limit))
14209 			break;
14210 
14211 		if (!(count % cq->notify_interval)) {
14212 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14213 						LPFC_QUEUE_NOARM);
14214 			consumed = 0;
14215 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14216 		}
14217 
14218 		if (count == LPFC_NVMET_CQ_NOTIFY)
14219 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14220 
14221 		cqe = lpfc_sli4_cq_get(cq);
14222 	}
14223 	if (count >= phba->cfg_cq_poll_threshold) {
14224 		*delay = 1;
14225 		arm = false;
14226 	}
14227 
14228 	/* Note: complete the irq_poll softirq before rearming CQ */
14229 	if (poll_mode == LPFC_IRQ_POLL)
14230 		irq_poll_complete(&cq->iop);
14231 
14232 	/* Track the max number of CQEs processed in 1 EQ */
14233 	if (count > cq->CQ_max_cqe)
14234 		cq->CQ_max_cqe = count;
14235 
14236 	cq->assoc_qp->EQ_cqe_cnt += count;
14237 
14238 	/* Catch the no cq entry condition */
14239 	if (unlikely(count == 0))
14240 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14241 				"0369 No entry from completion queue "
14242 				"qid=%d\n", cq->queue_id);
14243 
14244 	xchg(&cq->queue_claimed, 0);
14245 
14246 rearm_and_exit:
14247 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14248 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14249 
14250 	return workposted;
14251 }
14252 
14253 /**
14254  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14255  * @cq: pointer to CQ to process
14256  *
14257  * This routine calls the cq processing routine with a handler specific
14258  * to the type of queue bound to it.
14259  *
14260  * The CQ routine returns two values: the first is the calling status,
14261  * which indicates whether work was queued to the  background discovery
14262  * thread. If true, the routine should wakeup the discovery thread;
14263  * the second is the delay parameter. If non-zero, rather than rearming
14264  * the CQ and yet another interrupt, the CQ handler should be queued so
14265  * that it is processed in a subsequent polling action. The value of
14266  * the delay indicates when to reschedule it.
14267  **/
14268 static void
14269 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14270 {
14271 	struct lpfc_hba *phba = cq->phba;
14272 	unsigned long delay;
14273 	bool workposted = false;
14274 	int ret = 0;
14275 
14276 	/* Process and rearm the CQ */
14277 	switch (cq->type) {
14278 	case LPFC_MCQ:
14279 		workposted |= __lpfc_sli4_process_cq(phba, cq,
14280 						lpfc_sli4_sp_handle_mcqe,
14281 						&delay, LPFC_QUEUE_WORK);
14282 		break;
14283 	case LPFC_WCQ:
14284 		if (cq->subtype == LPFC_IO)
14285 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14286 						lpfc_sli4_fp_handle_cqe,
14287 						&delay, LPFC_QUEUE_WORK);
14288 		else
14289 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14290 						lpfc_sli4_sp_handle_cqe,
14291 						&delay, LPFC_QUEUE_WORK);
14292 		break;
14293 	default:
14294 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14295 				"0370 Invalid completion queue type (%d)\n",
14296 				cq->type);
14297 		return;
14298 	}
14299 
14300 	if (delay) {
14301 		if (is_kdump_kernel())
14302 			ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
14303 						delay);
14304 		else
14305 			ret = queue_delayed_work_on(cq->chann, phba->wq,
14306 						&cq->sched_spwork, delay);
14307 		if (!ret)
14308 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14309 				"0394 Cannot schedule queue work "
14310 				"for cqid=%d on CPU %d\n",
14311 				cq->queue_id, cq->chann);
14312 	}
14313 
14314 	/* wake up worker thread if there are works to be done */
14315 	if (workposted)
14316 		lpfc_worker_wake_up(phba);
14317 }
14318 
14319 /**
14320  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
14321  *   interrupt
14322  * @work: pointer to work element
14323  *
14324  * translates from the work handler and calls the slow-path handler.
14325  **/
14326 static void
14327 lpfc_sli4_sp_process_cq(struct work_struct *work)
14328 {
14329 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
14330 
14331 	__lpfc_sli4_sp_process_cq(cq);
14332 }
14333 
14334 /**
14335  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
14336  * @work: pointer to work element
14337  *
14338  * translates from the work handler and calls the slow-path handler.
14339  **/
14340 static void
14341 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
14342 {
14343 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
14344 					struct lpfc_queue, sched_spwork);
14345 
14346 	__lpfc_sli4_sp_process_cq(cq);
14347 }
14348 
14349 /**
14350  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
14351  * @phba: Pointer to HBA context object.
14352  * @cq: Pointer to associated CQ
14353  * @wcqe: Pointer to work-queue completion queue entry.
14354  *
14355  * This routine process a fast-path work queue completion entry from fast-path
14356  * event queue for FCP command response completion.
14357  **/
14358 static void
14359 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14360 			     struct lpfc_wcqe_complete *wcqe)
14361 {
14362 	struct lpfc_sli_ring *pring = cq->pring;
14363 	struct lpfc_iocbq *cmdiocbq;
14364 	struct lpfc_iocbq irspiocbq;
14365 	unsigned long iflags;
14366 
14367 	/* Check for response status */
14368 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14369 		/* If resource errors reported from HBA, reduce queue
14370 		 * depth of the SCSI device.
14371 		 */
14372 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
14373 		     IOSTAT_LOCAL_REJECT)) &&
14374 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
14375 		     IOERR_NO_RESOURCES))
14376 			phba->lpfc_rampdown_queue_depth(phba);
14377 
14378 		/* Log the cmpl status */
14379 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14380 				"0373 FCP CQE cmpl: status=x%x: "
14381 				"CQE: %08x %08x %08x %08x\n",
14382 				bf_get(lpfc_wcqe_c_status, wcqe),
14383 				wcqe->word0, wcqe->total_data_placed,
14384 				wcqe->parameter, wcqe->word3);
14385 	}
14386 
14387 	/* Look up the FCP command IOCB and create pseudo response IOCB */
14388 	spin_lock_irqsave(&pring->ring_lock, iflags);
14389 	pring->stats.iocb_event++;
14390 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
14391 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14392 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14393 	if (unlikely(!cmdiocbq)) {
14394 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14395 				"0374 FCP complete with no corresponding "
14396 				"cmdiocb: iotag (%d)\n",
14397 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14398 		return;
14399 	}
14400 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
14401 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
14402 #endif
14403 	if (cmdiocbq->iocb_cmpl == NULL) {
14404 		if (cmdiocbq->wqe_cmpl) {
14405 			/* For FCP the flag is cleared in wqe_cmpl */
14406 			if (!(cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
14407 			    cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
14408 				spin_lock_irqsave(&phba->hbalock, iflags);
14409 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
14410 				spin_unlock_irqrestore(&phba->hbalock, iflags);
14411 			}
14412 
14413 			/* Pass the cmd_iocb and the wcqe to the upper layer */
14414 			(cmdiocbq->wqe_cmpl)(phba, cmdiocbq, wcqe);
14415 			return;
14416 		}
14417 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14418 				"0375 FCP cmdiocb not callback function "
14419 				"iotag: (%d)\n",
14420 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14421 		return;
14422 	}
14423 
14424 	/* Only SLI4 non-IO commands stil use IOCB */
14425 	/* Fake the irspiocb and copy necessary response information */
14426 	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
14427 
14428 	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
14429 		spin_lock_irqsave(&phba->hbalock, iflags);
14430 		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
14431 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14432 	}
14433 
14434 	/* Pass the cmd_iocb and the rsp state to the upper layer */
14435 	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
14436 }
14437 
14438 /**
14439  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
14440  * @phba: Pointer to HBA context object.
14441  * @cq: Pointer to completion queue.
14442  * @wcqe: Pointer to work-queue completion queue entry.
14443  *
14444  * This routine handles an fast-path WQ entry consumed event by invoking the
14445  * proper WQ release routine to the slow-path WQ.
14446  **/
14447 static void
14448 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14449 			     struct lpfc_wcqe_release *wcqe)
14450 {
14451 	struct lpfc_queue *childwq;
14452 	bool wqid_matched = false;
14453 	uint16_t hba_wqid;
14454 
14455 	/* Check for fast-path FCP work queue release */
14456 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
14457 	list_for_each_entry(childwq, &cq->child_list, list) {
14458 		if (childwq->queue_id == hba_wqid) {
14459 			lpfc_sli4_wq_release(childwq,
14460 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14461 			if (childwq->q_flag & HBA_NVMET_WQFULL)
14462 				lpfc_nvmet_wqfull_process(phba, childwq);
14463 			wqid_matched = true;
14464 			break;
14465 		}
14466 	}
14467 	/* Report warning log message if no match found */
14468 	if (wqid_matched != true)
14469 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14470 				"2580 Fast-path wqe consume event carries "
14471 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
14472 }
14473 
14474 /**
14475  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
14476  * @phba: Pointer to HBA context object.
14477  * @cq: Pointer to completion queue.
14478  * @rcqe: Pointer to receive-queue completion queue entry.
14479  *
14480  * This routine process a receive-queue completion queue entry.
14481  *
14482  * Return: true if work posted to worker thread, otherwise false.
14483  **/
14484 static bool
14485 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14486 			    struct lpfc_rcqe *rcqe)
14487 {
14488 	bool workposted = false;
14489 	struct lpfc_queue *hrq;
14490 	struct lpfc_queue *drq;
14491 	struct rqb_dmabuf *dma_buf;
14492 	struct fc_frame_header *fc_hdr;
14493 	struct lpfc_nvmet_tgtport *tgtp;
14494 	uint32_t status, rq_id;
14495 	unsigned long iflags;
14496 	uint32_t fctl, idx;
14497 
14498 	if ((phba->nvmet_support == 0) ||
14499 	    (phba->sli4_hba.nvmet_cqset == NULL))
14500 		return workposted;
14501 
14502 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
14503 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
14504 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
14505 
14506 	/* sanity check on queue memory */
14507 	if (unlikely(!hrq) || unlikely(!drq))
14508 		return workposted;
14509 
14510 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14511 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14512 	else
14513 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14514 
14515 	if ((phba->nvmet_support == 0) ||
14516 	    (rq_id != hrq->queue_id))
14517 		return workposted;
14518 
14519 	status = bf_get(lpfc_rcqe_status, rcqe);
14520 	switch (status) {
14521 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14522 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14523 				"6126 Receive Frame Truncated!!\n");
14524 		fallthrough;
14525 	case FC_STATUS_RQ_SUCCESS:
14526 		spin_lock_irqsave(&phba->hbalock, iflags);
14527 		lpfc_sli4_rq_release(hrq, drq);
14528 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
14529 		if (!dma_buf) {
14530 			hrq->RQ_no_buf_found++;
14531 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14532 			goto out;
14533 		}
14534 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14535 		hrq->RQ_rcv_buf++;
14536 		hrq->RQ_buf_posted--;
14537 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14538 
14539 		/* Just some basic sanity checks on FCP Command frame */
14540 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
14541 			fc_hdr->fh_f_ctl[1] << 8 |
14542 			fc_hdr->fh_f_ctl[2]);
14543 		if (((fctl &
14544 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
14545 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
14546 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
14547 			goto drop;
14548 
14549 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
14550 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
14551 			lpfc_nvmet_unsol_fcp_event(
14552 				phba, idx, dma_buf, cq->isr_timestamp,
14553 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
14554 			return false;
14555 		}
14556 drop:
14557 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
14558 		break;
14559 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14560 		if (phba->nvmet_support) {
14561 			tgtp = phba->targetport->private;
14562 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14563 					"6401 RQE Error x%x, posted %d err_cnt "
14564 					"%d: %x %x %x\n",
14565 					status, hrq->RQ_buf_posted,
14566 					hrq->RQ_no_posted_buf,
14567 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14568 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14569 					atomic_read(&tgtp->xmt_fcp_release));
14570 		}
14571 		fallthrough;
14572 
14573 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14574 		hrq->RQ_no_posted_buf++;
14575 		/* Post more buffers if possible */
14576 		break;
14577 	}
14578 out:
14579 	return workposted;
14580 }
14581 
14582 /**
14583  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
14584  * @phba: adapter with cq
14585  * @cq: Pointer to the completion queue.
14586  * @cqe: Pointer to fast-path completion queue entry.
14587  *
14588  * This routine process a fast-path work queue completion entry from fast-path
14589  * event queue for FCP command response completion.
14590  *
14591  * Return: true if work posted to worker thread, otherwise false.
14592  **/
14593 static bool
14594 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14595 			 struct lpfc_cqe *cqe)
14596 {
14597 	struct lpfc_wcqe_release wcqe;
14598 	bool workposted = false;
14599 
14600 	/* Copy the work queue CQE and convert endian order if needed */
14601 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
14602 
14603 	/* Check and process for different type of WCQE and dispatch */
14604 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
14605 	case CQE_CODE_COMPL_WQE:
14606 	case CQE_CODE_NVME_ERSP:
14607 		cq->CQ_wq++;
14608 		/* Process the WQ complete event */
14609 		phba->last_completion_time = jiffies;
14610 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
14611 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
14612 				(struct lpfc_wcqe_complete *)&wcqe);
14613 		break;
14614 	case CQE_CODE_RELEASE_WQE:
14615 		cq->CQ_release_wqe++;
14616 		/* Process the WQ release event */
14617 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
14618 				(struct lpfc_wcqe_release *)&wcqe);
14619 		break;
14620 	case CQE_CODE_XRI_ABORTED:
14621 		cq->CQ_xri_aborted++;
14622 		/* Process the WQ XRI abort event */
14623 		phba->last_completion_time = jiffies;
14624 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14625 				(struct sli4_wcqe_xri_aborted *)&wcqe);
14626 		break;
14627 	case CQE_CODE_RECEIVE_V1:
14628 	case CQE_CODE_RECEIVE:
14629 		phba->last_completion_time = jiffies;
14630 		if (cq->subtype == LPFC_NVMET) {
14631 			workposted = lpfc_sli4_nvmet_handle_rcqe(
14632 				phba, cq, (struct lpfc_rcqe *)&wcqe);
14633 		}
14634 		break;
14635 	default:
14636 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14637 				"0144 Not a valid CQE code: x%x\n",
14638 				bf_get(lpfc_wcqe_c_code, &wcqe));
14639 		break;
14640 	}
14641 	return workposted;
14642 }
14643 
14644 /**
14645  * lpfc_sli4_sched_cq_work - Schedules cq work
14646  * @phba: Pointer to HBA context object.
14647  * @cq: Pointer to CQ
14648  * @cqid: CQ ID
14649  *
14650  * This routine checks the poll mode of the CQ corresponding to
14651  * cq->chann, then either schedules a softirq or queue_work to complete
14652  * cq work.
14653  *
14654  * queue_work path is taken if in NVMET mode, or if poll_mode is in
14655  * LPFC_QUEUE_WORK mode.  Otherwise, softirq path is taken.
14656  *
14657  **/
14658 static void lpfc_sli4_sched_cq_work(struct lpfc_hba *phba,
14659 				    struct lpfc_queue *cq, uint16_t cqid)
14660 {
14661 	int ret = 0;
14662 
14663 	switch (cq->poll_mode) {
14664 	case LPFC_IRQ_POLL:
14665 		irq_poll_sched(&cq->iop);
14666 		break;
14667 	case LPFC_QUEUE_WORK:
14668 	default:
14669 		if (is_kdump_kernel())
14670 			ret = queue_work(phba->wq, &cq->irqwork);
14671 		else
14672 			ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
14673 		if (!ret)
14674 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14675 					"0383 Cannot schedule queue work "
14676 					"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14677 					cqid, cq->queue_id,
14678 					raw_smp_processor_id());
14679 	}
14680 }
14681 
14682 /**
14683  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
14684  * @phba: Pointer to HBA context object.
14685  * @eq: Pointer to the queue structure.
14686  * @eqe: Pointer to fast-path event queue entry.
14687  *
14688  * This routine process a event queue entry from the fast-path event queue.
14689  * It will check the MajorCode and MinorCode to determine this is for a
14690  * completion event on a completion queue, if not, an error shall be logged
14691  * and just return. Otherwise, it will get to the corresponding completion
14692  * queue and process all the entries on the completion queue, rearm the
14693  * completion queue, and then return.
14694  **/
14695 static void
14696 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
14697 			 struct lpfc_eqe *eqe)
14698 {
14699 	struct lpfc_queue *cq = NULL;
14700 	uint32_t qidx = eq->hdwq;
14701 	uint16_t cqid, id;
14702 
14703 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
14704 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14705 				"0366 Not a valid completion "
14706 				"event: majorcode=x%x, minorcode=x%x\n",
14707 				bf_get_le32(lpfc_eqe_major_code, eqe),
14708 				bf_get_le32(lpfc_eqe_minor_code, eqe));
14709 		return;
14710 	}
14711 
14712 	/* Get the reference to the corresponding CQ */
14713 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14714 
14715 	/* Use the fast lookup method first */
14716 	if (cqid <= phba->sli4_hba.cq_max) {
14717 		cq = phba->sli4_hba.cq_lookup[cqid];
14718 		if (cq)
14719 			goto  work_cq;
14720 	}
14721 
14722 	/* Next check for NVMET completion */
14723 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
14724 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
14725 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
14726 			/* Process NVMET unsol rcv */
14727 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
14728 			goto  process_cq;
14729 		}
14730 	}
14731 
14732 	if (phba->sli4_hba.nvmels_cq &&
14733 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
14734 		/* Process NVME unsol rcv */
14735 		cq = phba->sli4_hba.nvmels_cq;
14736 	}
14737 
14738 	/* Otherwise this is a Slow path event */
14739 	if (cq == NULL) {
14740 		lpfc_sli4_sp_handle_eqe(phba, eqe,
14741 					phba->sli4_hba.hdwq[qidx].hba_eq);
14742 		return;
14743 	}
14744 
14745 process_cq:
14746 	if (unlikely(cqid != cq->queue_id)) {
14747 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14748 				"0368 Miss-matched fast-path completion "
14749 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
14750 				cqid, cq->queue_id);
14751 		return;
14752 	}
14753 
14754 work_cq:
14755 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
14756 	if (phba->ktime_on)
14757 		cq->isr_timestamp = ktime_get_ns();
14758 	else
14759 		cq->isr_timestamp = 0;
14760 #endif
14761 	lpfc_sli4_sched_cq_work(phba, cq, cqid);
14762 }
14763 
14764 /**
14765  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
14766  * @cq: Pointer to CQ to be processed
14767  * @poll_mode: Enum lpfc_poll_state to determine poll mode
14768  *
14769  * This routine calls the cq processing routine with the handler for
14770  * fast path CQEs.
14771  *
14772  * The CQ routine returns two values: the first is the calling status,
14773  * which indicates whether work was queued to the  background discovery
14774  * thread. If true, the routine should wakeup the discovery thread;
14775  * the second is the delay parameter. If non-zero, rather than rearming
14776  * the CQ and yet another interrupt, the CQ handler should be queued so
14777  * that it is processed in a subsequent polling action. The value of
14778  * the delay indicates when to reschedule it.
14779  **/
14780 static void
14781 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq,
14782 			   enum lpfc_poll_mode poll_mode)
14783 {
14784 	struct lpfc_hba *phba = cq->phba;
14785 	unsigned long delay;
14786 	bool workposted = false;
14787 	int ret = 0;
14788 
14789 	/* process and rearm the CQ */
14790 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
14791 					     &delay, poll_mode);
14792 
14793 	if (delay) {
14794 		if (is_kdump_kernel())
14795 			ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
14796 						delay);
14797 		else
14798 			ret = queue_delayed_work_on(cq->chann, phba->wq,
14799 						&cq->sched_irqwork, delay);
14800 		if (!ret)
14801 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14802 					"0367 Cannot schedule queue work "
14803 					"for cqid=%d on CPU %d\n",
14804 					cq->queue_id, cq->chann);
14805 	}
14806 
14807 	/* wake up worker thread if there are works to be done */
14808 	if (workposted)
14809 		lpfc_worker_wake_up(phba);
14810 }
14811 
14812 /**
14813  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
14814  *   interrupt
14815  * @work: pointer to work element
14816  *
14817  * translates from the work handler and calls the fast-path handler.
14818  **/
14819 static void
14820 lpfc_sli4_hba_process_cq(struct work_struct *work)
14821 {
14822 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
14823 
14824 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
14825 }
14826 
14827 /**
14828  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
14829  * @work: pointer to work element
14830  *
14831  * translates from the work handler and calls the fast-path handler.
14832  **/
14833 static void
14834 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
14835 {
14836 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
14837 					struct lpfc_queue, sched_irqwork);
14838 
14839 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
14840 }
14841 
14842 /**
14843  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
14844  * @irq: Interrupt number.
14845  * @dev_id: The device context pointer.
14846  *
14847  * This function is directly called from the PCI layer as an interrupt
14848  * service routine when device with SLI-4 interface spec is enabled with
14849  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
14850  * ring event in the HBA. However, when the device is enabled with either
14851  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
14852  * device-level interrupt handler. When the PCI slot is in error recovery
14853  * or the HBA is undergoing initialization, the interrupt handler will not
14854  * process the interrupt. The SCSI FCP fast-path ring event are handled in
14855  * the intrrupt context. This function is called without any lock held.
14856  * It gets the hbalock to access and update SLI data structures. Note that,
14857  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
14858  * equal to that of FCP CQ index.
14859  *
14860  * The link attention and ELS ring attention events are handled
14861  * by the worker thread. The interrupt handler signals the worker thread
14862  * and returns for these events. This function is called without any lock
14863  * held. It gets the hbalock to access and update SLI data structures.
14864  *
14865  * This function returns IRQ_HANDLED when interrupt is handled else it
14866  * returns IRQ_NONE.
14867  **/
14868 irqreturn_t
14869 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
14870 {
14871 	struct lpfc_hba *phba;
14872 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
14873 	struct lpfc_queue *fpeq;
14874 	unsigned long iflag;
14875 	int ecount = 0;
14876 	int hba_eqidx;
14877 	struct lpfc_eq_intr_info *eqi;
14878 
14879 	/* Get the driver's phba structure from the dev_id */
14880 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
14881 	phba = hba_eq_hdl->phba;
14882 	hba_eqidx = hba_eq_hdl->idx;
14883 
14884 	if (unlikely(!phba))
14885 		return IRQ_NONE;
14886 	if (unlikely(!phba->sli4_hba.hdwq))
14887 		return IRQ_NONE;
14888 
14889 	/* Get to the EQ struct associated with this vector */
14890 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
14891 	if (unlikely(!fpeq))
14892 		return IRQ_NONE;
14893 
14894 	/* Check device state for handling interrupt */
14895 	if (unlikely(lpfc_intr_state_check(phba))) {
14896 		/* Check again for link_state with lock held */
14897 		spin_lock_irqsave(&phba->hbalock, iflag);
14898 		if (phba->link_state < LPFC_LINK_DOWN)
14899 			/* Flush, clear interrupt, and rearm the EQ */
14900 			lpfc_sli4_eqcq_flush(phba, fpeq);
14901 		spin_unlock_irqrestore(&phba->hbalock, iflag);
14902 		return IRQ_NONE;
14903 	}
14904 
14905 	eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
14906 	eqi->icnt++;
14907 
14908 	fpeq->last_cpu = raw_smp_processor_id();
14909 
14910 	if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
14911 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
14912 	    phba->cfg_auto_imax &&
14913 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
14914 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
14915 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
14916 
14917 	/* process and rearm the EQ */
14918 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
14919 
14920 	if (unlikely(ecount == 0)) {
14921 		fpeq->EQ_no_entry++;
14922 		if (phba->intr_type == MSIX)
14923 			/* MSI-X treated interrupt served as no EQ share INT */
14924 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14925 					"0358 MSI-X interrupt with no EQE\n");
14926 		else
14927 			/* Non MSI-X treated on interrupt as EQ share INT */
14928 			return IRQ_NONE;
14929 	}
14930 
14931 	return IRQ_HANDLED;
14932 } /* lpfc_sli4_hba_intr_handler */
14933 
14934 /**
14935  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
14936  * @irq: Interrupt number.
14937  * @dev_id: The device context pointer.
14938  *
14939  * This function is the device-level interrupt handler to device with SLI-4
14940  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
14941  * interrupt mode is enabled and there is an event in the HBA which requires
14942  * driver attention. This function invokes the slow-path interrupt attention
14943  * handling function and fast-path interrupt attention handling function in
14944  * turn to process the relevant HBA attention events. This function is called
14945  * without any lock held. It gets the hbalock to access and update SLI data
14946  * structures.
14947  *
14948  * This function returns IRQ_HANDLED when interrupt is handled, else it
14949  * returns IRQ_NONE.
14950  **/
14951 irqreturn_t
14952 lpfc_sli4_intr_handler(int irq, void *dev_id)
14953 {
14954 	struct lpfc_hba  *phba;
14955 	irqreturn_t hba_irq_rc;
14956 	bool hba_handled = false;
14957 	int qidx;
14958 
14959 	/* Get the driver's phba structure from the dev_id */
14960 	phba = (struct lpfc_hba *)dev_id;
14961 
14962 	if (unlikely(!phba))
14963 		return IRQ_NONE;
14964 
14965 	/*
14966 	 * Invoke fast-path host attention interrupt handling as appropriate.
14967 	 */
14968 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
14969 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
14970 					&phba->sli4_hba.hba_eq_hdl[qidx]);
14971 		if (hba_irq_rc == IRQ_HANDLED)
14972 			hba_handled |= true;
14973 	}
14974 
14975 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
14976 } /* lpfc_sli4_intr_handler */
14977 
14978 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
14979 {
14980 	struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
14981 	struct lpfc_queue *eq;
14982 	int i = 0;
14983 
14984 	rcu_read_lock();
14985 
14986 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
14987 		i += lpfc_sli4_poll_eq(eq, LPFC_POLL_SLOWPATH);
14988 	if (!list_empty(&phba->poll_list))
14989 		mod_timer(&phba->cpuhp_poll_timer,
14990 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
14991 
14992 	rcu_read_unlock();
14993 }
14994 
14995 inline int lpfc_sli4_poll_eq(struct lpfc_queue *eq, uint8_t path)
14996 {
14997 	struct lpfc_hba *phba = eq->phba;
14998 	int i = 0;
14999 
15000 	/*
15001 	 * Unlocking an irq is one of the entry point to check
15002 	 * for re-schedule, but we are good for io submission
15003 	 * path as midlayer does a get_cpu to glue us in. Flush
15004 	 * out the invalidate queue so we can see the updated
15005 	 * value for flag.
15006 	 */
15007 	smp_rmb();
15008 
15009 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
15010 		/* We will not likely get the completion for the caller
15011 		 * during this iteration but i guess that's fine.
15012 		 * Future io's coming on this eq should be able to
15013 		 * pick it up.  As for the case of single io's, they
15014 		 * will be handled through a sched from polling timer
15015 		 * function which is currently triggered every 1msec.
15016 		 */
15017 		i = lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM);
15018 
15019 	return i;
15020 }
15021 
15022 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
15023 {
15024 	struct lpfc_hba *phba = eq->phba;
15025 
15026 	/* kickstart slowpath processing if needed */
15027 	if (list_empty(&phba->poll_list))
15028 		mod_timer(&phba->cpuhp_poll_timer,
15029 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15030 
15031 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
15032 	synchronize_rcu();
15033 }
15034 
15035 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
15036 {
15037 	struct lpfc_hba *phba = eq->phba;
15038 
15039 	/* Disable slowpath processing for this eq.  Kick start the eq
15040 	 * by RE-ARMING the eq's ASAP
15041 	 */
15042 	list_del_rcu(&eq->_poll_list);
15043 	synchronize_rcu();
15044 
15045 	if (list_empty(&phba->poll_list))
15046 		del_timer_sync(&phba->cpuhp_poll_timer);
15047 }
15048 
15049 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
15050 {
15051 	struct lpfc_queue *eq, *next;
15052 
15053 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
15054 		list_del(&eq->_poll_list);
15055 
15056 	INIT_LIST_HEAD(&phba->poll_list);
15057 	synchronize_rcu();
15058 }
15059 
15060 static inline void
15061 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
15062 {
15063 	if (mode == eq->mode)
15064 		return;
15065 	/*
15066 	 * currently this function is only called during a hotplug
15067 	 * event and the cpu on which this function is executing
15068 	 * is going offline.  By now the hotplug has instructed
15069 	 * the scheduler to remove this cpu from cpu active mask.
15070 	 * So we don't need to work about being put aside by the
15071 	 * scheduler for a high priority process.  Yes, the inte-
15072 	 * rrupts could come but they are known to retire ASAP.
15073 	 */
15074 
15075 	/* Disable polling in the fastpath */
15076 	WRITE_ONCE(eq->mode, mode);
15077 	/* flush out the store buffer */
15078 	smp_wmb();
15079 
15080 	/*
15081 	 * Add this eq to the polling list and start polling. For
15082 	 * a grace period both interrupt handler and poller will
15083 	 * try to process the eq _but_ that's fine.  We have a
15084 	 * synchronization mechanism in place (queue_claimed) to
15085 	 * deal with it.  This is just a draining phase for int-
15086 	 * errupt handler (not eq's) as we have guranteed through
15087 	 * barrier that all the CPUs have seen the new CQ_POLLED
15088 	 * state. which will effectively disable the REARMING of
15089 	 * the EQ.  The whole idea is eq's die off eventually as
15090 	 * we are not rearming EQ's anymore.
15091 	 */
15092 	mode ? lpfc_sli4_add_to_poll_list(eq) :
15093 	       lpfc_sli4_remove_from_poll_list(eq);
15094 }
15095 
15096 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15097 {
15098 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15099 }
15100 
15101 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15102 {
15103 	struct lpfc_hba *phba = eq->phba;
15104 
15105 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15106 
15107 	/* Kick start for the pending io's in h/w.
15108 	 * Once we switch back to interrupt processing on a eq
15109 	 * the io path completion will only arm eq's when it
15110 	 * receives a completion.  But since eq's are in disa-
15111 	 * rmed state it doesn't receive a completion.  This
15112 	 * creates a deadlock scenaro.
15113 	 */
15114 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15115 }
15116 
15117 /**
15118  * lpfc_sli4_queue_free - free a queue structure and associated memory
15119  * @queue: The queue structure to free.
15120  *
15121  * This function frees a queue structure and the DMAable memory used for
15122  * the host resident queue. This function must be called after destroying the
15123  * queue on the HBA.
15124  **/
15125 void
15126 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15127 {
15128 	struct lpfc_dmabuf *dmabuf;
15129 
15130 	if (!queue)
15131 		return;
15132 
15133 	if (!list_empty(&queue->wq_list))
15134 		list_del(&queue->wq_list);
15135 
15136 	while (!list_empty(&queue->page_list)) {
15137 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15138 				 list);
15139 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15140 				  dmabuf->virt, dmabuf->phys);
15141 		kfree(dmabuf);
15142 	}
15143 	if (queue->rqbp) {
15144 		lpfc_free_rq_buffer(queue->phba, queue);
15145 		kfree(queue->rqbp);
15146 	}
15147 
15148 	if (!list_empty(&queue->cpu_list))
15149 		list_del(&queue->cpu_list);
15150 
15151 	kfree(queue);
15152 	return;
15153 }
15154 
15155 /**
15156  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15157  * @phba: The HBA that this queue is being created on.
15158  * @page_size: The size of a queue page
15159  * @entry_size: The size of each queue entry for this queue.
15160  * @entry_count: The number of entries that this queue will handle.
15161  * @cpu: The cpu that will primarily utilize this queue.
15162  *
15163  * This function allocates a queue structure and the DMAable memory used for
15164  * the host resident queue. This function must be called before creating the
15165  * queue on the HBA.
15166  **/
15167 struct lpfc_queue *
15168 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15169 		      uint32_t entry_size, uint32_t entry_count, int cpu)
15170 {
15171 	struct lpfc_queue *queue;
15172 	struct lpfc_dmabuf *dmabuf;
15173 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15174 	uint16_t x, pgcnt;
15175 
15176 	if (!phba->sli4_hba.pc_sli4_params.supported)
15177 		hw_page_size = page_size;
15178 
15179 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15180 
15181 	/* If needed, Adjust page count to match the max the adapter supports */
15182 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15183 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15184 
15185 	queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
15186 			     GFP_KERNEL, cpu_to_node(cpu));
15187 	if (!queue)
15188 		return NULL;
15189 
15190 	INIT_LIST_HEAD(&queue->list);
15191 	INIT_LIST_HEAD(&queue->_poll_list);
15192 	INIT_LIST_HEAD(&queue->wq_list);
15193 	INIT_LIST_HEAD(&queue->wqfull_list);
15194 	INIT_LIST_HEAD(&queue->page_list);
15195 	INIT_LIST_HEAD(&queue->child_list);
15196 	INIT_LIST_HEAD(&queue->cpu_list);
15197 
15198 	/* Set queue parameters now.  If the system cannot provide memory
15199 	 * resources, the free routine needs to know what was allocated.
15200 	 */
15201 	queue->page_count = pgcnt;
15202 	queue->q_pgs = (void **)&queue[1];
15203 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
15204 	queue->entry_size = entry_size;
15205 	queue->entry_count = entry_count;
15206 	queue->page_size = hw_page_size;
15207 	queue->phba = phba;
15208 
15209 	for (x = 0; x < queue->page_count; x++) {
15210 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15211 				      dev_to_node(&phba->pcidev->dev));
15212 		if (!dmabuf)
15213 			goto out_fail;
15214 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15215 						  hw_page_size, &dmabuf->phys,
15216 						  GFP_KERNEL);
15217 		if (!dmabuf->virt) {
15218 			kfree(dmabuf);
15219 			goto out_fail;
15220 		}
15221 		dmabuf->buffer_tag = x;
15222 		list_add_tail(&dmabuf->list, &queue->page_list);
15223 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
15224 		queue->q_pgs[x] = dmabuf->virt;
15225 	}
15226 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15227 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15228 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15229 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15230 
15231 	/* notify_interval will be set during q creation */
15232 
15233 	return queue;
15234 out_fail:
15235 	lpfc_sli4_queue_free(queue);
15236 	return NULL;
15237 }
15238 
15239 /**
15240  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15241  * @phba: HBA structure that indicates port to create a queue on.
15242  * @pci_barset: PCI BAR set flag.
15243  *
15244  * This function shall perform iomap of the specified PCI BAR address to host
15245  * memory address if not already done so and return it. The returned host
15246  * memory address can be NULL.
15247  */
15248 static void __iomem *
15249 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15250 {
15251 	if (!phba->pcidev)
15252 		return NULL;
15253 
15254 	switch (pci_barset) {
15255 	case WQ_PCI_BAR_0_AND_1:
15256 		return phba->pci_bar0_memmap_p;
15257 	case WQ_PCI_BAR_2_AND_3:
15258 		return phba->pci_bar2_memmap_p;
15259 	case WQ_PCI_BAR_4_AND_5:
15260 		return phba->pci_bar4_memmap_p;
15261 	default:
15262 		break;
15263 	}
15264 	return NULL;
15265 }
15266 
15267 /**
15268  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
15269  * @phba: HBA structure that EQs are on.
15270  * @startq: The starting EQ index to modify
15271  * @numq: The number of EQs (consecutive indexes) to modify
15272  * @usdelay: amount of delay
15273  *
15274  * This function revises the EQ delay on 1 or more EQs. The EQ delay
15275  * is set either by writing to a register (if supported by the SLI Port)
15276  * or by mailbox command. The mailbox command allows several EQs to be
15277  * updated at once.
15278  *
15279  * The @phba struct is used to send a mailbox command to HBA. The @startq
15280  * is used to get the starting EQ index to change. The @numq value is
15281  * used to specify how many consecutive EQ indexes, starting at EQ index,
15282  * are to be changed. This function is asynchronous and will wait for any
15283  * mailbox commands to finish before returning.
15284  *
15285  * On success this function will return a zero. If unable to allocate
15286  * enough memory this function will return -ENOMEM. If a mailbox command
15287  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
15288  * have had their delay multipler changed.
15289  **/
15290 void
15291 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
15292 			 uint32_t numq, uint32_t usdelay)
15293 {
15294 	struct lpfc_mbx_modify_eq_delay *eq_delay;
15295 	LPFC_MBOXQ_t *mbox;
15296 	struct lpfc_queue *eq;
15297 	int cnt = 0, rc, length;
15298 	uint32_t shdr_status, shdr_add_status;
15299 	uint32_t dmult;
15300 	int qidx;
15301 	union lpfc_sli4_cfg_shdr *shdr;
15302 
15303 	if (startq >= phba->cfg_irq_chann)
15304 		return;
15305 
15306 	if (usdelay > 0xFFFF) {
15307 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
15308 				"6429 usdelay %d too large. Scaled down to "
15309 				"0xFFFF.\n", usdelay);
15310 		usdelay = 0xFFFF;
15311 	}
15312 
15313 	/* set values by EQ_DELAY register if supported */
15314 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
15315 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15316 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15317 			if (!eq)
15318 				continue;
15319 
15320 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
15321 
15322 			if (++cnt >= numq)
15323 				break;
15324 		}
15325 		return;
15326 	}
15327 
15328 	/* Otherwise, set values by mailbox cmd */
15329 
15330 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15331 	if (!mbox) {
15332 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15333 				"6428 Failed allocating mailbox cmd buffer."
15334 				" EQ delay was not set.\n");
15335 		return;
15336 	}
15337 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
15338 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15339 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15340 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
15341 			 length, LPFC_SLI4_MBX_EMBED);
15342 	eq_delay = &mbox->u.mqe.un.eq_delay;
15343 
15344 	/* Calculate delay multiper from maximum interrupt per second */
15345 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
15346 	if (dmult)
15347 		dmult--;
15348 	if (dmult > LPFC_DMULT_MAX)
15349 		dmult = LPFC_DMULT_MAX;
15350 
15351 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15352 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15353 		if (!eq)
15354 			continue;
15355 		eq->q_mode = usdelay;
15356 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
15357 		eq_delay->u.request.eq[cnt].phase = 0;
15358 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
15359 
15360 		if (++cnt >= numq)
15361 			break;
15362 	}
15363 	eq_delay->u.request.num_eq = cnt;
15364 
15365 	mbox->vport = phba->pport;
15366 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15367 	mbox->ctx_buf = NULL;
15368 	mbox->ctx_ndlp = NULL;
15369 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15370 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
15371 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15372 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15373 	if (shdr_status || shdr_add_status || rc) {
15374 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15375 				"2512 MODIFY_EQ_DELAY mailbox failed with "
15376 				"status x%x add_status x%x, mbx status x%x\n",
15377 				shdr_status, shdr_add_status, rc);
15378 	}
15379 	mempool_free(mbox, phba->mbox_mem_pool);
15380 	return;
15381 }
15382 
15383 /**
15384  * lpfc_eq_create - Create an Event Queue on the HBA
15385  * @phba: HBA structure that indicates port to create a queue on.
15386  * @eq: The queue structure to use to create the event queue.
15387  * @imax: The maximum interrupt per second limit.
15388  *
15389  * This function creates an event queue, as detailed in @eq, on a port,
15390  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
15391  *
15392  * The @phba struct is used to send mailbox command to HBA. The @eq struct
15393  * is used to get the entry count and entry size that are necessary to
15394  * determine the number of pages to allocate and use for this queue. This
15395  * function will send the EQ_CREATE mailbox command to the HBA to setup the
15396  * event queue. This function is asynchronous and will wait for the mailbox
15397  * command to finish before continuing.
15398  *
15399  * On success this function will return a zero. If unable to allocate enough
15400  * memory this function will return -ENOMEM. If the queue create mailbox command
15401  * fails this function will return -ENXIO.
15402  **/
15403 int
15404 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
15405 {
15406 	struct lpfc_mbx_eq_create *eq_create;
15407 	LPFC_MBOXQ_t *mbox;
15408 	int rc, length, status = 0;
15409 	struct lpfc_dmabuf *dmabuf;
15410 	uint32_t shdr_status, shdr_add_status;
15411 	union lpfc_sli4_cfg_shdr *shdr;
15412 	uint16_t dmult;
15413 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15414 
15415 	/* sanity check on queue memory */
15416 	if (!eq)
15417 		return -ENODEV;
15418 	if (!phba->sli4_hba.pc_sli4_params.supported)
15419 		hw_page_size = SLI4_PAGE_SIZE;
15420 
15421 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15422 	if (!mbox)
15423 		return -ENOMEM;
15424 	length = (sizeof(struct lpfc_mbx_eq_create) -
15425 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15426 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15427 			 LPFC_MBOX_OPCODE_EQ_CREATE,
15428 			 length, LPFC_SLI4_MBX_EMBED);
15429 	eq_create = &mbox->u.mqe.un.eq_create;
15430 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
15431 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
15432 	       eq->page_count);
15433 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
15434 	       LPFC_EQE_SIZE);
15435 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
15436 
15437 	/* Use version 2 of CREATE_EQ if eqav is set */
15438 	if (phba->sli4_hba.pc_sli4_params.eqav) {
15439 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
15440 		       LPFC_Q_CREATE_VERSION_2);
15441 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
15442 		       phba->sli4_hba.pc_sli4_params.eqav);
15443 	}
15444 
15445 	/* don't setup delay multiplier using EQ_CREATE */
15446 	dmult = 0;
15447 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
15448 	       dmult);
15449 	switch (eq->entry_count) {
15450 	default:
15451 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15452 				"0360 Unsupported EQ count. (%d)\n",
15453 				eq->entry_count);
15454 		if (eq->entry_count < 256) {
15455 			status = -EINVAL;
15456 			goto out;
15457 		}
15458 		fallthrough;	/* otherwise default to smallest count */
15459 	case 256:
15460 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15461 		       LPFC_EQ_CNT_256);
15462 		break;
15463 	case 512:
15464 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15465 		       LPFC_EQ_CNT_512);
15466 		break;
15467 	case 1024:
15468 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15469 		       LPFC_EQ_CNT_1024);
15470 		break;
15471 	case 2048:
15472 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15473 		       LPFC_EQ_CNT_2048);
15474 		break;
15475 	case 4096:
15476 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15477 		       LPFC_EQ_CNT_4096);
15478 		break;
15479 	}
15480 	list_for_each_entry(dmabuf, &eq->page_list, list) {
15481 		memset(dmabuf->virt, 0, hw_page_size);
15482 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15483 					putPaddrLow(dmabuf->phys);
15484 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15485 					putPaddrHigh(dmabuf->phys);
15486 	}
15487 	mbox->vport = phba->pport;
15488 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15489 	mbox->ctx_buf = NULL;
15490 	mbox->ctx_ndlp = NULL;
15491 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15492 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15493 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15494 	if (shdr_status || shdr_add_status || rc) {
15495 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15496 				"2500 EQ_CREATE mailbox failed with "
15497 				"status x%x add_status x%x, mbx status x%x\n",
15498 				shdr_status, shdr_add_status, rc);
15499 		status = -ENXIO;
15500 	}
15501 	eq->type = LPFC_EQ;
15502 	eq->subtype = LPFC_NONE;
15503 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
15504 	if (eq->queue_id == 0xFFFF)
15505 		status = -ENXIO;
15506 	eq->host_index = 0;
15507 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
15508 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
15509 out:
15510 	mempool_free(mbox, phba->mbox_mem_pool);
15511 	return status;
15512 }
15513 
15514 static int lpfc_cq_poll_hdler(struct irq_poll *iop, int budget)
15515 {
15516 	struct lpfc_queue *cq = container_of(iop, struct lpfc_queue, iop);
15517 
15518 	__lpfc_sli4_hba_process_cq(cq, LPFC_IRQ_POLL);
15519 
15520 	return 1;
15521 }
15522 
15523 /**
15524  * lpfc_cq_create - Create a Completion Queue on the HBA
15525  * @phba: HBA structure that indicates port to create a queue on.
15526  * @cq: The queue structure to use to create the completion queue.
15527  * @eq: The event queue to bind this completion queue to.
15528  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
15529  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
15530  *
15531  * This function creates a completion queue, as detailed in @wq, on a port,
15532  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
15533  *
15534  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15535  * is used to get the entry count and entry size that are necessary to
15536  * determine the number of pages to allocate and use for this queue. The @eq
15537  * is used to indicate which event queue to bind this completion queue to. This
15538  * function will send the CQ_CREATE mailbox command to the HBA to setup the
15539  * completion queue. This function is asynchronous and will wait for the mailbox
15540  * command to finish before continuing.
15541  *
15542  * On success this function will return a zero. If unable to allocate enough
15543  * memory this function will return -ENOMEM. If the queue create mailbox command
15544  * fails this function will return -ENXIO.
15545  **/
15546 int
15547 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
15548 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
15549 {
15550 	struct lpfc_mbx_cq_create *cq_create;
15551 	struct lpfc_dmabuf *dmabuf;
15552 	LPFC_MBOXQ_t *mbox;
15553 	int rc, length, status = 0;
15554 	uint32_t shdr_status, shdr_add_status;
15555 	union lpfc_sli4_cfg_shdr *shdr;
15556 
15557 	/* sanity check on queue memory */
15558 	if (!cq || !eq)
15559 		return -ENODEV;
15560 
15561 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15562 	if (!mbox)
15563 		return -ENOMEM;
15564 	length = (sizeof(struct lpfc_mbx_cq_create) -
15565 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15566 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15567 			 LPFC_MBOX_OPCODE_CQ_CREATE,
15568 			 length, LPFC_SLI4_MBX_EMBED);
15569 	cq_create = &mbox->u.mqe.un.cq_create;
15570 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
15571 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
15572 		    cq->page_count);
15573 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
15574 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
15575 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15576 	       phba->sli4_hba.pc_sli4_params.cqv);
15577 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
15578 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
15579 		       (cq->page_size / SLI4_PAGE_SIZE));
15580 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
15581 		       eq->queue_id);
15582 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
15583 		       phba->sli4_hba.pc_sli4_params.cqav);
15584 	} else {
15585 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
15586 		       eq->queue_id);
15587 	}
15588 	switch (cq->entry_count) {
15589 	case 2048:
15590 	case 4096:
15591 		if (phba->sli4_hba.pc_sli4_params.cqv ==
15592 		    LPFC_Q_CREATE_VERSION_2) {
15593 			cq_create->u.request.context.lpfc_cq_context_count =
15594 				cq->entry_count;
15595 			bf_set(lpfc_cq_context_count,
15596 			       &cq_create->u.request.context,
15597 			       LPFC_CQ_CNT_WORD7);
15598 			break;
15599 		}
15600 		fallthrough;
15601 	default:
15602 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15603 				"0361 Unsupported CQ count: "
15604 				"entry cnt %d sz %d pg cnt %d\n",
15605 				cq->entry_count, cq->entry_size,
15606 				cq->page_count);
15607 		if (cq->entry_count < 256) {
15608 			status = -EINVAL;
15609 			goto out;
15610 		}
15611 		fallthrough;	/* otherwise default to smallest count */
15612 	case 256:
15613 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15614 		       LPFC_CQ_CNT_256);
15615 		break;
15616 	case 512:
15617 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15618 		       LPFC_CQ_CNT_512);
15619 		break;
15620 	case 1024:
15621 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15622 		       LPFC_CQ_CNT_1024);
15623 		break;
15624 	}
15625 	list_for_each_entry(dmabuf, &cq->page_list, list) {
15626 		memset(dmabuf->virt, 0, cq->page_size);
15627 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15628 					putPaddrLow(dmabuf->phys);
15629 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15630 					putPaddrHigh(dmabuf->phys);
15631 	}
15632 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15633 
15634 	/* The IOCTL status is embedded in the mailbox subheader. */
15635 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15636 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15637 	if (shdr_status || shdr_add_status || rc) {
15638 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15639 				"2501 CQ_CREATE mailbox failed with "
15640 				"status x%x add_status x%x, mbx status x%x\n",
15641 				shdr_status, shdr_add_status, rc);
15642 		status = -ENXIO;
15643 		goto out;
15644 	}
15645 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15646 	if (cq->queue_id == 0xFFFF) {
15647 		status = -ENXIO;
15648 		goto out;
15649 	}
15650 	/* link the cq onto the parent eq child list */
15651 	list_add_tail(&cq->list, &eq->child_list);
15652 	/* Set up completion queue's type and subtype */
15653 	cq->type = type;
15654 	cq->subtype = subtype;
15655 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15656 	cq->assoc_qid = eq->queue_id;
15657 	cq->assoc_qp = eq;
15658 	cq->host_index = 0;
15659 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15660 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
15661 
15662 	if (cq->queue_id > phba->sli4_hba.cq_max)
15663 		phba->sli4_hba.cq_max = cq->queue_id;
15664 
15665 	irq_poll_init(&cq->iop, LPFC_IRQ_POLL_WEIGHT, lpfc_cq_poll_hdler);
15666 out:
15667 	mempool_free(mbox, phba->mbox_mem_pool);
15668 	return status;
15669 }
15670 
15671 /**
15672  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
15673  * @phba: HBA structure that indicates port to create a queue on.
15674  * @cqp: The queue structure array to use to create the completion queues.
15675  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
15676  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
15677  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
15678  *
15679  * This function creates a set of  completion queue, s to support MRQ
15680  * as detailed in @cqp, on a port,
15681  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
15682  *
15683  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15684  * is used to get the entry count and entry size that are necessary to
15685  * determine the number of pages to allocate and use for this queue. The @eq
15686  * is used to indicate which event queue to bind this completion queue to. This
15687  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
15688  * completion queue. This function is asynchronous and will wait for the mailbox
15689  * command to finish before continuing.
15690  *
15691  * On success this function will return a zero. If unable to allocate enough
15692  * memory this function will return -ENOMEM. If the queue create mailbox command
15693  * fails this function will return -ENXIO.
15694  **/
15695 int
15696 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
15697 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
15698 		   uint32_t subtype)
15699 {
15700 	struct lpfc_queue *cq;
15701 	struct lpfc_queue *eq;
15702 	struct lpfc_mbx_cq_create_set *cq_set;
15703 	struct lpfc_dmabuf *dmabuf;
15704 	LPFC_MBOXQ_t *mbox;
15705 	int rc, length, alloclen, status = 0;
15706 	int cnt, idx, numcq, page_idx = 0;
15707 	uint32_t shdr_status, shdr_add_status;
15708 	union lpfc_sli4_cfg_shdr *shdr;
15709 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15710 
15711 	/* sanity check on queue memory */
15712 	numcq = phba->cfg_nvmet_mrq;
15713 	if (!cqp || !hdwq || !numcq)
15714 		return -ENODEV;
15715 
15716 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15717 	if (!mbox)
15718 		return -ENOMEM;
15719 
15720 	length = sizeof(struct lpfc_mbx_cq_create_set);
15721 	length += ((numcq * cqp[0]->page_count) *
15722 		   sizeof(struct dma_address));
15723 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15724 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
15725 			LPFC_SLI4_MBX_NEMBED);
15726 	if (alloclen < length) {
15727 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15728 				"3098 Allocated DMA memory size (%d) is "
15729 				"less than the requested DMA memory size "
15730 				"(%d)\n", alloclen, length);
15731 		status = -ENOMEM;
15732 		goto out;
15733 	}
15734 	cq_set = mbox->sge_array->addr[0];
15735 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
15736 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
15737 
15738 	for (idx = 0; idx < numcq; idx++) {
15739 		cq = cqp[idx];
15740 		eq = hdwq[idx].hba_eq;
15741 		if (!cq || !eq) {
15742 			status = -ENOMEM;
15743 			goto out;
15744 		}
15745 		if (!phba->sli4_hba.pc_sli4_params.supported)
15746 			hw_page_size = cq->page_size;
15747 
15748 		switch (idx) {
15749 		case 0:
15750 			bf_set(lpfc_mbx_cq_create_set_page_size,
15751 			       &cq_set->u.request,
15752 			       (hw_page_size / SLI4_PAGE_SIZE));
15753 			bf_set(lpfc_mbx_cq_create_set_num_pages,
15754 			       &cq_set->u.request, cq->page_count);
15755 			bf_set(lpfc_mbx_cq_create_set_evt,
15756 			       &cq_set->u.request, 1);
15757 			bf_set(lpfc_mbx_cq_create_set_valid,
15758 			       &cq_set->u.request, 1);
15759 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
15760 			       &cq_set->u.request, 0);
15761 			bf_set(lpfc_mbx_cq_create_set_num_cq,
15762 			       &cq_set->u.request, numcq);
15763 			bf_set(lpfc_mbx_cq_create_set_autovalid,
15764 			       &cq_set->u.request,
15765 			       phba->sli4_hba.pc_sli4_params.cqav);
15766 			switch (cq->entry_count) {
15767 			case 2048:
15768 			case 4096:
15769 				if (phba->sli4_hba.pc_sli4_params.cqv ==
15770 				    LPFC_Q_CREATE_VERSION_2) {
15771 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15772 					       &cq_set->u.request,
15773 						cq->entry_count);
15774 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15775 					       &cq_set->u.request,
15776 					       LPFC_CQ_CNT_WORD7);
15777 					break;
15778 				}
15779 				fallthrough;
15780 			default:
15781 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15782 						"3118 Bad CQ count. (%d)\n",
15783 						cq->entry_count);
15784 				if (cq->entry_count < 256) {
15785 					status = -EINVAL;
15786 					goto out;
15787 				}
15788 				fallthrough;	/* otherwise default to smallest */
15789 			case 256:
15790 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15791 				       &cq_set->u.request, LPFC_CQ_CNT_256);
15792 				break;
15793 			case 512:
15794 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15795 				       &cq_set->u.request, LPFC_CQ_CNT_512);
15796 				break;
15797 			case 1024:
15798 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15799 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
15800 				break;
15801 			}
15802 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
15803 			       &cq_set->u.request, eq->queue_id);
15804 			break;
15805 		case 1:
15806 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
15807 			       &cq_set->u.request, eq->queue_id);
15808 			break;
15809 		case 2:
15810 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
15811 			       &cq_set->u.request, eq->queue_id);
15812 			break;
15813 		case 3:
15814 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
15815 			       &cq_set->u.request, eq->queue_id);
15816 			break;
15817 		case 4:
15818 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
15819 			       &cq_set->u.request, eq->queue_id);
15820 			break;
15821 		case 5:
15822 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
15823 			       &cq_set->u.request, eq->queue_id);
15824 			break;
15825 		case 6:
15826 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
15827 			       &cq_set->u.request, eq->queue_id);
15828 			break;
15829 		case 7:
15830 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
15831 			       &cq_set->u.request, eq->queue_id);
15832 			break;
15833 		case 8:
15834 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
15835 			       &cq_set->u.request, eq->queue_id);
15836 			break;
15837 		case 9:
15838 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
15839 			       &cq_set->u.request, eq->queue_id);
15840 			break;
15841 		case 10:
15842 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
15843 			       &cq_set->u.request, eq->queue_id);
15844 			break;
15845 		case 11:
15846 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
15847 			       &cq_set->u.request, eq->queue_id);
15848 			break;
15849 		case 12:
15850 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
15851 			       &cq_set->u.request, eq->queue_id);
15852 			break;
15853 		case 13:
15854 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
15855 			       &cq_set->u.request, eq->queue_id);
15856 			break;
15857 		case 14:
15858 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
15859 			       &cq_set->u.request, eq->queue_id);
15860 			break;
15861 		case 15:
15862 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
15863 			       &cq_set->u.request, eq->queue_id);
15864 			break;
15865 		}
15866 
15867 		/* link the cq onto the parent eq child list */
15868 		list_add_tail(&cq->list, &eq->child_list);
15869 		/* Set up completion queue's type and subtype */
15870 		cq->type = type;
15871 		cq->subtype = subtype;
15872 		cq->assoc_qid = eq->queue_id;
15873 		cq->assoc_qp = eq;
15874 		cq->host_index = 0;
15875 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15876 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
15877 					 cq->entry_count);
15878 		cq->chann = idx;
15879 
15880 		rc = 0;
15881 		list_for_each_entry(dmabuf, &cq->page_list, list) {
15882 			memset(dmabuf->virt, 0, hw_page_size);
15883 			cnt = page_idx + dmabuf->buffer_tag;
15884 			cq_set->u.request.page[cnt].addr_lo =
15885 					putPaddrLow(dmabuf->phys);
15886 			cq_set->u.request.page[cnt].addr_hi =
15887 					putPaddrHigh(dmabuf->phys);
15888 			rc++;
15889 		}
15890 		page_idx += rc;
15891 	}
15892 
15893 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15894 
15895 	/* The IOCTL status is embedded in the mailbox subheader. */
15896 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15897 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15898 	if (shdr_status || shdr_add_status || rc) {
15899 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15900 				"3119 CQ_CREATE_SET mailbox failed with "
15901 				"status x%x add_status x%x, mbx status x%x\n",
15902 				shdr_status, shdr_add_status, rc);
15903 		status = -ENXIO;
15904 		goto out;
15905 	}
15906 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
15907 	if (rc == 0xFFFF) {
15908 		status = -ENXIO;
15909 		goto out;
15910 	}
15911 
15912 	for (idx = 0; idx < numcq; idx++) {
15913 		cq = cqp[idx];
15914 		cq->queue_id = rc + idx;
15915 		if (cq->queue_id > phba->sli4_hba.cq_max)
15916 			phba->sli4_hba.cq_max = cq->queue_id;
15917 	}
15918 
15919 out:
15920 	lpfc_sli4_mbox_cmd_free(phba, mbox);
15921 	return status;
15922 }
15923 
15924 /**
15925  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
15926  * @phba: HBA structure that indicates port to create a queue on.
15927  * @mq: The queue structure to use to create the mailbox queue.
15928  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
15929  * @cq: The completion queue to associate with this cq.
15930  *
15931  * This function provides failback (fb) functionality when the
15932  * mq_create_ext fails on older FW generations.  It's purpose is identical
15933  * to mq_create_ext otherwise.
15934  *
15935  * This routine cannot fail as all attributes were previously accessed and
15936  * initialized in mq_create_ext.
15937  **/
15938 static void
15939 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
15940 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
15941 {
15942 	struct lpfc_mbx_mq_create *mq_create;
15943 	struct lpfc_dmabuf *dmabuf;
15944 	int length;
15945 
15946 	length = (sizeof(struct lpfc_mbx_mq_create) -
15947 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15948 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15949 			 LPFC_MBOX_OPCODE_MQ_CREATE,
15950 			 length, LPFC_SLI4_MBX_EMBED);
15951 	mq_create = &mbox->u.mqe.un.mq_create;
15952 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
15953 	       mq->page_count);
15954 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
15955 	       cq->queue_id);
15956 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
15957 	switch (mq->entry_count) {
15958 	case 16:
15959 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15960 		       LPFC_MQ_RING_SIZE_16);
15961 		break;
15962 	case 32:
15963 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15964 		       LPFC_MQ_RING_SIZE_32);
15965 		break;
15966 	case 64:
15967 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15968 		       LPFC_MQ_RING_SIZE_64);
15969 		break;
15970 	case 128:
15971 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15972 		       LPFC_MQ_RING_SIZE_128);
15973 		break;
15974 	}
15975 	list_for_each_entry(dmabuf, &mq->page_list, list) {
15976 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15977 			putPaddrLow(dmabuf->phys);
15978 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15979 			putPaddrHigh(dmabuf->phys);
15980 	}
15981 }
15982 
15983 /**
15984  * lpfc_mq_create - Create a mailbox Queue on the HBA
15985  * @phba: HBA structure that indicates port to create a queue on.
15986  * @mq: The queue structure to use to create the mailbox queue.
15987  * @cq: The completion queue to associate with this cq.
15988  * @subtype: The queue's subtype.
15989  *
15990  * This function creates a mailbox queue, as detailed in @mq, on a port,
15991  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
15992  *
15993  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15994  * is used to get the entry count and entry size that are necessary to
15995  * determine the number of pages to allocate and use for this queue. This
15996  * function will send the MQ_CREATE mailbox command to the HBA to setup the
15997  * mailbox queue. This function is asynchronous and will wait for the mailbox
15998  * command to finish before continuing.
15999  *
16000  * On success this function will return a zero. If unable to allocate enough
16001  * memory this function will return -ENOMEM. If the queue create mailbox command
16002  * fails this function will return -ENXIO.
16003  **/
16004 int32_t
16005 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
16006 	       struct lpfc_queue *cq, uint32_t subtype)
16007 {
16008 	struct lpfc_mbx_mq_create *mq_create;
16009 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
16010 	struct lpfc_dmabuf *dmabuf;
16011 	LPFC_MBOXQ_t *mbox;
16012 	int rc, length, status = 0;
16013 	uint32_t shdr_status, shdr_add_status;
16014 	union lpfc_sli4_cfg_shdr *shdr;
16015 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16016 
16017 	/* sanity check on queue memory */
16018 	if (!mq || !cq)
16019 		return -ENODEV;
16020 	if (!phba->sli4_hba.pc_sli4_params.supported)
16021 		hw_page_size = SLI4_PAGE_SIZE;
16022 
16023 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16024 	if (!mbox)
16025 		return -ENOMEM;
16026 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
16027 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16028 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16029 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
16030 			 length, LPFC_SLI4_MBX_EMBED);
16031 
16032 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
16033 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
16034 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
16035 	       &mq_create_ext->u.request, mq->page_count);
16036 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
16037 	       &mq_create_ext->u.request, 1);
16038 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
16039 	       &mq_create_ext->u.request, 1);
16040 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
16041 	       &mq_create_ext->u.request, 1);
16042 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
16043 	       &mq_create_ext->u.request, 1);
16044 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
16045 	       &mq_create_ext->u.request, 1);
16046 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
16047 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16048 	       phba->sli4_hba.pc_sli4_params.mqv);
16049 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
16050 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
16051 		       cq->queue_id);
16052 	else
16053 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
16054 		       cq->queue_id);
16055 	switch (mq->entry_count) {
16056 	default:
16057 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16058 				"0362 Unsupported MQ count. (%d)\n",
16059 				mq->entry_count);
16060 		if (mq->entry_count < 16) {
16061 			status = -EINVAL;
16062 			goto out;
16063 		}
16064 		fallthrough;	/* otherwise default to smallest count */
16065 	case 16:
16066 		bf_set(lpfc_mq_context_ring_size,
16067 		       &mq_create_ext->u.request.context,
16068 		       LPFC_MQ_RING_SIZE_16);
16069 		break;
16070 	case 32:
16071 		bf_set(lpfc_mq_context_ring_size,
16072 		       &mq_create_ext->u.request.context,
16073 		       LPFC_MQ_RING_SIZE_32);
16074 		break;
16075 	case 64:
16076 		bf_set(lpfc_mq_context_ring_size,
16077 		       &mq_create_ext->u.request.context,
16078 		       LPFC_MQ_RING_SIZE_64);
16079 		break;
16080 	case 128:
16081 		bf_set(lpfc_mq_context_ring_size,
16082 		       &mq_create_ext->u.request.context,
16083 		       LPFC_MQ_RING_SIZE_128);
16084 		break;
16085 	}
16086 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16087 		memset(dmabuf->virt, 0, hw_page_size);
16088 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16089 					putPaddrLow(dmabuf->phys);
16090 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16091 					putPaddrHigh(dmabuf->phys);
16092 	}
16093 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16094 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16095 			      &mq_create_ext->u.response);
16096 	if (rc != MBX_SUCCESS) {
16097 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16098 				"2795 MQ_CREATE_EXT failed with "
16099 				"status x%x. Failback to MQ_CREATE.\n",
16100 				rc);
16101 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16102 		mq_create = &mbox->u.mqe.un.mq_create;
16103 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16104 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16105 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16106 				      &mq_create->u.response);
16107 	}
16108 
16109 	/* The IOCTL status is embedded in the mailbox subheader. */
16110 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16111 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16112 	if (shdr_status || shdr_add_status || rc) {
16113 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16114 				"2502 MQ_CREATE mailbox failed with "
16115 				"status x%x add_status x%x, mbx status x%x\n",
16116 				shdr_status, shdr_add_status, rc);
16117 		status = -ENXIO;
16118 		goto out;
16119 	}
16120 	if (mq->queue_id == 0xFFFF) {
16121 		status = -ENXIO;
16122 		goto out;
16123 	}
16124 	mq->type = LPFC_MQ;
16125 	mq->assoc_qid = cq->queue_id;
16126 	mq->subtype = subtype;
16127 	mq->host_index = 0;
16128 	mq->hba_index = 0;
16129 
16130 	/* link the mq onto the parent cq child list */
16131 	list_add_tail(&mq->list, &cq->child_list);
16132 out:
16133 	mempool_free(mbox, phba->mbox_mem_pool);
16134 	return status;
16135 }
16136 
16137 /**
16138  * lpfc_wq_create - Create a Work Queue on the HBA
16139  * @phba: HBA structure that indicates port to create a queue on.
16140  * @wq: The queue structure to use to create the work queue.
16141  * @cq: The completion queue to bind this work queue to.
16142  * @subtype: The subtype of the work queue indicating its functionality.
16143  *
16144  * This function creates a work queue, as detailed in @wq, on a port, described
16145  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16146  *
16147  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16148  * is used to get the entry count and entry size that are necessary to
16149  * determine the number of pages to allocate and use for this queue. The @cq
16150  * is used to indicate which completion queue to bind this work queue to. This
16151  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16152  * work queue. This function is asynchronous and will wait for the mailbox
16153  * command to finish before continuing.
16154  *
16155  * On success this function will return a zero. If unable to allocate enough
16156  * memory this function will return -ENOMEM. If the queue create mailbox command
16157  * fails this function will return -ENXIO.
16158  **/
16159 int
16160 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16161 	       struct lpfc_queue *cq, uint32_t subtype)
16162 {
16163 	struct lpfc_mbx_wq_create *wq_create;
16164 	struct lpfc_dmabuf *dmabuf;
16165 	LPFC_MBOXQ_t *mbox;
16166 	int rc, length, status = 0;
16167 	uint32_t shdr_status, shdr_add_status;
16168 	union lpfc_sli4_cfg_shdr *shdr;
16169 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16170 	struct dma_address *page;
16171 	void __iomem *bar_memmap_p;
16172 	uint32_t db_offset;
16173 	uint16_t pci_barset;
16174 	uint8_t dpp_barset;
16175 	uint32_t dpp_offset;
16176 	uint8_t wq_create_version;
16177 #ifdef CONFIG_X86
16178 	unsigned long pg_addr;
16179 #endif
16180 
16181 	/* sanity check on queue memory */
16182 	if (!wq || !cq)
16183 		return -ENODEV;
16184 	if (!phba->sli4_hba.pc_sli4_params.supported)
16185 		hw_page_size = wq->page_size;
16186 
16187 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16188 	if (!mbox)
16189 		return -ENOMEM;
16190 	length = (sizeof(struct lpfc_mbx_wq_create) -
16191 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16192 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16193 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16194 			 length, LPFC_SLI4_MBX_EMBED);
16195 	wq_create = &mbox->u.mqe.un.wq_create;
16196 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16197 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16198 		    wq->page_count);
16199 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16200 		    cq->queue_id);
16201 
16202 	/* wqv is the earliest version supported, NOT the latest */
16203 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16204 	       phba->sli4_hba.pc_sli4_params.wqv);
16205 
16206 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16207 	    (wq->page_size > SLI4_PAGE_SIZE))
16208 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
16209 	else
16210 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
16211 
16212 	switch (wq_create_version) {
16213 	case LPFC_Q_CREATE_VERSION_1:
16214 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
16215 		       wq->entry_count);
16216 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16217 		       LPFC_Q_CREATE_VERSION_1);
16218 
16219 		switch (wq->entry_size) {
16220 		default:
16221 		case 64:
16222 			bf_set(lpfc_mbx_wq_create_wqe_size,
16223 			       &wq_create->u.request_1,
16224 			       LPFC_WQ_WQE_SIZE_64);
16225 			break;
16226 		case 128:
16227 			bf_set(lpfc_mbx_wq_create_wqe_size,
16228 			       &wq_create->u.request_1,
16229 			       LPFC_WQ_WQE_SIZE_128);
16230 			break;
16231 		}
16232 		/* Request DPP by default */
16233 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
16234 		bf_set(lpfc_mbx_wq_create_page_size,
16235 		       &wq_create->u.request_1,
16236 		       (wq->page_size / SLI4_PAGE_SIZE));
16237 		page = wq_create->u.request_1.page;
16238 		break;
16239 	default:
16240 		page = wq_create->u.request.page;
16241 		break;
16242 	}
16243 
16244 	list_for_each_entry(dmabuf, &wq->page_list, list) {
16245 		memset(dmabuf->virt, 0, hw_page_size);
16246 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
16247 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
16248 	}
16249 
16250 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16251 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
16252 
16253 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16254 	/* The IOCTL status is embedded in the mailbox subheader. */
16255 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16256 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16257 	if (shdr_status || shdr_add_status || rc) {
16258 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16259 				"2503 WQ_CREATE mailbox failed with "
16260 				"status x%x add_status x%x, mbx status x%x\n",
16261 				shdr_status, shdr_add_status, rc);
16262 		status = -ENXIO;
16263 		goto out;
16264 	}
16265 
16266 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
16267 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
16268 					&wq_create->u.response);
16269 	else
16270 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
16271 					&wq_create->u.response_1);
16272 
16273 	if (wq->queue_id == 0xFFFF) {
16274 		status = -ENXIO;
16275 		goto out;
16276 	}
16277 
16278 	wq->db_format = LPFC_DB_LIST_FORMAT;
16279 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
16280 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16281 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
16282 					       &wq_create->u.response);
16283 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
16284 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
16285 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16286 						"3265 WQ[%d] doorbell format "
16287 						"not supported: x%x\n",
16288 						wq->queue_id, wq->db_format);
16289 				status = -EINVAL;
16290 				goto out;
16291 			}
16292 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
16293 					    &wq_create->u.response);
16294 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16295 								   pci_barset);
16296 			if (!bar_memmap_p) {
16297 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16298 						"3263 WQ[%d] failed to memmap "
16299 						"pci barset:x%x\n",
16300 						wq->queue_id, pci_barset);
16301 				status = -ENOMEM;
16302 				goto out;
16303 			}
16304 			db_offset = wq_create->u.response.doorbell_offset;
16305 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
16306 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
16307 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16308 						"3252 WQ[%d] doorbell offset "
16309 						"not supported: x%x\n",
16310 						wq->queue_id, db_offset);
16311 				status = -EINVAL;
16312 				goto out;
16313 			}
16314 			wq->db_regaddr = bar_memmap_p + db_offset;
16315 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16316 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
16317 					"format:x%x\n", wq->queue_id,
16318 					pci_barset, db_offset, wq->db_format);
16319 		} else
16320 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
16321 	} else {
16322 		/* Check if DPP was honored by the firmware */
16323 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
16324 				    &wq_create->u.response_1);
16325 		if (wq->dpp_enable) {
16326 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
16327 					    &wq_create->u.response_1);
16328 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16329 								   pci_barset);
16330 			if (!bar_memmap_p) {
16331 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16332 						"3267 WQ[%d] failed to memmap "
16333 						"pci barset:x%x\n",
16334 						wq->queue_id, pci_barset);
16335 				status = -ENOMEM;
16336 				goto out;
16337 			}
16338 			db_offset = wq_create->u.response_1.doorbell_offset;
16339 			wq->db_regaddr = bar_memmap_p + db_offset;
16340 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
16341 					    &wq_create->u.response_1);
16342 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
16343 					    &wq_create->u.response_1);
16344 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16345 								   dpp_barset);
16346 			if (!bar_memmap_p) {
16347 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16348 						"3268 WQ[%d] failed to memmap "
16349 						"pci barset:x%x\n",
16350 						wq->queue_id, dpp_barset);
16351 				status = -ENOMEM;
16352 				goto out;
16353 			}
16354 			dpp_offset = wq_create->u.response_1.dpp_offset;
16355 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
16356 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16357 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
16358 					"dpp_id:x%x dpp_barset:x%x "
16359 					"dpp_offset:x%x\n",
16360 					wq->queue_id, pci_barset, db_offset,
16361 					wq->dpp_id, dpp_barset, dpp_offset);
16362 
16363 #ifdef CONFIG_X86
16364 			/* Enable combined writes for DPP aperture */
16365 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
16366 			rc = set_memory_wc(pg_addr, 1);
16367 			if (rc) {
16368 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16369 					"3272 Cannot setup Combined "
16370 					"Write on WQ[%d] - disable DPP\n",
16371 					wq->queue_id);
16372 				phba->cfg_enable_dpp = 0;
16373 			}
16374 #else
16375 			phba->cfg_enable_dpp = 0;
16376 #endif
16377 		} else
16378 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
16379 	}
16380 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
16381 	if (wq->pring == NULL) {
16382 		status = -ENOMEM;
16383 		goto out;
16384 	}
16385 	wq->type = LPFC_WQ;
16386 	wq->assoc_qid = cq->queue_id;
16387 	wq->subtype = subtype;
16388 	wq->host_index = 0;
16389 	wq->hba_index = 0;
16390 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
16391 
16392 	/* link the wq onto the parent cq child list */
16393 	list_add_tail(&wq->list, &cq->child_list);
16394 out:
16395 	mempool_free(mbox, phba->mbox_mem_pool);
16396 	return status;
16397 }
16398 
16399 /**
16400  * lpfc_rq_create - Create a Receive Queue on the HBA
16401  * @phba: HBA structure that indicates port to create a queue on.
16402  * @hrq: The queue structure to use to create the header receive queue.
16403  * @drq: The queue structure to use to create the data receive queue.
16404  * @cq: The completion queue to bind this work queue to.
16405  * @subtype: The subtype of the work queue indicating its functionality.
16406  *
16407  * This function creates a receive buffer queue pair , as detailed in @hrq and
16408  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
16409  * to the HBA.
16410  *
16411  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
16412  * struct is used to get the entry count that is necessary to determine the
16413  * number of pages to use for this queue. The @cq is used to indicate which
16414  * completion queue to bind received buffers that are posted to these queues to.
16415  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
16416  * receive queue pair. This function is asynchronous and will wait for the
16417  * mailbox command to finish before continuing.
16418  *
16419  * On success this function will return a zero. If unable to allocate enough
16420  * memory this function will return -ENOMEM. If the queue create mailbox command
16421  * fails this function will return -ENXIO.
16422  **/
16423 int
16424 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
16425 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
16426 {
16427 	struct lpfc_mbx_rq_create *rq_create;
16428 	struct lpfc_dmabuf *dmabuf;
16429 	LPFC_MBOXQ_t *mbox;
16430 	int rc, length, status = 0;
16431 	uint32_t shdr_status, shdr_add_status;
16432 	union lpfc_sli4_cfg_shdr *shdr;
16433 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16434 	void __iomem *bar_memmap_p;
16435 	uint32_t db_offset;
16436 	uint16_t pci_barset;
16437 
16438 	/* sanity check on queue memory */
16439 	if (!hrq || !drq || !cq)
16440 		return -ENODEV;
16441 	if (!phba->sli4_hba.pc_sli4_params.supported)
16442 		hw_page_size = SLI4_PAGE_SIZE;
16443 
16444 	if (hrq->entry_count != drq->entry_count)
16445 		return -EINVAL;
16446 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16447 	if (!mbox)
16448 		return -ENOMEM;
16449 	length = (sizeof(struct lpfc_mbx_rq_create) -
16450 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16451 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16452 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
16453 			 length, LPFC_SLI4_MBX_EMBED);
16454 	rq_create = &mbox->u.mqe.un.rq_create;
16455 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
16456 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16457 	       phba->sli4_hba.pc_sli4_params.rqv);
16458 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
16459 		bf_set(lpfc_rq_context_rqe_count_1,
16460 		       &rq_create->u.request.context,
16461 		       hrq->entry_count);
16462 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
16463 		bf_set(lpfc_rq_context_rqe_size,
16464 		       &rq_create->u.request.context,
16465 		       LPFC_RQE_SIZE_8);
16466 		bf_set(lpfc_rq_context_page_size,
16467 		       &rq_create->u.request.context,
16468 		       LPFC_RQ_PAGE_SIZE_4096);
16469 	} else {
16470 		switch (hrq->entry_count) {
16471 		default:
16472 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16473 					"2535 Unsupported RQ count. (%d)\n",
16474 					hrq->entry_count);
16475 			if (hrq->entry_count < 512) {
16476 				status = -EINVAL;
16477 				goto out;
16478 			}
16479 			fallthrough;	/* otherwise default to smallest count */
16480 		case 512:
16481 			bf_set(lpfc_rq_context_rqe_count,
16482 			       &rq_create->u.request.context,
16483 			       LPFC_RQ_RING_SIZE_512);
16484 			break;
16485 		case 1024:
16486 			bf_set(lpfc_rq_context_rqe_count,
16487 			       &rq_create->u.request.context,
16488 			       LPFC_RQ_RING_SIZE_1024);
16489 			break;
16490 		case 2048:
16491 			bf_set(lpfc_rq_context_rqe_count,
16492 			       &rq_create->u.request.context,
16493 			       LPFC_RQ_RING_SIZE_2048);
16494 			break;
16495 		case 4096:
16496 			bf_set(lpfc_rq_context_rqe_count,
16497 			       &rq_create->u.request.context,
16498 			       LPFC_RQ_RING_SIZE_4096);
16499 			break;
16500 		}
16501 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
16502 		       LPFC_HDR_BUF_SIZE);
16503 	}
16504 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16505 	       cq->queue_id);
16506 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16507 	       hrq->page_count);
16508 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
16509 		memset(dmabuf->virt, 0, hw_page_size);
16510 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16511 					putPaddrLow(dmabuf->phys);
16512 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16513 					putPaddrHigh(dmabuf->phys);
16514 	}
16515 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16516 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16517 
16518 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16519 	/* The IOCTL status is embedded in the mailbox subheader. */
16520 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16521 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16522 	if (shdr_status || shdr_add_status || rc) {
16523 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16524 				"2504 RQ_CREATE mailbox failed with "
16525 				"status x%x add_status x%x, mbx status x%x\n",
16526 				shdr_status, shdr_add_status, rc);
16527 		status = -ENXIO;
16528 		goto out;
16529 	}
16530 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16531 	if (hrq->queue_id == 0xFFFF) {
16532 		status = -ENXIO;
16533 		goto out;
16534 	}
16535 
16536 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16537 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
16538 					&rq_create->u.response);
16539 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
16540 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
16541 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16542 					"3262 RQ [%d] doorbell format not "
16543 					"supported: x%x\n", hrq->queue_id,
16544 					hrq->db_format);
16545 			status = -EINVAL;
16546 			goto out;
16547 		}
16548 
16549 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
16550 				    &rq_create->u.response);
16551 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
16552 		if (!bar_memmap_p) {
16553 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16554 					"3269 RQ[%d] failed to memmap pci "
16555 					"barset:x%x\n", hrq->queue_id,
16556 					pci_barset);
16557 			status = -ENOMEM;
16558 			goto out;
16559 		}
16560 
16561 		db_offset = rq_create->u.response.doorbell_offset;
16562 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
16563 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
16564 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16565 					"3270 RQ[%d] doorbell offset not "
16566 					"supported: x%x\n", hrq->queue_id,
16567 					db_offset);
16568 			status = -EINVAL;
16569 			goto out;
16570 		}
16571 		hrq->db_regaddr = bar_memmap_p + db_offset;
16572 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16573 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
16574 				"format:x%x\n", hrq->queue_id, pci_barset,
16575 				db_offset, hrq->db_format);
16576 	} else {
16577 		hrq->db_format = LPFC_DB_RING_FORMAT;
16578 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16579 	}
16580 	hrq->type = LPFC_HRQ;
16581 	hrq->assoc_qid = cq->queue_id;
16582 	hrq->subtype = subtype;
16583 	hrq->host_index = 0;
16584 	hrq->hba_index = 0;
16585 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16586 
16587 	/* now create the data queue */
16588 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16589 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
16590 			 length, LPFC_SLI4_MBX_EMBED);
16591 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16592 	       phba->sli4_hba.pc_sli4_params.rqv);
16593 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
16594 		bf_set(lpfc_rq_context_rqe_count_1,
16595 		       &rq_create->u.request.context, hrq->entry_count);
16596 		if (subtype == LPFC_NVMET)
16597 			rq_create->u.request.context.buffer_size =
16598 				LPFC_NVMET_DATA_BUF_SIZE;
16599 		else
16600 			rq_create->u.request.context.buffer_size =
16601 				LPFC_DATA_BUF_SIZE;
16602 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
16603 		       LPFC_RQE_SIZE_8);
16604 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
16605 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
16606 	} else {
16607 		switch (drq->entry_count) {
16608 		default:
16609 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16610 					"2536 Unsupported RQ count. (%d)\n",
16611 					drq->entry_count);
16612 			if (drq->entry_count < 512) {
16613 				status = -EINVAL;
16614 				goto out;
16615 			}
16616 			fallthrough;	/* otherwise default to smallest count */
16617 		case 512:
16618 			bf_set(lpfc_rq_context_rqe_count,
16619 			       &rq_create->u.request.context,
16620 			       LPFC_RQ_RING_SIZE_512);
16621 			break;
16622 		case 1024:
16623 			bf_set(lpfc_rq_context_rqe_count,
16624 			       &rq_create->u.request.context,
16625 			       LPFC_RQ_RING_SIZE_1024);
16626 			break;
16627 		case 2048:
16628 			bf_set(lpfc_rq_context_rqe_count,
16629 			       &rq_create->u.request.context,
16630 			       LPFC_RQ_RING_SIZE_2048);
16631 			break;
16632 		case 4096:
16633 			bf_set(lpfc_rq_context_rqe_count,
16634 			       &rq_create->u.request.context,
16635 			       LPFC_RQ_RING_SIZE_4096);
16636 			break;
16637 		}
16638 		if (subtype == LPFC_NVMET)
16639 			bf_set(lpfc_rq_context_buf_size,
16640 			       &rq_create->u.request.context,
16641 			       LPFC_NVMET_DATA_BUF_SIZE);
16642 		else
16643 			bf_set(lpfc_rq_context_buf_size,
16644 			       &rq_create->u.request.context,
16645 			       LPFC_DATA_BUF_SIZE);
16646 	}
16647 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16648 	       cq->queue_id);
16649 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16650 	       drq->page_count);
16651 	list_for_each_entry(dmabuf, &drq->page_list, list) {
16652 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16653 					putPaddrLow(dmabuf->phys);
16654 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16655 					putPaddrHigh(dmabuf->phys);
16656 	}
16657 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16658 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16659 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16660 	/* The IOCTL status is embedded in the mailbox subheader. */
16661 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
16662 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16663 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16664 	if (shdr_status || shdr_add_status || rc) {
16665 		status = -ENXIO;
16666 		goto out;
16667 	}
16668 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16669 	if (drq->queue_id == 0xFFFF) {
16670 		status = -ENXIO;
16671 		goto out;
16672 	}
16673 	drq->type = LPFC_DRQ;
16674 	drq->assoc_qid = cq->queue_id;
16675 	drq->subtype = subtype;
16676 	drq->host_index = 0;
16677 	drq->hba_index = 0;
16678 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16679 
16680 	/* link the header and data RQs onto the parent cq child list */
16681 	list_add_tail(&hrq->list, &cq->child_list);
16682 	list_add_tail(&drq->list, &cq->child_list);
16683 
16684 out:
16685 	mempool_free(mbox, phba->mbox_mem_pool);
16686 	return status;
16687 }
16688 
16689 /**
16690  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
16691  * @phba: HBA structure that indicates port to create a queue on.
16692  * @hrqp: The queue structure array to use to create the header receive queues.
16693  * @drqp: The queue structure array to use to create the data receive queues.
16694  * @cqp: The completion queue array to bind these receive queues to.
16695  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16696  *
16697  * This function creates a receive buffer queue pair , as detailed in @hrq and
16698  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
16699  * to the HBA.
16700  *
16701  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
16702  * struct is used to get the entry count that is necessary to determine the
16703  * number of pages to use for this queue. The @cq is used to indicate which
16704  * completion queue to bind received buffers that are posted to these queues to.
16705  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
16706  * receive queue pair. This function is asynchronous and will wait for the
16707  * mailbox command to finish before continuing.
16708  *
16709  * On success this function will return a zero. If unable to allocate enough
16710  * memory this function will return -ENOMEM. If the queue create mailbox command
16711  * fails this function will return -ENXIO.
16712  **/
16713 int
16714 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
16715 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
16716 		uint32_t subtype)
16717 {
16718 	struct lpfc_queue *hrq, *drq, *cq;
16719 	struct lpfc_mbx_rq_create_v2 *rq_create;
16720 	struct lpfc_dmabuf *dmabuf;
16721 	LPFC_MBOXQ_t *mbox;
16722 	int rc, length, alloclen, status = 0;
16723 	int cnt, idx, numrq, page_idx = 0;
16724 	uint32_t shdr_status, shdr_add_status;
16725 	union lpfc_sli4_cfg_shdr *shdr;
16726 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16727 
16728 	numrq = phba->cfg_nvmet_mrq;
16729 	/* sanity check on array memory */
16730 	if (!hrqp || !drqp || !cqp || !numrq)
16731 		return -ENODEV;
16732 	if (!phba->sli4_hba.pc_sli4_params.supported)
16733 		hw_page_size = SLI4_PAGE_SIZE;
16734 
16735 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16736 	if (!mbox)
16737 		return -ENOMEM;
16738 
16739 	length = sizeof(struct lpfc_mbx_rq_create_v2);
16740 	length += ((2 * numrq * hrqp[0]->page_count) *
16741 		   sizeof(struct dma_address));
16742 
16743 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16744 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
16745 				    LPFC_SLI4_MBX_NEMBED);
16746 	if (alloclen < length) {
16747 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16748 				"3099 Allocated DMA memory size (%d) is "
16749 				"less than the requested DMA memory size "
16750 				"(%d)\n", alloclen, length);
16751 		status = -ENOMEM;
16752 		goto out;
16753 	}
16754 
16755 
16756 
16757 	rq_create = mbox->sge_array->addr[0];
16758 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
16759 
16760 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
16761 	cnt = 0;
16762 
16763 	for (idx = 0; idx < numrq; idx++) {
16764 		hrq = hrqp[idx];
16765 		drq = drqp[idx];
16766 		cq  = cqp[idx];
16767 
16768 		/* sanity check on queue memory */
16769 		if (!hrq || !drq || !cq) {
16770 			status = -ENODEV;
16771 			goto out;
16772 		}
16773 
16774 		if (hrq->entry_count != drq->entry_count) {
16775 			status = -EINVAL;
16776 			goto out;
16777 		}
16778 
16779 		if (idx == 0) {
16780 			bf_set(lpfc_mbx_rq_create_num_pages,
16781 			       &rq_create->u.request,
16782 			       hrq->page_count);
16783 			bf_set(lpfc_mbx_rq_create_rq_cnt,
16784 			       &rq_create->u.request, (numrq * 2));
16785 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
16786 			       1);
16787 			bf_set(lpfc_rq_context_base_cq,
16788 			       &rq_create->u.request.context,
16789 			       cq->queue_id);
16790 			bf_set(lpfc_rq_context_data_size,
16791 			       &rq_create->u.request.context,
16792 			       LPFC_NVMET_DATA_BUF_SIZE);
16793 			bf_set(lpfc_rq_context_hdr_size,
16794 			       &rq_create->u.request.context,
16795 			       LPFC_HDR_BUF_SIZE);
16796 			bf_set(lpfc_rq_context_rqe_count_1,
16797 			       &rq_create->u.request.context,
16798 			       hrq->entry_count);
16799 			bf_set(lpfc_rq_context_rqe_size,
16800 			       &rq_create->u.request.context,
16801 			       LPFC_RQE_SIZE_8);
16802 			bf_set(lpfc_rq_context_page_size,
16803 			       &rq_create->u.request.context,
16804 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
16805 		}
16806 		rc = 0;
16807 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
16808 			memset(dmabuf->virt, 0, hw_page_size);
16809 			cnt = page_idx + dmabuf->buffer_tag;
16810 			rq_create->u.request.page[cnt].addr_lo =
16811 					putPaddrLow(dmabuf->phys);
16812 			rq_create->u.request.page[cnt].addr_hi =
16813 					putPaddrHigh(dmabuf->phys);
16814 			rc++;
16815 		}
16816 		page_idx += rc;
16817 
16818 		rc = 0;
16819 		list_for_each_entry(dmabuf, &drq->page_list, list) {
16820 			memset(dmabuf->virt, 0, hw_page_size);
16821 			cnt = page_idx + dmabuf->buffer_tag;
16822 			rq_create->u.request.page[cnt].addr_lo =
16823 					putPaddrLow(dmabuf->phys);
16824 			rq_create->u.request.page[cnt].addr_hi =
16825 					putPaddrHigh(dmabuf->phys);
16826 			rc++;
16827 		}
16828 		page_idx += rc;
16829 
16830 		hrq->db_format = LPFC_DB_RING_FORMAT;
16831 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16832 		hrq->type = LPFC_HRQ;
16833 		hrq->assoc_qid = cq->queue_id;
16834 		hrq->subtype = subtype;
16835 		hrq->host_index = 0;
16836 		hrq->hba_index = 0;
16837 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16838 
16839 		drq->db_format = LPFC_DB_RING_FORMAT;
16840 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16841 		drq->type = LPFC_DRQ;
16842 		drq->assoc_qid = cq->queue_id;
16843 		drq->subtype = subtype;
16844 		drq->host_index = 0;
16845 		drq->hba_index = 0;
16846 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16847 
16848 		list_add_tail(&hrq->list, &cq->child_list);
16849 		list_add_tail(&drq->list, &cq->child_list);
16850 	}
16851 
16852 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16853 	/* The IOCTL status is embedded in the mailbox subheader. */
16854 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16855 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16856 	if (shdr_status || shdr_add_status || rc) {
16857 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16858 				"3120 RQ_CREATE mailbox failed with "
16859 				"status x%x add_status x%x, mbx status x%x\n",
16860 				shdr_status, shdr_add_status, rc);
16861 		status = -ENXIO;
16862 		goto out;
16863 	}
16864 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16865 	if (rc == 0xFFFF) {
16866 		status = -ENXIO;
16867 		goto out;
16868 	}
16869 
16870 	/* Initialize all RQs with associated queue id */
16871 	for (idx = 0; idx < numrq; idx++) {
16872 		hrq = hrqp[idx];
16873 		hrq->queue_id = rc + (2 * idx);
16874 		drq = drqp[idx];
16875 		drq->queue_id = rc + (2 * idx) + 1;
16876 	}
16877 
16878 out:
16879 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16880 	return status;
16881 }
16882 
16883 /**
16884  * lpfc_eq_destroy - Destroy an event Queue on the HBA
16885  * @phba: HBA structure that indicates port to destroy a queue on.
16886  * @eq: The queue structure associated with the queue to destroy.
16887  *
16888  * This function destroys a queue, as detailed in @eq by sending an mailbox
16889  * command, specific to the type of queue, to the HBA.
16890  *
16891  * The @eq struct is used to get the queue ID of the queue to destroy.
16892  *
16893  * On success this function will return a zero. If the queue destroy mailbox
16894  * command fails this function will return -ENXIO.
16895  **/
16896 int
16897 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
16898 {
16899 	LPFC_MBOXQ_t *mbox;
16900 	int rc, length, status = 0;
16901 	uint32_t shdr_status, shdr_add_status;
16902 	union lpfc_sli4_cfg_shdr *shdr;
16903 
16904 	/* sanity check on queue memory */
16905 	if (!eq)
16906 		return -ENODEV;
16907 
16908 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
16909 	if (!mbox)
16910 		return -ENOMEM;
16911 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
16912 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16913 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16914 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
16915 			 length, LPFC_SLI4_MBX_EMBED);
16916 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
16917 	       eq->queue_id);
16918 	mbox->vport = eq->phba->pport;
16919 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16920 
16921 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
16922 	/* The IOCTL status is embedded in the mailbox subheader. */
16923 	shdr = (union lpfc_sli4_cfg_shdr *)
16924 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
16925 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16926 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16927 	if (shdr_status || shdr_add_status || rc) {
16928 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16929 				"2505 EQ_DESTROY mailbox failed with "
16930 				"status x%x add_status x%x, mbx status x%x\n",
16931 				shdr_status, shdr_add_status, rc);
16932 		status = -ENXIO;
16933 	}
16934 
16935 	/* Remove eq from any list */
16936 	list_del_init(&eq->list);
16937 	mempool_free(mbox, eq->phba->mbox_mem_pool);
16938 	return status;
16939 }
16940 
16941 /**
16942  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
16943  * @phba: HBA structure that indicates port to destroy a queue on.
16944  * @cq: The queue structure associated with the queue to destroy.
16945  *
16946  * This function destroys a queue, as detailed in @cq by sending an mailbox
16947  * command, specific to the type of queue, to the HBA.
16948  *
16949  * The @cq struct is used to get the queue ID of the queue to destroy.
16950  *
16951  * On success this function will return a zero. If the queue destroy mailbox
16952  * command fails this function will return -ENXIO.
16953  **/
16954 int
16955 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
16956 {
16957 	LPFC_MBOXQ_t *mbox;
16958 	int rc, length, status = 0;
16959 	uint32_t shdr_status, shdr_add_status;
16960 	union lpfc_sli4_cfg_shdr *shdr;
16961 
16962 	/* sanity check on queue memory */
16963 	if (!cq)
16964 		return -ENODEV;
16965 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
16966 	if (!mbox)
16967 		return -ENOMEM;
16968 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
16969 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16970 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16971 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
16972 			 length, LPFC_SLI4_MBX_EMBED);
16973 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
16974 	       cq->queue_id);
16975 	mbox->vport = cq->phba->pport;
16976 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16977 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
16978 	/* The IOCTL status is embedded in the mailbox subheader. */
16979 	shdr = (union lpfc_sli4_cfg_shdr *)
16980 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
16981 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16982 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16983 	if (shdr_status || shdr_add_status || rc) {
16984 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16985 				"2506 CQ_DESTROY mailbox failed with "
16986 				"status x%x add_status x%x, mbx status x%x\n",
16987 				shdr_status, shdr_add_status, rc);
16988 		status = -ENXIO;
16989 	}
16990 	/* Remove cq from any list */
16991 	list_del_init(&cq->list);
16992 	mempool_free(mbox, cq->phba->mbox_mem_pool);
16993 	return status;
16994 }
16995 
16996 /**
16997  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
16998  * @phba: HBA structure that indicates port to destroy a queue on.
16999  * @mq: The queue structure associated with the queue to destroy.
17000  *
17001  * This function destroys a queue, as detailed in @mq by sending an mailbox
17002  * command, specific to the type of queue, to the HBA.
17003  *
17004  * The @mq struct is used to get the queue ID of the queue to destroy.
17005  *
17006  * On success this function will return a zero. If the queue destroy mailbox
17007  * command fails this function will return -ENXIO.
17008  **/
17009 int
17010 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
17011 {
17012 	LPFC_MBOXQ_t *mbox;
17013 	int rc, length, status = 0;
17014 	uint32_t shdr_status, shdr_add_status;
17015 	union lpfc_sli4_cfg_shdr *shdr;
17016 
17017 	/* sanity check on queue memory */
17018 	if (!mq)
17019 		return -ENODEV;
17020 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
17021 	if (!mbox)
17022 		return -ENOMEM;
17023 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
17024 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17025 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17026 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
17027 			 length, LPFC_SLI4_MBX_EMBED);
17028 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
17029 	       mq->queue_id);
17030 	mbox->vport = mq->phba->pport;
17031 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17032 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
17033 	/* The IOCTL status is embedded in the mailbox subheader. */
17034 	shdr = (union lpfc_sli4_cfg_shdr *)
17035 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
17036 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17037 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17038 	if (shdr_status || shdr_add_status || rc) {
17039 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17040 				"2507 MQ_DESTROY mailbox failed with "
17041 				"status x%x add_status x%x, mbx status x%x\n",
17042 				shdr_status, shdr_add_status, rc);
17043 		status = -ENXIO;
17044 	}
17045 	/* Remove mq from any list */
17046 	list_del_init(&mq->list);
17047 	mempool_free(mbox, mq->phba->mbox_mem_pool);
17048 	return status;
17049 }
17050 
17051 /**
17052  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
17053  * @phba: HBA structure that indicates port to destroy a queue on.
17054  * @wq: The queue structure associated with the queue to destroy.
17055  *
17056  * This function destroys a queue, as detailed in @wq by sending an mailbox
17057  * command, specific to the type of queue, to the HBA.
17058  *
17059  * The @wq struct is used to get the queue ID of the queue to destroy.
17060  *
17061  * On success this function will return a zero. If the queue destroy mailbox
17062  * command fails this function will return -ENXIO.
17063  **/
17064 int
17065 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
17066 {
17067 	LPFC_MBOXQ_t *mbox;
17068 	int rc, length, status = 0;
17069 	uint32_t shdr_status, shdr_add_status;
17070 	union lpfc_sli4_cfg_shdr *shdr;
17071 
17072 	/* sanity check on queue memory */
17073 	if (!wq)
17074 		return -ENODEV;
17075 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17076 	if (!mbox)
17077 		return -ENOMEM;
17078 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
17079 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17080 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17081 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17082 			 length, LPFC_SLI4_MBX_EMBED);
17083 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17084 	       wq->queue_id);
17085 	mbox->vport = wq->phba->pport;
17086 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17087 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17088 	shdr = (union lpfc_sli4_cfg_shdr *)
17089 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17090 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17091 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17092 	if (shdr_status || shdr_add_status || rc) {
17093 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17094 				"2508 WQ_DESTROY mailbox failed with "
17095 				"status x%x add_status x%x, mbx status x%x\n",
17096 				shdr_status, shdr_add_status, rc);
17097 		status = -ENXIO;
17098 	}
17099 	/* Remove wq from any list */
17100 	list_del_init(&wq->list);
17101 	kfree(wq->pring);
17102 	wq->pring = NULL;
17103 	mempool_free(mbox, wq->phba->mbox_mem_pool);
17104 	return status;
17105 }
17106 
17107 /**
17108  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17109  * @phba: HBA structure that indicates port to destroy a queue on.
17110  * @hrq: The queue structure associated with the queue to destroy.
17111  * @drq: The queue structure associated with the queue to destroy.
17112  *
17113  * This function destroys a queue, as detailed in @rq by sending an mailbox
17114  * command, specific to the type of queue, to the HBA.
17115  *
17116  * The @rq struct is used to get the queue ID of the queue to destroy.
17117  *
17118  * On success this function will return a zero. If the queue destroy mailbox
17119  * command fails this function will return -ENXIO.
17120  **/
17121 int
17122 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17123 		struct lpfc_queue *drq)
17124 {
17125 	LPFC_MBOXQ_t *mbox;
17126 	int rc, length, status = 0;
17127 	uint32_t shdr_status, shdr_add_status;
17128 	union lpfc_sli4_cfg_shdr *shdr;
17129 
17130 	/* sanity check on queue memory */
17131 	if (!hrq || !drq)
17132 		return -ENODEV;
17133 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17134 	if (!mbox)
17135 		return -ENOMEM;
17136 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
17137 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17138 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17139 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17140 			 length, LPFC_SLI4_MBX_EMBED);
17141 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17142 	       hrq->queue_id);
17143 	mbox->vport = hrq->phba->pport;
17144 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17145 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17146 	/* The IOCTL status is embedded in the mailbox subheader. */
17147 	shdr = (union lpfc_sli4_cfg_shdr *)
17148 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17149 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17150 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17151 	if (shdr_status || shdr_add_status || rc) {
17152 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17153 				"2509 RQ_DESTROY mailbox failed with "
17154 				"status x%x add_status x%x, mbx status x%x\n",
17155 				shdr_status, shdr_add_status, rc);
17156 		mempool_free(mbox, hrq->phba->mbox_mem_pool);
17157 		return -ENXIO;
17158 	}
17159 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17160 	       drq->queue_id);
17161 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17162 	shdr = (union lpfc_sli4_cfg_shdr *)
17163 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17164 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17165 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17166 	if (shdr_status || shdr_add_status || rc) {
17167 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17168 				"2510 RQ_DESTROY mailbox failed with "
17169 				"status x%x add_status x%x, mbx status x%x\n",
17170 				shdr_status, shdr_add_status, rc);
17171 		status = -ENXIO;
17172 	}
17173 	list_del_init(&hrq->list);
17174 	list_del_init(&drq->list);
17175 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
17176 	return status;
17177 }
17178 
17179 /**
17180  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17181  * @phba: The virtual port for which this call being executed.
17182  * @pdma_phys_addr0: Physical address of the 1st SGL page.
17183  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
17184  * @xritag: the xritag that ties this io to the SGL pages.
17185  *
17186  * This routine will post the sgl pages for the IO that has the xritag
17187  * that is in the iocbq structure. The xritag is assigned during iocbq
17188  * creation and persists for as long as the driver is loaded.
17189  * if the caller has fewer than 256 scatter gather segments to map then
17190  * pdma_phys_addr1 should be 0.
17191  * If the caller needs to map more than 256 scatter gather segment then
17192  * pdma_phys_addr1 should be a valid physical address.
17193  * physical address for SGLs must be 64 byte aligned.
17194  * If you are going to map 2 SGL's then the first one must have 256 entries
17195  * the second sgl can have between 1 and 256 entries.
17196  *
17197  * Return codes:
17198  * 	0 - Success
17199  * 	-ENXIO, -ENOMEM - Failure
17200  **/
17201 int
17202 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
17203 		dma_addr_t pdma_phys_addr0,
17204 		dma_addr_t pdma_phys_addr1,
17205 		uint16_t xritag)
17206 {
17207 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
17208 	LPFC_MBOXQ_t *mbox;
17209 	int rc;
17210 	uint32_t shdr_status, shdr_add_status;
17211 	uint32_t mbox_tmo;
17212 	union lpfc_sli4_cfg_shdr *shdr;
17213 
17214 	if (xritag == NO_XRI) {
17215 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17216 				"0364 Invalid param:\n");
17217 		return -EINVAL;
17218 	}
17219 
17220 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17221 	if (!mbox)
17222 		return -ENOMEM;
17223 
17224 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17225 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17226 			sizeof(struct lpfc_mbx_post_sgl_pages) -
17227 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17228 
17229 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
17230 				&mbox->u.mqe.un.post_sgl_pages;
17231 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
17232 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
17233 
17234 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
17235 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
17236 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
17237 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
17238 
17239 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
17240 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
17241 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
17242 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
17243 	if (!phba->sli4_hba.intr_enable)
17244 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17245 	else {
17246 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17247 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17248 	}
17249 	/* The IOCTL status is embedded in the mailbox subheader. */
17250 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
17251 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17252 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17253 	if (!phba->sli4_hba.intr_enable)
17254 		mempool_free(mbox, phba->mbox_mem_pool);
17255 	else if (rc != MBX_TIMEOUT)
17256 		mempool_free(mbox, phba->mbox_mem_pool);
17257 	if (shdr_status || shdr_add_status || rc) {
17258 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17259 				"2511 POST_SGL mailbox failed with "
17260 				"status x%x add_status x%x, mbx status x%x\n",
17261 				shdr_status, shdr_add_status, rc);
17262 	}
17263 	return 0;
17264 }
17265 
17266 /**
17267  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
17268  * @phba: pointer to lpfc hba data structure.
17269  *
17270  * This routine is invoked to post rpi header templates to the
17271  * HBA consistent with the SLI-4 interface spec.  This routine
17272  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
17273  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
17274  *
17275  * Returns
17276  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
17277  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
17278  **/
17279 static uint16_t
17280 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
17281 {
17282 	unsigned long xri;
17283 
17284 	/*
17285 	 * Fetch the next logical xri.  Because this index is logical,
17286 	 * the driver starts at 0 each time.
17287 	 */
17288 	spin_lock_irq(&phba->hbalock);
17289 	xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
17290 				 phba->sli4_hba.max_cfg_param.max_xri, 0);
17291 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
17292 		spin_unlock_irq(&phba->hbalock);
17293 		return NO_XRI;
17294 	} else {
17295 		set_bit(xri, phba->sli4_hba.xri_bmask);
17296 		phba->sli4_hba.max_cfg_param.xri_used++;
17297 	}
17298 	spin_unlock_irq(&phba->hbalock);
17299 	return xri;
17300 }
17301 
17302 /**
17303  * __lpfc_sli4_free_xri - Release an xri for reuse.
17304  * @phba: pointer to lpfc hba data structure.
17305  * @xri: xri to release.
17306  *
17307  * This routine is invoked to release an xri to the pool of
17308  * available rpis maintained by the driver.
17309  **/
17310 static void
17311 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
17312 {
17313 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
17314 		phba->sli4_hba.max_cfg_param.xri_used--;
17315 	}
17316 }
17317 
17318 /**
17319  * lpfc_sli4_free_xri - Release an xri for reuse.
17320  * @phba: pointer to lpfc hba data structure.
17321  * @xri: xri to release.
17322  *
17323  * This routine is invoked to release an xri to the pool of
17324  * available rpis maintained by the driver.
17325  **/
17326 void
17327 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
17328 {
17329 	spin_lock_irq(&phba->hbalock);
17330 	__lpfc_sli4_free_xri(phba, xri);
17331 	spin_unlock_irq(&phba->hbalock);
17332 }
17333 
17334 /**
17335  * lpfc_sli4_next_xritag - Get an xritag for the io
17336  * @phba: Pointer to HBA context object.
17337  *
17338  * This function gets an xritag for the iocb. If there is no unused xritag
17339  * it will return 0xffff.
17340  * The function returns the allocated xritag if successful, else returns zero.
17341  * Zero is not a valid xritag.
17342  * The caller is not required to hold any lock.
17343  **/
17344 uint16_t
17345 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
17346 {
17347 	uint16_t xri_index;
17348 
17349 	xri_index = lpfc_sli4_alloc_xri(phba);
17350 	if (xri_index == NO_XRI)
17351 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
17352 				"2004 Failed to allocate XRI.last XRITAG is %d"
17353 				" Max XRI is %d, Used XRI is %d\n",
17354 				xri_index,
17355 				phba->sli4_hba.max_cfg_param.max_xri,
17356 				phba->sli4_hba.max_cfg_param.xri_used);
17357 	return xri_index;
17358 }
17359 
17360 /**
17361  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
17362  * @phba: pointer to lpfc hba data structure.
17363  * @post_sgl_list: pointer to els sgl entry list.
17364  * @post_cnt: number of els sgl entries on the list.
17365  *
17366  * This routine is invoked to post a block of driver's sgl pages to the
17367  * HBA using non-embedded mailbox command. No Lock is held. This routine
17368  * is only called when the driver is loading and after all IO has been
17369  * stopped.
17370  **/
17371 static int
17372 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
17373 			    struct list_head *post_sgl_list,
17374 			    int post_cnt)
17375 {
17376 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
17377 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
17378 	struct sgl_page_pairs *sgl_pg_pairs;
17379 	void *viraddr;
17380 	LPFC_MBOXQ_t *mbox;
17381 	uint32_t reqlen, alloclen, pg_pairs;
17382 	uint32_t mbox_tmo;
17383 	uint16_t xritag_start = 0;
17384 	int rc = 0;
17385 	uint32_t shdr_status, shdr_add_status;
17386 	union lpfc_sli4_cfg_shdr *shdr;
17387 
17388 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
17389 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
17390 	if (reqlen > SLI4_PAGE_SIZE) {
17391 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17392 				"2559 Block sgl registration required DMA "
17393 				"size (%d) great than a page\n", reqlen);
17394 		return -ENOMEM;
17395 	}
17396 
17397 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17398 	if (!mbox)
17399 		return -ENOMEM;
17400 
17401 	/* Allocate DMA memory and set up the non-embedded mailbox command */
17402 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17403 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
17404 			 LPFC_SLI4_MBX_NEMBED);
17405 
17406 	if (alloclen < reqlen) {
17407 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17408 				"0285 Allocated DMA memory size (%d) is "
17409 				"less than the requested DMA memory "
17410 				"size (%d)\n", alloclen, reqlen);
17411 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17412 		return -ENOMEM;
17413 	}
17414 	/* Set up the SGL pages in the non-embedded DMA pages */
17415 	viraddr = mbox->sge_array->addr[0];
17416 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
17417 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
17418 
17419 	pg_pairs = 0;
17420 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
17421 		/* Set up the sge entry */
17422 		sgl_pg_pairs->sgl_pg0_addr_lo =
17423 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
17424 		sgl_pg_pairs->sgl_pg0_addr_hi =
17425 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
17426 		sgl_pg_pairs->sgl_pg1_addr_lo =
17427 				cpu_to_le32(putPaddrLow(0));
17428 		sgl_pg_pairs->sgl_pg1_addr_hi =
17429 				cpu_to_le32(putPaddrHigh(0));
17430 
17431 		/* Keep the first xritag on the list */
17432 		if (pg_pairs == 0)
17433 			xritag_start = sglq_entry->sli4_xritag;
17434 		sgl_pg_pairs++;
17435 		pg_pairs++;
17436 	}
17437 
17438 	/* Complete initialization and perform endian conversion. */
17439 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
17440 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
17441 	sgl->word0 = cpu_to_le32(sgl->word0);
17442 
17443 	if (!phba->sli4_hba.intr_enable)
17444 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17445 	else {
17446 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17447 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17448 	}
17449 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
17450 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17451 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17452 	if (!phba->sli4_hba.intr_enable)
17453 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17454 	else if (rc != MBX_TIMEOUT)
17455 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17456 	if (shdr_status || shdr_add_status || rc) {
17457 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17458 				"2513 POST_SGL_BLOCK mailbox command failed "
17459 				"status x%x add_status x%x mbx status x%x\n",
17460 				shdr_status, shdr_add_status, rc);
17461 		rc = -ENXIO;
17462 	}
17463 	return rc;
17464 }
17465 
17466 /**
17467  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
17468  * @phba: pointer to lpfc hba data structure.
17469  * @nblist: pointer to nvme buffer list.
17470  * @count: number of scsi buffers on the list.
17471  *
17472  * This routine is invoked to post a block of @count scsi sgl pages from a
17473  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
17474  * No Lock is held.
17475  *
17476  **/
17477 static int
17478 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
17479 			    int count)
17480 {
17481 	struct lpfc_io_buf *lpfc_ncmd;
17482 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
17483 	struct sgl_page_pairs *sgl_pg_pairs;
17484 	void *viraddr;
17485 	LPFC_MBOXQ_t *mbox;
17486 	uint32_t reqlen, alloclen, pg_pairs;
17487 	uint32_t mbox_tmo;
17488 	uint16_t xritag_start = 0;
17489 	int rc = 0;
17490 	uint32_t shdr_status, shdr_add_status;
17491 	dma_addr_t pdma_phys_bpl1;
17492 	union lpfc_sli4_cfg_shdr *shdr;
17493 
17494 	/* Calculate the requested length of the dma memory */
17495 	reqlen = count * sizeof(struct sgl_page_pairs) +
17496 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
17497 	if (reqlen > SLI4_PAGE_SIZE) {
17498 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
17499 				"6118 Block sgl registration required DMA "
17500 				"size (%d) great than a page\n", reqlen);
17501 		return -ENOMEM;
17502 	}
17503 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17504 	if (!mbox) {
17505 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17506 				"6119 Failed to allocate mbox cmd memory\n");
17507 		return -ENOMEM;
17508 	}
17509 
17510 	/* Allocate DMA memory and set up the non-embedded mailbox command */
17511 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17512 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17513 				    reqlen, LPFC_SLI4_MBX_NEMBED);
17514 
17515 	if (alloclen < reqlen) {
17516 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17517 				"6120 Allocated DMA memory size (%d) is "
17518 				"less than the requested DMA memory "
17519 				"size (%d)\n", alloclen, reqlen);
17520 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17521 		return -ENOMEM;
17522 	}
17523 
17524 	/* Get the first SGE entry from the non-embedded DMA memory */
17525 	viraddr = mbox->sge_array->addr[0];
17526 
17527 	/* Set up the SGL pages in the non-embedded DMA pages */
17528 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
17529 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
17530 
17531 	pg_pairs = 0;
17532 	list_for_each_entry(lpfc_ncmd, nblist, list) {
17533 		/* Set up the sge entry */
17534 		sgl_pg_pairs->sgl_pg0_addr_lo =
17535 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
17536 		sgl_pg_pairs->sgl_pg0_addr_hi =
17537 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
17538 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
17539 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
17540 						SGL_PAGE_SIZE;
17541 		else
17542 			pdma_phys_bpl1 = 0;
17543 		sgl_pg_pairs->sgl_pg1_addr_lo =
17544 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
17545 		sgl_pg_pairs->sgl_pg1_addr_hi =
17546 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
17547 		/* Keep the first xritag on the list */
17548 		if (pg_pairs == 0)
17549 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
17550 		sgl_pg_pairs++;
17551 		pg_pairs++;
17552 	}
17553 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
17554 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
17555 	/* Perform endian conversion if necessary */
17556 	sgl->word0 = cpu_to_le32(sgl->word0);
17557 
17558 	if (!phba->sli4_hba.intr_enable) {
17559 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17560 	} else {
17561 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17562 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17563 	}
17564 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
17565 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17566 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17567 	if (!phba->sli4_hba.intr_enable)
17568 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17569 	else if (rc != MBX_TIMEOUT)
17570 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17571 	if (shdr_status || shdr_add_status || rc) {
17572 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17573 				"6125 POST_SGL_BLOCK mailbox command failed "
17574 				"status x%x add_status x%x mbx status x%x\n",
17575 				shdr_status, shdr_add_status, rc);
17576 		rc = -ENXIO;
17577 	}
17578 	return rc;
17579 }
17580 
17581 /**
17582  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
17583  * @phba: pointer to lpfc hba data structure.
17584  * @post_nblist: pointer to the nvme buffer list.
17585  * @sb_count: number of nvme buffers.
17586  *
17587  * This routine walks a list of nvme buffers that was passed in. It attempts
17588  * to construct blocks of nvme buffer sgls which contains contiguous xris and
17589  * uses the non-embedded SGL block post mailbox commands to post to the port.
17590  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
17591  * embedded SGL post mailbox command for posting. The @post_nblist passed in
17592  * must be local list, thus no lock is needed when manipulate the list.
17593  *
17594  * Returns: 0 = failure, non-zero number of successfully posted buffers.
17595  **/
17596 int
17597 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
17598 			   struct list_head *post_nblist, int sb_count)
17599 {
17600 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
17601 	int status, sgl_size;
17602 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
17603 	dma_addr_t pdma_phys_sgl1;
17604 	int last_xritag = NO_XRI;
17605 	int cur_xritag;
17606 	LIST_HEAD(prep_nblist);
17607 	LIST_HEAD(blck_nblist);
17608 	LIST_HEAD(nvme_nblist);
17609 
17610 	/* sanity check */
17611 	if (sb_count <= 0)
17612 		return -EINVAL;
17613 
17614 	sgl_size = phba->cfg_sg_dma_buf_size;
17615 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
17616 		list_del_init(&lpfc_ncmd->list);
17617 		block_cnt++;
17618 		if ((last_xritag != NO_XRI) &&
17619 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
17620 			/* a hole in xri block, form a sgl posting block */
17621 			list_splice_init(&prep_nblist, &blck_nblist);
17622 			post_cnt = block_cnt - 1;
17623 			/* prepare list for next posting block */
17624 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17625 			block_cnt = 1;
17626 		} else {
17627 			/* prepare list for next posting block */
17628 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17629 			/* enough sgls for non-embed sgl mbox command */
17630 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
17631 				list_splice_init(&prep_nblist, &blck_nblist);
17632 				post_cnt = block_cnt;
17633 				block_cnt = 0;
17634 			}
17635 		}
17636 		num_posting++;
17637 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17638 
17639 		/* end of repost sgl list condition for NVME buffers */
17640 		if (num_posting == sb_count) {
17641 			if (post_cnt == 0) {
17642 				/* last sgl posting block */
17643 				list_splice_init(&prep_nblist, &blck_nblist);
17644 				post_cnt = block_cnt;
17645 			} else if (block_cnt == 1) {
17646 				/* last single sgl with non-contiguous xri */
17647 				if (sgl_size > SGL_PAGE_SIZE)
17648 					pdma_phys_sgl1 =
17649 						lpfc_ncmd->dma_phys_sgl +
17650 						SGL_PAGE_SIZE;
17651 				else
17652 					pdma_phys_sgl1 = 0;
17653 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17654 				status = lpfc_sli4_post_sgl(
17655 						phba, lpfc_ncmd->dma_phys_sgl,
17656 						pdma_phys_sgl1, cur_xritag);
17657 				if (status) {
17658 					/* Post error.  Buffer unavailable. */
17659 					lpfc_ncmd->flags |=
17660 						LPFC_SBUF_NOT_POSTED;
17661 				} else {
17662 					/* Post success. Bffer available. */
17663 					lpfc_ncmd->flags &=
17664 						~LPFC_SBUF_NOT_POSTED;
17665 					lpfc_ncmd->status = IOSTAT_SUCCESS;
17666 					num_posted++;
17667 				}
17668 				/* success, put on NVME buffer sgl list */
17669 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17670 			}
17671 		}
17672 
17673 		/* continue until a nembed page worth of sgls */
17674 		if (post_cnt == 0)
17675 			continue;
17676 
17677 		/* post block of NVME buffer list sgls */
17678 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
17679 						     post_cnt);
17680 
17681 		/* don't reset xirtag due to hole in xri block */
17682 		if (block_cnt == 0)
17683 			last_xritag = NO_XRI;
17684 
17685 		/* reset NVME buffer post count for next round of posting */
17686 		post_cnt = 0;
17687 
17688 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
17689 		while (!list_empty(&blck_nblist)) {
17690 			list_remove_head(&blck_nblist, lpfc_ncmd,
17691 					 struct lpfc_io_buf, list);
17692 			if (status) {
17693 				/* Post error.  Mark buffer unavailable. */
17694 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
17695 			} else {
17696 				/* Post success, Mark buffer available. */
17697 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
17698 				lpfc_ncmd->status = IOSTAT_SUCCESS;
17699 				num_posted++;
17700 			}
17701 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17702 		}
17703 	}
17704 	/* Push NVME buffers with sgl posted to the available list */
17705 	lpfc_io_buf_replenish(phba, &nvme_nblist);
17706 
17707 	return num_posted;
17708 }
17709 
17710 /**
17711  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
17712  * @phba: pointer to lpfc_hba struct that the frame was received on
17713  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17714  *
17715  * This function checks the fields in the @fc_hdr to see if the FC frame is a
17716  * valid type of frame that the LPFC driver will handle. This function will
17717  * return a zero if the frame is a valid frame or a non zero value when the
17718  * frame does not pass the check.
17719  **/
17720 static int
17721 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
17722 {
17723 	/*  make rctl_names static to save stack space */
17724 	struct fc_vft_header *fc_vft_hdr;
17725 	uint32_t *header = (uint32_t *) fc_hdr;
17726 
17727 #define FC_RCTL_MDS_DIAGS	0xF4
17728 
17729 	switch (fc_hdr->fh_r_ctl) {
17730 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
17731 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
17732 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
17733 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
17734 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
17735 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
17736 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
17737 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
17738 	case FC_RCTL_ELS_REQ:	/* extended link services request */
17739 	case FC_RCTL_ELS_REP:	/* extended link services reply */
17740 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
17741 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
17742 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
17743 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
17744 	case FC_RCTL_BA_RMC: 	/* remove connection */
17745 	case FC_RCTL_BA_ACC:	/* basic accept */
17746 	case FC_RCTL_BA_RJT:	/* basic reject */
17747 	case FC_RCTL_BA_PRMT:
17748 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
17749 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
17750 	case FC_RCTL_P_RJT:	/* port reject */
17751 	case FC_RCTL_F_RJT:	/* fabric reject */
17752 	case FC_RCTL_P_BSY:	/* port busy */
17753 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
17754 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
17755 	case FC_RCTL_LCR:	/* link credit reset */
17756 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
17757 	case FC_RCTL_END:	/* end */
17758 		break;
17759 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
17760 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17761 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
17762 		return lpfc_fc_frame_check(phba, fc_hdr);
17763 	default:
17764 		goto drop;
17765 	}
17766 
17767 	switch (fc_hdr->fh_type) {
17768 	case FC_TYPE_BLS:
17769 	case FC_TYPE_ELS:
17770 	case FC_TYPE_FCP:
17771 	case FC_TYPE_CT:
17772 	case FC_TYPE_NVME:
17773 		break;
17774 	case FC_TYPE_IP:
17775 	case FC_TYPE_ILS:
17776 	default:
17777 		goto drop;
17778 	}
17779 
17780 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
17781 			"2538 Received frame rctl:x%x, type:x%x, "
17782 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
17783 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
17784 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
17785 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
17786 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
17787 			be32_to_cpu(header[6]));
17788 	return 0;
17789 drop:
17790 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
17791 			"2539 Dropped frame rctl:x%x type:x%x\n",
17792 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17793 	return 1;
17794 }
17795 
17796 /**
17797  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
17798  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17799  *
17800  * This function processes the FC header to retrieve the VFI from the VF
17801  * header, if one exists. This function will return the VFI if one exists
17802  * or 0 if no VSAN Header exists.
17803  **/
17804 static uint32_t
17805 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
17806 {
17807 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17808 
17809 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
17810 		return 0;
17811 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
17812 }
17813 
17814 /**
17815  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
17816  * @phba: Pointer to the HBA structure to search for the vport on
17817  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17818  * @fcfi: The FC Fabric ID that the frame came from
17819  * @did: Destination ID to match against
17820  *
17821  * This function searches the @phba for a vport that matches the content of the
17822  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
17823  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
17824  * returns the matching vport pointer or NULL if unable to match frame to a
17825  * vport.
17826  **/
17827 static struct lpfc_vport *
17828 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
17829 		       uint16_t fcfi, uint32_t did)
17830 {
17831 	struct lpfc_vport **vports;
17832 	struct lpfc_vport *vport = NULL;
17833 	int i;
17834 
17835 	if (did == Fabric_DID)
17836 		return phba->pport;
17837 	if ((phba->pport->fc_flag & FC_PT2PT) &&
17838 		!(phba->link_state == LPFC_HBA_READY))
17839 		return phba->pport;
17840 
17841 	vports = lpfc_create_vport_work_array(phba);
17842 	if (vports != NULL) {
17843 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
17844 			if (phba->fcf.fcfi == fcfi &&
17845 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
17846 			    vports[i]->fc_myDID == did) {
17847 				vport = vports[i];
17848 				break;
17849 			}
17850 		}
17851 	}
17852 	lpfc_destroy_vport_work_array(phba, vports);
17853 	return vport;
17854 }
17855 
17856 /**
17857  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
17858  * @vport: The vport to work on.
17859  *
17860  * This function updates the receive sequence time stamp for this vport. The
17861  * receive sequence time stamp indicates the time that the last frame of the
17862  * the sequence that has been idle for the longest amount of time was received.
17863  * the driver uses this time stamp to indicate if any received sequences have
17864  * timed out.
17865  **/
17866 static void
17867 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
17868 {
17869 	struct lpfc_dmabuf *h_buf;
17870 	struct hbq_dmabuf *dmabuf = NULL;
17871 
17872 	/* get the oldest sequence on the rcv list */
17873 	h_buf = list_get_first(&vport->rcv_buffer_list,
17874 			       struct lpfc_dmabuf, list);
17875 	if (!h_buf)
17876 		return;
17877 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17878 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
17879 }
17880 
17881 /**
17882  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
17883  * @vport: The vport that the received sequences were sent to.
17884  *
17885  * This function cleans up all outstanding received sequences. This is called
17886  * by the driver when a link event or user action invalidates all the received
17887  * sequences.
17888  **/
17889 void
17890 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
17891 {
17892 	struct lpfc_dmabuf *h_buf, *hnext;
17893 	struct lpfc_dmabuf *d_buf, *dnext;
17894 	struct hbq_dmabuf *dmabuf = NULL;
17895 
17896 	/* start with the oldest sequence on the rcv list */
17897 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17898 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17899 		list_del_init(&dmabuf->hbuf.list);
17900 		list_for_each_entry_safe(d_buf, dnext,
17901 					 &dmabuf->dbuf.list, list) {
17902 			list_del_init(&d_buf->list);
17903 			lpfc_in_buf_free(vport->phba, d_buf);
17904 		}
17905 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17906 	}
17907 }
17908 
17909 /**
17910  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
17911  * @vport: The vport that the received sequences were sent to.
17912  *
17913  * This function determines whether any received sequences have timed out by
17914  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
17915  * indicates that there is at least one timed out sequence this routine will
17916  * go through the received sequences one at a time from most inactive to most
17917  * active to determine which ones need to be cleaned up. Once it has determined
17918  * that a sequence needs to be cleaned up it will simply free up the resources
17919  * without sending an abort.
17920  **/
17921 void
17922 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
17923 {
17924 	struct lpfc_dmabuf *h_buf, *hnext;
17925 	struct lpfc_dmabuf *d_buf, *dnext;
17926 	struct hbq_dmabuf *dmabuf = NULL;
17927 	unsigned long timeout;
17928 	int abort_count = 0;
17929 
17930 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17931 		   vport->rcv_buffer_time_stamp);
17932 	if (list_empty(&vport->rcv_buffer_list) ||
17933 	    time_before(jiffies, timeout))
17934 		return;
17935 	/* start with the oldest sequence on the rcv list */
17936 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17937 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17938 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17939 			   dmabuf->time_stamp);
17940 		if (time_before(jiffies, timeout))
17941 			break;
17942 		abort_count++;
17943 		list_del_init(&dmabuf->hbuf.list);
17944 		list_for_each_entry_safe(d_buf, dnext,
17945 					 &dmabuf->dbuf.list, list) {
17946 			list_del_init(&d_buf->list);
17947 			lpfc_in_buf_free(vport->phba, d_buf);
17948 		}
17949 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17950 	}
17951 	if (abort_count)
17952 		lpfc_update_rcv_time_stamp(vport);
17953 }
17954 
17955 /**
17956  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
17957  * @vport: pointer to a vitural port
17958  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
17959  *
17960  * This function searches through the existing incomplete sequences that have
17961  * been sent to this @vport. If the frame matches one of the incomplete
17962  * sequences then the dbuf in the @dmabuf is added to the list of frames that
17963  * make up that sequence. If no sequence is found that matches this frame then
17964  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
17965  * This function returns a pointer to the first dmabuf in the sequence list that
17966  * the frame was linked to.
17967  **/
17968 static struct hbq_dmabuf *
17969 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
17970 {
17971 	struct fc_frame_header *new_hdr;
17972 	struct fc_frame_header *temp_hdr;
17973 	struct lpfc_dmabuf *d_buf;
17974 	struct lpfc_dmabuf *h_buf;
17975 	struct hbq_dmabuf *seq_dmabuf = NULL;
17976 	struct hbq_dmabuf *temp_dmabuf = NULL;
17977 	uint8_t	found = 0;
17978 
17979 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
17980 	dmabuf->time_stamp = jiffies;
17981 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17982 
17983 	/* Use the hdr_buf to find the sequence that this frame belongs to */
17984 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
17985 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
17986 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
17987 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
17988 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
17989 			continue;
17990 		/* found a pending sequence that matches this frame */
17991 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17992 		break;
17993 	}
17994 	if (!seq_dmabuf) {
17995 		/*
17996 		 * This indicates first frame received for this sequence.
17997 		 * Queue the buffer on the vport's rcv_buffer_list.
17998 		 */
17999 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18000 		lpfc_update_rcv_time_stamp(vport);
18001 		return dmabuf;
18002 	}
18003 	temp_hdr = seq_dmabuf->hbuf.virt;
18004 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
18005 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18006 		list_del_init(&seq_dmabuf->hbuf.list);
18007 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18008 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18009 		lpfc_update_rcv_time_stamp(vport);
18010 		return dmabuf;
18011 	}
18012 	/* move this sequence to the tail to indicate a young sequence */
18013 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
18014 	seq_dmabuf->time_stamp = jiffies;
18015 	lpfc_update_rcv_time_stamp(vport);
18016 	if (list_empty(&seq_dmabuf->dbuf.list)) {
18017 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18018 		return seq_dmabuf;
18019 	}
18020 	/* find the correct place in the sequence to insert this frame */
18021 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
18022 	while (!found) {
18023 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18024 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
18025 		/*
18026 		 * If the frame's sequence count is greater than the frame on
18027 		 * the list then insert the frame right after this frame
18028 		 */
18029 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
18030 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18031 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
18032 			found = 1;
18033 			break;
18034 		}
18035 
18036 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
18037 			break;
18038 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
18039 	}
18040 
18041 	if (found)
18042 		return seq_dmabuf;
18043 	return NULL;
18044 }
18045 
18046 /**
18047  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
18048  * @vport: pointer to a vitural port
18049  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18050  *
18051  * This function tries to abort from the partially assembed sequence, described
18052  * by the information from basic abbort @dmabuf. It checks to see whether such
18053  * partially assembled sequence held by the driver. If so, it shall free up all
18054  * the frames from the partially assembled sequence.
18055  *
18056  * Return
18057  * true  -- if there is matching partially assembled sequence present and all
18058  *          the frames freed with the sequence;
18059  * false -- if there is no matching partially assembled sequence present so
18060  *          nothing got aborted in the lower layer driver
18061  **/
18062 static bool
18063 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
18064 			    struct hbq_dmabuf *dmabuf)
18065 {
18066 	struct fc_frame_header *new_hdr;
18067 	struct fc_frame_header *temp_hdr;
18068 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
18069 	struct hbq_dmabuf *seq_dmabuf = NULL;
18070 
18071 	/* Use the hdr_buf to find the sequence that matches this frame */
18072 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18073 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
18074 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18075 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18076 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18077 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18078 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18079 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18080 			continue;
18081 		/* found a pending sequence that matches this frame */
18082 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18083 		break;
18084 	}
18085 
18086 	/* Free up all the frames from the partially assembled sequence */
18087 	if (seq_dmabuf) {
18088 		list_for_each_entry_safe(d_buf, n_buf,
18089 					 &seq_dmabuf->dbuf.list, list) {
18090 			list_del_init(&d_buf->list);
18091 			lpfc_in_buf_free(vport->phba, d_buf);
18092 		}
18093 		return true;
18094 	}
18095 	return false;
18096 }
18097 
18098 /**
18099  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18100  * @vport: pointer to a vitural port
18101  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18102  *
18103  * This function tries to abort from the assembed sequence from upper level
18104  * protocol, described by the information from basic abbort @dmabuf. It
18105  * checks to see whether such pending context exists at upper level protocol.
18106  * If so, it shall clean up the pending context.
18107  *
18108  * Return
18109  * true  -- if there is matching pending context of the sequence cleaned
18110  *          at ulp;
18111  * false -- if there is no matching pending context of the sequence present
18112  *          at ulp.
18113  **/
18114 static bool
18115 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18116 {
18117 	struct lpfc_hba *phba = vport->phba;
18118 	int handled;
18119 
18120 	/* Accepting abort at ulp with SLI4 only */
18121 	if (phba->sli_rev < LPFC_SLI_REV4)
18122 		return false;
18123 
18124 	/* Register all caring upper level protocols to attend abort */
18125 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18126 	if (handled)
18127 		return true;
18128 
18129 	return false;
18130 }
18131 
18132 /**
18133  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18134  * @phba: Pointer to HBA context object.
18135  * @cmd_iocbq: pointer to the command iocbq structure.
18136  * @rsp_iocbq: pointer to the response iocbq structure.
18137  *
18138  * This function handles the sequence abort response iocb command complete
18139  * event. It properly releases the memory allocated to the sequence abort
18140  * accept iocb.
18141  **/
18142 static void
18143 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18144 			     struct lpfc_iocbq *cmd_iocbq,
18145 			     struct lpfc_iocbq *rsp_iocbq)
18146 {
18147 	struct lpfc_nodelist *ndlp;
18148 
18149 	if (cmd_iocbq) {
18150 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
18151 		lpfc_nlp_put(ndlp);
18152 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
18153 	}
18154 
18155 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
18156 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18157 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18158 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
18159 			rsp_iocbq->iocb.ulpStatus,
18160 			rsp_iocbq->iocb.un.ulpWord[4]);
18161 }
18162 
18163 /**
18164  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
18165  * @phba: Pointer to HBA context object.
18166  * @xri: xri id in transaction.
18167  *
18168  * This function validates the xri maps to the known range of XRIs allocated an
18169  * used by the driver.
18170  **/
18171 uint16_t
18172 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
18173 		      uint16_t xri)
18174 {
18175 	uint16_t i;
18176 
18177 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
18178 		if (xri == phba->sli4_hba.xri_ids[i])
18179 			return i;
18180 	}
18181 	return NO_XRI;
18182 }
18183 
18184 /**
18185  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
18186  * @vport: pointer to a virtual port.
18187  * @fc_hdr: pointer to a FC frame header.
18188  * @aborted: was the partially assembled receive sequence successfully aborted
18189  *
18190  * This function sends a basic response to a previous unsol sequence abort
18191  * event after aborting the sequence handling.
18192  **/
18193 void
18194 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
18195 			struct fc_frame_header *fc_hdr, bool aborted)
18196 {
18197 	struct lpfc_hba *phba = vport->phba;
18198 	struct lpfc_iocbq *ctiocb = NULL;
18199 	struct lpfc_nodelist *ndlp;
18200 	uint16_t oxid, rxid, xri, lxri;
18201 	uint32_t sid, fctl;
18202 	IOCB_t *icmd;
18203 	int rc;
18204 
18205 	if (!lpfc_is_link_up(phba))
18206 		return;
18207 
18208 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18209 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
18210 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
18211 
18212 	ndlp = lpfc_findnode_did(vport, sid);
18213 	if (!ndlp) {
18214 		ndlp = lpfc_nlp_init(vport, sid);
18215 		if (!ndlp) {
18216 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
18217 					 "1268 Failed to allocate ndlp for "
18218 					 "oxid:x%x SID:x%x\n", oxid, sid);
18219 			return;
18220 		}
18221 		/* Put ndlp onto pport node list */
18222 		lpfc_enqueue_node(vport, ndlp);
18223 	}
18224 
18225 	/* Allocate buffer for rsp iocb */
18226 	ctiocb = lpfc_sli_get_iocbq(phba);
18227 	if (!ctiocb)
18228 		return;
18229 
18230 	/* Extract the F_CTL field from FC_HDR */
18231 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
18232 
18233 	icmd = &ctiocb->iocb;
18234 	icmd->un.xseq64.bdl.bdeSize = 0;
18235 	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
18236 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
18237 	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
18238 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
18239 
18240 	/* Fill in the rest of iocb fields */
18241 	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
18242 	icmd->ulpBdeCount = 0;
18243 	icmd->ulpLe = 1;
18244 	icmd->ulpClass = CLASS3;
18245 	icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
18246 	ctiocb->context1 = lpfc_nlp_get(ndlp);
18247 	if (!ctiocb->context1) {
18248 		lpfc_sli_release_iocbq(phba, ctiocb);
18249 		return;
18250 	}
18251 
18252 	ctiocb->vport = phba->pport;
18253 	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
18254 	ctiocb->sli4_lxritag = NO_XRI;
18255 	ctiocb->sli4_xritag = NO_XRI;
18256 
18257 	if (fctl & FC_FC_EX_CTX)
18258 		/* Exchange responder sent the abort so we
18259 		 * own the oxid.
18260 		 */
18261 		xri = oxid;
18262 	else
18263 		xri = rxid;
18264 	lxri = lpfc_sli4_xri_inrange(phba, xri);
18265 	if (lxri != NO_XRI)
18266 		lpfc_set_rrq_active(phba, ndlp, lxri,
18267 			(xri == oxid) ? rxid : oxid, 0);
18268 	/* For BA_ABTS from exchange responder, if the logical xri with
18269 	 * the oxid maps to the FCP XRI range, the port no longer has
18270 	 * that exchange context, send a BLS_RJT. Override the IOCB for
18271 	 * a BA_RJT.
18272 	 */
18273 	if ((fctl & FC_FC_EX_CTX) &&
18274 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
18275 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
18276 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
18277 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
18278 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
18279 	}
18280 
18281 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
18282 	 * the driver no longer has that exchange, send a BLS_RJT. Override
18283 	 * the IOCB for a BA_RJT.
18284 	 */
18285 	if (aborted == false) {
18286 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
18287 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
18288 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
18289 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
18290 	}
18291 
18292 	if (fctl & FC_FC_EX_CTX) {
18293 		/* ABTS sent by responder to CT exchange, construction
18294 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
18295 		 * field and RX_ID from ABTS for RX_ID field.
18296 		 */
18297 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
18298 	} else {
18299 		/* ABTS sent by initiator to CT exchange, construction
18300 		 * of BA_ACC will need to allocate a new XRI as for the
18301 		 * XRI_TAG field.
18302 		 */
18303 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
18304 	}
18305 	bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
18306 	bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
18307 
18308 	/* Xmit CT abts response on exchange <xid> */
18309 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
18310 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
18311 			 icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
18312 
18313 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
18314 	if (rc == IOCB_ERROR) {
18315 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
18316 				 "2925 Failed to issue CT ABTS RSP x%x on "
18317 				 "xri x%x, Data x%x\n",
18318 				 icmd->un.xseq64.w5.hcsw.Rctl, oxid,
18319 				 phba->link_state);
18320 		lpfc_nlp_put(ndlp);
18321 		ctiocb->context1 = NULL;
18322 		lpfc_sli_release_iocbq(phba, ctiocb);
18323 	}
18324 }
18325 
18326 /**
18327  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
18328  * @vport: Pointer to the vport on which this sequence was received
18329  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18330  *
18331  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
18332  * receive sequence is only partially assembed by the driver, it shall abort
18333  * the partially assembled frames for the sequence. Otherwise, if the
18334  * unsolicited receive sequence has been completely assembled and passed to
18335  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
18336  * unsolicited sequence has been aborted. After that, it will issue a basic
18337  * accept to accept the abort.
18338  **/
18339 static void
18340 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
18341 			     struct hbq_dmabuf *dmabuf)
18342 {
18343 	struct lpfc_hba *phba = vport->phba;
18344 	struct fc_frame_header fc_hdr;
18345 	uint32_t fctl;
18346 	bool aborted;
18347 
18348 	/* Make a copy of fc_hdr before the dmabuf being released */
18349 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
18350 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
18351 
18352 	if (fctl & FC_FC_EX_CTX) {
18353 		/* ABTS by responder to exchange, no cleanup needed */
18354 		aborted = true;
18355 	} else {
18356 		/* ABTS by initiator to exchange, need to do cleanup */
18357 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
18358 		if (aborted == false)
18359 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
18360 	}
18361 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18362 
18363 	if (phba->nvmet_support) {
18364 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
18365 		return;
18366 	}
18367 
18368 	/* Respond with BA_ACC or BA_RJT accordingly */
18369 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
18370 }
18371 
18372 /**
18373  * lpfc_seq_complete - Indicates if a sequence is complete
18374  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18375  *
18376  * This function checks the sequence, starting with the frame described by
18377  * @dmabuf, to see if all the frames associated with this sequence are present.
18378  * the frames associated with this sequence are linked to the @dmabuf using the
18379  * dbuf list. This function looks for two major things. 1) That the first frame
18380  * has a sequence count of zero. 2) There is a frame with last frame of sequence
18381  * set. 3) That there are no holes in the sequence count. The function will
18382  * return 1 when the sequence is complete, otherwise it will return 0.
18383  **/
18384 static int
18385 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
18386 {
18387 	struct fc_frame_header *hdr;
18388 	struct lpfc_dmabuf *d_buf;
18389 	struct hbq_dmabuf *seq_dmabuf;
18390 	uint32_t fctl;
18391 	int seq_count = 0;
18392 
18393 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18394 	/* make sure first fame of sequence has a sequence count of zero */
18395 	if (hdr->fh_seq_cnt != seq_count)
18396 		return 0;
18397 	fctl = (hdr->fh_f_ctl[0] << 16 |
18398 		hdr->fh_f_ctl[1] << 8 |
18399 		hdr->fh_f_ctl[2]);
18400 	/* If last frame of sequence we can return success. */
18401 	if (fctl & FC_FC_END_SEQ)
18402 		return 1;
18403 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
18404 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18405 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18406 		/* If there is a hole in the sequence count then fail. */
18407 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
18408 			return 0;
18409 		fctl = (hdr->fh_f_ctl[0] << 16 |
18410 			hdr->fh_f_ctl[1] << 8 |
18411 			hdr->fh_f_ctl[2]);
18412 		/* If last frame of sequence we can return success. */
18413 		if (fctl & FC_FC_END_SEQ)
18414 			return 1;
18415 	}
18416 	return 0;
18417 }
18418 
18419 /**
18420  * lpfc_prep_seq - Prep sequence for ULP processing
18421  * @vport: Pointer to the vport on which this sequence was received
18422  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
18423  *
18424  * This function takes a sequence, described by a list of frames, and creates
18425  * a list of iocbq structures to describe the sequence. This iocbq list will be
18426  * used to issue to the generic unsolicited sequence handler. This routine
18427  * returns a pointer to the first iocbq in the list. If the function is unable
18428  * to allocate an iocbq then it throw out the received frames that were not
18429  * able to be described and return a pointer to the first iocbq. If unable to
18430  * allocate any iocbqs (including the first) this function will return NULL.
18431  **/
18432 static struct lpfc_iocbq *
18433 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
18434 {
18435 	struct hbq_dmabuf *hbq_buf;
18436 	struct lpfc_dmabuf *d_buf, *n_buf;
18437 	struct lpfc_iocbq *first_iocbq, *iocbq;
18438 	struct fc_frame_header *fc_hdr;
18439 	uint32_t sid;
18440 	uint32_t len, tot_len;
18441 	struct ulp_bde64 *pbde;
18442 
18443 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18444 	/* remove from receive buffer list */
18445 	list_del_init(&seq_dmabuf->hbuf.list);
18446 	lpfc_update_rcv_time_stamp(vport);
18447 	/* get the Remote Port's SID */
18448 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18449 	tot_len = 0;
18450 	/* Get an iocbq struct to fill in. */
18451 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
18452 	if (first_iocbq) {
18453 		/* Initialize the first IOCB. */
18454 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
18455 		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
18456 		first_iocbq->vport = vport;
18457 
18458 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
18459 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
18460 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
18461 			first_iocbq->iocb.un.rcvels.parmRo =
18462 				sli4_did_from_fc_hdr(fc_hdr);
18463 			first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
18464 		} else
18465 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
18466 		first_iocbq->iocb.ulpContext = NO_XRI;
18467 		first_iocbq->iocb.unsli3.rcvsli3.ox_id =
18468 			be16_to_cpu(fc_hdr->fh_ox_id);
18469 		/* iocbq is prepped for internal consumption.  Physical vpi. */
18470 		first_iocbq->iocb.unsli3.rcvsli3.vpi =
18471 			vport->phba->vpi_ids[vport->vpi];
18472 		/* put the first buffer into the first IOCBq */
18473 		tot_len = bf_get(lpfc_rcqe_length,
18474 				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
18475 
18476 		first_iocbq->context2 = &seq_dmabuf->dbuf;
18477 		first_iocbq->context3 = NULL;
18478 		first_iocbq->iocb.ulpBdeCount = 1;
18479 		if (tot_len > LPFC_DATA_BUF_SIZE)
18480 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
18481 							LPFC_DATA_BUF_SIZE;
18482 		else
18483 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
18484 
18485 		first_iocbq->iocb.un.rcvels.remoteID = sid;
18486 
18487 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
18488 	}
18489 	iocbq = first_iocbq;
18490 	/*
18491 	 * Each IOCBq can have two Buffers assigned, so go through the list
18492 	 * of buffers for this sequence and save two buffers in each IOCBq
18493 	 */
18494 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
18495 		if (!iocbq) {
18496 			lpfc_in_buf_free(vport->phba, d_buf);
18497 			continue;
18498 		}
18499 		if (!iocbq->context3) {
18500 			iocbq->context3 = d_buf;
18501 			iocbq->iocb.ulpBdeCount++;
18502 			/* We need to get the size out of the right CQE */
18503 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18504 			len = bf_get(lpfc_rcqe_length,
18505 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
18506 			pbde = (struct ulp_bde64 *)
18507 					&iocbq->iocb.unsli3.sli3Words[4];
18508 			if (len > LPFC_DATA_BUF_SIZE)
18509 				pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
18510 			else
18511 				pbde->tus.f.bdeSize = len;
18512 
18513 			iocbq->iocb.unsli3.rcvsli3.acc_len += len;
18514 			tot_len += len;
18515 		} else {
18516 			iocbq = lpfc_sli_get_iocbq(vport->phba);
18517 			if (!iocbq) {
18518 				if (first_iocbq) {
18519 					first_iocbq->iocb.ulpStatus =
18520 							IOSTAT_FCP_RSP_ERROR;
18521 					first_iocbq->iocb.un.ulpWord[4] =
18522 							IOERR_NO_RESOURCES;
18523 				}
18524 				lpfc_in_buf_free(vport->phba, d_buf);
18525 				continue;
18526 			}
18527 			/* We need to get the size out of the right CQE */
18528 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18529 			len = bf_get(lpfc_rcqe_length,
18530 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
18531 			iocbq->context2 = d_buf;
18532 			iocbq->context3 = NULL;
18533 			iocbq->iocb.ulpBdeCount = 1;
18534 			if (len > LPFC_DATA_BUF_SIZE)
18535 				iocbq->iocb.un.cont64[0].tus.f.bdeSize =
18536 							LPFC_DATA_BUF_SIZE;
18537 			else
18538 				iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
18539 
18540 			tot_len += len;
18541 			iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
18542 
18543 			iocbq->iocb.un.rcvels.remoteID = sid;
18544 			list_add_tail(&iocbq->list, &first_iocbq->list);
18545 		}
18546 	}
18547 	/* Free the sequence's header buffer */
18548 	if (!first_iocbq)
18549 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
18550 
18551 	return first_iocbq;
18552 }
18553 
18554 static void
18555 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
18556 			  struct hbq_dmabuf *seq_dmabuf)
18557 {
18558 	struct fc_frame_header *fc_hdr;
18559 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
18560 	struct lpfc_hba *phba = vport->phba;
18561 
18562 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18563 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
18564 	if (!iocbq) {
18565 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18566 				"2707 Ring %d handler: Failed to allocate "
18567 				"iocb Rctl x%x Type x%x received\n",
18568 				LPFC_ELS_RING,
18569 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18570 		return;
18571 	}
18572 	if (!lpfc_complete_unsol_iocb(phba,
18573 				      phba->sli4_hba.els_wq->pring,
18574 				      iocbq, fc_hdr->fh_r_ctl,
18575 				      fc_hdr->fh_type))
18576 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18577 				"2540 Ring %d handler: unexpected Rctl "
18578 				"x%x Type x%x received\n",
18579 				LPFC_ELS_RING,
18580 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18581 
18582 	/* Free iocb created in lpfc_prep_seq */
18583 	list_for_each_entry_safe(curr_iocb, next_iocb,
18584 		&iocbq->list, list) {
18585 		list_del_init(&curr_iocb->list);
18586 		lpfc_sli_release_iocbq(phba, curr_iocb);
18587 	}
18588 	lpfc_sli_release_iocbq(phba, iocbq);
18589 }
18590 
18591 static void
18592 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
18593 			    struct lpfc_iocbq *rspiocb)
18594 {
18595 	struct lpfc_dmabuf *pcmd = cmdiocb->context2;
18596 
18597 	if (pcmd && pcmd->virt)
18598 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18599 	kfree(pcmd);
18600 	lpfc_sli_release_iocbq(phba, cmdiocb);
18601 	lpfc_drain_txq(phba);
18602 }
18603 
18604 static void
18605 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
18606 			      struct hbq_dmabuf *dmabuf)
18607 {
18608 	struct fc_frame_header *fc_hdr;
18609 	struct lpfc_hba *phba = vport->phba;
18610 	struct lpfc_iocbq *iocbq = NULL;
18611 	union  lpfc_wqe *wqe;
18612 	struct lpfc_dmabuf *pcmd = NULL;
18613 	uint32_t frame_len;
18614 	int rc;
18615 	unsigned long iflags;
18616 
18617 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18618 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
18619 
18620 	/* Send the received frame back */
18621 	iocbq = lpfc_sli_get_iocbq(phba);
18622 	if (!iocbq) {
18623 		/* Queue cq event and wakeup worker thread to process it */
18624 		spin_lock_irqsave(&phba->hbalock, iflags);
18625 		list_add_tail(&dmabuf->cq_event.list,
18626 			      &phba->sli4_hba.sp_queue_event);
18627 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
18628 		spin_unlock_irqrestore(&phba->hbalock, iflags);
18629 		lpfc_worker_wake_up(phba);
18630 		return;
18631 	}
18632 
18633 	/* Allocate buffer for command payload */
18634 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
18635 	if (pcmd)
18636 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
18637 					    &pcmd->phys);
18638 	if (!pcmd || !pcmd->virt)
18639 		goto exit;
18640 
18641 	INIT_LIST_HEAD(&pcmd->list);
18642 
18643 	/* copyin the payload */
18644 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
18645 
18646 	/* fill in BDE's for command */
18647 	iocbq->iocb.un.xseq64.bdl.addrHigh = putPaddrHigh(pcmd->phys);
18648 	iocbq->iocb.un.xseq64.bdl.addrLow = putPaddrLow(pcmd->phys);
18649 	iocbq->iocb.un.xseq64.bdl.bdeFlags = BUFF_TYPE_BDE_64;
18650 	iocbq->iocb.un.xseq64.bdl.bdeSize = frame_len;
18651 
18652 	iocbq->context2 = pcmd;
18653 	iocbq->vport = vport;
18654 	iocbq->iocb_flag &= ~LPFC_FIP_ELS_ID_MASK;
18655 	iocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
18656 
18657 	/*
18658 	 * Setup rest of the iocb as though it were a WQE
18659 	 * Build the SEND_FRAME WQE
18660 	 */
18661 	wqe = (union lpfc_wqe *)&iocbq->iocb;
18662 
18663 	wqe->send_frame.frame_len = frame_len;
18664 	wqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((uint32_t *)fc_hdr));
18665 	wqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((uint32_t *)fc_hdr + 1));
18666 	wqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((uint32_t *)fc_hdr + 2));
18667 	wqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((uint32_t *)fc_hdr + 3));
18668 	wqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((uint32_t *)fc_hdr + 4));
18669 	wqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((uint32_t *)fc_hdr + 5));
18670 
18671 	iocbq->iocb.ulpCommand = CMD_SEND_FRAME;
18672 	iocbq->iocb.ulpLe = 1;
18673 	iocbq->iocb_cmpl = lpfc_sli4_mds_loopback_cmpl;
18674 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
18675 	if (rc == IOCB_ERROR)
18676 		goto exit;
18677 
18678 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18679 	return;
18680 
18681 exit:
18682 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18683 			"2023 Unable to process MDS loopback frame\n");
18684 	if (pcmd && pcmd->virt)
18685 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18686 	kfree(pcmd);
18687 	if (iocbq)
18688 		lpfc_sli_release_iocbq(phba, iocbq);
18689 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18690 }
18691 
18692 /**
18693  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
18694  * @phba: Pointer to HBA context object.
18695  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
18696  *
18697  * This function is called with no lock held. This function processes all
18698  * the received buffers and gives it to upper layers when a received buffer
18699  * indicates that it is the final frame in the sequence. The interrupt
18700  * service routine processes received buffers at interrupt contexts.
18701  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
18702  * appropriate receive function when the final frame in a sequence is received.
18703  **/
18704 void
18705 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
18706 				 struct hbq_dmabuf *dmabuf)
18707 {
18708 	struct hbq_dmabuf *seq_dmabuf;
18709 	struct fc_frame_header *fc_hdr;
18710 	struct lpfc_vport *vport;
18711 	uint32_t fcfi;
18712 	uint32_t did;
18713 
18714 	/* Process each received buffer */
18715 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18716 
18717 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
18718 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
18719 		vport = phba->pport;
18720 		/* Handle MDS Loopback frames */
18721 		if  (!(phba->pport->load_flag & FC_UNLOADING))
18722 			lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18723 		else
18724 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
18725 		return;
18726 	}
18727 
18728 	/* check to see if this a valid type of frame */
18729 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
18730 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18731 		return;
18732 	}
18733 
18734 	if ((bf_get(lpfc_cqe_code,
18735 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
18736 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
18737 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
18738 	else
18739 		fcfi = bf_get(lpfc_rcqe_fcf_id,
18740 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
18741 
18742 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
18743 		vport = phba->pport;
18744 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
18745 				"2023 MDS Loopback %d bytes\n",
18746 				bf_get(lpfc_rcqe_length,
18747 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
18748 		/* Handle MDS Loopback frames */
18749 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18750 		return;
18751 	}
18752 
18753 	/* d_id this frame is directed to */
18754 	did = sli4_did_from_fc_hdr(fc_hdr);
18755 
18756 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
18757 	if (!vport) {
18758 		/* throw out the frame */
18759 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18760 		return;
18761 	}
18762 
18763 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
18764 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
18765 		(did != Fabric_DID)) {
18766 		/*
18767 		 * Throw out the frame if we are not pt2pt.
18768 		 * The pt2pt protocol allows for discovery frames
18769 		 * to be received without a registered VPI.
18770 		 */
18771 		if (!(vport->fc_flag & FC_PT2PT) ||
18772 			(phba->link_state == LPFC_HBA_READY)) {
18773 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
18774 			return;
18775 		}
18776 	}
18777 
18778 	/* Handle the basic abort sequence (BA_ABTS) event */
18779 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
18780 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
18781 		return;
18782 	}
18783 
18784 	/* Link this frame */
18785 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
18786 	if (!seq_dmabuf) {
18787 		/* unable to add frame to vport - throw it out */
18788 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18789 		return;
18790 	}
18791 	/* If not last frame in sequence continue processing frames. */
18792 	if (!lpfc_seq_complete(seq_dmabuf))
18793 		return;
18794 
18795 	/* Send the complete sequence to the upper layer protocol */
18796 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
18797 }
18798 
18799 /**
18800  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
18801  * @phba: pointer to lpfc hba data structure.
18802  *
18803  * This routine is invoked to post rpi header templates to the
18804  * HBA consistent with the SLI-4 interface spec.  This routine
18805  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18806  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18807  *
18808  * This routine does not require any locks.  It's usage is expected
18809  * to be driver load or reset recovery when the driver is
18810  * sequential.
18811  *
18812  * Return codes
18813  * 	0 - successful
18814  *      -EIO - The mailbox failed to complete successfully.
18815  * 	When this error occurs, the driver is not guaranteed
18816  *	to have any rpi regions posted to the device and
18817  *	must either attempt to repost the regions or take a
18818  *	fatal error.
18819  **/
18820 int
18821 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
18822 {
18823 	struct lpfc_rpi_hdr *rpi_page;
18824 	uint32_t rc = 0;
18825 	uint16_t lrpi = 0;
18826 
18827 	/* SLI4 ports that support extents do not require RPI headers. */
18828 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18829 		goto exit;
18830 	if (phba->sli4_hba.extents_in_use)
18831 		return -EIO;
18832 
18833 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
18834 		/*
18835 		 * Assign the rpi headers a physical rpi only if the driver
18836 		 * has not initialized those resources.  A port reset only
18837 		 * needs the headers posted.
18838 		 */
18839 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
18840 		    LPFC_RPI_RSRC_RDY)
18841 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18842 
18843 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
18844 		if (rc != MBX_SUCCESS) {
18845 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18846 					"2008 Error %d posting all rpi "
18847 					"headers\n", rc);
18848 			rc = -EIO;
18849 			break;
18850 		}
18851 	}
18852 
18853  exit:
18854 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
18855 	       LPFC_RPI_RSRC_RDY);
18856 	return rc;
18857 }
18858 
18859 /**
18860  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
18861  * @phba: pointer to lpfc hba data structure.
18862  * @rpi_page:  pointer to the rpi memory region.
18863  *
18864  * This routine is invoked to post a single rpi header to the
18865  * HBA consistent with the SLI-4 interface spec.  This memory region
18866  * maps up to 64 rpi context regions.
18867  *
18868  * Return codes
18869  * 	0 - successful
18870  * 	-ENOMEM - No available memory
18871  *      -EIO - The mailbox failed to complete successfully.
18872  **/
18873 int
18874 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
18875 {
18876 	LPFC_MBOXQ_t *mboxq;
18877 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
18878 	uint32_t rc = 0;
18879 	uint32_t shdr_status, shdr_add_status;
18880 	union lpfc_sli4_cfg_shdr *shdr;
18881 
18882 	/* SLI4 ports that support extents do not require RPI headers. */
18883 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18884 		return rc;
18885 	if (phba->sli4_hba.extents_in_use)
18886 		return -EIO;
18887 
18888 	/* The port is notified of the header region via a mailbox command. */
18889 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18890 	if (!mboxq) {
18891 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18892 				"2001 Unable to allocate memory for issuing "
18893 				"SLI_CONFIG_SPECIAL mailbox command\n");
18894 		return -ENOMEM;
18895 	}
18896 
18897 	/* Post all rpi memory regions to the port. */
18898 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
18899 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
18900 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
18901 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
18902 			 sizeof(struct lpfc_sli4_cfg_mhdr),
18903 			 LPFC_SLI4_MBX_EMBED);
18904 
18905 
18906 	/* Post the physical rpi to the port for this rpi header. */
18907 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
18908 	       rpi_page->start_rpi);
18909 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
18910 	       hdr_tmpl, rpi_page->page_count);
18911 
18912 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
18913 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
18914 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
18915 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
18916 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18917 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18918 	mempool_free(mboxq, phba->mbox_mem_pool);
18919 	if (shdr_status || shdr_add_status || rc) {
18920 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18921 				"2514 POST_RPI_HDR mailbox failed with "
18922 				"status x%x add_status x%x, mbx status x%x\n",
18923 				shdr_status, shdr_add_status, rc);
18924 		rc = -ENXIO;
18925 	} else {
18926 		/*
18927 		 * The next_rpi stores the next logical module-64 rpi value used
18928 		 * to post physical rpis in subsequent rpi postings.
18929 		 */
18930 		spin_lock_irq(&phba->hbalock);
18931 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
18932 		spin_unlock_irq(&phba->hbalock);
18933 	}
18934 	return rc;
18935 }
18936 
18937 /**
18938  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
18939  * @phba: pointer to lpfc hba data structure.
18940  *
18941  * This routine is invoked to post rpi header templates to the
18942  * HBA consistent with the SLI-4 interface spec.  This routine
18943  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18944  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18945  *
18946  * Returns
18947  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
18948  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
18949  **/
18950 int
18951 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
18952 {
18953 	unsigned long rpi;
18954 	uint16_t max_rpi, rpi_limit;
18955 	uint16_t rpi_remaining, lrpi = 0;
18956 	struct lpfc_rpi_hdr *rpi_hdr;
18957 	unsigned long iflag;
18958 
18959 	/*
18960 	 * Fetch the next logical rpi.  Because this index is logical,
18961 	 * the  driver starts at 0 each time.
18962 	 */
18963 	spin_lock_irqsave(&phba->hbalock, iflag);
18964 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
18965 	rpi_limit = phba->sli4_hba.next_rpi;
18966 
18967 	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
18968 	if (rpi >= rpi_limit)
18969 		rpi = LPFC_RPI_ALLOC_ERROR;
18970 	else {
18971 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
18972 		phba->sli4_hba.max_cfg_param.rpi_used++;
18973 		phba->sli4_hba.rpi_count++;
18974 	}
18975 	lpfc_printf_log(phba, KERN_INFO,
18976 			LOG_NODE | LOG_DISCOVERY,
18977 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
18978 			(int) rpi, max_rpi, rpi_limit);
18979 
18980 	/*
18981 	 * Don't try to allocate more rpi header regions if the device limit
18982 	 * has been exhausted.
18983 	 */
18984 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
18985 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
18986 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18987 		return rpi;
18988 	}
18989 
18990 	/*
18991 	 * RPI header postings are not required for SLI4 ports capable of
18992 	 * extents.
18993 	 */
18994 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
18995 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18996 		return rpi;
18997 	}
18998 
18999 	/*
19000 	 * If the driver is running low on rpi resources, allocate another
19001 	 * page now.  Note that the next_rpi value is used because
19002 	 * it represents how many are actually in use whereas max_rpi notes
19003 	 * how many are supported max by the device.
19004 	 */
19005 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
19006 	spin_unlock_irqrestore(&phba->hbalock, iflag);
19007 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
19008 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
19009 		if (!rpi_hdr) {
19010 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19011 					"2002 Error Could not grow rpi "
19012 					"count\n");
19013 		} else {
19014 			lrpi = rpi_hdr->start_rpi;
19015 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19016 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
19017 		}
19018 	}
19019 
19020 	return rpi;
19021 }
19022 
19023 /**
19024  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
19025  * @phba: pointer to lpfc hba data structure.
19026  * @rpi: rpi to free
19027  *
19028  * This routine is invoked to release an rpi to the pool of
19029  * available rpis maintained by the driver.
19030  **/
19031 static void
19032 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19033 {
19034 	/*
19035 	 * if the rpi value indicates a prior unreg has already
19036 	 * been done, skip the unreg.
19037 	 */
19038 	if (rpi == LPFC_RPI_ALLOC_ERROR)
19039 		return;
19040 
19041 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
19042 		phba->sli4_hba.rpi_count--;
19043 		phba->sli4_hba.max_cfg_param.rpi_used--;
19044 	} else {
19045 		lpfc_printf_log(phba, KERN_INFO,
19046 				LOG_NODE | LOG_DISCOVERY,
19047 				"2016 rpi %x not inuse\n",
19048 				rpi);
19049 	}
19050 }
19051 
19052 /**
19053  * lpfc_sli4_free_rpi - Release an rpi for reuse.
19054  * @phba: pointer to lpfc hba data structure.
19055  * @rpi: rpi to free
19056  *
19057  * This routine is invoked to release an rpi to the pool of
19058  * available rpis maintained by the driver.
19059  **/
19060 void
19061 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19062 {
19063 	spin_lock_irq(&phba->hbalock);
19064 	__lpfc_sli4_free_rpi(phba, rpi);
19065 	spin_unlock_irq(&phba->hbalock);
19066 }
19067 
19068 /**
19069  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19070  * @phba: pointer to lpfc hba data structure.
19071  *
19072  * This routine is invoked to remove the memory region that
19073  * provided rpi via a bitmask.
19074  **/
19075 void
19076 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19077 {
19078 	kfree(phba->sli4_hba.rpi_bmask);
19079 	kfree(phba->sli4_hba.rpi_ids);
19080 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19081 }
19082 
19083 /**
19084  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
19085  * @ndlp: pointer to lpfc nodelist data structure.
19086  * @cmpl: completion call-back.
19087  * @arg: data to load as MBox 'caller buffer information'
19088  *
19089  * This routine is invoked to remove the memory region that
19090  * provided rpi via a bitmask.
19091  **/
19092 int
19093 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19094 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
19095 {
19096 	LPFC_MBOXQ_t *mboxq;
19097 	struct lpfc_hba *phba = ndlp->phba;
19098 	int rc;
19099 
19100 	/* The port is notified of the header region via a mailbox command. */
19101 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19102 	if (!mboxq)
19103 		return -ENOMEM;
19104 
19105 	/* If cmpl assigned, then this nlp_get pairs with
19106 	 * lpfc_mbx_cmpl_resume_rpi.
19107 	 *
19108 	 * Else cmpl is NULL, then this nlp_get pairs with
19109 	 * lpfc_sli_def_mbox_cmpl.
19110 	 */
19111 	if (!lpfc_nlp_get(ndlp)) {
19112 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19113 				"2122 %s: Failed to get nlp ref\n",
19114 				__func__);
19115 		mempool_free(mboxq, phba->mbox_mem_pool);
19116 		return -EIO;
19117 	}
19118 
19119 	/* Post all rpi memory regions to the port. */
19120 	lpfc_resume_rpi(mboxq, ndlp);
19121 	if (cmpl) {
19122 		mboxq->mbox_cmpl = cmpl;
19123 		mboxq->ctx_buf = arg;
19124 	} else
19125 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19126 	mboxq->ctx_ndlp = ndlp;
19127 	mboxq->vport = ndlp->vport;
19128 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19129 	if (rc == MBX_NOT_FINISHED) {
19130 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19131 				"2010 Resume RPI Mailbox failed "
19132 				"status %d, mbxStatus x%x\n", rc,
19133 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19134 		lpfc_nlp_put(ndlp);
19135 		mempool_free(mboxq, phba->mbox_mem_pool);
19136 		return -EIO;
19137 	}
19138 	return 0;
19139 }
19140 
19141 /**
19142  * lpfc_sli4_init_vpi - Initialize a vpi with the port
19143  * @vport: Pointer to the vport for which the vpi is being initialized
19144  *
19145  * This routine is invoked to activate a vpi with the port.
19146  *
19147  * Returns:
19148  *    0 success
19149  *    -Evalue otherwise
19150  **/
19151 int
19152 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
19153 {
19154 	LPFC_MBOXQ_t *mboxq;
19155 	int rc = 0;
19156 	int retval = MBX_SUCCESS;
19157 	uint32_t mbox_tmo;
19158 	struct lpfc_hba *phba = vport->phba;
19159 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19160 	if (!mboxq)
19161 		return -ENOMEM;
19162 	lpfc_init_vpi(phba, mboxq, vport->vpi);
19163 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
19164 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
19165 	if (rc != MBX_SUCCESS) {
19166 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19167 				"2022 INIT VPI Mailbox failed "
19168 				"status %d, mbxStatus x%x\n", rc,
19169 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19170 		retval = -EIO;
19171 	}
19172 	if (rc != MBX_TIMEOUT)
19173 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
19174 
19175 	return retval;
19176 }
19177 
19178 /**
19179  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
19180  * @phba: pointer to lpfc hba data structure.
19181  * @mboxq: Pointer to mailbox object.
19182  *
19183  * This routine is invoked to manually add a single FCF record. The caller
19184  * must pass a completely initialized FCF_Record.  This routine takes
19185  * care of the nonembedded mailbox operations.
19186  **/
19187 static void
19188 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
19189 {
19190 	void *virt_addr;
19191 	union lpfc_sli4_cfg_shdr *shdr;
19192 	uint32_t shdr_status, shdr_add_status;
19193 
19194 	virt_addr = mboxq->sge_array->addr[0];
19195 	/* The IOCTL status is embedded in the mailbox subheader. */
19196 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
19197 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19198 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19199 
19200 	if ((shdr_status || shdr_add_status) &&
19201 		(shdr_status != STATUS_FCF_IN_USE))
19202 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19203 			"2558 ADD_FCF_RECORD mailbox failed with "
19204 			"status x%x add_status x%x\n",
19205 			shdr_status, shdr_add_status);
19206 
19207 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
19208 }
19209 
19210 /**
19211  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
19212  * @phba: pointer to lpfc hba data structure.
19213  * @fcf_record:  pointer to the initialized fcf record to add.
19214  *
19215  * This routine is invoked to manually add a single FCF record. The caller
19216  * must pass a completely initialized FCF_Record.  This routine takes
19217  * care of the nonembedded mailbox operations.
19218  **/
19219 int
19220 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
19221 {
19222 	int rc = 0;
19223 	LPFC_MBOXQ_t *mboxq;
19224 	uint8_t *bytep;
19225 	void *virt_addr;
19226 	struct lpfc_mbx_sge sge;
19227 	uint32_t alloc_len, req_len;
19228 	uint32_t fcfindex;
19229 
19230 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19231 	if (!mboxq) {
19232 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19233 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
19234 		return -ENOMEM;
19235 	}
19236 
19237 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
19238 		  sizeof(uint32_t);
19239 
19240 	/* Allocate DMA memory and set up the non-embedded mailbox command */
19241 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19242 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
19243 				     req_len, LPFC_SLI4_MBX_NEMBED);
19244 	if (alloc_len < req_len) {
19245 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19246 			"2523 Allocated DMA memory size (x%x) is "
19247 			"less than the requested DMA memory "
19248 			"size (x%x)\n", alloc_len, req_len);
19249 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19250 		return -ENOMEM;
19251 	}
19252 
19253 	/*
19254 	 * Get the first SGE entry from the non-embedded DMA memory.  This
19255 	 * routine only uses a single SGE.
19256 	 */
19257 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
19258 	virt_addr = mboxq->sge_array->addr[0];
19259 	/*
19260 	 * Configure the FCF record for FCFI 0.  This is the driver's
19261 	 * hardcoded default and gets used in nonFIP mode.
19262 	 */
19263 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
19264 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
19265 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
19266 
19267 	/*
19268 	 * Copy the fcf_index and the FCF Record Data. The data starts after
19269 	 * the FCoE header plus word10. The data copy needs to be endian
19270 	 * correct.
19271 	 */
19272 	bytep += sizeof(uint32_t);
19273 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
19274 	mboxq->vport = phba->pport;
19275 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
19276 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19277 	if (rc == MBX_NOT_FINISHED) {
19278 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19279 			"2515 ADD_FCF_RECORD mailbox failed with "
19280 			"status 0x%x\n", rc);
19281 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19282 		rc = -EIO;
19283 	} else
19284 		rc = 0;
19285 
19286 	return rc;
19287 }
19288 
19289 /**
19290  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
19291  * @phba: pointer to lpfc hba data structure.
19292  * @fcf_record:  pointer to the fcf record to write the default data.
19293  * @fcf_index: FCF table entry index.
19294  *
19295  * This routine is invoked to build the driver's default FCF record.  The
19296  * values used are hardcoded.  This routine handles memory initialization.
19297  *
19298  **/
19299 void
19300 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
19301 				struct fcf_record *fcf_record,
19302 				uint16_t fcf_index)
19303 {
19304 	memset(fcf_record, 0, sizeof(struct fcf_record));
19305 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
19306 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
19307 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
19308 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
19309 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
19310 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
19311 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
19312 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
19313 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
19314 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
19315 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
19316 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
19317 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
19318 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
19319 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
19320 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
19321 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
19322 	/* Set the VLAN bit map */
19323 	if (phba->valid_vlan) {
19324 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
19325 			= 1 << (phba->vlan_id % 8);
19326 	}
19327 }
19328 
19329 /**
19330  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
19331  * @phba: pointer to lpfc hba data structure.
19332  * @fcf_index: FCF table entry offset.
19333  *
19334  * This routine is invoked to scan the entire FCF table by reading FCF
19335  * record and processing it one at a time starting from the @fcf_index
19336  * for initial FCF discovery or fast FCF failover rediscovery.
19337  *
19338  * Return 0 if the mailbox command is submitted successfully, none 0
19339  * otherwise.
19340  **/
19341 int
19342 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19343 {
19344 	int rc = 0, error;
19345 	LPFC_MBOXQ_t *mboxq;
19346 
19347 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
19348 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
19349 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19350 	if (!mboxq) {
19351 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19352 				"2000 Failed to allocate mbox for "
19353 				"READ_FCF cmd\n");
19354 		error = -ENOMEM;
19355 		goto fail_fcf_scan;
19356 	}
19357 	/* Construct the read FCF record mailbox command */
19358 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19359 	if (rc) {
19360 		error = -EINVAL;
19361 		goto fail_fcf_scan;
19362 	}
19363 	/* Issue the mailbox command asynchronously */
19364 	mboxq->vport = phba->pport;
19365 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
19366 
19367 	spin_lock_irq(&phba->hbalock);
19368 	phba->hba_flag |= FCF_TS_INPROG;
19369 	spin_unlock_irq(&phba->hbalock);
19370 
19371 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19372 	if (rc == MBX_NOT_FINISHED)
19373 		error = -EIO;
19374 	else {
19375 		/* Reset eligible FCF count for new scan */
19376 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
19377 			phba->fcf.eligible_fcf_cnt = 0;
19378 		error = 0;
19379 	}
19380 fail_fcf_scan:
19381 	if (error) {
19382 		if (mboxq)
19383 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
19384 		/* FCF scan failed, clear FCF_TS_INPROG flag */
19385 		spin_lock_irq(&phba->hbalock);
19386 		phba->hba_flag &= ~FCF_TS_INPROG;
19387 		spin_unlock_irq(&phba->hbalock);
19388 	}
19389 	return error;
19390 }
19391 
19392 /**
19393  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
19394  * @phba: pointer to lpfc hba data structure.
19395  * @fcf_index: FCF table entry offset.
19396  *
19397  * This routine is invoked to read an FCF record indicated by @fcf_index
19398  * and to use it for FLOGI roundrobin FCF failover.
19399  *
19400  * Return 0 if the mailbox command is submitted successfully, none 0
19401  * otherwise.
19402  **/
19403 int
19404 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19405 {
19406 	int rc = 0, error;
19407 	LPFC_MBOXQ_t *mboxq;
19408 
19409 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19410 	if (!mboxq) {
19411 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
19412 				"2763 Failed to allocate mbox for "
19413 				"READ_FCF cmd\n");
19414 		error = -ENOMEM;
19415 		goto fail_fcf_read;
19416 	}
19417 	/* Construct the read FCF record mailbox command */
19418 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19419 	if (rc) {
19420 		error = -EINVAL;
19421 		goto fail_fcf_read;
19422 	}
19423 	/* Issue the mailbox command asynchronously */
19424 	mboxq->vport = phba->pport;
19425 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
19426 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19427 	if (rc == MBX_NOT_FINISHED)
19428 		error = -EIO;
19429 	else
19430 		error = 0;
19431 
19432 fail_fcf_read:
19433 	if (error && mboxq)
19434 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19435 	return error;
19436 }
19437 
19438 /**
19439  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
19440  * @phba: pointer to lpfc hba data structure.
19441  * @fcf_index: FCF table entry offset.
19442  *
19443  * This routine is invoked to read an FCF record indicated by @fcf_index to
19444  * determine whether it's eligible for FLOGI roundrobin failover list.
19445  *
19446  * Return 0 if the mailbox command is submitted successfully, none 0
19447  * otherwise.
19448  **/
19449 int
19450 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19451 {
19452 	int rc = 0, error;
19453 	LPFC_MBOXQ_t *mboxq;
19454 
19455 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19456 	if (!mboxq) {
19457 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
19458 				"2758 Failed to allocate mbox for "
19459 				"READ_FCF cmd\n");
19460 				error = -ENOMEM;
19461 				goto fail_fcf_read;
19462 	}
19463 	/* Construct the read FCF record mailbox command */
19464 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19465 	if (rc) {
19466 		error = -EINVAL;
19467 		goto fail_fcf_read;
19468 	}
19469 	/* Issue the mailbox command asynchronously */
19470 	mboxq->vport = phba->pport;
19471 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
19472 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19473 	if (rc == MBX_NOT_FINISHED)
19474 		error = -EIO;
19475 	else
19476 		error = 0;
19477 
19478 fail_fcf_read:
19479 	if (error && mboxq)
19480 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19481 	return error;
19482 }
19483 
19484 /**
19485  * lpfc_check_next_fcf_pri_level
19486  * @phba: pointer to the lpfc_hba struct for this port.
19487  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
19488  * routine when the rr_bmask is empty. The FCF indecies are put into the
19489  * rr_bmask based on their priority level. Starting from the highest priority
19490  * to the lowest. The most likely FCF candidate will be in the highest
19491  * priority group. When this routine is called it searches the fcf_pri list for
19492  * next lowest priority group and repopulates the rr_bmask with only those
19493  * fcf_indexes.
19494  * returns:
19495  * 1=success 0=failure
19496  **/
19497 static int
19498 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
19499 {
19500 	uint16_t next_fcf_pri;
19501 	uint16_t last_index;
19502 	struct lpfc_fcf_pri *fcf_pri;
19503 	int rc;
19504 	int ret = 0;
19505 
19506 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
19507 			LPFC_SLI4_FCF_TBL_INDX_MAX);
19508 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19509 			"3060 Last IDX %d\n", last_index);
19510 
19511 	/* Verify the priority list has 2 or more entries */
19512 	spin_lock_irq(&phba->hbalock);
19513 	if (list_empty(&phba->fcf.fcf_pri_list) ||
19514 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
19515 		spin_unlock_irq(&phba->hbalock);
19516 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19517 			"3061 Last IDX %d\n", last_index);
19518 		return 0; /* Empty rr list */
19519 	}
19520 	spin_unlock_irq(&phba->hbalock);
19521 
19522 	next_fcf_pri = 0;
19523 	/*
19524 	 * Clear the rr_bmask and set all of the bits that are at this
19525 	 * priority.
19526 	 */
19527 	memset(phba->fcf.fcf_rr_bmask, 0,
19528 			sizeof(*phba->fcf.fcf_rr_bmask));
19529 	spin_lock_irq(&phba->hbalock);
19530 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
19531 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
19532 			continue;
19533 		/*
19534 		 * the 1st priority that has not FLOGI failed
19535 		 * will be the highest.
19536 		 */
19537 		if (!next_fcf_pri)
19538 			next_fcf_pri = fcf_pri->fcf_rec.priority;
19539 		spin_unlock_irq(&phba->hbalock);
19540 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
19541 			rc = lpfc_sli4_fcf_rr_index_set(phba,
19542 						fcf_pri->fcf_rec.fcf_index);
19543 			if (rc)
19544 				return 0;
19545 		}
19546 		spin_lock_irq(&phba->hbalock);
19547 	}
19548 	/*
19549 	 * if next_fcf_pri was not set above and the list is not empty then
19550 	 * we have failed flogis on all of them. So reset flogi failed
19551 	 * and start at the beginning.
19552 	 */
19553 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
19554 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
19555 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
19556 			/*
19557 			 * the 1st priority that has not FLOGI failed
19558 			 * will be the highest.
19559 			 */
19560 			if (!next_fcf_pri)
19561 				next_fcf_pri = fcf_pri->fcf_rec.priority;
19562 			spin_unlock_irq(&phba->hbalock);
19563 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
19564 				rc = lpfc_sli4_fcf_rr_index_set(phba,
19565 						fcf_pri->fcf_rec.fcf_index);
19566 				if (rc)
19567 					return 0;
19568 			}
19569 			spin_lock_irq(&phba->hbalock);
19570 		}
19571 	} else
19572 		ret = 1;
19573 	spin_unlock_irq(&phba->hbalock);
19574 
19575 	return ret;
19576 }
19577 /**
19578  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
19579  * @phba: pointer to lpfc hba data structure.
19580  *
19581  * This routine is to get the next eligible FCF record index in a round
19582  * robin fashion. If the next eligible FCF record index equals to the
19583  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
19584  * shall be returned, otherwise, the next eligible FCF record's index
19585  * shall be returned.
19586  **/
19587 uint16_t
19588 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
19589 {
19590 	uint16_t next_fcf_index;
19591 
19592 initial_priority:
19593 	/* Search start from next bit of currently registered FCF index */
19594 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
19595 
19596 next_priority:
19597 	/* Determine the next fcf index to check */
19598 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
19599 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
19600 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
19601 				       next_fcf_index);
19602 
19603 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
19604 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19605 		/*
19606 		 * If we have wrapped then we need to clear the bits that
19607 		 * have been tested so that we can detect when we should
19608 		 * change the priority level.
19609 		 */
19610 		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
19611 					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
19612 	}
19613 
19614 
19615 	/* Check roundrobin failover list empty condition */
19616 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
19617 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
19618 		/*
19619 		 * If next fcf index is not found check if there are lower
19620 		 * Priority level fcf's in the fcf_priority list.
19621 		 * Set up the rr_bmask with all of the avaiable fcf bits
19622 		 * at that level and continue the selection process.
19623 		 */
19624 		if (lpfc_check_next_fcf_pri_level(phba))
19625 			goto initial_priority;
19626 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
19627 				"2844 No roundrobin failover FCF available\n");
19628 
19629 		return LPFC_FCOE_FCF_NEXT_NONE;
19630 	}
19631 
19632 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
19633 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
19634 		LPFC_FCF_FLOGI_FAILED) {
19635 		if (list_is_singular(&phba->fcf.fcf_pri_list))
19636 			return LPFC_FCOE_FCF_NEXT_NONE;
19637 
19638 		goto next_priority;
19639 	}
19640 
19641 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19642 			"2845 Get next roundrobin failover FCF (x%x)\n",
19643 			next_fcf_index);
19644 
19645 	return next_fcf_index;
19646 }
19647 
19648 /**
19649  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
19650  * @phba: pointer to lpfc hba data structure.
19651  * @fcf_index: index into the FCF table to 'set'
19652  *
19653  * This routine sets the FCF record index in to the eligible bmask for
19654  * roundrobin failover search. It checks to make sure that the index
19655  * does not go beyond the range of the driver allocated bmask dimension
19656  * before setting the bit.
19657  *
19658  * Returns 0 if the index bit successfully set, otherwise, it returns
19659  * -EINVAL.
19660  **/
19661 int
19662 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
19663 {
19664 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19665 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19666 				"2610 FCF (x%x) reached driver's book "
19667 				"keeping dimension:x%x\n",
19668 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19669 		return -EINVAL;
19670 	}
19671 	/* Set the eligible FCF record index bmask */
19672 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19673 
19674 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19675 			"2790 Set FCF (x%x) to roundrobin FCF failover "
19676 			"bmask\n", fcf_index);
19677 
19678 	return 0;
19679 }
19680 
19681 /**
19682  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
19683  * @phba: pointer to lpfc hba data structure.
19684  * @fcf_index: index into the FCF table to 'clear'
19685  *
19686  * This routine clears the FCF record index from the eligible bmask for
19687  * roundrobin failover search. It checks to make sure that the index
19688  * does not go beyond the range of the driver allocated bmask dimension
19689  * before clearing the bit.
19690  **/
19691 void
19692 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
19693 {
19694 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
19695 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19696 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19697 				"2762 FCF (x%x) reached driver's book "
19698 				"keeping dimension:x%x\n",
19699 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19700 		return;
19701 	}
19702 	/* Clear the eligible FCF record index bmask */
19703 	spin_lock_irq(&phba->hbalock);
19704 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
19705 				 list) {
19706 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
19707 			list_del_init(&fcf_pri->list);
19708 			break;
19709 		}
19710 	}
19711 	spin_unlock_irq(&phba->hbalock);
19712 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19713 
19714 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19715 			"2791 Clear FCF (x%x) from roundrobin failover "
19716 			"bmask\n", fcf_index);
19717 }
19718 
19719 /**
19720  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
19721  * @phba: pointer to lpfc hba data structure.
19722  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
19723  *
19724  * This routine is the completion routine for the rediscover FCF table mailbox
19725  * command. If the mailbox command returned failure, it will try to stop the
19726  * FCF rediscover wait timer.
19727  **/
19728 static void
19729 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
19730 {
19731 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19732 	uint32_t shdr_status, shdr_add_status;
19733 
19734 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19735 
19736 	shdr_status = bf_get(lpfc_mbox_hdr_status,
19737 			     &redisc_fcf->header.cfg_shdr.response);
19738 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
19739 			     &redisc_fcf->header.cfg_shdr.response);
19740 	if (shdr_status || shdr_add_status) {
19741 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19742 				"2746 Requesting for FCF rediscovery failed "
19743 				"status x%x add_status x%x\n",
19744 				shdr_status, shdr_add_status);
19745 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
19746 			spin_lock_irq(&phba->hbalock);
19747 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
19748 			spin_unlock_irq(&phba->hbalock);
19749 			/*
19750 			 * CVL event triggered FCF rediscover request failed,
19751 			 * last resort to re-try current registered FCF entry.
19752 			 */
19753 			lpfc_retry_pport_discovery(phba);
19754 		} else {
19755 			spin_lock_irq(&phba->hbalock);
19756 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
19757 			spin_unlock_irq(&phba->hbalock);
19758 			/*
19759 			 * DEAD FCF event triggered FCF rediscover request
19760 			 * failed, last resort to fail over as a link down
19761 			 * to FCF registration.
19762 			 */
19763 			lpfc_sli4_fcf_dead_failthrough(phba);
19764 		}
19765 	} else {
19766 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19767 				"2775 Start FCF rediscover quiescent timer\n");
19768 		/*
19769 		 * Start FCF rediscovery wait timer for pending FCF
19770 		 * before rescan FCF record table.
19771 		 */
19772 		lpfc_fcf_redisc_wait_start_timer(phba);
19773 	}
19774 
19775 	mempool_free(mbox, phba->mbox_mem_pool);
19776 }
19777 
19778 /**
19779  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
19780  * @phba: pointer to lpfc hba data structure.
19781  *
19782  * This routine is invoked to request for rediscovery of the entire FCF table
19783  * by the port.
19784  **/
19785 int
19786 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
19787 {
19788 	LPFC_MBOXQ_t *mbox;
19789 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19790 	int rc, length;
19791 
19792 	/* Cancel retry delay timers to all vports before FCF rediscover */
19793 	lpfc_cancel_all_vport_retry_delay_timer(phba);
19794 
19795 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19796 	if (!mbox) {
19797 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19798 				"2745 Failed to allocate mbox for "
19799 				"requesting FCF rediscover.\n");
19800 		return -ENOMEM;
19801 	}
19802 
19803 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
19804 		  sizeof(struct lpfc_sli4_cfg_mhdr));
19805 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
19806 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
19807 			 length, LPFC_SLI4_MBX_EMBED);
19808 
19809 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19810 	/* Set count to 0 for invalidating the entire FCF database */
19811 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
19812 
19813 	/* Issue the mailbox command asynchronously */
19814 	mbox->vport = phba->pport;
19815 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
19816 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
19817 
19818 	if (rc == MBX_NOT_FINISHED) {
19819 		mempool_free(mbox, phba->mbox_mem_pool);
19820 		return -EIO;
19821 	}
19822 	return 0;
19823 }
19824 
19825 /**
19826  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
19827  * @phba: pointer to lpfc hba data structure.
19828  *
19829  * This function is the failover routine as a last resort to the FCF DEAD
19830  * event when driver failed to perform fast FCF failover.
19831  **/
19832 void
19833 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
19834 {
19835 	uint32_t link_state;
19836 
19837 	/*
19838 	 * Last resort as FCF DEAD event failover will treat this as
19839 	 * a link down, but save the link state because we don't want
19840 	 * it to be changed to Link Down unless it is already down.
19841 	 */
19842 	link_state = phba->link_state;
19843 	lpfc_linkdown(phba);
19844 	phba->link_state = link_state;
19845 
19846 	/* Unregister FCF if no devices connected to it */
19847 	lpfc_unregister_unused_fcf(phba);
19848 }
19849 
19850 /**
19851  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
19852  * @phba: pointer to lpfc hba data structure.
19853  * @rgn23_data: pointer to configure region 23 data.
19854  *
19855  * This function gets SLI3 port configure region 23 data through memory dump
19856  * mailbox command. When it successfully retrieves data, the size of the data
19857  * will be returned, otherwise, 0 will be returned.
19858  **/
19859 static uint32_t
19860 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19861 {
19862 	LPFC_MBOXQ_t *pmb = NULL;
19863 	MAILBOX_t *mb;
19864 	uint32_t offset = 0;
19865 	int rc;
19866 
19867 	if (!rgn23_data)
19868 		return 0;
19869 
19870 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19871 	if (!pmb) {
19872 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19873 				"2600 failed to allocate mailbox memory\n");
19874 		return 0;
19875 	}
19876 	mb = &pmb->u.mb;
19877 
19878 	do {
19879 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
19880 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
19881 
19882 		if (rc != MBX_SUCCESS) {
19883 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19884 					"2601 failed to read config "
19885 					"region 23, rc 0x%x Status 0x%x\n",
19886 					rc, mb->mbxStatus);
19887 			mb->un.varDmp.word_cnt = 0;
19888 		}
19889 		/*
19890 		 * dump mem may return a zero when finished or we got a
19891 		 * mailbox error, either way we are done.
19892 		 */
19893 		if (mb->un.varDmp.word_cnt == 0)
19894 			break;
19895 
19896 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
19897 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
19898 
19899 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
19900 				       rgn23_data + offset,
19901 				       mb->un.varDmp.word_cnt);
19902 		offset += mb->un.varDmp.word_cnt;
19903 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
19904 
19905 	mempool_free(pmb, phba->mbox_mem_pool);
19906 	return offset;
19907 }
19908 
19909 /**
19910  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
19911  * @phba: pointer to lpfc hba data structure.
19912  * @rgn23_data: pointer to configure region 23 data.
19913  *
19914  * This function gets SLI4 port configure region 23 data through memory dump
19915  * mailbox command. When it successfully retrieves data, the size of the data
19916  * will be returned, otherwise, 0 will be returned.
19917  **/
19918 static uint32_t
19919 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19920 {
19921 	LPFC_MBOXQ_t *mboxq = NULL;
19922 	struct lpfc_dmabuf *mp = NULL;
19923 	struct lpfc_mqe *mqe;
19924 	uint32_t data_length = 0;
19925 	int rc;
19926 
19927 	if (!rgn23_data)
19928 		return 0;
19929 
19930 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19931 	if (!mboxq) {
19932 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19933 				"3105 failed to allocate mailbox memory\n");
19934 		return 0;
19935 	}
19936 
19937 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
19938 		goto out;
19939 	mqe = &mboxq->u.mqe;
19940 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
19941 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19942 	if (rc)
19943 		goto out;
19944 	data_length = mqe->un.mb_words[5];
19945 	if (data_length == 0)
19946 		goto out;
19947 	if (data_length > DMP_RGN23_SIZE) {
19948 		data_length = 0;
19949 		goto out;
19950 	}
19951 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
19952 out:
19953 	mempool_free(mboxq, phba->mbox_mem_pool);
19954 	if (mp) {
19955 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
19956 		kfree(mp);
19957 	}
19958 	return data_length;
19959 }
19960 
19961 /**
19962  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
19963  * @phba: pointer to lpfc hba data structure.
19964  *
19965  * This function read region 23 and parse TLV for port status to
19966  * decide if the user disaled the port. If the TLV indicates the
19967  * port is disabled, the hba_flag is set accordingly.
19968  **/
19969 void
19970 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
19971 {
19972 	uint8_t *rgn23_data = NULL;
19973 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
19974 	uint32_t offset = 0;
19975 
19976 	/* Get adapter Region 23 data */
19977 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
19978 	if (!rgn23_data)
19979 		goto out;
19980 
19981 	if (phba->sli_rev < LPFC_SLI_REV4)
19982 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
19983 	else {
19984 		if_type = bf_get(lpfc_sli_intf_if_type,
19985 				 &phba->sli4_hba.sli_intf);
19986 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
19987 			goto out;
19988 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
19989 	}
19990 
19991 	if (!data_size)
19992 		goto out;
19993 
19994 	/* Check the region signature first */
19995 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
19996 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19997 			"2619 Config region 23 has bad signature\n");
19998 			goto out;
19999 	}
20000 	offset += 4;
20001 
20002 	/* Check the data structure version */
20003 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
20004 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20005 			"2620 Config region 23 has bad version\n");
20006 		goto out;
20007 	}
20008 	offset += 4;
20009 
20010 	/* Parse TLV entries in the region */
20011 	while (offset < data_size) {
20012 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
20013 			break;
20014 		/*
20015 		 * If the TLV is not driver specific TLV or driver id is
20016 		 * not linux driver id, skip the record.
20017 		 */
20018 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
20019 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
20020 		    (rgn23_data[offset + 3] != 0)) {
20021 			offset += rgn23_data[offset + 1] * 4 + 4;
20022 			continue;
20023 		}
20024 
20025 		/* Driver found a driver specific TLV in the config region */
20026 		sub_tlv_len = rgn23_data[offset + 1] * 4;
20027 		offset += 4;
20028 		tlv_offset = 0;
20029 
20030 		/*
20031 		 * Search for configured port state sub-TLV.
20032 		 */
20033 		while ((offset < data_size) &&
20034 			(tlv_offset < sub_tlv_len)) {
20035 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
20036 				offset += 4;
20037 				tlv_offset += 4;
20038 				break;
20039 			}
20040 			if (rgn23_data[offset] != PORT_STE_TYPE) {
20041 				offset += rgn23_data[offset + 1] * 4 + 4;
20042 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
20043 				continue;
20044 			}
20045 
20046 			/* This HBA contains PORT_STE configured */
20047 			if (!rgn23_data[offset + 2])
20048 				phba->hba_flag |= LINK_DISABLED;
20049 
20050 			goto out;
20051 		}
20052 	}
20053 
20054 out:
20055 	kfree(rgn23_data);
20056 	return;
20057 }
20058 
20059 /**
20060  * lpfc_log_fw_write_cmpl - logs firmware write completion status
20061  * @phba: pointer to lpfc hba data structure
20062  * @shdr_status: wr_object rsp's status field
20063  * @shdr_add_status: wr_object rsp's add_status field
20064  * @shdr_add_status_2: wr_object rsp's add_status_2 field
20065  * @shdr_change_status: wr_object rsp's change_status field
20066  * @shdr_csf: wr_object rsp's csf bit
20067  *
20068  * This routine is intended to be called after a firmware write completes.
20069  * It will log next action items to be performed by the user to instantiate
20070  * the newly downloaded firmware or reason for incompatibility.
20071  **/
20072 static void
20073 lpfc_log_fw_write_cmpl(struct lpfc_hba *phba, u32 shdr_status,
20074 		       u32 shdr_add_status, u32 shdr_add_status_2,
20075 		       u32 shdr_change_status, u32 shdr_csf)
20076 {
20077 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20078 			"4198 %s: flash_id x%02x, asic_rev x%02x, "
20079 			"status x%02x, add_status x%02x, add_status_2 x%02x, "
20080 			"change_status x%02x, csf %01x\n", __func__,
20081 			phba->sli4_hba.flash_id, phba->sli4_hba.asic_rev,
20082 			shdr_status, shdr_add_status, shdr_add_status_2,
20083 			shdr_change_status, shdr_csf);
20084 
20085 	if (shdr_add_status == LPFC_ADD_STATUS_INCOMPAT_OBJ) {
20086 		switch (shdr_add_status_2) {
20087 		case LPFC_ADD_STATUS_2_INCOMPAT_FLASH:
20088 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20089 					"4199 Firmware write failed: "
20090 					"image incompatible with flash x%02x\n",
20091 					phba->sli4_hba.flash_id);
20092 			break;
20093 		case LPFC_ADD_STATUS_2_INCORRECT_ASIC:
20094 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20095 					"4200 Firmware write failed: "
20096 					"image incompatible with ASIC "
20097 					"architecture x%02x\n",
20098 					phba->sli4_hba.asic_rev);
20099 			break;
20100 		default:
20101 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20102 					"4210 Firmware write failed: "
20103 					"add_status_2 x%02x\n",
20104 					shdr_add_status_2);
20105 			break;
20106 		}
20107 	} else if (!shdr_status && !shdr_add_status) {
20108 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20109 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20110 			if (shdr_csf)
20111 				shdr_change_status =
20112 						   LPFC_CHANGE_STATUS_PCI_RESET;
20113 		}
20114 
20115 		switch (shdr_change_status) {
20116 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20117 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20118 					"3198 Firmware write complete: System "
20119 					"reboot required to instantiate\n");
20120 			break;
20121 		case (LPFC_CHANGE_STATUS_FW_RESET):
20122 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20123 					"3199 Firmware write complete: "
20124 					"Firmware reset required to "
20125 					"instantiate\n");
20126 			break;
20127 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20128 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20129 					"3200 Firmware write complete: Port "
20130 					"Migration or PCI Reset required to "
20131 					"instantiate\n");
20132 			break;
20133 		case (LPFC_CHANGE_STATUS_PCI_RESET):
20134 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20135 					"3201 Firmware write complete: PCI "
20136 					"Reset required to instantiate\n");
20137 			break;
20138 		default:
20139 			break;
20140 		}
20141 	}
20142 }
20143 
20144 /**
20145  * lpfc_wr_object - write an object to the firmware
20146  * @phba: HBA structure that indicates port to create a queue on.
20147  * @dmabuf_list: list of dmabufs to write to the port.
20148  * @size: the total byte value of the objects to write to the port.
20149  * @offset: the current offset to be used to start the transfer.
20150  *
20151  * This routine will create a wr_object mailbox command to send to the port.
20152  * the mailbox command will be constructed using the dma buffers described in
20153  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
20154  * BDEs that the imbedded mailbox can support. The @offset variable will be
20155  * used to indicate the starting offset of the transfer and will also return
20156  * the offset after the write object mailbox has completed. @size is used to
20157  * determine the end of the object and whether the eof bit should be set.
20158  *
20159  * Return 0 is successful and offset will contain the the new offset to use
20160  * for the next write.
20161  * Return negative value for error cases.
20162  **/
20163 int
20164 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
20165 	       uint32_t size, uint32_t *offset)
20166 {
20167 	struct lpfc_mbx_wr_object *wr_object;
20168 	LPFC_MBOXQ_t *mbox;
20169 	int rc = 0, i = 0;
20170 	uint32_t shdr_status, shdr_add_status, shdr_add_status_2;
20171 	uint32_t shdr_change_status = 0, shdr_csf = 0;
20172 	uint32_t mbox_tmo;
20173 	struct lpfc_dmabuf *dmabuf;
20174 	uint32_t written = 0;
20175 	bool check_change_status = false;
20176 
20177 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20178 	if (!mbox)
20179 		return -ENOMEM;
20180 
20181 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
20182 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
20183 			sizeof(struct lpfc_mbx_wr_object) -
20184 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
20185 
20186 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
20187 	wr_object->u.request.write_offset = *offset;
20188 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
20189 	wr_object->u.request.object_name[0] =
20190 		cpu_to_le32(wr_object->u.request.object_name[0]);
20191 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
20192 	list_for_each_entry(dmabuf, dmabuf_list, list) {
20193 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
20194 			break;
20195 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
20196 		wr_object->u.request.bde[i].addrHigh =
20197 			putPaddrHigh(dmabuf->phys);
20198 		if (written + SLI4_PAGE_SIZE >= size) {
20199 			wr_object->u.request.bde[i].tus.f.bdeSize =
20200 				(size - written);
20201 			written += (size - written);
20202 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
20203 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
20204 			check_change_status = true;
20205 		} else {
20206 			wr_object->u.request.bde[i].tus.f.bdeSize =
20207 				SLI4_PAGE_SIZE;
20208 			written += SLI4_PAGE_SIZE;
20209 		}
20210 		i++;
20211 	}
20212 	wr_object->u.request.bde_count = i;
20213 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
20214 	if (!phba->sli4_hba.intr_enable)
20215 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
20216 	else {
20217 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
20218 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
20219 	}
20220 	/* The IOCTL status is embedded in the mailbox subheader. */
20221 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20222 			     &wr_object->header.cfg_shdr.response);
20223 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20224 				 &wr_object->header.cfg_shdr.response);
20225 	shdr_add_status_2 = bf_get(lpfc_mbox_hdr_add_status_2,
20226 				   &wr_object->header.cfg_shdr.response);
20227 	if (check_change_status) {
20228 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
20229 					    &wr_object->u.response);
20230 		shdr_csf = bf_get(lpfc_wr_object_csf,
20231 				  &wr_object->u.response);
20232 	}
20233 
20234 	if (!phba->sli4_hba.intr_enable)
20235 		mempool_free(mbox, phba->mbox_mem_pool);
20236 	else if (rc != MBX_TIMEOUT)
20237 		mempool_free(mbox, phba->mbox_mem_pool);
20238 	if (shdr_status || shdr_add_status || shdr_add_status_2 || rc) {
20239 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20240 				"3025 Write Object mailbox failed with "
20241 				"status x%x add_status x%x, add_status_2 x%x, "
20242 				"mbx status x%x\n",
20243 				shdr_status, shdr_add_status, shdr_add_status_2,
20244 				rc);
20245 		rc = -ENXIO;
20246 		*offset = shdr_add_status;
20247 	} else {
20248 		*offset += wr_object->u.response.actual_write_length;
20249 	}
20250 
20251 	if (rc || check_change_status)
20252 		lpfc_log_fw_write_cmpl(phba, shdr_status, shdr_add_status,
20253 				       shdr_add_status_2, shdr_change_status,
20254 				       shdr_csf);
20255 	return rc;
20256 }
20257 
20258 /**
20259  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
20260  * @vport: pointer to vport data structure.
20261  *
20262  * This function iterate through the mailboxq and clean up all REG_LOGIN
20263  * and REG_VPI mailbox commands associated with the vport. This function
20264  * is called when driver want to restart discovery of the vport due to
20265  * a Clear Virtual Link event.
20266  **/
20267 void
20268 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
20269 {
20270 	struct lpfc_hba *phba = vport->phba;
20271 	LPFC_MBOXQ_t *mb, *nextmb;
20272 	struct lpfc_dmabuf *mp;
20273 	struct lpfc_nodelist *ndlp;
20274 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
20275 	LIST_HEAD(mbox_cmd_list);
20276 	uint8_t restart_loop;
20277 
20278 	/* Clean up internally queued mailbox commands with the vport */
20279 	spin_lock_irq(&phba->hbalock);
20280 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
20281 		if (mb->vport != vport)
20282 			continue;
20283 
20284 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
20285 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
20286 			continue;
20287 
20288 		list_move_tail(&mb->list, &mbox_cmd_list);
20289 	}
20290 	/* Clean up active mailbox command with the vport */
20291 	mb = phba->sli.mbox_active;
20292 	if (mb && (mb->vport == vport)) {
20293 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
20294 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
20295 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
20296 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20297 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20298 			/* Put reference count for delayed processing */
20299 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
20300 			/* Unregister the RPI when mailbox complete */
20301 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
20302 		}
20303 	}
20304 	/* Cleanup any mailbox completions which are not yet processed */
20305 	do {
20306 		restart_loop = 0;
20307 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
20308 			/*
20309 			 * If this mailox is already processed or it is
20310 			 * for another vport ignore it.
20311 			 */
20312 			if ((mb->vport != vport) ||
20313 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
20314 				continue;
20315 
20316 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
20317 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
20318 				continue;
20319 
20320 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
20321 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20322 				ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20323 				/* Unregister the RPI when mailbox complete */
20324 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
20325 				restart_loop = 1;
20326 				spin_unlock_irq(&phba->hbalock);
20327 				spin_lock(&ndlp->lock);
20328 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20329 				spin_unlock(&ndlp->lock);
20330 				spin_lock_irq(&phba->hbalock);
20331 				break;
20332 			}
20333 		}
20334 	} while (restart_loop);
20335 
20336 	spin_unlock_irq(&phba->hbalock);
20337 
20338 	/* Release the cleaned-up mailbox commands */
20339 	while (!list_empty(&mbox_cmd_list)) {
20340 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
20341 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20342 			mp = (struct lpfc_dmabuf *)(mb->ctx_buf);
20343 			if (mp) {
20344 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
20345 				kfree(mp);
20346 			}
20347 			mb->ctx_buf = NULL;
20348 			ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20349 			mb->ctx_ndlp = NULL;
20350 			if (ndlp) {
20351 				spin_lock(&ndlp->lock);
20352 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20353 				spin_unlock(&ndlp->lock);
20354 				lpfc_nlp_put(ndlp);
20355 			}
20356 		}
20357 		mempool_free(mb, phba->mbox_mem_pool);
20358 	}
20359 
20360 	/* Release the ndlp with the cleaned-up active mailbox command */
20361 	if (act_mbx_ndlp) {
20362 		spin_lock(&act_mbx_ndlp->lock);
20363 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20364 		spin_unlock(&act_mbx_ndlp->lock);
20365 		lpfc_nlp_put(act_mbx_ndlp);
20366 	}
20367 }
20368 
20369 /**
20370  * lpfc_drain_txq - Drain the txq
20371  * @phba: Pointer to HBA context object.
20372  *
20373  * This function attempt to submit IOCBs on the txq
20374  * to the adapter.  For SLI4 adapters, the txq contains
20375  * ELS IOCBs that have been deferred because the there
20376  * are no SGLs.  This congestion can occur with large
20377  * vport counts during node discovery.
20378  **/
20379 
20380 uint32_t
20381 lpfc_drain_txq(struct lpfc_hba *phba)
20382 {
20383 	LIST_HEAD(completions);
20384 	struct lpfc_sli_ring *pring;
20385 	struct lpfc_iocbq *piocbq = NULL;
20386 	unsigned long iflags = 0;
20387 	char *fail_msg = NULL;
20388 	struct lpfc_sglq *sglq;
20389 	union lpfc_wqe128 wqe;
20390 	uint32_t txq_cnt = 0;
20391 	struct lpfc_queue *wq;
20392 
20393 	if (phba->link_flag & LS_MDS_LOOPBACK) {
20394 		/* MDS WQE are posted only to first WQ*/
20395 		wq = phba->sli4_hba.hdwq[0].io_wq;
20396 		if (unlikely(!wq))
20397 			return 0;
20398 		pring = wq->pring;
20399 	} else {
20400 		wq = phba->sli4_hba.els_wq;
20401 		if (unlikely(!wq))
20402 			return 0;
20403 		pring = lpfc_phba_elsring(phba);
20404 	}
20405 
20406 	if (unlikely(!pring) || list_empty(&pring->txq))
20407 		return 0;
20408 
20409 	spin_lock_irqsave(&pring->ring_lock, iflags);
20410 	list_for_each_entry(piocbq, &pring->txq, list) {
20411 		txq_cnt++;
20412 	}
20413 
20414 	if (txq_cnt > pring->txq_max)
20415 		pring->txq_max = txq_cnt;
20416 
20417 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
20418 
20419 	while (!list_empty(&pring->txq)) {
20420 		spin_lock_irqsave(&pring->ring_lock, iflags);
20421 
20422 		piocbq = lpfc_sli_ringtx_get(phba, pring);
20423 		if (!piocbq) {
20424 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20425 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20426 				"2823 txq empty and txq_cnt is %d\n ",
20427 				txq_cnt);
20428 			break;
20429 		}
20430 		sglq = __lpfc_sli_get_els_sglq(phba, piocbq);
20431 		if (!sglq) {
20432 			__lpfc_sli_ringtx_put(phba, pring, piocbq);
20433 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20434 			break;
20435 		}
20436 		txq_cnt--;
20437 
20438 		/* The xri and iocb resources secured,
20439 		 * attempt to issue request
20440 		 */
20441 		piocbq->sli4_lxritag = sglq->sli4_lxritag;
20442 		piocbq->sli4_xritag = sglq->sli4_xritag;
20443 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
20444 			fail_msg = "to convert bpl to sgl";
20445 		else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
20446 			fail_msg = "to convert iocb to wqe";
20447 		else if (lpfc_sli4_wq_put(wq, &wqe))
20448 			fail_msg = " - Wq is full";
20449 		else
20450 			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
20451 
20452 		if (fail_msg) {
20453 			/* Failed means we can't issue and need to cancel */
20454 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20455 					"2822 IOCB failed %s iotag 0x%x "
20456 					"xri 0x%x\n",
20457 					fail_msg,
20458 					piocbq->iotag, piocbq->sli4_xritag);
20459 			list_add_tail(&piocbq->list, &completions);
20460 		}
20461 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20462 	}
20463 
20464 	/* Cancel all the IOCBs that cannot be issued */
20465 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
20466 				IOERR_SLI_ABORTED);
20467 
20468 	return txq_cnt;
20469 }
20470 
20471 /**
20472  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
20473  * @phba: Pointer to HBA context object.
20474  * @pwqeq: Pointer to command WQE.
20475  * @sglq: Pointer to the scatter gather queue object.
20476  *
20477  * This routine converts the bpl or bde that is in the WQE
20478  * to a sgl list for the sli4 hardware. The physical address
20479  * of the bpl/bde is converted back to a virtual address.
20480  * If the WQE contains a BPL then the list of BDE's is
20481  * converted to sli4_sge's. If the WQE contains a single
20482  * BDE then it is converted to a single sli_sge.
20483  * The WQE is still in cpu endianness so the contents of
20484  * the bpl can be used without byte swapping.
20485  *
20486  * Returns valid XRI = Success, NO_XRI = Failure.
20487  */
20488 static uint16_t
20489 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
20490 		 struct lpfc_sglq *sglq)
20491 {
20492 	uint16_t xritag = NO_XRI;
20493 	struct ulp_bde64 *bpl = NULL;
20494 	struct ulp_bde64 bde;
20495 	struct sli4_sge *sgl  = NULL;
20496 	struct lpfc_dmabuf *dmabuf;
20497 	union lpfc_wqe128 *wqe;
20498 	int numBdes = 0;
20499 	int i = 0;
20500 	uint32_t offset = 0; /* accumulated offset in the sg request list */
20501 	int inbound = 0; /* number of sg reply entries inbound from firmware */
20502 	uint32_t cmd;
20503 
20504 	if (!pwqeq || !sglq)
20505 		return xritag;
20506 
20507 	sgl  = (struct sli4_sge *)sglq->sgl;
20508 	wqe = &pwqeq->wqe;
20509 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
20510 
20511 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
20512 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
20513 		return sglq->sli4_xritag;
20514 	numBdes = pwqeq->rsvd2;
20515 	if (numBdes) {
20516 		/* The addrHigh and addrLow fields within the WQE
20517 		 * have not been byteswapped yet so there is no
20518 		 * need to swap them back.
20519 		 */
20520 		if (pwqeq->context3)
20521 			dmabuf = (struct lpfc_dmabuf *)pwqeq->context3;
20522 		else
20523 			return xritag;
20524 
20525 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
20526 		if (!bpl)
20527 			return xritag;
20528 
20529 		for (i = 0; i < numBdes; i++) {
20530 			/* Should already be byte swapped. */
20531 			sgl->addr_hi = bpl->addrHigh;
20532 			sgl->addr_lo = bpl->addrLow;
20533 
20534 			sgl->word2 = le32_to_cpu(sgl->word2);
20535 			if ((i+1) == numBdes)
20536 				bf_set(lpfc_sli4_sge_last, sgl, 1);
20537 			else
20538 				bf_set(lpfc_sli4_sge_last, sgl, 0);
20539 			/* swap the size field back to the cpu so we
20540 			 * can assign it to the sgl.
20541 			 */
20542 			bde.tus.w = le32_to_cpu(bpl->tus.w);
20543 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
20544 			/* The offsets in the sgl need to be accumulated
20545 			 * separately for the request and reply lists.
20546 			 * The request is always first, the reply follows.
20547 			 */
20548 			switch (cmd) {
20549 			case CMD_GEN_REQUEST64_WQE:
20550 				/* add up the reply sg entries */
20551 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
20552 					inbound++;
20553 				/* first inbound? reset the offset */
20554 				if (inbound == 1)
20555 					offset = 0;
20556 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
20557 				bf_set(lpfc_sli4_sge_type, sgl,
20558 					LPFC_SGE_TYPE_DATA);
20559 				offset += bde.tus.f.bdeSize;
20560 				break;
20561 			case CMD_FCP_TRSP64_WQE:
20562 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
20563 				bf_set(lpfc_sli4_sge_type, sgl,
20564 					LPFC_SGE_TYPE_DATA);
20565 				break;
20566 			case CMD_FCP_TSEND64_WQE:
20567 			case CMD_FCP_TRECEIVE64_WQE:
20568 				bf_set(lpfc_sli4_sge_type, sgl,
20569 					bpl->tus.f.bdeFlags);
20570 				if (i < 3)
20571 					offset = 0;
20572 				else
20573 					offset += bde.tus.f.bdeSize;
20574 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
20575 				break;
20576 			}
20577 			sgl->word2 = cpu_to_le32(sgl->word2);
20578 			bpl++;
20579 			sgl++;
20580 		}
20581 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
20582 		/* The addrHigh and addrLow fields of the BDE have not
20583 		 * been byteswapped yet so they need to be swapped
20584 		 * before putting them in the sgl.
20585 		 */
20586 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
20587 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
20588 		sgl->word2 = le32_to_cpu(sgl->word2);
20589 		bf_set(lpfc_sli4_sge_last, sgl, 1);
20590 		sgl->word2 = cpu_to_le32(sgl->word2);
20591 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
20592 	}
20593 	return sglq->sli4_xritag;
20594 }
20595 
20596 /**
20597  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
20598  * @phba: Pointer to HBA context object.
20599  * @qp: Pointer to HDW queue.
20600  * @pwqe: Pointer to command WQE.
20601  **/
20602 int
20603 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
20604 		    struct lpfc_iocbq *pwqe)
20605 {
20606 	union lpfc_wqe128 *wqe = &pwqe->wqe;
20607 	struct lpfc_async_xchg_ctx *ctxp;
20608 	struct lpfc_queue *wq;
20609 	struct lpfc_sglq *sglq;
20610 	struct lpfc_sli_ring *pring;
20611 	unsigned long iflags;
20612 	uint32_t ret = 0;
20613 
20614 	/* NVME_LS and NVME_LS ABTS requests. */
20615 	if (pwqe->iocb_flag & LPFC_IO_NVME_LS) {
20616 		pring =  phba->sli4_hba.nvmels_wq->pring;
20617 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20618 					  qp, wq_access);
20619 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
20620 		if (!sglq) {
20621 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20622 			return WQE_BUSY;
20623 		}
20624 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
20625 		pwqe->sli4_xritag = sglq->sli4_xritag;
20626 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
20627 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20628 			return WQE_ERROR;
20629 		}
20630 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
20631 		       pwqe->sli4_xritag);
20632 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
20633 		if (ret) {
20634 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20635 			return ret;
20636 		}
20637 
20638 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20639 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20640 
20641 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20642 		return 0;
20643 	}
20644 
20645 	/* NVME_FCREQ and NVME_ABTS requests */
20646 	if (pwqe->iocb_flag & LPFC_IO_NVME ||
20647 	    pwqe->iocb_flag & LPFC_IO_FCP) {
20648 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
20649 		wq = qp->io_wq;
20650 		pring = wq->pring;
20651 
20652 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
20653 
20654 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20655 					  qp, wq_access);
20656 		ret = lpfc_sli4_wq_put(wq, wqe);
20657 		if (ret) {
20658 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20659 			return ret;
20660 		}
20661 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20662 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20663 
20664 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20665 		return 0;
20666 	}
20667 
20668 	/* NVMET requests */
20669 	if (pwqe->iocb_flag & LPFC_IO_NVMET) {
20670 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
20671 		wq = qp->io_wq;
20672 		pring = wq->pring;
20673 
20674 		ctxp = pwqe->context2;
20675 		sglq = ctxp->ctxbuf->sglq;
20676 		if (pwqe->sli4_xritag ==  NO_XRI) {
20677 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
20678 			pwqe->sli4_xritag = sglq->sli4_xritag;
20679 		}
20680 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
20681 		       pwqe->sli4_xritag);
20682 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
20683 
20684 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20685 					  qp, wq_access);
20686 		ret = lpfc_sli4_wq_put(wq, wqe);
20687 		if (ret) {
20688 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20689 			return ret;
20690 		}
20691 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20692 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20693 
20694 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20695 		return 0;
20696 	}
20697 	return WQE_ERROR;
20698 }
20699 
20700 /**
20701  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
20702  * @phba: Pointer to HBA context object.
20703  * @cmdiocb: Pointer to driver command iocb object.
20704  * @cmpl: completion function.
20705  *
20706  * Fill the appropriate fields for the abort WQE and call
20707  * internal routine lpfc_sli4_issue_wqe to send the WQE
20708  * This function is called with hbalock held and no ring_lock held.
20709  *
20710  * RETURNS 0 - SUCCESS
20711  **/
20712 
20713 int
20714 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
20715 			    void *cmpl)
20716 {
20717 	struct lpfc_vport *vport = cmdiocb->vport;
20718 	struct lpfc_iocbq *abtsiocb = NULL;
20719 	union lpfc_wqe128 *abtswqe;
20720 	struct lpfc_io_buf *lpfc_cmd;
20721 	int retval = IOCB_ERROR;
20722 	u16 xritag = cmdiocb->sli4_xritag;
20723 
20724 	/*
20725 	 * The scsi command can not be in txq and it is in flight because the
20726 	 * pCmd is still pointing at the SCSI command we have to abort. There
20727 	 * is no need to search the txcmplq. Just send an abort to the FW.
20728 	 */
20729 
20730 	abtsiocb = __lpfc_sli_get_iocbq(phba);
20731 	if (!abtsiocb)
20732 		return WQE_NORESOURCE;
20733 
20734 	/* Indicate the IO is being aborted by the driver. */
20735 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
20736 
20737 	abtswqe = &abtsiocb->wqe;
20738 	memset(abtswqe, 0, sizeof(*abtswqe));
20739 
20740 	if (!lpfc_is_link_up(phba))
20741 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
20742 	bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
20743 	abtswqe->abort_cmd.rsrvd5 = 0;
20744 	abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
20745 	bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
20746 	bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
20747 	bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
20748 	bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
20749 	bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
20750 	bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
20751 
20752 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
20753 	abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
20754 	abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
20755 	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
20756 		abtsiocb->iocb_flag |= LPFC_IO_FCP;
20757 	if (cmdiocb->iocb_flag & LPFC_IO_NVME)
20758 		abtsiocb->iocb_flag |= LPFC_IO_NVME;
20759 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
20760 		abtsiocb->iocb_flag |= LPFC_IO_FOF;
20761 	abtsiocb->vport = vport;
20762 	abtsiocb->wqe_cmpl = cmpl;
20763 
20764 	lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
20765 	retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
20766 
20767 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
20768 			 "0359 Abort xri x%x, original iotag x%x, "
20769 			 "abort cmd iotag x%x retval x%x\n",
20770 			 xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
20771 
20772 	if (retval) {
20773 		cmdiocb->iocb_flag &= ~LPFC_DRIVER_ABORTED;
20774 		__lpfc_sli_release_iocbq(phba, abtsiocb);
20775 	}
20776 
20777 	return retval;
20778 }
20779 
20780 #ifdef LPFC_MXP_STAT
20781 /**
20782  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
20783  * @phba: pointer to lpfc hba data structure.
20784  * @hwqid: belong to which HWQ.
20785  *
20786  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
20787  * 15 seconds after a test case is running.
20788  *
20789  * The user should call lpfc_debugfs_multixripools_write before running a test
20790  * case to clear stat_snapshot_taken. Then the user starts a test case. During
20791  * test case is running, stat_snapshot_taken is incremented by 1 every time when
20792  * this routine is called from heartbeat timer. When stat_snapshot_taken is
20793  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
20794  **/
20795 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
20796 {
20797 	struct lpfc_sli4_hdw_queue *qp;
20798 	struct lpfc_multixri_pool *multixri_pool;
20799 	struct lpfc_pvt_pool *pvt_pool;
20800 	struct lpfc_pbl_pool *pbl_pool;
20801 	u32 txcmplq_cnt;
20802 
20803 	qp = &phba->sli4_hba.hdwq[hwqid];
20804 	multixri_pool = qp->p_multixri_pool;
20805 	if (!multixri_pool)
20806 		return;
20807 
20808 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
20809 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
20810 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
20811 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20812 
20813 		multixri_pool->stat_pbl_count = pbl_pool->count;
20814 		multixri_pool->stat_pvt_count = pvt_pool->count;
20815 		multixri_pool->stat_busy_count = txcmplq_cnt;
20816 	}
20817 
20818 	multixri_pool->stat_snapshot_taken++;
20819 }
20820 #endif
20821 
20822 /**
20823  * lpfc_adjust_pvt_pool_count - Adjust private pool count
20824  * @phba: pointer to lpfc hba data structure.
20825  * @hwqid: belong to which HWQ.
20826  *
20827  * This routine moves some XRIs from private to public pool when private pool
20828  * is not busy.
20829  **/
20830 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
20831 {
20832 	struct lpfc_multixri_pool *multixri_pool;
20833 	u32 io_req_count;
20834 	u32 prev_io_req_count;
20835 
20836 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
20837 	if (!multixri_pool)
20838 		return;
20839 	io_req_count = multixri_pool->io_req_count;
20840 	prev_io_req_count = multixri_pool->prev_io_req_count;
20841 
20842 	if (prev_io_req_count != io_req_count) {
20843 		/* Private pool is busy */
20844 		multixri_pool->prev_io_req_count = io_req_count;
20845 	} else {
20846 		/* Private pool is not busy.
20847 		 * Move XRIs from private to public pool.
20848 		 */
20849 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
20850 	}
20851 }
20852 
20853 /**
20854  * lpfc_adjust_high_watermark - Adjust high watermark
20855  * @phba: pointer to lpfc hba data structure.
20856  * @hwqid: belong to which HWQ.
20857  *
20858  * This routine sets high watermark as number of outstanding XRIs,
20859  * but make sure the new value is between xri_limit/2 and xri_limit.
20860  **/
20861 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
20862 {
20863 	u32 new_watermark;
20864 	u32 watermark_max;
20865 	u32 watermark_min;
20866 	u32 xri_limit;
20867 	u32 txcmplq_cnt;
20868 	u32 abts_io_bufs;
20869 	struct lpfc_multixri_pool *multixri_pool;
20870 	struct lpfc_sli4_hdw_queue *qp;
20871 
20872 	qp = &phba->sli4_hba.hdwq[hwqid];
20873 	multixri_pool = qp->p_multixri_pool;
20874 	if (!multixri_pool)
20875 		return;
20876 	xri_limit = multixri_pool->xri_limit;
20877 
20878 	watermark_max = xri_limit;
20879 	watermark_min = xri_limit / 2;
20880 
20881 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20882 	abts_io_bufs = qp->abts_scsi_io_bufs;
20883 	abts_io_bufs += qp->abts_nvme_io_bufs;
20884 
20885 	new_watermark = txcmplq_cnt + abts_io_bufs;
20886 	new_watermark = min(watermark_max, new_watermark);
20887 	new_watermark = max(watermark_min, new_watermark);
20888 	multixri_pool->pvt_pool.high_watermark = new_watermark;
20889 
20890 #ifdef LPFC_MXP_STAT
20891 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
20892 					  new_watermark);
20893 #endif
20894 }
20895 
20896 /**
20897  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
20898  * @phba: pointer to lpfc hba data structure.
20899  * @hwqid: belong to which HWQ.
20900  *
20901  * This routine is called from hearbeat timer when pvt_pool is idle.
20902  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
20903  * The first step moves (all - low_watermark) amount of XRIs.
20904  * The second step moves the rest of XRIs.
20905  **/
20906 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
20907 {
20908 	struct lpfc_pbl_pool *pbl_pool;
20909 	struct lpfc_pvt_pool *pvt_pool;
20910 	struct lpfc_sli4_hdw_queue *qp;
20911 	struct lpfc_io_buf *lpfc_ncmd;
20912 	struct lpfc_io_buf *lpfc_ncmd_next;
20913 	unsigned long iflag;
20914 	struct list_head tmp_list;
20915 	u32 tmp_count;
20916 
20917 	qp = &phba->sli4_hba.hdwq[hwqid];
20918 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
20919 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
20920 	tmp_count = 0;
20921 
20922 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
20923 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
20924 
20925 	if (pvt_pool->count > pvt_pool->low_watermark) {
20926 		/* Step 1: move (all - low_watermark) from pvt_pool
20927 		 * to pbl_pool
20928 		 */
20929 
20930 		/* Move low watermark of bufs from pvt_pool to tmp_list */
20931 		INIT_LIST_HEAD(&tmp_list);
20932 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20933 					 &pvt_pool->list, list) {
20934 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
20935 			tmp_count++;
20936 			if (tmp_count >= pvt_pool->low_watermark)
20937 				break;
20938 		}
20939 
20940 		/* Move all bufs from pvt_pool to pbl_pool */
20941 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
20942 
20943 		/* Move all bufs from tmp_list to pvt_pool */
20944 		list_splice(&tmp_list, &pvt_pool->list);
20945 
20946 		pbl_pool->count += (pvt_pool->count - tmp_count);
20947 		pvt_pool->count = tmp_count;
20948 	} else {
20949 		/* Step 2: move the rest from pvt_pool to pbl_pool */
20950 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
20951 		pbl_pool->count += pvt_pool->count;
20952 		pvt_pool->count = 0;
20953 	}
20954 
20955 	spin_unlock(&pvt_pool->lock);
20956 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20957 }
20958 
20959 /**
20960  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
20961  * @phba: pointer to lpfc hba data structure
20962  * @qp: pointer to HDW queue
20963  * @pbl_pool: specified public free XRI pool
20964  * @pvt_pool: specified private free XRI pool
20965  * @count: number of XRIs to move
20966  *
20967  * This routine tries to move some free common bufs from the specified pbl_pool
20968  * to the specified pvt_pool. It might move less than count XRIs if there's not
20969  * enough in public pool.
20970  *
20971  * Return:
20972  *   true - if XRIs are successfully moved from the specified pbl_pool to the
20973  *          specified pvt_pool
20974  *   false - if the specified pbl_pool is empty or locked by someone else
20975  **/
20976 static bool
20977 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
20978 			  struct lpfc_pbl_pool *pbl_pool,
20979 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
20980 {
20981 	struct lpfc_io_buf *lpfc_ncmd;
20982 	struct lpfc_io_buf *lpfc_ncmd_next;
20983 	unsigned long iflag;
20984 	int ret;
20985 
20986 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
20987 	if (ret) {
20988 		if (pbl_pool->count) {
20989 			/* Move a batch of XRIs from public to private pool */
20990 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
20991 			list_for_each_entry_safe(lpfc_ncmd,
20992 						 lpfc_ncmd_next,
20993 						 &pbl_pool->list,
20994 						 list) {
20995 				list_move_tail(&lpfc_ncmd->list,
20996 					       &pvt_pool->list);
20997 				pvt_pool->count++;
20998 				pbl_pool->count--;
20999 				count--;
21000 				if (count == 0)
21001 					break;
21002 			}
21003 
21004 			spin_unlock(&pvt_pool->lock);
21005 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21006 			return true;
21007 		}
21008 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21009 	}
21010 
21011 	return false;
21012 }
21013 
21014 /**
21015  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21016  * @phba: pointer to lpfc hba data structure.
21017  * @hwqid: belong to which HWQ.
21018  * @count: number of XRIs to move
21019  *
21020  * This routine tries to find some free common bufs in one of public pools with
21021  * Round Robin method. The search always starts from local hwqid, then the next
21022  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
21023  * a batch of free common bufs are moved to private pool on hwqid.
21024  * It might move less than count XRIs if there's not enough in public pool.
21025  **/
21026 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
21027 {
21028 	struct lpfc_multixri_pool *multixri_pool;
21029 	struct lpfc_multixri_pool *next_multixri_pool;
21030 	struct lpfc_pvt_pool *pvt_pool;
21031 	struct lpfc_pbl_pool *pbl_pool;
21032 	struct lpfc_sli4_hdw_queue *qp;
21033 	u32 next_hwqid;
21034 	u32 hwq_count;
21035 	int ret;
21036 
21037 	qp = &phba->sli4_hba.hdwq[hwqid];
21038 	multixri_pool = qp->p_multixri_pool;
21039 	pvt_pool = &multixri_pool->pvt_pool;
21040 	pbl_pool = &multixri_pool->pbl_pool;
21041 
21042 	/* Check if local pbl_pool is available */
21043 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
21044 	if (ret) {
21045 #ifdef LPFC_MXP_STAT
21046 		multixri_pool->local_pbl_hit_count++;
21047 #endif
21048 		return;
21049 	}
21050 
21051 	hwq_count = phba->cfg_hdw_queue;
21052 
21053 	/* Get the next hwqid which was found last time */
21054 	next_hwqid = multixri_pool->rrb_next_hwqid;
21055 
21056 	do {
21057 		/* Go to next hwq */
21058 		next_hwqid = (next_hwqid + 1) % hwq_count;
21059 
21060 		next_multixri_pool =
21061 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
21062 		pbl_pool = &next_multixri_pool->pbl_pool;
21063 
21064 		/* Check if the public free xri pool is available */
21065 		ret = _lpfc_move_xri_pbl_to_pvt(
21066 			phba, qp, pbl_pool, pvt_pool, count);
21067 
21068 		/* Exit while-loop if success or all hwqid are checked */
21069 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
21070 
21071 	/* Starting point for the next time */
21072 	multixri_pool->rrb_next_hwqid = next_hwqid;
21073 
21074 	if (!ret) {
21075 		/* stats: all public pools are empty*/
21076 		multixri_pool->pbl_empty_count++;
21077 	}
21078 
21079 #ifdef LPFC_MXP_STAT
21080 	if (ret) {
21081 		if (next_hwqid == hwqid)
21082 			multixri_pool->local_pbl_hit_count++;
21083 		else
21084 			multixri_pool->other_pbl_hit_count++;
21085 	}
21086 #endif
21087 }
21088 
21089 /**
21090  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
21091  * @phba: pointer to lpfc hba data structure.
21092  * @hwqid: belong to which HWQ.
21093  *
21094  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
21095  * low watermark.
21096  **/
21097 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
21098 {
21099 	struct lpfc_multixri_pool *multixri_pool;
21100 	struct lpfc_pvt_pool *pvt_pool;
21101 
21102 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21103 	pvt_pool = &multixri_pool->pvt_pool;
21104 
21105 	if (pvt_pool->count < pvt_pool->low_watermark)
21106 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21107 }
21108 
21109 /**
21110  * lpfc_release_io_buf - Return one IO buf back to free pool
21111  * @phba: pointer to lpfc hba data structure.
21112  * @lpfc_ncmd: IO buf to be returned.
21113  * @qp: belong to which HWQ.
21114  *
21115  * This routine returns one IO buf back to free pool. If this is an urgent IO,
21116  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
21117  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
21118  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
21119  * lpfc_io_buf_list_put.
21120  **/
21121 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
21122 			 struct lpfc_sli4_hdw_queue *qp)
21123 {
21124 	unsigned long iflag;
21125 	struct lpfc_pbl_pool *pbl_pool;
21126 	struct lpfc_pvt_pool *pvt_pool;
21127 	struct lpfc_epd_pool *epd_pool;
21128 	u32 txcmplq_cnt;
21129 	u32 xri_owned;
21130 	u32 xri_limit;
21131 	u32 abts_io_bufs;
21132 
21133 	/* MUST zero fields if buffer is reused by another protocol */
21134 	lpfc_ncmd->nvmeCmd = NULL;
21135 	lpfc_ncmd->cur_iocbq.wqe_cmpl = NULL;
21136 	lpfc_ncmd->cur_iocbq.iocb_cmpl = NULL;
21137 
21138 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
21139 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
21140 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
21141 
21142 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
21143 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
21144 
21145 	if (phba->cfg_xri_rebalancing) {
21146 		if (lpfc_ncmd->expedite) {
21147 			/* Return to expedite pool */
21148 			epd_pool = &phba->epd_pool;
21149 			spin_lock_irqsave(&epd_pool->lock, iflag);
21150 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21151 			epd_pool->count++;
21152 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
21153 			return;
21154 		}
21155 
21156 		/* Avoid invalid access if an IO sneaks in and is being rejected
21157 		 * just _after_ xri pools are destroyed in lpfc_offline.
21158 		 * Nothing much can be done at this point.
21159 		 */
21160 		if (!qp->p_multixri_pool)
21161 			return;
21162 
21163 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21164 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21165 
21166 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21167 		abts_io_bufs = qp->abts_scsi_io_bufs;
21168 		abts_io_bufs += qp->abts_nvme_io_bufs;
21169 
21170 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21171 		xri_limit = qp->p_multixri_pool->xri_limit;
21172 
21173 #ifdef LPFC_MXP_STAT
21174 		if (xri_owned <= xri_limit)
21175 			qp->p_multixri_pool->below_limit_count++;
21176 		else
21177 			qp->p_multixri_pool->above_limit_count++;
21178 #endif
21179 
21180 		/* XRI goes to either public or private free xri pool
21181 		 *     based on watermark and xri_limit
21182 		 */
21183 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
21184 		    (xri_owned < xri_limit &&
21185 		     pvt_pool->count < pvt_pool->high_watermark)) {
21186 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
21187 						  qp, free_pvt_pool);
21188 			list_add_tail(&lpfc_ncmd->list,
21189 				      &pvt_pool->list);
21190 			pvt_pool->count++;
21191 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21192 		} else {
21193 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
21194 						  qp, free_pub_pool);
21195 			list_add_tail(&lpfc_ncmd->list,
21196 				      &pbl_pool->list);
21197 			pbl_pool->count++;
21198 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21199 		}
21200 	} else {
21201 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
21202 					  qp, free_xri);
21203 		list_add_tail(&lpfc_ncmd->list,
21204 			      &qp->lpfc_io_buf_list_put);
21205 		qp->put_io_bufs++;
21206 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
21207 				       iflag);
21208 	}
21209 }
21210 
21211 /**
21212  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
21213  * @phba: pointer to lpfc hba data structure.
21214  * @qp: pointer to HDW queue
21215  * @pvt_pool: pointer to private pool data structure.
21216  * @ndlp: pointer to lpfc nodelist data structure.
21217  *
21218  * This routine tries to get one free IO buf from private pool.
21219  *
21220  * Return:
21221  *   pointer to one free IO buf - if private pool is not empty
21222  *   NULL - if private pool is empty
21223  **/
21224 static struct lpfc_io_buf *
21225 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
21226 				  struct lpfc_sli4_hdw_queue *qp,
21227 				  struct lpfc_pvt_pool *pvt_pool,
21228 				  struct lpfc_nodelist *ndlp)
21229 {
21230 	struct lpfc_io_buf *lpfc_ncmd;
21231 	struct lpfc_io_buf *lpfc_ncmd_next;
21232 	unsigned long iflag;
21233 
21234 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
21235 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21236 				 &pvt_pool->list, list) {
21237 		if (lpfc_test_rrq_active(
21238 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
21239 			continue;
21240 		list_del(&lpfc_ncmd->list);
21241 		pvt_pool->count--;
21242 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21243 		return lpfc_ncmd;
21244 	}
21245 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21246 
21247 	return NULL;
21248 }
21249 
21250 /**
21251  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
21252  * @phba: pointer to lpfc hba data structure.
21253  *
21254  * This routine tries to get one free IO buf from expedite pool.
21255  *
21256  * Return:
21257  *   pointer to one free IO buf - if expedite pool is not empty
21258  *   NULL - if expedite pool is empty
21259  **/
21260 static struct lpfc_io_buf *
21261 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
21262 {
21263 	struct lpfc_io_buf *lpfc_ncmd;
21264 	struct lpfc_io_buf *lpfc_ncmd_next;
21265 	unsigned long iflag;
21266 	struct lpfc_epd_pool *epd_pool;
21267 
21268 	epd_pool = &phba->epd_pool;
21269 	lpfc_ncmd = NULL;
21270 
21271 	spin_lock_irqsave(&epd_pool->lock, iflag);
21272 	if (epd_pool->count > 0) {
21273 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21274 					 &epd_pool->list, list) {
21275 			list_del(&lpfc_ncmd->list);
21276 			epd_pool->count--;
21277 			break;
21278 		}
21279 	}
21280 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
21281 
21282 	return lpfc_ncmd;
21283 }
21284 
21285 /**
21286  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
21287  * @phba: pointer to lpfc hba data structure.
21288  * @ndlp: pointer to lpfc nodelist data structure.
21289  * @hwqid: belong to which HWQ
21290  * @expedite: 1 means this request is urgent.
21291  *
21292  * This routine will do the following actions and then return a pointer to
21293  * one free IO buf.
21294  *
21295  * 1. If private free xri count is empty, move some XRIs from public to
21296  *    private pool.
21297  * 2. Get one XRI from private free xri pool.
21298  * 3. If we fail to get one from pvt_pool and this is an expedite request,
21299  *    get one free xri from expedite pool.
21300  *
21301  * Note: ndlp is only used on SCSI side for RRQ testing.
21302  *       The caller should pass NULL for ndlp on NVME side.
21303  *
21304  * Return:
21305  *   pointer to one free IO buf - if private pool is not empty
21306  *   NULL - if private pool is empty
21307  **/
21308 static struct lpfc_io_buf *
21309 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
21310 				    struct lpfc_nodelist *ndlp,
21311 				    int hwqid, int expedite)
21312 {
21313 	struct lpfc_sli4_hdw_queue *qp;
21314 	struct lpfc_multixri_pool *multixri_pool;
21315 	struct lpfc_pvt_pool *pvt_pool;
21316 	struct lpfc_io_buf *lpfc_ncmd;
21317 
21318 	qp = &phba->sli4_hba.hdwq[hwqid];
21319 	lpfc_ncmd = NULL;
21320 	multixri_pool = qp->p_multixri_pool;
21321 	pvt_pool = &multixri_pool->pvt_pool;
21322 	multixri_pool->io_req_count++;
21323 
21324 	/* If pvt_pool is empty, move some XRIs from public to private pool */
21325 	if (pvt_pool->count == 0)
21326 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21327 
21328 	/* Get one XRI from private free xri pool */
21329 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
21330 
21331 	if (lpfc_ncmd) {
21332 		lpfc_ncmd->hdwq = qp;
21333 		lpfc_ncmd->hdwq_no = hwqid;
21334 	} else if (expedite) {
21335 		/* If we fail to get one from pvt_pool and this is an expedite
21336 		 * request, get one free xri from expedite pool.
21337 		 */
21338 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
21339 	}
21340 
21341 	return lpfc_ncmd;
21342 }
21343 
21344 static inline struct lpfc_io_buf *
21345 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
21346 {
21347 	struct lpfc_sli4_hdw_queue *qp;
21348 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
21349 
21350 	qp = &phba->sli4_hba.hdwq[idx];
21351 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
21352 				 &qp->lpfc_io_buf_list_get, list) {
21353 		if (lpfc_test_rrq_active(phba, ndlp,
21354 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
21355 			continue;
21356 
21357 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
21358 			continue;
21359 
21360 		list_del_init(&lpfc_cmd->list);
21361 		qp->get_io_bufs--;
21362 		lpfc_cmd->hdwq = qp;
21363 		lpfc_cmd->hdwq_no = idx;
21364 		return lpfc_cmd;
21365 	}
21366 	return NULL;
21367 }
21368 
21369 /**
21370  * lpfc_get_io_buf - Get one IO buffer from free pool
21371  * @phba: The HBA for which this call is being executed.
21372  * @ndlp: pointer to lpfc nodelist data structure.
21373  * @hwqid: belong to which HWQ
21374  * @expedite: 1 means this request is urgent.
21375  *
21376  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
21377  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
21378  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
21379  *
21380  * Note: ndlp is only used on SCSI side for RRQ testing.
21381  *       The caller should pass NULL for ndlp on NVME side.
21382  *
21383  * Return codes:
21384  *   NULL - Error
21385  *   Pointer to lpfc_io_buf - Success
21386  **/
21387 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
21388 				    struct lpfc_nodelist *ndlp,
21389 				    u32 hwqid, int expedite)
21390 {
21391 	struct lpfc_sli4_hdw_queue *qp;
21392 	unsigned long iflag;
21393 	struct lpfc_io_buf *lpfc_cmd;
21394 
21395 	qp = &phba->sli4_hba.hdwq[hwqid];
21396 	lpfc_cmd = NULL;
21397 
21398 	if (phba->cfg_xri_rebalancing)
21399 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
21400 			phba, ndlp, hwqid, expedite);
21401 	else {
21402 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
21403 					  qp, alloc_xri_get);
21404 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
21405 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
21406 		if (!lpfc_cmd) {
21407 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
21408 					  qp, alloc_xri_put);
21409 			list_splice(&qp->lpfc_io_buf_list_put,
21410 				    &qp->lpfc_io_buf_list_get);
21411 			qp->get_io_bufs += qp->put_io_bufs;
21412 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
21413 			qp->put_io_bufs = 0;
21414 			spin_unlock(&qp->io_buf_list_put_lock);
21415 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
21416 			    expedite)
21417 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
21418 		}
21419 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
21420 	}
21421 
21422 	return lpfc_cmd;
21423 }
21424 
21425 /**
21426  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
21427  * @phba: The HBA for which this call is being executed.
21428  * @lpfc_buf: IO buf structure to append the SGL chunk
21429  *
21430  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
21431  * and will allocate an SGL chunk if the pool is empty.
21432  *
21433  * Return codes:
21434  *   NULL - Error
21435  *   Pointer to sli4_hybrid_sgl - Success
21436  **/
21437 struct sli4_hybrid_sgl *
21438 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
21439 {
21440 	struct sli4_hybrid_sgl *list_entry = NULL;
21441 	struct sli4_hybrid_sgl *tmp = NULL;
21442 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
21443 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21444 	struct list_head *buf_list = &hdwq->sgl_list;
21445 	unsigned long iflags;
21446 
21447 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21448 
21449 	if (likely(!list_empty(buf_list))) {
21450 		/* break off 1 chunk from the sgl_list */
21451 		list_for_each_entry_safe(list_entry, tmp,
21452 					 buf_list, list_node) {
21453 			list_move_tail(&list_entry->list_node,
21454 				       &lpfc_buf->dma_sgl_xtra_list);
21455 			break;
21456 		}
21457 	} else {
21458 		/* allocate more */
21459 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21460 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
21461 				   cpu_to_node(hdwq->io_wq->chann));
21462 		if (!tmp) {
21463 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21464 					"8353 error kmalloc memory for HDWQ "
21465 					"%d %s\n",
21466 					lpfc_buf->hdwq_no, __func__);
21467 			return NULL;
21468 		}
21469 
21470 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
21471 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
21472 		if (!tmp->dma_sgl) {
21473 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21474 					"8354 error pool_alloc memory for HDWQ "
21475 					"%d %s\n",
21476 					lpfc_buf->hdwq_no, __func__);
21477 			kfree(tmp);
21478 			return NULL;
21479 		}
21480 
21481 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21482 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
21483 	}
21484 
21485 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
21486 					struct sli4_hybrid_sgl,
21487 					list_node);
21488 
21489 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21490 
21491 	return allocated_sgl;
21492 }
21493 
21494 /**
21495  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
21496  * @phba: The HBA for which this call is being executed.
21497  * @lpfc_buf: IO buf structure with the SGL chunk
21498  *
21499  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
21500  *
21501  * Return codes:
21502  *   0 - Success
21503  *   -EINVAL - Error
21504  **/
21505 int
21506 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
21507 {
21508 	int rc = 0;
21509 	struct sli4_hybrid_sgl *list_entry = NULL;
21510 	struct sli4_hybrid_sgl *tmp = NULL;
21511 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21512 	struct list_head *buf_list = &hdwq->sgl_list;
21513 	unsigned long iflags;
21514 
21515 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21516 
21517 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
21518 		list_for_each_entry_safe(list_entry, tmp,
21519 					 &lpfc_buf->dma_sgl_xtra_list,
21520 					 list_node) {
21521 			list_move_tail(&list_entry->list_node,
21522 				       buf_list);
21523 		}
21524 	} else {
21525 		rc = -EINVAL;
21526 	}
21527 
21528 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21529 	return rc;
21530 }
21531 
21532 /**
21533  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
21534  * @phba: phba object
21535  * @hdwq: hdwq to cleanup sgl buff resources on
21536  *
21537  * This routine frees all SGL chunks of hdwq SGL chunk pool.
21538  *
21539  * Return codes:
21540  *   None
21541  **/
21542 void
21543 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
21544 		       struct lpfc_sli4_hdw_queue *hdwq)
21545 {
21546 	struct list_head *buf_list = &hdwq->sgl_list;
21547 	struct sli4_hybrid_sgl *list_entry = NULL;
21548 	struct sli4_hybrid_sgl *tmp = NULL;
21549 	unsigned long iflags;
21550 
21551 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21552 
21553 	/* Free sgl pool */
21554 	list_for_each_entry_safe(list_entry, tmp,
21555 				 buf_list, list_node) {
21556 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
21557 			      list_entry->dma_sgl,
21558 			      list_entry->dma_phys_sgl);
21559 		list_del(&list_entry->list_node);
21560 		kfree(list_entry);
21561 	}
21562 
21563 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21564 }
21565 
21566 /**
21567  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
21568  * @phba: The HBA for which this call is being executed.
21569  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
21570  *
21571  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
21572  * and will allocate an CMD/RSP buffer if the pool is empty.
21573  *
21574  * Return codes:
21575  *   NULL - Error
21576  *   Pointer to fcp_cmd_rsp_buf - Success
21577  **/
21578 struct fcp_cmd_rsp_buf *
21579 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
21580 			      struct lpfc_io_buf *lpfc_buf)
21581 {
21582 	struct fcp_cmd_rsp_buf *list_entry = NULL;
21583 	struct fcp_cmd_rsp_buf *tmp = NULL;
21584 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
21585 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21586 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
21587 	unsigned long iflags;
21588 
21589 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21590 
21591 	if (likely(!list_empty(buf_list))) {
21592 		/* break off 1 chunk from the list */
21593 		list_for_each_entry_safe(list_entry, tmp,
21594 					 buf_list,
21595 					 list_node) {
21596 			list_move_tail(&list_entry->list_node,
21597 				       &lpfc_buf->dma_cmd_rsp_list);
21598 			break;
21599 		}
21600 	} else {
21601 		/* allocate more */
21602 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21603 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
21604 				   cpu_to_node(hdwq->io_wq->chann));
21605 		if (!tmp) {
21606 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21607 					"8355 error kmalloc memory for HDWQ "
21608 					"%d %s\n",
21609 					lpfc_buf->hdwq_no, __func__);
21610 			return NULL;
21611 		}
21612 
21613 		tmp->fcp_cmnd = dma_pool_alloc(phba->lpfc_cmd_rsp_buf_pool,
21614 						GFP_ATOMIC,
21615 						&tmp->fcp_cmd_rsp_dma_handle);
21616 
21617 		if (!tmp->fcp_cmnd) {
21618 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21619 					"8356 error pool_alloc memory for HDWQ "
21620 					"%d %s\n",
21621 					lpfc_buf->hdwq_no, __func__);
21622 			kfree(tmp);
21623 			return NULL;
21624 		}
21625 
21626 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
21627 				sizeof(struct fcp_cmnd));
21628 
21629 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21630 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
21631 	}
21632 
21633 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
21634 					struct fcp_cmd_rsp_buf,
21635 					list_node);
21636 
21637 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21638 
21639 	return allocated_buf;
21640 }
21641 
21642 /**
21643  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
21644  * @phba: The HBA for which this call is being executed.
21645  * @lpfc_buf: IO buf structure with the CMD/RSP buf
21646  *
21647  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
21648  *
21649  * Return codes:
21650  *   0 - Success
21651  *   -EINVAL - Error
21652  **/
21653 int
21654 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
21655 			      struct lpfc_io_buf *lpfc_buf)
21656 {
21657 	int rc = 0;
21658 	struct fcp_cmd_rsp_buf *list_entry = NULL;
21659 	struct fcp_cmd_rsp_buf *tmp = NULL;
21660 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21661 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
21662 	unsigned long iflags;
21663 
21664 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21665 
21666 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
21667 		list_for_each_entry_safe(list_entry, tmp,
21668 					 &lpfc_buf->dma_cmd_rsp_list,
21669 					 list_node) {
21670 			list_move_tail(&list_entry->list_node,
21671 				       buf_list);
21672 		}
21673 	} else {
21674 		rc = -EINVAL;
21675 	}
21676 
21677 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21678 	return rc;
21679 }
21680 
21681 /**
21682  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
21683  * @phba: phba object
21684  * @hdwq: hdwq to cleanup cmd rsp buff resources on
21685  *
21686  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
21687  *
21688  * Return codes:
21689  *   None
21690  **/
21691 void
21692 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
21693 			       struct lpfc_sli4_hdw_queue *hdwq)
21694 {
21695 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
21696 	struct fcp_cmd_rsp_buf *list_entry = NULL;
21697 	struct fcp_cmd_rsp_buf *tmp = NULL;
21698 	unsigned long iflags;
21699 
21700 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21701 
21702 	/* Free cmd_rsp buf pool */
21703 	list_for_each_entry_safe(list_entry, tmp,
21704 				 buf_list,
21705 				 list_node) {
21706 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
21707 			      list_entry->fcp_cmnd,
21708 			      list_entry->fcp_cmd_rsp_dma_handle);
21709 		list_del(&list_entry->list_node);
21710 		kfree(list_entry);
21711 	}
21712 
21713 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21714 }
21715