xref: /linux/drivers/scsi/lpfc/lpfc_sli.c (revision cc9d25b451196e1cdbea5891902cb65b03da1226)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2026 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.     *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/pci.h>
26 #include <linux/interrupt.h>
27 #include <linux/delay.h>
28 #include <linux/seq_buf.h>
29 #include <linux/slab.h>
30 #include <linux/lockdep.h>
31 #include <linux/dmi.h>
32 #include <linux/of.h>
33 
34 #include <scsi/scsi.h>
35 #include <scsi/scsi_cmnd.h>
36 #include <scsi/scsi_device.h>
37 #include <scsi/scsi_host.h>
38 #include <scsi/scsi_transport_fc.h>
39 #include <scsi/fc/fc_fs.h>
40 #include <linux/crash_dump.h>
41 #ifdef CONFIG_X86
42 #include <asm/set_memory.h>
43 #endif
44 
45 #include "lpfc_hw4.h"
46 #include "lpfc_hw.h"
47 #include "lpfc_sli.h"
48 #include "lpfc_sli4.h"
49 #include "lpfc_nl.h"
50 #include "lpfc_disc.h"
51 #include "lpfc.h"
52 #include "lpfc_scsi.h"
53 #include "lpfc_nvme.h"
54 #include "lpfc_crtn.h"
55 #include "lpfc_logmsg.h"
56 #include "lpfc_compat.h"
57 #include "lpfc_debugfs.h"
58 #include "lpfc_vport.h"
59 #include "lpfc_version.h"
60 
61 /* There are only four IOCB completion types. */
62 typedef enum _lpfc_iocb_type {
63 	LPFC_UNKNOWN_IOCB,
64 	LPFC_UNSOL_IOCB,
65 	LPFC_SOL_IOCB,
66 	LPFC_ABORT_IOCB
67 } lpfc_iocb_type;
68 
69 
70 /* Provide function prototypes local to this module. */
71 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
72 				  uint32_t);
73 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
74 			      uint8_t *, uint32_t *);
75 static struct lpfc_iocbq *
76 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
77 				  struct lpfc_iocbq *rspiocbq);
78 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
79 				      struct hbq_dmabuf *);
80 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
81 					  struct hbq_dmabuf *dmabuf);
82 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
83 				   struct lpfc_queue *cq, struct lpfc_cqe *cqe);
84 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
85 				       int);
86 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
87 				     struct lpfc_queue *eq,
88 				     struct lpfc_eqe *eqe,
89 				     enum lpfc_poll_mode poll_mode);
90 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
91 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
92 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
93 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
94 				    struct lpfc_queue *cq,
95 				    struct lpfc_cqe *cqe);
96 static uint16_t lpfc_wqe_bpl2sgl(struct lpfc_hba *phba,
97 				 struct lpfc_iocbq *pwqeq,
98 				 struct lpfc_sglq *sglq);
99 
100 union lpfc_wqe128 lpfc_iread_cmd_template;
101 union lpfc_wqe128 lpfc_iwrite_cmd_template;
102 union lpfc_wqe128 lpfc_icmnd_cmd_template;
103 
104 /* Setup WQE templates for IOs */
105 void lpfc_wqe_cmd_template(void)
106 {
107 	union lpfc_wqe128 *wqe;
108 
109 	/* IREAD template */
110 	wqe = &lpfc_iread_cmd_template;
111 	memset(wqe, 0, sizeof(union lpfc_wqe128));
112 
113 	/* Word 0, 1, 2 - BDE is variable */
114 
115 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
116 
117 	/* Word 4 - total_xfer_len is variable */
118 
119 	/* Word 5 - is zero */
120 
121 	/* Word 6 - ctxt_tag, xri_tag is variable */
122 
123 	/* Word 7 */
124 	bf_set(wqe_cmnd, &wqe->fcp_iread.wqe_com, CMD_FCP_IREAD64_WQE);
125 	bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, PARM_READ_CHECK);
126 	bf_set(wqe_class, &wqe->fcp_iread.wqe_com, CLASS3);
127 	bf_set(wqe_ct, &wqe->fcp_iread.wqe_com, SLI4_CT_RPI);
128 
129 	/* Word 8 - abort_tag is variable */
130 
131 	/* Word 9  - reqtag is variable */
132 
133 	/* Word 10 - dbde, wqes is variable */
134 	bf_set(wqe_qosd, &wqe->fcp_iread.wqe_com, 0);
135 	bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
136 	bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com, LPFC_WQE_LENLOC_WORD4);
137 	bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
138 	bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
139 
140 	/* Word 11 */
141 	bf_set(wqe_cmd_type, &wqe->fcp_iread.wqe_com, COMMAND_DATA_IN);
142 	bf_set(wqe_cqid, &wqe->fcp_iread.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
143 
144 	/* Word 12 - is zero */
145 
146 	/* IWRITE template */
147 	wqe = &lpfc_iwrite_cmd_template;
148 	memset(wqe, 0, sizeof(union lpfc_wqe128));
149 
150 	/* Word 0, 1, 2 - BDE is variable */
151 
152 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
153 
154 	/* Word 4 - total_xfer_len is variable */
155 
156 	/* Word 5 - initial_xfer_len is variable */
157 
158 	/* Word 6 - ctxt_tag, xri_tag is variable */
159 
160 	/* Word 7 */
161 	bf_set(wqe_cmnd, &wqe->fcp_iwrite.wqe_com, CMD_FCP_IWRITE64_WQE);
162 	bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, PARM_READ_CHECK);
163 	bf_set(wqe_class, &wqe->fcp_iwrite.wqe_com, CLASS3);
164 	bf_set(wqe_ct, &wqe->fcp_iwrite.wqe_com, SLI4_CT_RPI);
165 
166 	/* Word 8 - abort_tag is variable */
167 
168 	/* Word 9  - reqtag is variable */
169 
170 	/* Word 10 - dbde, wqes is variable */
171 	bf_set(wqe_qosd, &wqe->fcp_iwrite.wqe_com, 0);
172 	bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
173 	bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_LENLOC_WORD4);
174 	bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
175 	bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
176 
177 	/* Word 11 */
178 	bf_set(wqe_cmd_type, &wqe->fcp_iwrite.wqe_com, COMMAND_DATA_OUT);
179 	bf_set(wqe_cqid, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
180 
181 	/* Word 12 - is zero */
182 
183 	/* ICMND template */
184 	wqe = &lpfc_icmnd_cmd_template;
185 	memset(wqe, 0, sizeof(union lpfc_wqe128));
186 
187 	/* Word 0, 1, 2 - BDE is variable */
188 
189 	/* Word 3 - payload_offset_len is variable */
190 
191 	/* Word 4, 5 - is zero */
192 
193 	/* Word 6 - ctxt_tag, xri_tag is variable */
194 
195 	/* Word 7 */
196 	bf_set(wqe_cmnd, &wqe->fcp_icmd.wqe_com, CMD_FCP_ICMND64_WQE);
197 	bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
198 	bf_set(wqe_class, &wqe->fcp_icmd.wqe_com, CLASS3);
199 	bf_set(wqe_ct, &wqe->fcp_icmd.wqe_com, SLI4_CT_RPI);
200 
201 	/* Word 8 - abort_tag is variable */
202 
203 	/* Word 9  - reqtag is variable */
204 
205 	/* Word 10 - dbde, wqes is variable */
206 	bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
207 	bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_NONE);
208 	bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com, LPFC_WQE_LENLOC_NONE);
209 	bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
210 	bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
211 
212 	/* Word 11 */
213 	bf_set(wqe_cmd_type, &wqe->fcp_icmd.wqe_com, COMMAND_DATA_IN);
214 	bf_set(wqe_cqid, &wqe->fcp_icmd.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
215 
216 	/* Word 12, 13, 14, 15 - is zero */
217 }
218 
219 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
220 /**
221  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
222  * @srcp: Source memory pointer.
223  * @destp: Destination memory pointer.
224  * @cnt: Number of words required to be copied.
225  *       Must be a multiple of sizeof(uint64_t)
226  *
227  * This function is used for copying data between driver memory
228  * and the SLI WQ. This function also changes the endianness
229  * of each word if native endianness is different from SLI
230  * endianness. This function can be called with or without
231  * lock.
232  **/
233 static void
234 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
235 {
236 	uint64_t *src = srcp;
237 	uint64_t *dest = destp;
238 	int i;
239 
240 	for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
241 		*dest++ = *src++;
242 }
243 #else
244 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
245 #endif
246 
247 /**
248  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
249  * @q: The Work Queue to operate on.
250  * @wqe: The work Queue Entry to put on the Work queue.
251  *
252  * This routine will copy the contents of @wqe to the next available entry on
253  * the @q. This function will then ring the Work Queue Doorbell to signal the
254  * HBA to start processing the Work Queue Entry. This function returns 0 if
255  * successful. If no entries are available on @q then this function will return
256  * -ENOMEM.
257  * The caller is expected to hold the hbalock when calling this routine.
258  **/
259 static int
260 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
261 {
262 	union lpfc_wqe *temp_wqe;
263 	struct lpfc_register doorbell;
264 	uint32_t host_index;
265 	uint32_t idx;
266 	uint32_t i = 0;
267 	uint8_t *tmp;
268 	u32 if_type;
269 
270 	/* sanity check on queue memory */
271 	if (unlikely(!q))
272 		return -ENOMEM;
273 
274 	temp_wqe = lpfc_sli4_qe(q, q->host_index);
275 
276 	/* If the host has not yet processed the next entry then we are done */
277 	idx = ((q->host_index + 1) % q->entry_count);
278 	if (idx == q->hba_index) {
279 		q->WQ_overflow++;
280 		return -EBUSY;
281 	}
282 	q->WQ_posted++;
283 	/* set consumption flag every once in a while */
284 	if (!((q->host_index + 1) % q->notify_interval))
285 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
286 	else
287 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
288 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
289 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
290 	lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
291 	if (q->dpp_enable && q->phba->cfg_enable_dpp) {
292 		/* write to DPP aperture taking advatage of Combined Writes */
293 		tmp = (uint8_t *)temp_wqe;
294 #ifdef __raw_writeq
295 		for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
296 			__raw_writeq(*((uint64_t *)(tmp + i)),
297 					q->dpp_regaddr + i);
298 #else
299 		for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
300 			__raw_writel(*((uint32_t *)(tmp + i)),
301 					q->dpp_regaddr + i);
302 #endif
303 	}
304 	/* ensure WQE bcopy and DPP flushed before doorbell write */
305 	wmb();
306 
307 	/* Update the host index before invoking device */
308 	host_index = q->host_index;
309 
310 	q->host_index = idx;
311 
312 	/* Ring Doorbell */
313 	doorbell.word0 = 0;
314 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
315 		if (q->dpp_enable && q->phba->cfg_enable_dpp) {
316 			bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
317 			bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
318 			bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
319 			    q->dpp_id);
320 			bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
321 			    q->queue_id);
322 		} else {
323 			bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
324 			bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
325 
326 			/* Leave bits <23:16> clear for if_type 6 dpp */
327 			if_type = bf_get(lpfc_sli_intf_if_type,
328 					 &q->phba->sli4_hba.sli_intf);
329 			if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
330 				bf_set(lpfc_wq_db_list_fm_index, &doorbell,
331 				       host_index);
332 		}
333 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
334 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
335 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
336 	} else {
337 		return -EINVAL;
338 	}
339 	writel(doorbell.word0, q->db_regaddr);
340 
341 	return 0;
342 }
343 
344 /**
345  * lpfc_sli4_wq_release - Updates internal hba index for WQ
346  * @q: The Work Queue to operate on.
347  * @index: The index to advance the hba index to.
348  *
349  * This routine will update the HBA index of a queue to reflect consumption of
350  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
351  * an entry the host calls this function to update the queue's internal
352  * pointers.
353  **/
354 static void
355 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
356 {
357 	/* sanity check on queue memory */
358 	if (unlikely(!q))
359 		return;
360 
361 	q->hba_index = index;
362 }
363 
364 /**
365  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
366  * @q: The Mailbox Queue to operate on.
367  * @mqe: The Mailbox Queue Entry to put on the Work queue.
368  *
369  * This routine will copy the contents of @mqe to the next available entry on
370  * the @q. This function will then ring the Work Queue Doorbell to signal the
371  * HBA to start processing the Work Queue Entry. This function returns 0 if
372  * successful. If no entries are available on @q then this function will return
373  * -ENOMEM.
374  * The caller is expected to hold the hbalock when calling this routine.
375  **/
376 static uint32_t
377 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
378 {
379 	struct lpfc_mqe *temp_mqe;
380 	struct lpfc_register doorbell;
381 
382 	/* sanity check on queue memory */
383 	if (unlikely(!q))
384 		return -ENOMEM;
385 	temp_mqe = lpfc_sli4_qe(q, q->host_index);
386 
387 	/* If the host has not yet processed the next entry then we are done */
388 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
389 		return -ENOMEM;
390 	lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
391 	/* Save off the mailbox pointer for completion */
392 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
393 
394 	/* Update the host index before invoking device */
395 	q->host_index = ((q->host_index + 1) % q->entry_count);
396 
397 	/* Ring Doorbell */
398 	doorbell.word0 = 0;
399 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
400 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
401 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
402 	return 0;
403 }
404 
405 /**
406  * lpfc_sli4_mq_release - Updates internal hba index for MQ
407  * @q: The Mailbox Queue to operate on.
408  *
409  * This routine will update the HBA index of a queue to reflect consumption of
410  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
411  * an entry the host calls this function to update the queue's internal
412  * pointers. This routine returns the number of entries that were consumed by
413  * the HBA.
414  **/
415 static uint32_t
416 lpfc_sli4_mq_release(struct lpfc_queue *q)
417 {
418 	/* sanity check on queue memory */
419 	if (unlikely(!q))
420 		return 0;
421 
422 	/* Clear the mailbox pointer for completion */
423 	q->phba->mbox = NULL;
424 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
425 	return 1;
426 }
427 
428 /**
429  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
430  * @q: The Event Queue to get the first valid EQE from
431  *
432  * This routine will get the first valid Event Queue Entry from @q, update
433  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
434  * the Queue (no more work to do), or the Queue is full of EQEs that have been
435  * processed, but not popped back to the HBA then this routine will return NULL.
436  **/
437 static struct lpfc_eqe *
438 lpfc_sli4_eq_get(struct lpfc_queue *q)
439 {
440 	struct lpfc_eqe *eqe;
441 
442 	/* sanity check on queue memory */
443 	if (unlikely(!q))
444 		return NULL;
445 	eqe = lpfc_sli4_qe(q, q->host_index);
446 
447 	/* If the next EQE is not valid then we are done */
448 	if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
449 		return NULL;
450 
451 	/*
452 	 * insert barrier for instruction interlock : data from the hardware
453 	 * must have the valid bit checked before it can be copied and acted
454 	 * upon. Speculative instructions were allowing a bcopy at the start
455 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
456 	 * after our return, to copy data before the valid bit check above
457 	 * was done. As such, some of the copied data was stale. The barrier
458 	 * ensures the check is before any data is copied.
459 	 */
460 	mb();
461 	return eqe;
462 }
463 
464 /**
465  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
466  * @q: The Event Queue to disable interrupts
467  *
468  **/
469 void
470 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
471 {
472 	struct lpfc_register doorbell;
473 
474 	doorbell.word0 = 0;
475 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
476 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
477 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
478 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
479 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
480 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
481 }
482 
483 /**
484  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
485  * @q: The Event Queue to disable interrupts
486  *
487  **/
488 void
489 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
490 {
491 	struct lpfc_register doorbell;
492 
493 	doorbell.word0 = 0;
494 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
495 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
496 }
497 
498 /**
499  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
500  * @phba: adapter with EQ
501  * @q: The Event Queue that the host has completed processing for.
502  * @count: Number of elements that have been consumed
503  * @arm: Indicates whether the host wants to arms this CQ.
504  *
505  * This routine will notify the HBA, by ringing the doorbell, that count
506  * number of EQEs have been processed. The @arm parameter indicates whether
507  * the queue should be rearmed when ringing the doorbell.
508  **/
509 void
510 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
511 		     uint32_t count, bool arm)
512 {
513 	struct lpfc_register doorbell;
514 
515 	/* sanity check on queue memory */
516 	if (unlikely(!q || (count == 0 && !arm)))
517 		return;
518 
519 	/* ring doorbell for number popped */
520 	doorbell.word0 = 0;
521 	if (arm) {
522 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
523 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
524 	}
525 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
526 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
527 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
528 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
529 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
530 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
531 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
532 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
533 		readl(q->phba->sli4_hba.EQDBregaddr);
534 }
535 
536 /**
537  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
538  * @phba: adapter with EQ
539  * @q: The Event Queue that the host has completed processing for.
540  * @count: Number of elements that have been consumed
541  * @arm: Indicates whether the host wants to arms this CQ.
542  *
543  * This routine will notify the HBA, by ringing the doorbell, that count
544  * number of EQEs have been processed. The @arm parameter indicates whether
545  * the queue should be rearmed when ringing the doorbell.
546  **/
547 void
548 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
549 			  uint32_t count, bool arm)
550 {
551 	struct lpfc_register doorbell;
552 
553 	/* sanity check on queue memory */
554 	if (unlikely(!q || (count == 0 && !arm)))
555 		return;
556 
557 	/* ring doorbell for number popped */
558 	doorbell.word0 = 0;
559 	if (arm)
560 		bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
561 	bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
562 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
563 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
564 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
565 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
566 		readl(q->phba->sli4_hba.EQDBregaddr);
567 }
568 
569 static void
570 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
571 			struct lpfc_eqe *eqe)
572 {
573 	if (!phba->sli4_hba.pc_sli4_params.eqav)
574 		bf_set_le32(lpfc_eqe_valid, eqe, 0);
575 
576 	eq->host_index = ((eq->host_index + 1) % eq->entry_count);
577 
578 	/* if the index wrapped around, toggle the valid bit */
579 	if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
580 		eq->qe_valid = (eq->qe_valid) ? 0 : 1;
581 }
582 
583 static void
584 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
585 {
586 	struct lpfc_eqe *eqe = NULL;
587 	u32 eq_count = 0, cq_count = 0;
588 	struct lpfc_cqe *cqe = NULL;
589 	struct lpfc_queue *cq = NULL, *childq = NULL;
590 	int cqid = 0;
591 
592 	/* walk all the EQ entries and drop on the floor */
593 	eqe = lpfc_sli4_eq_get(eq);
594 	while (eqe) {
595 		/* Get the reference to the corresponding CQ */
596 		cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
597 		cq = NULL;
598 
599 		list_for_each_entry(childq, &eq->child_list, list) {
600 			if (childq->queue_id == cqid) {
601 				cq = childq;
602 				break;
603 			}
604 		}
605 		/* If CQ is valid, iterate through it and drop all the CQEs */
606 		if (cq) {
607 			cqe = lpfc_sli4_cq_get(cq);
608 			while (cqe) {
609 				__lpfc_sli4_consume_cqe(phba, cq, cqe);
610 				cq_count++;
611 				cqe = lpfc_sli4_cq_get(cq);
612 			}
613 			/* Clear and re-arm the CQ */
614 			phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
615 			    LPFC_QUEUE_REARM);
616 			cq_count = 0;
617 		}
618 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
619 		eq_count++;
620 		eqe = lpfc_sli4_eq_get(eq);
621 	}
622 
623 	/* Clear and re-arm the EQ */
624 	phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
625 }
626 
627 static int
628 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
629 		     u8 rearm, enum lpfc_poll_mode poll_mode)
630 {
631 	struct lpfc_eqe *eqe;
632 	int count = 0, consumed = 0;
633 
634 	if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
635 		goto rearm_and_exit;
636 
637 	eqe = lpfc_sli4_eq_get(eq);
638 	while (eqe) {
639 		lpfc_sli4_hba_handle_eqe(phba, eq, eqe, poll_mode);
640 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
641 
642 		consumed++;
643 		if (!(++count % eq->max_proc_limit))
644 			break;
645 
646 		if (!(count % eq->notify_interval)) {
647 			phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
648 							LPFC_QUEUE_NOARM);
649 			consumed = 0;
650 		}
651 
652 		eqe = lpfc_sli4_eq_get(eq);
653 	}
654 	eq->EQ_processed += count;
655 
656 	/* Track the max number of EQEs processed in 1 intr */
657 	if (count > eq->EQ_max_eqe)
658 		eq->EQ_max_eqe = count;
659 
660 	xchg(&eq->queue_claimed, 0);
661 
662 rearm_and_exit:
663 	/* Always clear the EQ. */
664 	phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
665 
666 	return count;
667 }
668 
669 /**
670  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
671  * @q: The Completion Queue to get the first valid CQE from
672  *
673  * This routine will get the first valid Completion Queue Entry from @q, update
674  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
675  * the Queue (no more work to do), or the Queue is full of CQEs that have been
676  * processed, but not popped back to the HBA then this routine will return NULL.
677  **/
678 static struct lpfc_cqe *
679 lpfc_sli4_cq_get(struct lpfc_queue *q)
680 {
681 	struct lpfc_cqe *cqe;
682 
683 	/* sanity check on queue memory */
684 	if (unlikely(!q))
685 		return NULL;
686 	cqe = lpfc_sli4_qe(q, q->host_index);
687 
688 	/* If the next CQE is not valid then we are done */
689 	if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
690 		return NULL;
691 
692 	/*
693 	 * insert barrier for instruction interlock : data from the hardware
694 	 * must have the valid bit checked before it can be copied and acted
695 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
696 	 * instructions allowing action on content before valid bit checked,
697 	 * add barrier here as well. May not be needed as "content" is a
698 	 * single 32-bit entity here (vs multi word structure for cq's).
699 	 */
700 	mb();
701 	return cqe;
702 }
703 
704 static void
705 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
706 			struct lpfc_cqe *cqe)
707 {
708 	if (!phba->sli4_hba.pc_sli4_params.cqav)
709 		bf_set_le32(lpfc_cqe_valid, cqe, 0);
710 
711 	cq->host_index = ((cq->host_index + 1) % cq->entry_count);
712 
713 	/* if the index wrapped around, toggle the valid bit */
714 	if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
715 		cq->qe_valid = (cq->qe_valid) ? 0 : 1;
716 }
717 
718 /**
719  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
720  * @phba: the adapter with the CQ
721  * @q: The Completion Queue that the host has completed processing for.
722  * @count: the number of elements that were consumed
723  * @arm: Indicates whether the host wants to arms this CQ.
724  *
725  * This routine will notify the HBA, by ringing the doorbell, that the
726  * CQEs have been processed. The @arm parameter specifies whether the
727  * queue should be rearmed when ringing the doorbell.
728  **/
729 void
730 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
731 		     uint32_t count, bool arm)
732 {
733 	struct lpfc_register doorbell;
734 
735 	/* sanity check on queue memory */
736 	if (unlikely(!q || (count == 0 && !arm)))
737 		return;
738 
739 	/* ring doorbell for number popped */
740 	doorbell.word0 = 0;
741 	if (arm)
742 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
743 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
744 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
745 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
746 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
747 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
748 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
749 }
750 
751 /**
752  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
753  * @phba: the adapter with the CQ
754  * @q: The Completion Queue that the host has completed processing for.
755  * @count: the number of elements that were consumed
756  * @arm: Indicates whether the host wants to arms this CQ.
757  *
758  * This routine will notify the HBA, by ringing the doorbell, that the
759  * CQEs have been processed. The @arm parameter specifies whether the
760  * queue should be rearmed when ringing the doorbell.
761  **/
762 void
763 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
764 			 uint32_t count, bool arm)
765 {
766 	struct lpfc_register doorbell;
767 
768 	/* sanity check on queue memory */
769 	if (unlikely(!q || (count == 0 && !arm)))
770 		return;
771 
772 	/* ring doorbell for number popped */
773 	doorbell.word0 = 0;
774 	if (arm)
775 		bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
776 	bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
777 	bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
778 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
779 }
780 
781 /*
782  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
783  *
784  * This routine will copy the contents of @wqe to the next available entry on
785  * the @q. This function will then ring the Receive Queue Doorbell to signal the
786  * HBA to start processing the Receive Queue Entry. This function returns the
787  * index that the rqe was copied to if successful. If no entries are available
788  * on @q then this function will return -ENOMEM.
789  * The caller is expected to hold the hbalock when calling this routine.
790  **/
791 int
792 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
793 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
794 {
795 	struct lpfc_rqe *temp_hrqe;
796 	struct lpfc_rqe *temp_drqe;
797 	struct lpfc_register doorbell;
798 	int hq_put_index;
799 	int dq_put_index;
800 
801 	/* sanity check on queue memory */
802 	if (unlikely(!hq) || unlikely(!dq))
803 		return -ENOMEM;
804 	hq_put_index = hq->host_index;
805 	dq_put_index = dq->host_index;
806 	temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
807 	temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
808 
809 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
810 		return -EINVAL;
811 	if (hq_put_index != dq_put_index)
812 		return -EINVAL;
813 	/* If the host has not yet processed the next entry then we are done */
814 	if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
815 		return -EBUSY;
816 	lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
817 	lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
818 
819 	/* Update the host index to point to the next slot */
820 	hq->host_index = ((hq_put_index + 1) % hq->entry_count);
821 	dq->host_index = ((dq_put_index + 1) % dq->entry_count);
822 	hq->RQ_buf_posted++;
823 
824 	/* Ring The Header Receive Queue Doorbell */
825 	if (!(hq->host_index % hq->notify_interval)) {
826 		doorbell.word0 = 0;
827 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
828 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
829 			       hq->notify_interval);
830 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
831 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
832 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
833 			       hq->notify_interval);
834 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
835 			       hq->host_index);
836 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
837 		} else {
838 			return -EINVAL;
839 		}
840 		writel(doorbell.word0, hq->db_regaddr);
841 	}
842 	return hq_put_index;
843 }
844 
845 /*
846  * lpfc_sli4_rq_release - Updates internal hba index for RQ
847  *
848  * This routine will update the HBA index of a queue to reflect consumption of
849  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
850  * consumed an entry the host calls this function to update the queue's
851  * internal pointers. This routine returns the number of entries that were
852  * consumed by the HBA.
853  **/
854 static uint32_t
855 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
856 {
857 	/* sanity check on queue memory */
858 	if (unlikely(!hq) || unlikely(!dq))
859 		return 0;
860 
861 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
862 		return 0;
863 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
864 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
865 	return 1;
866 }
867 
868 /**
869  * lpfc_cmd_iocb - Get next command iocb entry in the ring
870  * @phba: Pointer to HBA context object.
871  * @pring: Pointer to driver SLI ring object.
872  *
873  * This function returns pointer to next command iocb entry
874  * in the command ring. The caller must hold hbalock to prevent
875  * other threads consume the next command iocb.
876  * SLI-2/SLI-3 provide different sized iocbs.
877  **/
878 static inline IOCB_t *
879 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
880 {
881 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
882 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
883 }
884 
885 /**
886  * lpfc_resp_iocb - Get next response iocb entry in the ring
887  * @phba: Pointer to HBA context object.
888  * @pring: Pointer to driver SLI ring object.
889  *
890  * This function returns pointer to next response iocb entry
891  * in the response ring. The caller must hold hbalock to make sure
892  * that no other thread consume the next response iocb.
893  * SLI-2/SLI-3 provide different sized iocbs.
894  **/
895 static inline IOCB_t *
896 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
897 {
898 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
899 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
900 }
901 
902 /**
903  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
904  * @phba: Pointer to HBA context object.
905  *
906  * This function is called with hbalock held. This function
907  * allocates a new driver iocb object from the iocb pool. If the
908  * allocation is successful, it returns pointer to the newly
909  * allocated iocb object else it returns NULL.
910  **/
911 struct lpfc_iocbq *
912 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
913 {
914 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
915 	struct lpfc_iocbq * iocbq = NULL;
916 
917 	lockdep_assert_held(&phba->hbalock);
918 
919 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
920 	if (iocbq)
921 		phba->iocb_cnt++;
922 	if (phba->iocb_cnt > phba->iocb_max)
923 		phba->iocb_max = phba->iocb_cnt;
924 	return iocbq;
925 }
926 
927 /**
928  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
929  * @phba: Pointer to HBA context object.
930  * @xritag: XRI value.
931  *
932  * This function clears the sglq pointer from the array of active
933  * sglq's. The xritag that is passed in is used to index into the
934  * array. Before the xritag can be used it needs to be adjusted
935  * by subtracting the xribase.
936  *
937  * Returns sglq ponter = success, NULL = Failure.
938  **/
939 struct lpfc_sglq *
940 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
941 {
942 	struct lpfc_sglq *sglq;
943 
944 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
945 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
946 	return sglq;
947 }
948 
949 /**
950  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
951  * @phba: Pointer to HBA context object.
952  * @xritag: XRI value.
953  *
954  * This function returns the sglq pointer from the array of active
955  * sglq's. The xritag that is passed in is used to index into the
956  * array. Before the xritag can be used it needs to be adjusted
957  * by subtracting the xribase.
958  *
959  * Returns sglq ponter = success, NULL = Failure.
960  **/
961 struct lpfc_sglq *
962 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
963 {
964 	struct lpfc_sglq *sglq;
965 
966 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
967 	return sglq;
968 }
969 
970 /**
971  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
972  * @phba: Pointer to HBA context object.
973  * @xritag: xri used in this exchange.
974  * @rrq: The RRQ to be cleared.
975  *
976  **/
977 void
978 lpfc_clr_rrq_active(struct lpfc_hba *phba,
979 		    uint16_t xritag,
980 		    struct lpfc_node_rrq *rrq)
981 {
982 	struct lpfc_nodelist *ndlp = NULL;
983 
984 	/* Lookup did to verify if did is still active on this vport */
985 	if (rrq->vport)
986 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
987 
988 	if (!ndlp)
989 		goto out;
990 
991 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
992 		rrq->send_rrq = 0;
993 		rrq->xritag = 0;
994 		rrq->rrq_stop_time = 0;
995 	}
996 out:
997 	mempool_free(rrq, phba->rrq_pool);
998 }
999 
1000 /**
1001  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
1002  * @phba: Pointer to HBA context object.
1003  *
1004  * This function is called with hbalock held. This function
1005  * Checks if stop_time (ratov from setting rrq active) has
1006  * been reached, if it has and the send_rrq flag is set then
1007  * it will call lpfc_send_rrq. If the send_rrq flag is not set
1008  * then it will just call the routine to clear the rrq and
1009  * free the rrq resource.
1010  * The timer is set to the next rrq that is going to expire before
1011  * leaving the routine.
1012  *
1013  **/
1014 void
1015 lpfc_handle_rrq_active(struct lpfc_hba *phba)
1016 {
1017 	struct lpfc_node_rrq *rrq;
1018 	struct lpfc_node_rrq *nextrrq;
1019 	unsigned long next_time;
1020 	unsigned long iflags;
1021 	LIST_HEAD(send_rrq);
1022 
1023 	clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1024 	next_time = jiffies + secs_to_jiffies(phba->fc_ratov + 1);
1025 	spin_lock_irqsave(&phba->rrq_list_lock, iflags);
1026 	list_for_each_entry_safe(rrq, nextrrq,
1027 				 &phba->active_rrq_list, list) {
1028 		if (time_after(jiffies, rrq->rrq_stop_time))
1029 			list_move(&rrq->list, &send_rrq);
1030 		else if (time_before(rrq->rrq_stop_time, next_time))
1031 			next_time = rrq->rrq_stop_time;
1032 	}
1033 	spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1034 	if ((!list_empty(&phba->active_rrq_list)) &&
1035 	    (!test_bit(FC_UNLOADING, &phba->pport->load_flag)))
1036 		mod_timer(&phba->rrq_tmr, next_time);
1037 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
1038 		list_del(&rrq->list);
1039 		if (!rrq->send_rrq) {
1040 			/* this call will free the rrq */
1041 			lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1042 		} else if (lpfc_send_rrq(phba, rrq)) {
1043 			/* if we send the rrq then the completion handler
1044 			*  will clear the bit in the xribitmap.
1045 			*/
1046 			lpfc_clr_rrq_active(phba, rrq->xritag,
1047 					    rrq);
1048 		}
1049 	}
1050 }
1051 
1052 /**
1053  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
1054  * @vport: Pointer to vport context object.
1055  * @xri: The xri used in the exchange.
1056  * @did: The targets DID for this exchange.
1057  *
1058  * returns NULL = rrq not found in the phba->active_rrq_list.
1059  *         rrq = rrq for this xri and target.
1060  **/
1061 struct lpfc_node_rrq *
1062 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
1063 {
1064 	struct lpfc_hba *phba = vport->phba;
1065 	struct lpfc_node_rrq *rrq;
1066 	struct lpfc_node_rrq *nextrrq;
1067 	unsigned long iflags;
1068 
1069 	if (phba->sli_rev != LPFC_SLI_REV4)
1070 		return NULL;
1071 	spin_lock_irqsave(&phba->rrq_list_lock, iflags);
1072 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1073 		if (rrq->vport == vport && rrq->xritag == xri &&
1074 				rrq->nlp_DID == did){
1075 			list_del(&rrq->list);
1076 			spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1077 			return rrq;
1078 		}
1079 	}
1080 	spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1081 	return NULL;
1082 }
1083 
1084 /**
1085  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
1086  * @vport: Pointer to vport context object.
1087  * @ndlp: Pointer to the lpfc_node_list structure.
1088  * If ndlp is NULL Remove all active RRQs for this vport from the
1089  * phba->active_rrq_list and clear the rrq.
1090  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
1091  **/
1092 void
1093 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
1094 
1095 {
1096 	struct lpfc_hba *phba = vport->phba;
1097 	struct lpfc_node_rrq *rrq;
1098 	struct lpfc_node_rrq *nextrrq;
1099 	unsigned long iflags;
1100 	LIST_HEAD(rrq_list);
1101 
1102 	if (phba->sli_rev != LPFC_SLI_REV4)
1103 		return;
1104 	if (!ndlp) {
1105 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
1106 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
1107 	}
1108 	spin_lock_irqsave(&phba->rrq_list_lock, iflags);
1109 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1110 		if (rrq->vport != vport)
1111 			continue;
1112 
1113 		if (!ndlp || ndlp == lpfc_findnode_did(vport, rrq->nlp_DID))
1114 			list_move(&rrq->list, &rrq_list);
1115 
1116 	}
1117 	spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1118 
1119 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1120 		list_del(&rrq->list);
1121 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1122 	}
1123 }
1124 
1125 /**
1126  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1127  * @phba: Pointer to HBA context object.
1128  * @ndlp: Targets nodelist pointer for this exchange.
1129  * @xritag: the xri in the bitmap to test.
1130  *
1131  * This function returns:
1132  * 0 = rrq not active for this xri
1133  * 1 = rrq is valid for this xri.
1134  **/
1135 int
1136 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1137 			uint16_t  xritag)
1138 {
1139 	if (!ndlp)
1140 		return 0;
1141 	if (!ndlp->active_rrqs_xri_bitmap)
1142 		return 0;
1143 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1144 		return 1;
1145 	else
1146 		return 0;
1147 }
1148 
1149 /**
1150  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1151  * @phba: Pointer to HBA context object.
1152  * @ndlp: nodelist pointer for this target.
1153  * @xritag: xri used in this exchange.
1154  * @rxid: Remote Exchange ID.
1155  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1156  *
1157  * This function takes the hbalock.
1158  * The active bit is always set in the active rrq xri_bitmap even
1159  * if there is no slot available for the other rrq information.
1160  *
1161  * returns 0 rrq activated for this xri
1162  *         < 0 No memory or invalid ndlp.
1163  **/
1164 int
1165 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1166 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1167 {
1168 	unsigned long iflags;
1169 	struct lpfc_node_rrq *rrq;
1170 	int empty;
1171 
1172 	if (!ndlp)
1173 		return -EINVAL;
1174 
1175 	if (!phba->cfg_enable_rrq)
1176 		return -EINVAL;
1177 
1178 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
1179 		clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1180 		goto outnl;
1181 	}
1182 
1183 	spin_lock_irqsave(&phba->hbalock, iflags);
1184 	if (ndlp->vport && test_bit(FC_UNLOADING, &ndlp->vport->load_flag))
1185 		goto out;
1186 
1187 	if (!ndlp->active_rrqs_xri_bitmap)
1188 		goto out;
1189 
1190 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1191 		goto out;
1192 
1193 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1194 	rrq = mempool_alloc(phba->rrq_pool, GFP_ATOMIC);
1195 	if (!rrq) {
1196 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1197 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1198 				" DID:0x%x Send:%d\n",
1199 				xritag, rxid, ndlp->nlp_DID, send_rrq);
1200 		return -EINVAL;
1201 	}
1202 	if (phba->cfg_enable_rrq == 1)
1203 		rrq->send_rrq = send_rrq;
1204 	else
1205 		rrq->send_rrq = 0;
1206 	rrq->xritag = xritag;
1207 	rrq->rrq_stop_time = jiffies + secs_to_jiffies(phba->fc_ratov + 1);
1208 	rrq->nlp_DID = ndlp->nlp_DID;
1209 	rrq->vport = ndlp->vport;
1210 	rrq->rxid = rxid;
1211 
1212 	spin_lock_irqsave(&phba->rrq_list_lock, iflags);
1213 	empty = list_empty(&phba->active_rrq_list);
1214 	list_add_tail(&rrq->list, &phba->active_rrq_list);
1215 	spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1216 	set_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1217 	if (empty)
1218 		lpfc_worker_wake_up(phba);
1219 	return 0;
1220 out:
1221 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1222 outnl:
1223 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1224 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
1225 			" DID:0x%x Send:%d\n",
1226 			xritag, rxid, ndlp->nlp_DID, send_rrq);
1227 	return -EINVAL;
1228 }
1229 
1230 /**
1231  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1232  * @phba: Pointer to HBA context object.
1233  * @piocbq: Pointer to the iocbq.
1234  *
1235  * The driver calls this function with either the nvme ls ring lock
1236  * or the fc els ring lock held depending on the iocb usage.  This function
1237  * gets a new driver sglq object from the sglq list. If the list is not empty
1238  * then it is successful, it returns pointer to the newly allocated sglq
1239  * object else it returns NULL.
1240  **/
1241 static struct lpfc_sglq *
1242 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1243 {
1244 	struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1245 	struct lpfc_sglq *sglq = NULL;
1246 	struct lpfc_sglq *start_sglq = NULL;
1247 	struct lpfc_io_buf *lpfc_cmd;
1248 	struct lpfc_nodelist *ndlp;
1249 	int found = 0;
1250 	u8 cmnd;
1251 
1252 	cmnd = get_job_cmnd(phba, piocbq);
1253 
1254 	if (piocbq->cmd_flag & LPFC_IO_FCP) {
1255 		lpfc_cmd = piocbq->io_buf;
1256 		ndlp = lpfc_cmd->rdata->pnode;
1257 	} else  if ((cmnd == CMD_GEN_REQUEST64_CR) &&
1258 			!(piocbq->cmd_flag & LPFC_IO_LIBDFC)) {
1259 		ndlp = piocbq->ndlp;
1260 	} else  if (piocbq->cmd_flag & LPFC_IO_LIBDFC) {
1261 		if (piocbq->cmd_flag & LPFC_IO_LOOPBACK)
1262 			ndlp = NULL;
1263 		else
1264 			ndlp = piocbq->ndlp;
1265 	} else {
1266 		ndlp = piocbq->ndlp;
1267 	}
1268 
1269 	spin_lock(&phba->sli4_hba.sgl_list_lock);
1270 	list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1271 	start_sglq = sglq;
1272 	while (!found) {
1273 		if (!sglq)
1274 			break;
1275 		if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1276 		    test_bit(sglq->sli4_lxritag,
1277 		    ndlp->active_rrqs_xri_bitmap)) {
1278 			/* This xri has an rrq outstanding for this DID.
1279 			 * put it back in the list and get another xri.
1280 			 */
1281 			list_add_tail(&sglq->list, lpfc_els_sgl_list);
1282 			sglq = NULL;
1283 			list_remove_head(lpfc_els_sgl_list, sglq,
1284 						struct lpfc_sglq, list);
1285 			if (sglq == start_sglq) {
1286 				list_add_tail(&sglq->list, lpfc_els_sgl_list);
1287 				sglq = NULL;
1288 				break;
1289 			} else
1290 				continue;
1291 		}
1292 		sglq->ndlp = ndlp;
1293 		found = 1;
1294 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1295 		sglq->state = SGL_ALLOCATED;
1296 	}
1297 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
1298 	return sglq;
1299 }
1300 
1301 /**
1302  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1303  * @phba: Pointer to HBA context object.
1304  * @piocbq: Pointer to the iocbq.
1305  *
1306  * This function is called with the sgl_list lock held. This function
1307  * gets a new driver sglq object from the sglq list. If the
1308  * list is not empty then it is successful, it returns pointer to the newly
1309  * allocated sglq object else it returns NULL.
1310  **/
1311 struct lpfc_sglq *
1312 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1313 {
1314 	struct list_head *lpfc_nvmet_sgl_list;
1315 	struct lpfc_sglq *sglq = NULL;
1316 
1317 	lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1318 
1319 	lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1320 
1321 	list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1322 	if (!sglq)
1323 		return NULL;
1324 	phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1325 	sglq->state = SGL_ALLOCATED;
1326 	return sglq;
1327 }
1328 
1329 /**
1330  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1331  * @phba: Pointer to HBA context object.
1332  *
1333  * This function is called with no lock held. This function
1334  * allocates a new driver iocb object from the iocb pool. If the
1335  * allocation is successful, it returns pointer to the newly
1336  * allocated iocb object else it returns NULL.
1337  **/
1338 struct lpfc_iocbq *
1339 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1340 {
1341 	struct lpfc_iocbq * iocbq = NULL;
1342 	unsigned long iflags;
1343 
1344 	spin_lock_irqsave(&phba->hbalock, iflags);
1345 	iocbq = __lpfc_sli_get_iocbq(phba);
1346 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1347 	return iocbq;
1348 }
1349 
1350 /**
1351  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1352  * @phba: Pointer to HBA context object.
1353  * @iocbq: Pointer to driver iocb object.
1354  *
1355  * This function is called to release the driver iocb object
1356  * to the iocb pool. The iotag in the iocb object
1357  * does not change for each use of the iocb object. This function
1358  * clears all other fields of the iocb object when it is freed.
1359  * The sqlq structure that holds the xritag and phys and virtual
1360  * mappings for the scatter gather list is retrieved from the
1361  * active array of sglq. The get of the sglq pointer also clears
1362  * the entry in the array. If the status of the IO indiactes that
1363  * this IO was aborted then the sglq entry it put on the
1364  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1365  * IO has good status or fails for any other reason then the sglq
1366  * entry is added to the free list (lpfc_els_sgl_list). The hbalock is
1367  *  asserted held in the code path calling this routine.
1368  **/
1369 static void
1370 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1371 {
1372 	struct lpfc_sglq *sglq;
1373 	unsigned long iflag = 0;
1374 	struct lpfc_sli_ring *pring;
1375 
1376 	if (iocbq->sli4_xritag == NO_XRI)
1377 		sglq = NULL;
1378 	else
1379 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1380 
1381 
1382 	if (sglq)  {
1383 		if (iocbq->cmd_flag & LPFC_IO_NVMET) {
1384 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1385 					  iflag);
1386 			sglq->state = SGL_FREED;
1387 			sglq->ndlp = NULL;
1388 			list_add_tail(&sglq->list,
1389 				      &phba->sli4_hba.lpfc_nvmet_sgl_list);
1390 			spin_unlock_irqrestore(
1391 				&phba->sli4_hba.sgl_list_lock, iflag);
1392 			goto out;
1393 		}
1394 
1395 		if ((iocbq->cmd_flag & LPFC_EXCHANGE_BUSY) &&
1396 		    (!(unlikely(pci_channel_offline(phba->pcidev)))) &&
1397 		    sglq->state != SGL_XRI_ABORTED) {
1398 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1399 					  iflag);
1400 
1401 			/* Check if we can get a reference on ndlp */
1402 			if (sglq->ndlp && !lpfc_nlp_get(sglq->ndlp))
1403 				sglq->ndlp = NULL;
1404 
1405 			list_add(&sglq->list,
1406 				 &phba->sli4_hba.lpfc_abts_els_sgl_list);
1407 			spin_unlock_irqrestore(
1408 				&phba->sli4_hba.sgl_list_lock, iflag);
1409 		} else {
1410 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1411 					  iflag);
1412 			sglq->state = SGL_FREED;
1413 			sglq->ndlp = NULL;
1414 			list_add_tail(&sglq->list,
1415 				      &phba->sli4_hba.lpfc_els_sgl_list);
1416 			spin_unlock_irqrestore(
1417 				&phba->sli4_hba.sgl_list_lock, iflag);
1418 			pring = lpfc_phba_elsring(phba);
1419 			/* Check if TXQ queue needs to be serviced */
1420 			if (pring && (!list_empty(&pring->txq)))
1421 				lpfc_worker_wake_up(phba);
1422 		}
1423 	}
1424 
1425 out:
1426 	/*
1427 	 * Clean all volatile data fields, preserve iotag and node struct.
1428 	 */
1429 	memset_startat(iocbq, 0, wqe);
1430 	iocbq->sli4_lxritag = NO_XRI;
1431 	iocbq->sli4_xritag = NO_XRI;
1432 	iocbq->cmd_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET | LPFC_IO_CMF |
1433 			      LPFC_IO_NVME_LS);
1434 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1435 }
1436 
1437 
1438 /**
1439  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1440  * @phba: Pointer to HBA context object.
1441  * @iocbq: Pointer to driver iocb object.
1442  *
1443  * This function is called to release the driver iocb object to the
1444  * iocb pool. The iotag in the iocb object does not change for each
1445  * use of the iocb object. This function clears all other fields of
1446  * the iocb object when it is freed. The hbalock is asserted held in
1447  * the code path calling this routine.
1448  **/
1449 static void
1450 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1451 {
1452 
1453 	/*
1454 	 * Clean all volatile data fields, preserve iotag and node struct.
1455 	 */
1456 	memset_startat(iocbq, 0, iocb);
1457 	iocbq->sli4_xritag = NO_XRI;
1458 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1459 }
1460 
1461 /**
1462  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1463  * @phba: Pointer to HBA context object.
1464  * @iocbq: Pointer to driver iocb object.
1465  *
1466  * This function is called with hbalock held to release driver
1467  * iocb object to the iocb pool. The iotag in the iocb object
1468  * does not change for each use of the iocb object. This function
1469  * clears all other fields of the iocb object when it is freed.
1470  **/
1471 static void
1472 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1473 {
1474 	lockdep_assert_held(&phba->hbalock);
1475 
1476 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1477 	phba->iocb_cnt--;
1478 }
1479 
1480 /**
1481  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1482  * @phba: Pointer to HBA context object.
1483  * @iocbq: Pointer to driver iocb object.
1484  *
1485  * This function is called with no lock held to release the iocb to
1486  * iocb pool.
1487  **/
1488 void
1489 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1490 {
1491 	unsigned long iflags;
1492 
1493 	/*
1494 	 * Clean all volatile data fields, preserve iotag and node struct.
1495 	 */
1496 	spin_lock_irqsave(&phba->hbalock, iflags);
1497 	__lpfc_sli_release_iocbq(phba, iocbq);
1498 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1499 }
1500 
1501 /**
1502  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1503  * @phba: Pointer to HBA context object.
1504  * @iocblist: List of IOCBs.
1505  * @ulpstatus: ULP status in IOCB command field.
1506  * @ulpWord4: ULP word-4 in IOCB command field.
1507  *
1508  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1509  * on the list by invoking the complete callback function associated with the
1510  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1511  * fields.
1512  **/
1513 void
1514 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1515 		      uint32_t ulpstatus, uint32_t ulpWord4)
1516 {
1517 	struct lpfc_iocbq *piocb;
1518 
1519 	while (!list_empty(iocblist)) {
1520 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1521 		if (piocb->cmd_cmpl) {
1522 			if (piocb->cmd_flag & LPFC_IO_NVME) {
1523 				lpfc_nvme_cancel_iocb(phba, piocb,
1524 						      ulpstatus, ulpWord4);
1525 			} else {
1526 				if (phba->sli_rev == LPFC_SLI_REV4) {
1527 					bf_set(lpfc_wcqe_c_status,
1528 					       &piocb->wcqe_cmpl, ulpstatus);
1529 					piocb->wcqe_cmpl.parameter = ulpWord4;
1530 				} else {
1531 					piocb->iocb.ulpStatus = ulpstatus;
1532 					piocb->iocb.un.ulpWord[4] = ulpWord4;
1533 				}
1534 				(piocb->cmd_cmpl) (phba, piocb, piocb);
1535 			}
1536 		} else {
1537 			lpfc_sli_release_iocbq(phba, piocb);
1538 		}
1539 	}
1540 	return;
1541 }
1542 
1543 /**
1544  * lpfc_sli_iocb_cmd_type - Get the iocb type
1545  * @iocb_cmnd: iocb command code.
1546  *
1547  * This function is called by ring event handler function to get the iocb type.
1548  * This function translates the iocb command to an iocb command type used to
1549  * decide the final disposition of each completed IOCB.
1550  * The function returns
1551  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1552  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1553  * LPFC_ABORT_IOCB   if it is an abort iocb
1554  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1555  *
1556  * The caller is not required to hold any lock.
1557  **/
1558 static lpfc_iocb_type
1559 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1560 {
1561 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1562 
1563 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1564 		return 0;
1565 
1566 	switch (iocb_cmnd) {
1567 	case CMD_XMIT_SEQUENCE_CR:
1568 	case CMD_XMIT_SEQUENCE_CX:
1569 	case CMD_XMIT_BCAST_CN:
1570 	case CMD_XMIT_BCAST_CX:
1571 	case CMD_ELS_REQUEST_CR:
1572 	case CMD_ELS_REQUEST_CX:
1573 	case CMD_CREATE_XRI_CR:
1574 	case CMD_CREATE_XRI_CX:
1575 	case CMD_GET_RPI_CN:
1576 	case CMD_XMIT_ELS_RSP_CX:
1577 	case CMD_GET_RPI_CR:
1578 	case CMD_FCP_IWRITE_CR:
1579 	case CMD_FCP_IWRITE_CX:
1580 	case CMD_FCP_IREAD_CR:
1581 	case CMD_FCP_IREAD_CX:
1582 	case CMD_FCP_ICMND_CR:
1583 	case CMD_FCP_ICMND_CX:
1584 	case CMD_FCP_TSEND_CX:
1585 	case CMD_FCP_TRSP_CX:
1586 	case CMD_FCP_TRECEIVE_CX:
1587 	case CMD_FCP_AUTO_TRSP_CX:
1588 	case CMD_ADAPTER_MSG:
1589 	case CMD_ADAPTER_DUMP:
1590 	case CMD_XMIT_SEQUENCE64_CR:
1591 	case CMD_XMIT_SEQUENCE64_CX:
1592 	case CMD_XMIT_BCAST64_CN:
1593 	case CMD_XMIT_BCAST64_CX:
1594 	case CMD_ELS_REQUEST64_CR:
1595 	case CMD_ELS_REQUEST64_CX:
1596 	case CMD_FCP_IWRITE64_CR:
1597 	case CMD_FCP_IWRITE64_CX:
1598 	case CMD_FCP_IREAD64_CR:
1599 	case CMD_FCP_IREAD64_CX:
1600 	case CMD_FCP_ICMND64_CR:
1601 	case CMD_FCP_ICMND64_CX:
1602 	case CMD_FCP_TSEND64_CX:
1603 	case CMD_FCP_TRSP64_CX:
1604 	case CMD_FCP_TRECEIVE64_CX:
1605 	case CMD_GEN_REQUEST64_CR:
1606 	case CMD_GEN_REQUEST64_CX:
1607 	case CMD_XMIT_ELS_RSP64_CX:
1608 	case DSSCMD_IWRITE64_CR:
1609 	case DSSCMD_IWRITE64_CX:
1610 	case DSSCMD_IREAD64_CR:
1611 	case DSSCMD_IREAD64_CX:
1612 	case CMD_SEND_FRAME:
1613 		type = LPFC_SOL_IOCB;
1614 		break;
1615 	case CMD_ABORT_XRI_CN:
1616 	case CMD_ABORT_XRI_CX:
1617 	case CMD_CLOSE_XRI_CN:
1618 	case CMD_CLOSE_XRI_CX:
1619 	case CMD_XRI_ABORTED_CX:
1620 	case CMD_ABORT_MXRI64_CN:
1621 	case CMD_XMIT_BLS_RSP64_CX:
1622 		type = LPFC_ABORT_IOCB;
1623 		break;
1624 	case CMD_RCV_SEQUENCE_CX:
1625 	case CMD_RCV_ELS_REQ_CX:
1626 	case CMD_RCV_SEQUENCE64_CX:
1627 	case CMD_RCV_ELS_REQ64_CX:
1628 	case CMD_ASYNC_STATUS:
1629 	case CMD_IOCB_RCV_SEQ64_CX:
1630 	case CMD_IOCB_RCV_ELS64_CX:
1631 	case CMD_IOCB_RCV_CONT64_CX:
1632 	case CMD_IOCB_RET_XRI64_CX:
1633 		type = LPFC_UNSOL_IOCB;
1634 		break;
1635 	case CMD_IOCB_XMIT_MSEQ64_CR:
1636 	case CMD_IOCB_XMIT_MSEQ64_CX:
1637 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1638 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1639 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1640 	case CMD_IOCB_ABORT_EXTENDED_CN:
1641 	case CMD_IOCB_RET_HBQE64_CN:
1642 	case CMD_IOCB_FCP_IBIDIR64_CR:
1643 	case CMD_IOCB_FCP_IBIDIR64_CX:
1644 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1645 	case CMD_IOCB_LOGENTRY_CN:
1646 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1647 		printk("%s - Unhandled SLI-3 Command x%x\n",
1648 				__func__, iocb_cmnd);
1649 		type = LPFC_UNKNOWN_IOCB;
1650 		break;
1651 	default:
1652 		type = LPFC_UNKNOWN_IOCB;
1653 		break;
1654 	}
1655 
1656 	return type;
1657 }
1658 
1659 /**
1660  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1661  * @phba: Pointer to HBA context object.
1662  *
1663  * This function is called from SLI initialization code
1664  * to configure every ring of the HBA's SLI interface. The
1665  * caller is not required to hold any lock. This function issues
1666  * a config_ring mailbox command for each ring.
1667  * This function returns zero if successful else returns a negative
1668  * error code.
1669  **/
1670 static int
1671 lpfc_sli_ring_map(struct lpfc_hba *phba)
1672 {
1673 	struct lpfc_sli *psli = &phba->sli;
1674 	LPFC_MBOXQ_t *pmb;
1675 	MAILBOX_t *pmbox;
1676 	int i, rc, ret = 0;
1677 
1678 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1679 	if (!pmb)
1680 		return -ENOMEM;
1681 	pmbox = &pmb->u.mb;
1682 	phba->link_state = LPFC_INIT_MBX_CMDS;
1683 	for (i = 0; i < psli->num_rings; i++) {
1684 		lpfc_config_ring(phba, i, pmb);
1685 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1686 		if (rc != MBX_SUCCESS) {
1687 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1688 					"0446 Adapter failed to init (%d), "
1689 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1690 					"ring %d\n",
1691 					rc, pmbox->mbxCommand,
1692 					pmbox->mbxStatus, i);
1693 			phba->link_state = LPFC_HBA_ERROR;
1694 			ret = -ENXIO;
1695 			break;
1696 		}
1697 	}
1698 	mempool_free(pmb, phba->mbox_mem_pool);
1699 	return ret;
1700 }
1701 
1702 /**
1703  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1704  * @phba: Pointer to HBA context object.
1705  * @pring: Pointer to driver SLI ring object.
1706  * @piocb: Pointer to the driver iocb object.
1707  *
1708  * The driver calls this function with the hbalock held for SLI3 ports or
1709  * the ring lock held for SLI4 ports. The function adds the
1710  * new iocb to txcmplq of the given ring. This function always returns
1711  * 0. If this function is called for ELS ring, this function checks if
1712  * there is a vport associated with the ELS command. This function also
1713  * starts els_tmofunc timer if this is an ELS command.
1714  **/
1715 static int
1716 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1717 			struct lpfc_iocbq *piocb)
1718 {
1719 	u32 ulp_command = 0;
1720 
1721 	BUG_ON(!piocb);
1722 	ulp_command = get_job_cmnd(phba, piocb);
1723 
1724 	list_add_tail(&piocb->list, &pring->txcmplq);
1725 	piocb->cmd_flag |= LPFC_IO_ON_TXCMPLQ;
1726 	pring->txcmplq_cnt++;
1727 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1728 	   (ulp_command != CMD_ABORT_XRI_WQE) &&
1729 	   (ulp_command != CMD_ABORT_XRI_CN) &&
1730 	   (ulp_command != CMD_CLOSE_XRI_CN)) {
1731 		BUG_ON(!piocb->vport);
1732 		if (!test_bit(FC_UNLOADING, &piocb->vport->load_flag))
1733 			mod_timer(&piocb->vport->els_tmofunc,
1734 				  jiffies + secs_to_jiffies(phba->fc_ratov << 1));
1735 	}
1736 
1737 	return 0;
1738 }
1739 
1740 /**
1741  * lpfc_sli_ringtx_get - Get first element of the txq
1742  * @phba: Pointer to HBA context object.
1743  * @pring: Pointer to driver SLI ring object.
1744  *
1745  * This function is called with hbalock held to get next
1746  * iocb in txq of the given ring. If there is any iocb in
1747  * the txq, the function returns first iocb in the list after
1748  * removing the iocb from the list, else it returns NULL.
1749  **/
1750 struct lpfc_iocbq *
1751 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1752 {
1753 	struct lpfc_iocbq *cmd_iocb;
1754 
1755 	lockdep_assert_held(&phba->hbalock);
1756 
1757 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1758 	return cmd_iocb;
1759 }
1760 
1761 /**
1762  * lpfc_cmf_sync_cmpl - Process a CMF_SYNC_WQE cmpl
1763  * @phba: Pointer to HBA context object.
1764  * @cmdiocb: Pointer to driver command iocb object.
1765  * @rspiocb: Pointer to driver response iocb object.
1766  *
1767  * This routine will inform the driver of any BW adjustments we need
1768  * to make. These changes will be picked up during the next CMF
1769  * timer interrupt. In addition, any BW changes will be logged
1770  * with LOG_CGN_MGMT.
1771  **/
1772 static void
1773 lpfc_cmf_sync_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
1774 		   struct lpfc_iocbq *rspiocb)
1775 {
1776 	union lpfc_wqe128 *wqe;
1777 	uint32_t status, info;
1778 	struct lpfc_wcqe_complete *wcqe = &rspiocb->wcqe_cmpl;
1779 	uint64_t bw, bwdif, slop;
1780 	uint64_t pcent, bwpcent;
1781 	int asig, afpin, sigcnt, fpincnt;
1782 	int wsigmax, wfpinmax, cg, tdp;
1783 	char *s;
1784 
1785 	/* First check for error */
1786 	status = bf_get(lpfc_wcqe_c_status, wcqe);
1787 	if (status) {
1788 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1789 				"6211 CMF_SYNC_WQE Error "
1790 				"req_tag x%x status x%x hwstatus x%x "
1791 				"tdatap x%x parm x%x\n",
1792 				bf_get(lpfc_wcqe_c_request_tag, wcqe),
1793 				bf_get(lpfc_wcqe_c_status, wcqe),
1794 				bf_get(lpfc_wcqe_c_hw_status, wcqe),
1795 				wcqe->total_data_placed,
1796 				wcqe->parameter);
1797 		goto out;
1798 	}
1799 
1800 	/* Gather congestion information on a successful cmpl */
1801 	info = wcqe->parameter;
1802 	phba->cmf_active_info = info;
1803 
1804 	/* See if firmware info count is valid or has changed */
1805 	if (info > LPFC_MAX_CMF_INFO || phba->cmf_info_per_interval == info)
1806 		info = 0;
1807 	else
1808 		phba->cmf_info_per_interval = info;
1809 
1810 	tdp = bf_get(lpfc_wcqe_c_cmf_bw, wcqe);
1811 	cg = bf_get(lpfc_wcqe_c_cmf_cg, wcqe);
1812 
1813 	/* Get BW requirement from firmware */
1814 	bw = (uint64_t)tdp * LPFC_CMF_BLK_SIZE;
1815 	if (!bw) {
1816 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1817 				"6212 CMF_SYNC_WQE x%x: NULL bw\n",
1818 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
1819 		goto out;
1820 	}
1821 
1822 	/* Gather information needed for logging if a BW change is required */
1823 	wqe = &cmdiocb->wqe;
1824 	asig = bf_get(cmf_sync_asig, &wqe->cmf_sync);
1825 	afpin = bf_get(cmf_sync_afpin, &wqe->cmf_sync);
1826 	fpincnt = bf_get(cmf_sync_wfpincnt, &wqe->cmf_sync);
1827 	sigcnt = bf_get(cmf_sync_wsigcnt, &wqe->cmf_sync);
1828 	if (phba->cmf_max_bytes_per_interval != bw ||
1829 	    (asig || afpin || sigcnt || fpincnt)) {
1830 		/* Are we increasing or decreasing BW */
1831 		if (phba->cmf_max_bytes_per_interval <  bw) {
1832 			bwdif = bw - phba->cmf_max_bytes_per_interval;
1833 			s = "Increase";
1834 		} else {
1835 			bwdif = phba->cmf_max_bytes_per_interval - bw;
1836 			s = "Decrease";
1837 		}
1838 
1839 		/* What is the change percentage */
1840 		slop = div_u64(phba->cmf_link_byte_count, 200); /*For rounding*/
1841 		pcent = div64_u64(bwdif * 100 + slop,
1842 				  phba->cmf_link_byte_count);
1843 		bwpcent = div64_u64(bw * 100 + slop,
1844 				    phba->cmf_link_byte_count);
1845 		/* Because of bytes adjustment due to shorter timer in
1846 		 * lpfc_cmf_timer() the cmf_link_byte_count can be shorter and
1847 		 * may seem like BW is above 100%.
1848 		 */
1849 		if (bwpcent > 100)
1850 			bwpcent = 100;
1851 
1852 		if (phba->cmf_max_bytes_per_interval < bw &&
1853 		    bwpcent > 95)
1854 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1855 					"6208 Congestion bandwidth "
1856 					"limits removed\n");
1857 		else if ((phba->cmf_max_bytes_per_interval > bw) &&
1858 			 ((bwpcent + pcent) <= 100) && ((bwpcent + pcent) > 95))
1859 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1860 					"6209 Congestion bandwidth "
1861 					"limits in effect\n");
1862 
1863 		if (asig) {
1864 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1865 					"6237 BW Threshold %lld%% (%lld): "
1866 					"%lld%% %s: Signal Alarm: cg:%d "
1867 					"Info:%u\n",
1868 					bwpcent, bw, pcent, s, cg,
1869 					phba->cmf_active_info);
1870 		} else if (afpin) {
1871 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1872 					"6238 BW Threshold %lld%% (%lld): "
1873 					"%lld%% %s: FPIN Alarm: cg:%d "
1874 					"Info:%u\n",
1875 					bwpcent, bw, pcent, s, cg,
1876 					phba->cmf_active_info);
1877 		} else if (sigcnt) {
1878 			wsigmax = bf_get(cmf_sync_wsigmax, &wqe->cmf_sync);
1879 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1880 					"6239 BW Threshold %lld%% (%lld): "
1881 					"%lld%% %s: Signal Warning: "
1882 					"Cnt %d Max %d: cg:%d Info:%u\n",
1883 					bwpcent, bw, pcent, s, sigcnt,
1884 					wsigmax, cg, phba->cmf_active_info);
1885 		} else if (fpincnt) {
1886 			wfpinmax = bf_get(cmf_sync_wfpinmax, &wqe->cmf_sync);
1887 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1888 					"6240 BW Threshold %lld%% (%lld): "
1889 					"%lld%% %s: FPIN Warning: "
1890 					"Cnt %d Max %d: cg:%d Info:%u\n",
1891 					bwpcent, bw, pcent, s, fpincnt,
1892 					wfpinmax, cg, phba->cmf_active_info);
1893 		} else {
1894 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1895 					"6241 BW Threshold %lld%% (%lld): "
1896 					"CMF %lld%% %s: cg:%d Info:%u\n",
1897 					bwpcent, bw, pcent, s, cg,
1898 					phba->cmf_active_info);
1899 		}
1900 	} else if (info) {
1901 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1902 				"6246 Info Threshold %u\n", info);
1903 	}
1904 
1905 	/* Save BW change to be picked up during next timer interrupt */
1906 	phba->cmf_last_sync_bw = bw;
1907 out:
1908 	lpfc_sli_release_iocbq(phba, cmdiocb);
1909 }
1910 
1911 /**
1912  * lpfc_issue_cmf_sync_wqe - Issue a CMF_SYNC_WQE
1913  * @phba: Pointer to HBA context object.
1914  * @ms:   ms to set in WQE interval, 0 means use init op
1915  * @total: Total rcv bytes for this interval
1916  *
1917  * This routine is called every CMF timer interrupt. Its purpose is
1918  * to issue a CMF_SYNC_WQE to the firmware to inform it of any events
1919  * that may indicate we have congestion (FPINs or Signals). Upon
1920  * completion, the firmware will indicate any BW restrictions the
1921  * driver may need to take.
1922  **/
1923 int
1924 lpfc_issue_cmf_sync_wqe(struct lpfc_hba *phba, u32 ms, u64 total)
1925 {
1926 	union lpfc_wqe128 *wqe;
1927 	struct lpfc_iocbq *sync_buf;
1928 	unsigned long iflags;
1929 	u32 ret_val, cgn_sig_freq;
1930 	u32 atot, wtot, max;
1931 	u8 warn_sync_period = 0;
1932 
1933 	/* First address any alarm / warning activity */
1934 	atot = atomic_xchg(&phba->cgn_sync_alarm_cnt, 0);
1935 	wtot = atomic_xchg(&phba->cgn_sync_warn_cnt, 0);
1936 
1937 	spin_lock_irqsave(&phba->hbalock, iflags);
1938 
1939 	/* ONLY Managed mode will send the CMF_SYNC_WQE to the HBA */
1940 	if (phba->cmf_active_mode != LPFC_CFG_MANAGED ||
1941 	    phba->link_state < LPFC_LINK_UP) {
1942 		ret_val = 0;
1943 		goto out_unlock;
1944 	}
1945 
1946 	sync_buf = __lpfc_sli_get_iocbq(phba);
1947 	if (!sync_buf) {
1948 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
1949 				"6244 No available WQEs for CMF_SYNC_WQE\n");
1950 		ret_val = ENOMEM;
1951 		goto out_unlock;
1952 	}
1953 
1954 	wqe = &sync_buf->wqe;
1955 
1956 	/* WQEs are reused.  Clear stale data and set key fields to zero */
1957 	memset(wqe, 0, sizeof(*wqe));
1958 
1959 	/* If this is the very first CMF_SYNC_WQE, issue an init operation */
1960 	if (!ms) {
1961 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1962 				"6441 CMF Init %d - CMF_SYNC_WQE\n",
1963 				phba->fc_eventTag);
1964 		bf_set(cmf_sync_op, &wqe->cmf_sync, 1); /* 1=init */
1965 		bf_set(cmf_sync_interval, &wqe->cmf_sync, LPFC_CMF_INTERVAL);
1966 		goto initpath;
1967 	}
1968 
1969 	bf_set(cmf_sync_op, &wqe->cmf_sync, 0); /* 0=recalc */
1970 	bf_set(cmf_sync_interval, &wqe->cmf_sync, ms);
1971 
1972 	/* Check for alarms / warnings */
1973 	if (atot) {
1974 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1975 			/* We hit an Signal alarm condition */
1976 			bf_set(cmf_sync_asig, &wqe->cmf_sync, 1);
1977 		} else {
1978 			/* We hit a FPIN alarm condition */
1979 			bf_set(cmf_sync_afpin, &wqe->cmf_sync, 1);
1980 		}
1981 	} else if (wtot) {
1982 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
1983 		    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1984 			cgn_sig_freq = phba->cgn_sig_freq ? phba->cgn_sig_freq :
1985 					lpfc_fabric_cgn_frequency;
1986 			/* We hit an Signal warning condition */
1987 			max = LPFC_SEC_TO_MSEC / cgn_sig_freq *
1988 				lpfc_acqe_cgn_frequency;
1989 			bf_set(cmf_sync_wsigmax, &wqe->cmf_sync, max);
1990 			bf_set(cmf_sync_wsigcnt, &wqe->cmf_sync, wtot);
1991 			warn_sync_period = lpfc_acqe_cgn_frequency;
1992 		} else {
1993 			/* We hit a FPIN warning condition */
1994 			bf_set(cmf_sync_wfpinmax, &wqe->cmf_sync, 1);
1995 			bf_set(cmf_sync_wfpincnt, &wqe->cmf_sync, 1);
1996 			if (phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ)
1997 				warn_sync_period =
1998 				LPFC_MSECS_TO_SECS(phba->cgn_fpin_frequency);
1999 		}
2000 	}
2001 
2002 	/* Update total read blocks during previous timer interval */
2003 	wqe->cmf_sync.read_bytes = (u32)(total / LPFC_CMF_BLK_SIZE);
2004 
2005 initpath:
2006 	bf_set(cmf_sync_ver, &wqe->cmf_sync, LPFC_CMF_SYNC_VER);
2007 	wqe->cmf_sync.event_tag = phba->fc_eventTag;
2008 	bf_set(cmf_sync_cmnd, &wqe->cmf_sync, CMD_CMF_SYNC_WQE);
2009 
2010 	/* Setup reqtag to match the wqe completion. */
2011 	bf_set(cmf_sync_reqtag, &wqe->cmf_sync, sync_buf->iotag);
2012 
2013 	bf_set(cmf_sync_qosd, &wqe->cmf_sync, 1);
2014 	bf_set(cmf_sync_period, &wqe->cmf_sync, warn_sync_period);
2015 
2016 	bf_set(cmf_sync_cmd_type, &wqe->cmf_sync, CMF_SYNC_COMMAND);
2017 	bf_set(cmf_sync_wqec, &wqe->cmf_sync, 1);
2018 	bf_set(cmf_sync_cqid, &wqe->cmf_sync, LPFC_WQE_CQ_ID_DEFAULT);
2019 
2020 	sync_buf->vport = phba->pport;
2021 	sync_buf->cmd_cmpl = lpfc_cmf_sync_cmpl;
2022 	sync_buf->cmd_dmabuf = NULL;
2023 	sync_buf->rsp_dmabuf = NULL;
2024 	sync_buf->bpl_dmabuf = NULL;
2025 	sync_buf->sli4_xritag = NO_XRI;
2026 
2027 	sync_buf->cmd_flag |= LPFC_IO_CMF;
2028 	ret_val = lpfc_sli4_issue_wqe(phba, &phba->sli4_hba.hdwq[0], sync_buf);
2029 	if (ret_val) {
2030 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
2031 				"6214 Cannot issue CMF_SYNC_WQE: x%x\n",
2032 				ret_val);
2033 		__lpfc_sli_release_iocbq(phba, sync_buf);
2034 	}
2035 out_unlock:
2036 	spin_unlock_irqrestore(&phba->hbalock, iflags);
2037 	return ret_val;
2038 }
2039 
2040 /**
2041  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
2042  * @phba: Pointer to HBA context object.
2043  * @pring: Pointer to driver SLI ring object.
2044  *
2045  * This function is called with hbalock held and the caller must post the
2046  * iocb without releasing the lock. If the caller releases the lock,
2047  * iocb slot returned by the function is not guaranteed to be available.
2048  * The function returns pointer to the next available iocb slot if there
2049  * is available slot in the ring, else it returns NULL.
2050  * If the get index of the ring is ahead of the put index, the function
2051  * will post an error attention event to the worker thread to take the
2052  * HBA to offline state.
2053  **/
2054 static IOCB_t *
2055 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2056 {
2057 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2058 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
2059 
2060 	lockdep_assert_held(&phba->hbalock);
2061 
2062 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
2063 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
2064 		pring->sli.sli3.next_cmdidx = 0;
2065 
2066 	if (unlikely(pring->sli.sli3.local_getidx ==
2067 		pring->sli.sli3.next_cmdidx)) {
2068 
2069 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
2070 
2071 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
2072 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2073 					"0315 Ring %d issue: portCmdGet %d "
2074 					"is bigger than cmd ring %d\n",
2075 					pring->ringno,
2076 					pring->sli.sli3.local_getidx,
2077 					max_cmd_idx);
2078 
2079 			phba->link_state = LPFC_HBA_ERROR;
2080 			/*
2081 			 * All error attention handlers are posted to
2082 			 * worker thread
2083 			 */
2084 			phba->work_ha |= HA_ERATT;
2085 			phba->work_hs = HS_FFER3;
2086 
2087 			lpfc_worker_wake_up(phba);
2088 
2089 			return NULL;
2090 		}
2091 
2092 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
2093 			return NULL;
2094 	}
2095 
2096 	return lpfc_cmd_iocb(phba, pring);
2097 }
2098 
2099 /**
2100  * lpfc_sli_next_iotag - Get an iotag for the iocb
2101  * @phba: Pointer to HBA context object.
2102  * @iocbq: Pointer to driver iocb object.
2103  *
2104  * This function gets an iotag for the iocb. If there is no unused iotag and
2105  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
2106  * array and assigns a new iotag.
2107  * The function returns the allocated iotag if successful, else returns zero.
2108  * Zero is not a valid iotag.
2109  * The caller is not required to hold any lock.
2110  **/
2111 uint16_t
2112 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
2113 {
2114 	struct lpfc_iocbq **new_arr;
2115 	struct lpfc_iocbq **old_arr;
2116 	size_t new_len;
2117 	struct lpfc_sli *psli = &phba->sli;
2118 	uint16_t iotag;
2119 
2120 	spin_lock_irq(&phba->hbalock);
2121 	iotag = psli->last_iotag;
2122 	if(++iotag < psli->iocbq_lookup_len) {
2123 		psli->last_iotag = iotag;
2124 		psli->iocbq_lookup[iotag] = iocbq;
2125 		spin_unlock_irq(&phba->hbalock);
2126 		iocbq->iotag = iotag;
2127 		return iotag;
2128 	} else if (psli->iocbq_lookup_len < (0xffff
2129 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
2130 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
2131 		spin_unlock_irq(&phba->hbalock);
2132 		new_arr = kzalloc_objs(struct lpfc_iocbq *, new_len);
2133 		if (new_arr) {
2134 			spin_lock_irq(&phba->hbalock);
2135 			old_arr = psli->iocbq_lookup;
2136 			if (new_len <= psli->iocbq_lookup_len) {
2137 				/* highly unprobable case */
2138 				kfree(new_arr);
2139 				iotag = psli->last_iotag;
2140 				if(++iotag < psli->iocbq_lookup_len) {
2141 					psli->last_iotag = iotag;
2142 					psli->iocbq_lookup[iotag] = iocbq;
2143 					spin_unlock_irq(&phba->hbalock);
2144 					iocbq->iotag = iotag;
2145 					return iotag;
2146 				}
2147 				spin_unlock_irq(&phba->hbalock);
2148 				return 0;
2149 			}
2150 			if (psli->iocbq_lookup)
2151 				memcpy(new_arr, old_arr,
2152 				       ((psli->last_iotag  + 1) *
2153 					sizeof (struct lpfc_iocbq *)));
2154 			psli->iocbq_lookup = new_arr;
2155 			psli->iocbq_lookup_len = new_len;
2156 			psli->last_iotag = iotag;
2157 			psli->iocbq_lookup[iotag] = iocbq;
2158 			spin_unlock_irq(&phba->hbalock);
2159 			iocbq->iotag = iotag;
2160 			kfree(old_arr);
2161 			return iotag;
2162 		}
2163 	} else
2164 		spin_unlock_irq(&phba->hbalock);
2165 
2166 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2167 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
2168 			psli->last_iotag);
2169 
2170 	return 0;
2171 }
2172 
2173 /**
2174  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
2175  * @phba: Pointer to HBA context object.
2176  * @pring: Pointer to driver SLI ring object.
2177  * @iocb: Pointer to iocb slot in the ring.
2178  * @nextiocb: Pointer to driver iocb object which need to be
2179  *            posted to firmware.
2180  *
2181  * This function is called to post a new iocb to the firmware. This
2182  * function copies the new iocb to ring iocb slot and updates the
2183  * ring pointers. It adds the new iocb to txcmplq if there is
2184  * a completion call back for this iocb else the function will free the
2185  * iocb object.  The hbalock is asserted held in the code path calling
2186  * this routine.
2187  **/
2188 static void
2189 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2190 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
2191 {
2192 	/*
2193 	 * Set up an iotag
2194 	 */
2195 	nextiocb->iocb.ulpIoTag = (nextiocb->cmd_cmpl) ? nextiocb->iotag : 0;
2196 
2197 
2198 	if (pring->ringno == LPFC_ELS_RING) {
2199 		lpfc_debugfs_slow_ring_trc(phba,
2200 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
2201 			*(((uint32_t *) &nextiocb->iocb) + 4),
2202 			*(((uint32_t *) &nextiocb->iocb) + 6),
2203 			*(((uint32_t *) &nextiocb->iocb) + 7));
2204 	}
2205 
2206 	/*
2207 	 * Issue iocb command to adapter
2208 	 */
2209 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
2210 	wmb();
2211 	pring->stats.iocb_cmd++;
2212 
2213 	/*
2214 	 * If there is no completion routine to call, we can release the
2215 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
2216 	 * that have no rsp ring completion, cmd_cmpl MUST be NULL.
2217 	 */
2218 	if (nextiocb->cmd_cmpl)
2219 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
2220 	else
2221 		__lpfc_sli_release_iocbq(phba, nextiocb);
2222 
2223 	/*
2224 	 * Let the HBA know what IOCB slot will be the next one the
2225 	 * driver will put a command into.
2226 	 */
2227 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
2228 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
2229 }
2230 
2231 /**
2232  * lpfc_sli_update_full_ring - Update the chip attention register
2233  * @phba: Pointer to HBA context object.
2234  * @pring: Pointer to driver SLI ring object.
2235  *
2236  * The caller is not required to hold any lock for calling this function.
2237  * This function updates the chip attention bits for the ring to inform firmware
2238  * that there are pending work to be done for this ring and requests an
2239  * interrupt when there is space available in the ring. This function is
2240  * called when the driver is unable to post more iocbs to the ring due
2241  * to unavailability of space in the ring.
2242  **/
2243 static void
2244 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2245 {
2246 	int ringno = pring->ringno;
2247 
2248 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
2249 
2250 	wmb();
2251 
2252 	/*
2253 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
2254 	 * The HBA will tell us when an IOCB entry is available.
2255 	 */
2256 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
2257 	readl(phba->CAregaddr); /* flush */
2258 
2259 	pring->stats.iocb_cmd_full++;
2260 }
2261 
2262 /**
2263  * lpfc_sli_update_ring - Update chip attention register
2264  * @phba: Pointer to HBA context object.
2265  * @pring: Pointer to driver SLI ring object.
2266  *
2267  * This function updates the chip attention register bit for the
2268  * given ring to inform HBA that there is more work to be done
2269  * in this ring. The caller is not required to hold any lock.
2270  **/
2271 static void
2272 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2273 {
2274 	int ringno = pring->ringno;
2275 
2276 	/*
2277 	 * Tell the HBA that there is work to do in this ring.
2278 	 */
2279 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
2280 		wmb();
2281 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
2282 		readl(phba->CAregaddr); /* flush */
2283 	}
2284 }
2285 
2286 /**
2287  * lpfc_sli_resume_iocb - Process iocbs in the txq
2288  * @phba: Pointer to HBA context object.
2289  * @pring: Pointer to driver SLI ring object.
2290  *
2291  * This function is called with hbalock held to post pending iocbs
2292  * in the txq to the firmware. This function is called when driver
2293  * detects space available in the ring.
2294  **/
2295 static void
2296 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2297 {
2298 	IOCB_t *iocb;
2299 	struct lpfc_iocbq *nextiocb;
2300 
2301 	lockdep_assert_held(&phba->hbalock);
2302 
2303 	/*
2304 	 * Check to see if:
2305 	 *  (a) there is anything on the txq to send
2306 	 *  (b) link is up
2307 	 *  (c) link attention events can be processed (fcp ring only)
2308 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
2309 	 */
2310 
2311 	if (lpfc_is_link_up(phba) &&
2312 	    (!list_empty(&pring->txq)) &&
2313 	    (pring->ringno != LPFC_FCP_RING ||
2314 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
2315 
2316 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
2317 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
2318 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
2319 
2320 		if (iocb)
2321 			lpfc_sli_update_ring(phba, pring);
2322 		else
2323 			lpfc_sli_update_full_ring(phba, pring);
2324 	}
2325 
2326 	return;
2327 }
2328 
2329 /**
2330  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
2331  * @phba: Pointer to HBA context object.
2332  * @hbqno: HBQ number.
2333  *
2334  * This function is called with hbalock held to get the next
2335  * available slot for the given HBQ. If there is free slot
2336  * available for the HBQ it will return pointer to the next available
2337  * HBQ entry else it will return NULL.
2338  **/
2339 static struct lpfc_hbq_entry *
2340 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
2341 {
2342 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
2343 
2344 	lockdep_assert_held(&phba->hbalock);
2345 
2346 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
2347 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
2348 		hbqp->next_hbqPutIdx = 0;
2349 
2350 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
2351 		uint32_t raw_index = phba->hbq_get[hbqno];
2352 		uint32_t getidx = le32_to_cpu(raw_index);
2353 
2354 		hbqp->local_hbqGetIdx = getidx;
2355 
2356 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
2357 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2358 					"1802 HBQ %d: local_hbqGetIdx "
2359 					"%u is > than hbqp->entry_count %u\n",
2360 					hbqno, hbqp->local_hbqGetIdx,
2361 					hbqp->entry_count);
2362 
2363 			phba->link_state = LPFC_HBA_ERROR;
2364 			return NULL;
2365 		}
2366 
2367 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
2368 			return NULL;
2369 	}
2370 
2371 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
2372 			hbqp->hbqPutIdx;
2373 }
2374 
2375 /**
2376  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
2377  * @phba: Pointer to HBA context object.
2378  *
2379  * This function is called with no lock held to free all the
2380  * hbq buffers while uninitializing the SLI interface. It also
2381  * frees the HBQ buffers returned by the firmware but not yet
2382  * processed by the upper layers.
2383  **/
2384 void
2385 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
2386 {
2387 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
2388 	struct hbq_dmabuf *hbq_buf;
2389 	unsigned long flags;
2390 	int i, hbq_count;
2391 
2392 	hbq_count = lpfc_sli_hbq_count();
2393 	/* Return all memory used by all HBQs */
2394 	spin_lock_irqsave(&phba->hbalock, flags);
2395 	for (i = 0; i < hbq_count; ++i) {
2396 		list_for_each_entry_safe(dmabuf, next_dmabuf,
2397 				&phba->hbqs[i].hbq_buffer_list, list) {
2398 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2399 			list_del(&hbq_buf->dbuf.list);
2400 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2401 		}
2402 		phba->hbqs[i].buffer_count = 0;
2403 	}
2404 
2405 	/* Mark the HBQs not in use */
2406 	phba->hbq_in_use = 0;
2407 	spin_unlock_irqrestore(&phba->hbalock, flags);
2408 }
2409 
2410 /**
2411  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2412  * @phba: Pointer to HBA context object.
2413  * @hbqno: HBQ number.
2414  * @hbq_buf: Pointer to HBQ buffer.
2415  *
2416  * This function is called with the hbalock held to post a
2417  * hbq buffer to the firmware. If the function finds an empty
2418  * slot in the HBQ, it will post the buffer. The function will return
2419  * pointer to the hbq entry if it successfully post the buffer
2420  * else it will return NULL.
2421  **/
2422 static int
2423 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2424 			 struct hbq_dmabuf *hbq_buf)
2425 {
2426 	lockdep_assert_held(&phba->hbalock);
2427 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2428 }
2429 
2430 /**
2431  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2432  * @phba: Pointer to HBA context object.
2433  * @hbqno: HBQ number.
2434  * @hbq_buf: Pointer to HBQ buffer.
2435  *
2436  * This function is called with the hbalock held to post a hbq buffer to the
2437  * firmware. If the function finds an empty slot in the HBQ, it will post the
2438  * buffer and place it on the hbq_buffer_list. The function will return zero if
2439  * it successfully post the buffer else it will return an error.
2440  **/
2441 static int
2442 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2443 			    struct hbq_dmabuf *hbq_buf)
2444 {
2445 	struct lpfc_hbq_entry *hbqe;
2446 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
2447 
2448 	lockdep_assert_held(&phba->hbalock);
2449 	/* Get next HBQ entry slot to use */
2450 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2451 	if (hbqe) {
2452 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
2453 
2454 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2455 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2456 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2457 		hbqe->bde.tus.f.bdeFlags = 0;
2458 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2459 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2460 				/* Sync SLIM */
2461 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2462 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2463 				/* flush */
2464 		readl(phba->hbq_put + hbqno);
2465 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2466 		return 0;
2467 	} else
2468 		return -ENOMEM;
2469 }
2470 
2471 /**
2472  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2473  * @phba: Pointer to HBA context object.
2474  * @hbqno: HBQ number.
2475  * @hbq_buf: Pointer to HBQ buffer.
2476  *
2477  * This function is called with the hbalock held to post an RQE to the SLI4
2478  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2479  * the hbq_buffer_list and return zero, otherwise it will return an error.
2480  **/
2481 static int
2482 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2483 			    struct hbq_dmabuf *hbq_buf)
2484 {
2485 	int rc;
2486 	struct lpfc_rqe hrqe;
2487 	struct lpfc_rqe drqe;
2488 	struct lpfc_queue *hrq;
2489 	struct lpfc_queue *drq;
2490 
2491 	if (hbqno != LPFC_ELS_HBQ)
2492 		return 1;
2493 	hrq = phba->sli4_hba.hdr_rq;
2494 	drq = phba->sli4_hba.dat_rq;
2495 
2496 	lockdep_assert_held(&phba->hbalock);
2497 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2498 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2499 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2500 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2501 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2502 	if (rc < 0)
2503 		return rc;
2504 	hbq_buf->tag = (rc | (hbqno << 16));
2505 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2506 	return 0;
2507 }
2508 
2509 /* HBQ for ELS and CT traffic. */
2510 static struct lpfc_hbq_init lpfc_els_hbq = {
2511 	.rn = 1,
2512 	.entry_count = 256,
2513 	.mask_count = 0,
2514 	.profile = 0,
2515 	.ring_mask = (1 << LPFC_ELS_RING),
2516 	.buffer_count = 0,
2517 	.init_count = 40,
2518 	.add_count = 40,
2519 };
2520 
2521 /* Array of HBQs */
2522 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2523 	&lpfc_els_hbq,
2524 };
2525 
2526 /**
2527  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2528  * @phba: Pointer to HBA context object.
2529  * @hbqno: HBQ number.
2530  * @count: Number of HBQ buffers to be posted.
2531  *
2532  * This function is called with no lock held to post more hbq buffers to the
2533  * given HBQ. The function returns the number of HBQ buffers successfully
2534  * posted.
2535  **/
2536 static int
2537 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2538 {
2539 	uint32_t i, posted = 0;
2540 	unsigned long flags;
2541 	struct hbq_dmabuf *hbq_buffer;
2542 	LIST_HEAD(hbq_buf_list);
2543 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2544 		return 0;
2545 
2546 	if ((phba->hbqs[hbqno].buffer_count + count) >
2547 	    lpfc_hbq_defs[hbqno]->entry_count)
2548 		count = lpfc_hbq_defs[hbqno]->entry_count -
2549 					phba->hbqs[hbqno].buffer_count;
2550 	if (!count)
2551 		return 0;
2552 	/* Allocate HBQ entries */
2553 	for (i = 0; i < count; i++) {
2554 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2555 		if (!hbq_buffer)
2556 			break;
2557 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2558 	}
2559 	/* Check whether HBQ is still in use */
2560 	spin_lock_irqsave(&phba->hbalock, flags);
2561 	if (!phba->hbq_in_use)
2562 		goto err;
2563 	while (!list_empty(&hbq_buf_list)) {
2564 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2565 				 dbuf.list);
2566 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2567 				      (hbqno << 16));
2568 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2569 			phba->hbqs[hbqno].buffer_count++;
2570 			posted++;
2571 		} else
2572 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2573 	}
2574 	spin_unlock_irqrestore(&phba->hbalock, flags);
2575 	return posted;
2576 err:
2577 	spin_unlock_irqrestore(&phba->hbalock, flags);
2578 	while (!list_empty(&hbq_buf_list)) {
2579 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2580 				 dbuf.list);
2581 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2582 	}
2583 	return 0;
2584 }
2585 
2586 /**
2587  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2588  * @phba: Pointer to HBA context object.
2589  * @qno: HBQ number.
2590  *
2591  * This function posts more buffers to the HBQ. This function
2592  * is called with no lock held. The function returns the number of HBQ entries
2593  * successfully allocated.
2594  **/
2595 int
2596 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2597 {
2598 	if (phba->sli_rev == LPFC_SLI_REV4)
2599 		return 0;
2600 	else
2601 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2602 					 lpfc_hbq_defs[qno]->add_count);
2603 }
2604 
2605 /**
2606  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2607  * @phba: Pointer to HBA context object.
2608  * @qno:  HBQ queue number.
2609  *
2610  * This function is called from SLI initialization code path with
2611  * no lock held to post initial HBQ buffers to firmware. The
2612  * function returns the number of HBQ entries successfully allocated.
2613  **/
2614 static int
2615 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2616 {
2617 	if (phba->sli_rev == LPFC_SLI_REV4)
2618 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2619 					lpfc_hbq_defs[qno]->entry_count);
2620 	else
2621 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2622 					 lpfc_hbq_defs[qno]->init_count);
2623 }
2624 
2625 /*
2626  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2627  *
2628  * This function removes the first hbq buffer on an hbq list and returns a
2629  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2630  **/
2631 static struct hbq_dmabuf *
2632 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2633 {
2634 	struct lpfc_dmabuf *d_buf;
2635 
2636 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2637 	if (!d_buf)
2638 		return NULL;
2639 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2640 }
2641 
2642 /**
2643  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2644  * @phba: Pointer to HBA context object.
2645  * @hrq: HBQ number.
2646  *
2647  * This function removes the first RQ buffer on an RQ buffer list and returns a
2648  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2649  **/
2650 static struct rqb_dmabuf *
2651 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2652 {
2653 	struct lpfc_dmabuf *h_buf;
2654 	struct lpfc_rqb *rqbp;
2655 
2656 	rqbp = hrq->rqbp;
2657 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2658 			 struct lpfc_dmabuf, list);
2659 	if (!h_buf)
2660 		return NULL;
2661 	rqbp->buffer_count--;
2662 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2663 }
2664 
2665 /**
2666  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2667  * @phba: Pointer to HBA context object.
2668  * @tag: Tag of the hbq buffer.
2669  *
2670  * This function searches for the hbq buffer associated with the given tag in
2671  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2672  * otherwise it returns NULL.
2673  **/
2674 static struct hbq_dmabuf *
2675 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2676 {
2677 	struct lpfc_dmabuf *d_buf;
2678 	struct hbq_dmabuf *hbq_buf;
2679 	uint32_t hbqno;
2680 
2681 	hbqno = tag >> 16;
2682 	if (hbqno >= LPFC_MAX_HBQS)
2683 		return NULL;
2684 
2685 	spin_lock_irq(&phba->hbalock);
2686 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2687 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2688 		if (hbq_buf->tag == tag) {
2689 			spin_unlock_irq(&phba->hbalock);
2690 			return hbq_buf;
2691 		}
2692 	}
2693 	spin_unlock_irq(&phba->hbalock);
2694 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2695 			"1803 Bad hbq tag. Data: x%x x%x\n",
2696 			tag, phba->hbqs[tag >> 16].buffer_count);
2697 	return NULL;
2698 }
2699 
2700 /**
2701  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2702  * @phba: Pointer to HBA context object.
2703  * @hbq_buffer: Pointer to HBQ buffer.
2704  *
2705  * This function is called with hbalock. This function gives back
2706  * the hbq buffer to firmware. If the HBQ does not have space to
2707  * post the buffer, it will free the buffer.
2708  **/
2709 void
2710 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2711 {
2712 	uint32_t hbqno;
2713 
2714 	if (hbq_buffer) {
2715 		hbqno = hbq_buffer->tag >> 16;
2716 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2717 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2718 	}
2719 }
2720 
2721 /**
2722  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2723  * @mbxCommand: mailbox command code.
2724  *
2725  * This function is called by the mailbox event handler function to verify
2726  * that the completed mailbox command is a legitimate mailbox command. If the
2727  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2728  * and the mailbox event handler will take the HBA offline.
2729  **/
2730 static int
2731 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2732 {
2733 	uint8_t ret;
2734 
2735 	switch (mbxCommand) {
2736 	case MBX_LOAD_SM:
2737 	case MBX_READ_NV:
2738 	case MBX_WRITE_NV:
2739 	case MBX_WRITE_VPARMS:
2740 	case MBX_RUN_BIU_DIAG:
2741 	case MBX_INIT_LINK:
2742 	case MBX_DOWN_LINK:
2743 	case MBX_CONFIG_LINK:
2744 	case MBX_CONFIG_RING:
2745 	case MBX_RESET_RING:
2746 	case MBX_READ_CONFIG:
2747 	case MBX_READ_RCONFIG:
2748 	case MBX_READ_SPARM:
2749 	case MBX_READ_STATUS:
2750 	case MBX_READ_RPI:
2751 	case MBX_READ_XRI:
2752 	case MBX_READ_REV:
2753 	case MBX_READ_LNK_STAT:
2754 	case MBX_REG_LOGIN:
2755 	case MBX_UNREG_LOGIN:
2756 	case MBX_CLEAR_LA:
2757 	case MBX_DUMP_MEMORY:
2758 	case MBX_DUMP_CONTEXT:
2759 	case MBX_RUN_DIAGS:
2760 	case MBX_RESTART:
2761 	case MBX_UPDATE_CFG:
2762 	case MBX_DOWN_LOAD:
2763 	case MBX_DEL_LD_ENTRY:
2764 	case MBX_RUN_PROGRAM:
2765 	case MBX_SET_MASK:
2766 	case MBX_SET_VARIABLE:
2767 	case MBX_UNREG_D_ID:
2768 	case MBX_KILL_BOARD:
2769 	case MBX_CONFIG_FARP:
2770 	case MBX_BEACON:
2771 	case MBX_LOAD_AREA:
2772 	case MBX_RUN_BIU_DIAG64:
2773 	case MBX_CONFIG_PORT:
2774 	case MBX_READ_SPARM64:
2775 	case MBX_READ_RPI64:
2776 	case MBX_REG_LOGIN64:
2777 	case MBX_READ_TOPOLOGY:
2778 	case MBX_WRITE_WWN:
2779 	case MBX_SET_DEBUG:
2780 	case MBX_LOAD_EXP_ROM:
2781 	case MBX_ASYNCEVT_ENABLE:
2782 	case MBX_REG_VPI:
2783 	case MBX_UNREG_VPI:
2784 	case MBX_HEARTBEAT:
2785 	case MBX_PORT_CAPABILITIES:
2786 	case MBX_PORT_IOV_CONTROL:
2787 	case MBX_SLI4_CONFIG:
2788 	case MBX_SLI4_REQ_FTRS:
2789 	case MBX_REG_FCFI:
2790 	case MBX_UNREG_FCFI:
2791 	case MBX_REG_VFI:
2792 	case MBX_UNREG_VFI:
2793 	case MBX_INIT_VPI:
2794 	case MBX_INIT_VFI:
2795 	case MBX_RESUME_RPI:
2796 	case MBX_READ_EVENT_LOG_STATUS:
2797 	case MBX_READ_EVENT_LOG:
2798 	case MBX_SECURITY_MGMT:
2799 	case MBX_AUTH_PORT:
2800 	case MBX_ACCESS_VDATA:
2801 		ret = mbxCommand;
2802 		break;
2803 	default:
2804 		ret = MBX_SHUTDOWN;
2805 		break;
2806 	}
2807 	return ret;
2808 }
2809 
2810 /**
2811  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2812  * @phba: Pointer to HBA context object.
2813  * @pmboxq: Pointer to mailbox command.
2814  *
2815  * This is completion handler function for mailbox commands issued from
2816  * lpfc_sli_issue_mbox_wait function. This function is called by the
2817  * mailbox event handler function with no lock held. This function
2818  * will wake up thread waiting on the wait queue pointed by context1
2819  * of the mailbox.
2820  **/
2821 void
2822 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2823 {
2824 	unsigned long drvr_flag;
2825 	struct completion *pmbox_done;
2826 
2827 	/*
2828 	 * If pmbox_done is empty, the driver thread gave up waiting and
2829 	 * continued running.
2830 	 */
2831 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2832 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2833 	pmbox_done = pmboxq->ctx_u.mbox_wait;
2834 	if (pmbox_done)
2835 		complete(pmbox_done);
2836 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2837 	return;
2838 }
2839 
2840 /**
2841  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2842  * @phba: Pointer to HBA context object.
2843  * @pmb: Pointer to mailbox object.
2844  *
2845  * This function is the default mailbox completion handler. It
2846  * frees the memory resources associated with the completed mailbox
2847  * command. If the completed command is a REG_LOGIN mailbox command,
2848  * this function will issue a UREG_LOGIN to re-claim the RPI.
2849  **/
2850 void
2851 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2852 {
2853 	struct lpfc_vport  *vport = pmb->vport;
2854 	struct lpfc_dmabuf *mp;
2855 	struct lpfc_nodelist *ndlp;
2856 	struct Scsi_Host *shost;
2857 	uint16_t rpi, vpi;
2858 	int rc;
2859 
2860 	/*
2861 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2862 	 * is in re-discovery driver need to cleanup the RPI.
2863 	 */
2864 	if (!test_bit(FC_UNLOADING, &phba->pport->load_flag) &&
2865 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2866 	    !pmb->u.mb.mbxStatus) {
2867 		mp = pmb->ctx_buf;
2868 		if (mp) {
2869 			pmb->ctx_buf = NULL;
2870 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
2871 			kfree(mp);
2872 		}
2873 		rpi = pmb->u.mb.un.varWords[0];
2874 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2875 		if (phba->sli_rev == LPFC_SLI_REV4)
2876 			vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2877 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2878 		pmb->vport = vport;
2879 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2880 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2881 		if (rc != MBX_NOT_FINISHED)
2882 			return;
2883 	}
2884 
2885 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2886 		!test_bit(FC_UNLOADING, &phba->pport->load_flag) &&
2887 		!pmb->u.mb.mbxStatus) {
2888 		shost = lpfc_shost_from_vport(vport);
2889 		spin_lock_irq(shost->host_lock);
2890 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2891 		spin_unlock_irq(shost->host_lock);
2892 		clear_bit(FC_VPORT_NEEDS_REG_VPI, &vport->fc_flag);
2893 	}
2894 
2895 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2896 		ndlp = pmb->ctx_ndlp;
2897 		lpfc_nlp_put(ndlp);
2898 	}
2899 
2900 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2901 		ndlp = pmb->ctx_ndlp;
2902 
2903 		/* Check to see if there are any deferred events to process */
2904 		if (ndlp) {
2905 			lpfc_printf_vlog(
2906 				vport,
2907 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2908 				"1438 UNREG cmpl deferred mbox x%x "
2909 				"on NPort x%x Data: x%lx x%x x%px x%lx x%x\n",
2910 				ndlp->nlp_rpi, ndlp->nlp_DID,
2911 				ndlp->nlp_flag, ndlp->nlp_defer_did,
2912 				ndlp, vport->load_flag, kref_read(&ndlp->kref));
2913 
2914 			if (test_bit(NLP_UNREG_INP, &ndlp->nlp_flag) &&
2915 			    ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING) {
2916 				clear_bit(NLP_UNREG_INP, &ndlp->nlp_flag);
2917 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2918 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2919 			} else {
2920 				clear_bit(NLP_UNREG_INP, &ndlp->nlp_flag);
2921 			}
2922 
2923 			/* The unreg_login mailbox is complete and had a
2924 			 * reference that has to be released.  The PLOGI
2925 			 * got its own ref.
2926 			 */
2927 			lpfc_nlp_put(ndlp);
2928 			pmb->ctx_ndlp = NULL;
2929 		}
2930 	}
2931 
2932 	/* This nlp_put pairs with lpfc_sli4_resume_rpi */
2933 	if (pmb->u.mb.mbxCommand == MBX_RESUME_RPI) {
2934 		ndlp = pmb->ctx_ndlp;
2935 		lpfc_nlp_put(ndlp);
2936 	}
2937 
2938 	/* Check security permission status on INIT_LINK mailbox command */
2939 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2940 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2941 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2942 				"2860 SLI authentication is required "
2943 				"for INIT_LINK but has not done yet\n");
2944 
2945 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2946 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2947 	else
2948 		lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2949 }
2950  /**
2951  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2952  * @phba: Pointer to HBA context object.
2953  * @pmb: Pointer to mailbox object.
2954  *
2955  * This function is the unreg rpi mailbox completion handler. It
2956  * frees the memory resources associated with the completed mailbox
2957  * command. An additional reference is put on the ndlp to prevent
2958  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2959  * the unreg mailbox command completes, this routine puts the
2960  * reference back.
2961  *
2962  **/
2963 void
2964 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2965 {
2966 	struct lpfc_vport  *vport = pmb->vport;
2967 	struct lpfc_nodelist *ndlp;
2968 	bool unreg_inp;
2969 
2970 	ndlp = pmb->ctx_ndlp;
2971 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2972 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2973 		    (bf_get(lpfc_sli_intf_if_type,
2974 		     &phba->sli4_hba.sli_intf) >=
2975 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2976 			if (ndlp) {
2977 				lpfc_printf_vlog(
2978 					 vport, KERN_INFO,
2979 					 LOG_MBOX | LOG_SLI | LOG_NODE,
2980 					 "0010 UNREG_LOGIN vpi:x%x "
2981 					 "rpi:%x DID:%x defer x%x flg x%lx "
2982 					 "x%px\n",
2983 					 vport->vpi, ndlp->nlp_rpi,
2984 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
2985 					 ndlp->nlp_flag,
2986 					 ndlp);
2987 
2988 				/* Cleanup the nlp_flag now that the UNREG RPI
2989 				 * has completed.
2990 				 */
2991 				unreg_inp = test_and_clear_bit(NLP_UNREG_INP,
2992 							       &ndlp->nlp_flag);
2993 				clear_bit(NLP_LOGO_ACC, &ndlp->nlp_flag);
2994 
2995 				/* Check to see if there are any deferred
2996 				 * events to process
2997 				 */
2998 				if (unreg_inp &&
2999 				    ndlp->nlp_defer_did !=
3000 				    NLP_EVT_NOTHING_PENDING) {
3001 					lpfc_printf_vlog(
3002 						vport, KERN_INFO,
3003 						LOG_MBOX | LOG_SLI | LOG_NODE,
3004 						"4111 UNREG cmpl deferred "
3005 						"clr x%x on "
3006 						"NPort x%x Data: x%x x%px\n",
3007 						ndlp->nlp_rpi, ndlp->nlp_DID,
3008 						ndlp->nlp_defer_did, ndlp);
3009 					ndlp->nlp_defer_did =
3010 						NLP_EVT_NOTHING_PENDING;
3011 					lpfc_issue_els_plogi(
3012 						vport, ndlp->nlp_DID, 0);
3013 				}
3014 
3015 				lpfc_nlp_put(ndlp);
3016 			}
3017 		}
3018 	}
3019 
3020 	mempool_free(pmb, phba->mbox_mem_pool);
3021 }
3022 
3023 /**
3024  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
3025  * @phba: Pointer to HBA context object.
3026  *
3027  * This function is called with no lock held. This function processes all
3028  * the completed mailbox commands and gives it to upper layers. The interrupt
3029  * service routine processes mailbox completion interrupt and adds completed
3030  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
3031  * Worker thread call lpfc_sli_handle_mb_event, which will return the
3032  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
3033  * function returns the mailbox commands to the upper layer by calling the
3034  * completion handler function of each mailbox.
3035  **/
3036 int
3037 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
3038 {
3039 	MAILBOX_t *pmbox;
3040 	LPFC_MBOXQ_t *pmb;
3041 	int rc;
3042 	LIST_HEAD(cmplq);
3043 
3044 	phba->sli.slistat.mbox_event++;
3045 
3046 	/* Get all completed mailboxe buffers into the cmplq */
3047 	spin_lock_irq(&phba->hbalock);
3048 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
3049 	spin_unlock_irq(&phba->hbalock);
3050 
3051 	/* Get a Mailbox buffer to setup mailbox commands for callback */
3052 	do {
3053 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
3054 		if (pmb == NULL)
3055 			break;
3056 
3057 		pmbox = &pmb->u.mb;
3058 
3059 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
3060 			if (pmb->vport) {
3061 				lpfc_debugfs_disc_trc(pmb->vport,
3062 					LPFC_DISC_TRC_MBOX_VPORT,
3063 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
3064 					(uint32_t)pmbox->mbxCommand,
3065 					pmbox->un.varWords[0],
3066 					pmbox->un.varWords[1]);
3067 			}
3068 			else {
3069 				lpfc_debugfs_disc_trc(phba->pport,
3070 					LPFC_DISC_TRC_MBOX,
3071 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
3072 					(uint32_t)pmbox->mbxCommand,
3073 					pmbox->un.varWords[0],
3074 					pmbox->un.varWords[1]);
3075 			}
3076 		}
3077 
3078 		/*
3079 		 * It is a fatal error if unknown mbox command completion.
3080 		 */
3081 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
3082 		    MBX_SHUTDOWN) {
3083 			/* Unknown mailbox command compl */
3084 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3085 					"(%d):0323 Unknown Mailbox command "
3086 					"x%x (x%x/x%x) Cmpl\n",
3087 					pmb->vport ? pmb->vport->vpi :
3088 					LPFC_VPORT_UNKNOWN,
3089 					pmbox->mbxCommand,
3090 					lpfc_sli_config_mbox_subsys_get(phba,
3091 									pmb),
3092 					lpfc_sli_config_mbox_opcode_get(phba,
3093 									pmb));
3094 			phba->link_state = LPFC_HBA_ERROR;
3095 			phba->work_hs = HS_FFER3;
3096 			lpfc_handle_eratt(phba);
3097 			continue;
3098 		}
3099 
3100 		if (pmbox->mbxStatus) {
3101 			phba->sli.slistat.mbox_stat_err++;
3102 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
3103 				/* Mbox cmd cmpl error - RETRYing */
3104 				lpfc_printf_log(phba, KERN_INFO,
3105 					LOG_MBOX | LOG_SLI,
3106 					"(%d):0305 Mbox cmd cmpl "
3107 					"error - RETRYing Data: x%x "
3108 					"(x%x/x%x) x%x x%x x%x\n",
3109 					pmb->vport ? pmb->vport->vpi :
3110 					LPFC_VPORT_UNKNOWN,
3111 					pmbox->mbxCommand,
3112 					lpfc_sli_config_mbox_subsys_get(phba,
3113 									pmb),
3114 					lpfc_sli_config_mbox_opcode_get(phba,
3115 									pmb),
3116 					pmbox->mbxStatus,
3117 					pmbox->un.varWords[0],
3118 					pmb->vport ? pmb->vport->port_state :
3119 					LPFC_VPORT_UNKNOWN);
3120 				pmbox->mbxStatus = 0;
3121 				pmbox->mbxOwner = OWN_HOST;
3122 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3123 				if (rc != MBX_NOT_FINISHED)
3124 					continue;
3125 			}
3126 		}
3127 
3128 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
3129 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
3130 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
3131 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
3132 				"x%x x%x x%x\n",
3133 				pmb->vport ? pmb->vport->vpi : 0,
3134 				pmbox->mbxCommand,
3135 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
3136 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
3137 				pmb->mbox_cmpl,
3138 				*((uint32_t *) pmbox),
3139 				pmbox->un.varWords[0],
3140 				pmbox->un.varWords[1],
3141 				pmbox->un.varWords[2],
3142 				pmbox->un.varWords[3],
3143 				pmbox->un.varWords[4],
3144 				pmbox->un.varWords[5],
3145 				pmbox->un.varWords[6],
3146 				pmbox->un.varWords[7],
3147 				pmbox->un.varWords[8],
3148 				pmbox->un.varWords[9],
3149 				pmbox->un.varWords[10]);
3150 
3151 		if (pmb->mbox_cmpl)
3152 			pmb->mbox_cmpl(phba,pmb);
3153 	} while (1);
3154 	return 0;
3155 }
3156 
3157 /**
3158  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
3159  * @phba: Pointer to HBA context object.
3160  * @pring: Pointer to driver SLI ring object.
3161  * @tag: buffer tag.
3162  *
3163  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
3164  * is set in the tag the buffer is posted for a particular exchange,
3165  * the function will return the buffer without replacing the buffer.
3166  * If the buffer is for unsolicited ELS or CT traffic, this function
3167  * returns the buffer and also posts another buffer to the firmware.
3168  **/
3169 static struct lpfc_dmabuf *
3170 lpfc_sli_get_buff(struct lpfc_hba *phba,
3171 		  struct lpfc_sli_ring *pring,
3172 		  uint32_t tag)
3173 {
3174 	struct hbq_dmabuf *hbq_entry;
3175 
3176 	if (tag & QUE_BUFTAG_BIT)
3177 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
3178 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
3179 	if (!hbq_entry)
3180 		return NULL;
3181 	return &hbq_entry->dbuf;
3182 }
3183 
3184 /**
3185  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
3186  *                              containing a NVME LS request.
3187  * @phba: pointer to lpfc hba data structure.
3188  * @piocb: pointer to the iocbq struct representing the sequence starting
3189  *        frame.
3190  *
3191  * This routine initially validates the NVME LS, validates there is a login
3192  * with the port that sent the LS, and then calls the appropriate nvme host
3193  * or target LS request handler.
3194  **/
3195 static void
3196 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
3197 {
3198 	struct lpfc_nodelist *ndlp;
3199 	struct lpfc_dmabuf *d_buf;
3200 	struct hbq_dmabuf *nvmebuf;
3201 	struct fc_frame_header *fc_hdr;
3202 	struct lpfc_async_xchg_ctx *axchg = NULL;
3203 	char *failwhy = NULL;
3204 	uint32_t oxid, sid, did, fctl, size;
3205 	int ret = 1;
3206 
3207 	d_buf = piocb->cmd_dmabuf;
3208 
3209 	nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
3210 	fc_hdr = nvmebuf->hbuf.virt;
3211 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
3212 	sid = sli4_sid_from_fc_hdr(fc_hdr);
3213 	did = sli4_did_from_fc_hdr(fc_hdr);
3214 	fctl = (fc_hdr->fh_f_ctl[0] << 16 |
3215 		fc_hdr->fh_f_ctl[1] << 8 |
3216 		fc_hdr->fh_f_ctl[2]);
3217 	size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
3218 
3219 	lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
3220 			 oxid, size, sid);
3221 
3222 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
3223 		failwhy = "Driver Unloading";
3224 	} else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
3225 		failwhy = "NVME FC4 Disabled";
3226 	} else if (!phba->nvmet_support && !phba->pport->localport) {
3227 		failwhy = "No Localport";
3228 	} else if (phba->nvmet_support && !phba->targetport) {
3229 		failwhy = "No Targetport";
3230 	} else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
3231 		failwhy = "Bad NVME LS R_CTL";
3232 	} else if (unlikely((fctl & 0x00FF0000) !=
3233 			(FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
3234 		failwhy = "Bad NVME LS F_CTL";
3235 	} else {
3236 		axchg = kzalloc_obj(*axchg, GFP_ATOMIC);
3237 		if (!axchg)
3238 			failwhy = "No CTX memory";
3239 	}
3240 
3241 	if (unlikely(failwhy)) {
3242 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3243 				"6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
3244 				sid, oxid, failwhy);
3245 		goto out_fail;
3246 	}
3247 
3248 	/* validate the source of the LS is logged in */
3249 	ndlp = lpfc_findnode_did(phba->pport, sid);
3250 	if (!ndlp ||
3251 	    ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
3252 	     (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
3253 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
3254 				"6216 NVME Unsol rcv: No ndlp: "
3255 				"NPort_ID x%x oxid x%x\n",
3256 				sid, oxid);
3257 		goto out_fail;
3258 	}
3259 
3260 	axchg->phba = phba;
3261 	axchg->ndlp = ndlp;
3262 	axchg->size = size;
3263 	axchg->oxid = oxid;
3264 	axchg->sid = sid;
3265 	axchg->wqeq = NULL;
3266 	axchg->state = LPFC_NVME_STE_LS_RCV;
3267 	axchg->entry_cnt = 1;
3268 	axchg->rqb_buffer = (void *)nvmebuf;
3269 	axchg->hdwq = &phba->sli4_hba.hdwq[0];
3270 	axchg->payload = nvmebuf->dbuf.virt;
3271 	INIT_LIST_HEAD(&axchg->list);
3272 
3273 	if (phba->nvmet_support) {
3274 		ret = lpfc_nvmet_handle_lsreq(phba, axchg);
3275 		spin_lock_irq(&ndlp->lock);
3276 		if (!ret && !(ndlp->fc4_xpt_flags & NLP_XPT_HAS_HH)) {
3277 			ndlp->fc4_xpt_flags |= NLP_XPT_HAS_HH;
3278 			spin_unlock_irq(&ndlp->lock);
3279 
3280 			/* This reference is a single occurrence to hold the
3281 			 * node valid until the nvmet transport calls
3282 			 * host_release.
3283 			 */
3284 			if (!lpfc_nlp_get(ndlp))
3285 				goto out_fail;
3286 
3287 			lpfc_printf_log(phba, KERN_ERR, LOG_NODE,
3288 					"6206 NVMET unsol ls_req ndlp x%px "
3289 					"DID x%x xflags x%x refcnt %d\n",
3290 					ndlp, ndlp->nlp_DID,
3291 					ndlp->fc4_xpt_flags,
3292 					kref_read(&ndlp->kref));
3293 		} else {
3294 			spin_unlock_irq(&ndlp->lock);
3295 		}
3296 	} else {
3297 		ret = lpfc_nvme_handle_lsreq(phba, axchg);
3298 	}
3299 
3300 	/* if zero, LS was successfully handled. If non-zero, LS not handled */
3301 	if (!ret)
3302 		return;
3303 
3304 out_fail:
3305 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3306 			"6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
3307 			"NVMe%s handler failed %d\n",
3308 			did, sid, oxid,
3309 			(phba->nvmet_support) ? "T" : "I", ret);
3310 
3311 	/* recycle receive buffer */
3312 	lpfc_in_buf_free(phba, &nvmebuf->dbuf);
3313 
3314 	/* If start of new exchange, abort it */
3315 	if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
3316 		ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
3317 
3318 	if (ret)
3319 		kfree(axchg);
3320 }
3321 
3322 /**
3323  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
3324  * @phba: Pointer to HBA context object.
3325  * @pring: Pointer to driver SLI ring object.
3326  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
3327  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
3328  * @fch_type: the type for the first frame of the sequence.
3329  *
3330  * This function is called with no lock held. This function uses the r_ctl and
3331  * type of the received sequence to find the correct callback function to call
3332  * to process the sequence.
3333  **/
3334 static int
3335 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3336 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
3337 			 uint32_t fch_type)
3338 {
3339 	int i;
3340 
3341 	switch (fch_type) {
3342 	case FC_TYPE_NVME:
3343 		lpfc_nvme_unsol_ls_handler(phba, saveq);
3344 		return 1;
3345 	default:
3346 		break;
3347 	}
3348 
3349 	/* unSolicited Responses */
3350 	if (pring->prt[0].profile) {
3351 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
3352 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
3353 									saveq);
3354 		return 1;
3355 	}
3356 	/* We must search, based on rctl / type
3357 	   for the right routine */
3358 	for (i = 0; i < pring->num_mask; i++) {
3359 		if ((pring->prt[i].rctl == fch_r_ctl) &&
3360 		    (pring->prt[i].type == fch_type)) {
3361 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
3362 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
3363 						(phba, pring, saveq);
3364 			return 1;
3365 		}
3366 	}
3367 	return 0;
3368 }
3369 
3370 static void
3371 lpfc_sli_prep_unsol_wqe(struct lpfc_hba *phba,
3372 			struct lpfc_iocbq *saveq)
3373 {
3374 	IOCB_t *irsp;
3375 	union lpfc_wqe128 *wqe;
3376 	u16 i = 0;
3377 
3378 	irsp = &saveq->iocb;
3379 	wqe = &saveq->wqe;
3380 
3381 	/* Fill wcqe with the IOCB status fields */
3382 	bf_set(lpfc_wcqe_c_status, &saveq->wcqe_cmpl, irsp->ulpStatus);
3383 	saveq->wcqe_cmpl.word3 = irsp->ulpBdeCount;
3384 	saveq->wcqe_cmpl.parameter = irsp->un.ulpWord[4];
3385 	saveq->wcqe_cmpl.total_data_placed = irsp->unsli3.rcvsli3.acc_len;
3386 
3387 	/* Source ID */
3388 	bf_set(els_rsp64_sid, &wqe->xmit_els_rsp, irsp->un.rcvels.parmRo);
3389 
3390 	/* rx-id of the response frame */
3391 	bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com, irsp->ulpContext);
3392 
3393 	/* ox-id of the frame */
3394 	bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
3395 	       irsp->unsli3.rcvsli3.ox_id);
3396 
3397 	/* DID */
3398 	bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
3399 	       irsp->un.rcvels.remoteID);
3400 
3401 	/* unsol data len */
3402 	for (i = 0; i < irsp->ulpBdeCount; i++) {
3403 		struct lpfc_hbq_entry *hbqe = NULL;
3404 
3405 		if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3406 			if (i == 0) {
3407 				hbqe = (struct lpfc_hbq_entry *)
3408 					&irsp->un.ulpWord[0];
3409 				saveq->wqe.gen_req.bde.tus.f.bdeSize =
3410 					hbqe->bde.tus.f.bdeSize;
3411 			} else if (i == 1) {
3412 				hbqe = (struct lpfc_hbq_entry *)
3413 					&irsp->unsli3.sli3Words[4];
3414 				saveq->unsol_rcv_len = hbqe->bde.tus.f.bdeSize;
3415 			}
3416 		}
3417 	}
3418 }
3419 
3420 /**
3421  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
3422  * @phba: Pointer to HBA context object.
3423  * @pring: Pointer to driver SLI ring object.
3424  * @saveq: Pointer to the unsolicited iocb.
3425  *
3426  * This function is called with no lock held by the ring event handler
3427  * when there is an unsolicited iocb posted to the response ring by the
3428  * firmware. This function gets the buffer associated with the iocbs
3429  * and calls the event handler for the ring. This function handles both
3430  * qring buffers and hbq buffers.
3431  * When the function returns 1 the caller can free the iocb object otherwise
3432  * upper layer functions will free the iocb objects.
3433  **/
3434 static int
3435 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3436 			    struct lpfc_iocbq *saveq)
3437 {
3438 	IOCB_t           * irsp;
3439 	WORD5            * w5p;
3440 	dma_addr_t	 paddr;
3441 	uint32_t           Rctl, Type;
3442 	struct lpfc_iocbq *iocbq;
3443 	struct lpfc_dmabuf *dmzbuf;
3444 
3445 	irsp = &saveq->iocb;
3446 	saveq->vport = phba->pport;
3447 
3448 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
3449 		if (pring->lpfc_sli_rcv_async_status)
3450 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
3451 		else
3452 			lpfc_printf_log(phba,
3453 					KERN_WARNING,
3454 					LOG_SLI,
3455 					"0316 Ring %d handler: unexpected "
3456 					"ASYNC_STATUS iocb received evt_code "
3457 					"0x%x\n",
3458 					pring->ringno,
3459 					irsp->un.asyncstat.evt_code);
3460 		return 1;
3461 	}
3462 
3463 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3464 	    (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3465 		if (irsp->ulpBdeCount > 0) {
3466 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3467 						   irsp->un.ulpWord[3]);
3468 			lpfc_in_buf_free(phba, dmzbuf);
3469 		}
3470 
3471 		if (irsp->ulpBdeCount > 1) {
3472 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3473 						   irsp->unsli3.sli3Words[3]);
3474 			lpfc_in_buf_free(phba, dmzbuf);
3475 		}
3476 
3477 		if (irsp->ulpBdeCount > 2) {
3478 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3479 						   irsp->unsli3.sli3Words[7]);
3480 			lpfc_in_buf_free(phba, dmzbuf);
3481 		}
3482 
3483 		return 1;
3484 	}
3485 
3486 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3487 		if (irsp->ulpBdeCount != 0) {
3488 			saveq->cmd_dmabuf = lpfc_sli_get_buff(phba, pring,
3489 						irsp->un.ulpWord[3]);
3490 			if (!saveq->cmd_dmabuf)
3491 				lpfc_printf_log(phba,
3492 					KERN_ERR,
3493 					LOG_SLI,
3494 					"0341 Ring %d Cannot find buffer for "
3495 					"an unsolicited iocb. tag 0x%x\n",
3496 					pring->ringno,
3497 					irsp->un.ulpWord[3]);
3498 		}
3499 		if (irsp->ulpBdeCount == 2) {
3500 			saveq->bpl_dmabuf = lpfc_sli_get_buff(phba, pring,
3501 						irsp->unsli3.sli3Words[7]);
3502 			if (!saveq->bpl_dmabuf)
3503 				lpfc_printf_log(phba,
3504 					KERN_ERR,
3505 					LOG_SLI,
3506 					"0342 Ring %d Cannot find buffer for an"
3507 					" unsolicited iocb. tag 0x%x\n",
3508 					pring->ringno,
3509 					irsp->unsli3.sli3Words[7]);
3510 		}
3511 		list_for_each_entry(iocbq, &saveq->list, list) {
3512 			irsp = &iocbq->iocb;
3513 			if (irsp->ulpBdeCount != 0) {
3514 				iocbq->cmd_dmabuf = lpfc_sli_get_buff(phba,
3515 							pring,
3516 							irsp->un.ulpWord[3]);
3517 				if (!iocbq->cmd_dmabuf)
3518 					lpfc_printf_log(phba,
3519 						KERN_ERR,
3520 						LOG_SLI,
3521 						"0343 Ring %d Cannot find "
3522 						"buffer for an unsolicited iocb"
3523 						". tag 0x%x\n", pring->ringno,
3524 						irsp->un.ulpWord[3]);
3525 			}
3526 			if (irsp->ulpBdeCount == 2) {
3527 				iocbq->bpl_dmabuf = lpfc_sli_get_buff(phba,
3528 						pring,
3529 						irsp->unsli3.sli3Words[7]);
3530 				if (!iocbq->bpl_dmabuf)
3531 					lpfc_printf_log(phba,
3532 						KERN_ERR,
3533 						LOG_SLI,
3534 						"0344 Ring %d Cannot find "
3535 						"buffer for an unsolicited "
3536 						"iocb. tag 0x%x\n",
3537 						pring->ringno,
3538 						irsp->unsli3.sli3Words[7]);
3539 			}
3540 		}
3541 	} else {
3542 		paddr = getPaddr(irsp->un.cont64[0].addrHigh,
3543 				 irsp->un.cont64[0].addrLow);
3544 		saveq->cmd_dmabuf = lpfc_sli_ringpostbuf_get(phba, pring,
3545 							     paddr);
3546 		if (irsp->ulpBdeCount == 2) {
3547 			paddr = getPaddr(irsp->un.cont64[1].addrHigh,
3548 					 irsp->un.cont64[1].addrLow);
3549 			saveq->bpl_dmabuf = lpfc_sli_ringpostbuf_get(phba,
3550 								   pring,
3551 								   paddr);
3552 		}
3553 	}
3554 
3555 	if (irsp->ulpBdeCount != 0 &&
3556 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3557 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3558 		int found = 0;
3559 
3560 		/* search continue save q for same XRI */
3561 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3562 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3563 				saveq->iocb.unsli3.rcvsli3.ox_id) {
3564 				list_add_tail(&saveq->list, &iocbq->list);
3565 				found = 1;
3566 				break;
3567 			}
3568 		}
3569 		if (!found)
3570 			list_add_tail(&saveq->clist,
3571 				      &pring->iocb_continue_saveq);
3572 
3573 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3574 			list_del_init(&iocbq->clist);
3575 			saveq = iocbq;
3576 			irsp = &saveq->iocb;
3577 		} else {
3578 			return 0;
3579 		}
3580 	}
3581 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3582 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3583 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3584 		Rctl = FC_RCTL_ELS_REQ;
3585 		Type = FC_TYPE_ELS;
3586 	} else {
3587 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3588 		Rctl = w5p->hcsw.Rctl;
3589 		Type = w5p->hcsw.Type;
3590 
3591 		/* Firmware Workaround */
3592 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3593 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3594 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3595 			Rctl = FC_RCTL_ELS_REQ;
3596 			Type = FC_TYPE_ELS;
3597 			w5p->hcsw.Rctl = Rctl;
3598 			w5p->hcsw.Type = Type;
3599 		}
3600 	}
3601 
3602 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) &&
3603 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX ||
3604 	    irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3605 		if (irsp->unsli3.rcvsli3.vpi == 0xffff)
3606 			saveq->vport = phba->pport;
3607 		else
3608 			saveq->vport = lpfc_find_vport_by_vpid(phba,
3609 					       irsp->unsli3.rcvsli3.vpi);
3610 	}
3611 
3612 	/* Prepare WQE with Unsol frame */
3613 	lpfc_sli_prep_unsol_wqe(phba, saveq);
3614 
3615 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3616 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3617 				"0313 Ring %d handler: unexpected Rctl x%x "
3618 				"Type x%x received\n",
3619 				pring->ringno, Rctl, Type);
3620 
3621 	return 1;
3622 }
3623 
3624 /**
3625  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3626  * @phba: Pointer to HBA context object.
3627  * @pring: Pointer to driver SLI ring object.
3628  * @prspiocb: Pointer to response iocb object.
3629  *
3630  * This function looks up the iocb_lookup table to get the command iocb
3631  * corresponding to the given response iocb using the iotag of the
3632  * response iocb. The driver calls this function with the hbalock held
3633  * for SLI3 ports or the ring lock held for SLI4 ports.
3634  * This function returns the command iocb object if it finds the command
3635  * iocb else returns NULL.
3636  **/
3637 static struct lpfc_iocbq *
3638 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3639 		      struct lpfc_sli_ring *pring,
3640 		      struct lpfc_iocbq *prspiocb)
3641 {
3642 	struct lpfc_iocbq *cmd_iocb = NULL;
3643 	u16 iotag;
3644 
3645 	if (phba->sli_rev == LPFC_SLI_REV4)
3646 		iotag = get_wqe_reqtag(prspiocb);
3647 	else
3648 		iotag = prspiocb->iocb.ulpIoTag;
3649 
3650 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3651 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3652 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3653 			/* remove from txcmpl queue list */
3654 			list_del_init(&cmd_iocb->list);
3655 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3656 			pring->txcmplq_cnt--;
3657 			return cmd_iocb;
3658 		}
3659 	}
3660 
3661 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3662 			"0317 iotag x%x is out of "
3663 			"range: max iotag x%x\n",
3664 			iotag, phba->sli.last_iotag);
3665 	return NULL;
3666 }
3667 
3668 /**
3669  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3670  * @phba: Pointer to HBA context object.
3671  * @pring: Pointer to driver SLI ring object.
3672  * @iotag: IOCB tag.
3673  *
3674  * This function looks up the iocb_lookup table to get the command iocb
3675  * corresponding to the given iotag. The driver calls this function with
3676  * the ring lock held because this function is an SLI4 port only helper.
3677  * This function returns the command iocb object if it finds the command
3678  * iocb else returns NULL.
3679  **/
3680 static struct lpfc_iocbq *
3681 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3682 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3683 {
3684 	struct lpfc_iocbq *cmd_iocb = NULL;
3685 
3686 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3687 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3688 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3689 			/* remove from txcmpl queue list */
3690 			list_del_init(&cmd_iocb->list);
3691 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3692 			pring->txcmplq_cnt--;
3693 			return cmd_iocb;
3694 		}
3695 	}
3696 
3697 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3698 			"0372 iotag x%x lookup error: max iotag (x%x) "
3699 			"cmd_flag x%x\n",
3700 			iotag, phba->sli.last_iotag,
3701 			cmd_iocb ? cmd_iocb->cmd_flag : 0xffff);
3702 	return NULL;
3703 }
3704 
3705 /**
3706  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3707  * @phba: Pointer to HBA context object.
3708  * @pring: Pointer to driver SLI ring object.
3709  * @saveq: Pointer to the response iocb to be processed.
3710  *
3711  * This function is called by the ring event handler for non-fcp
3712  * rings when there is a new response iocb in the response ring.
3713  * The caller is not required to hold any locks. This function
3714  * gets the command iocb associated with the response iocb and
3715  * calls the completion handler for the command iocb. If there
3716  * is no completion handler, the function will free the resources
3717  * associated with command iocb. If the response iocb is for
3718  * an already aborted command iocb, the status of the completion
3719  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3720  * This function always returns 1.
3721  **/
3722 static int
3723 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3724 			  struct lpfc_iocbq *saveq)
3725 {
3726 	struct lpfc_iocbq *cmdiocbp;
3727 	unsigned long iflag;
3728 	u32 ulp_command, ulp_status, ulp_word4, ulp_context, iotag;
3729 
3730 	if (phba->sli_rev == LPFC_SLI_REV4)
3731 		spin_lock_irqsave(&pring->ring_lock, iflag);
3732 	else
3733 		spin_lock_irqsave(&phba->hbalock, iflag);
3734 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3735 	if (phba->sli_rev == LPFC_SLI_REV4)
3736 		spin_unlock_irqrestore(&pring->ring_lock, iflag);
3737 	else
3738 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3739 
3740 	ulp_command = get_job_cmnd(phba, saveq);
3741 	ulp_status = get_job_ulpstatus(phba, saveq);
3742 	ulp_word4 = get_job_word4(phba, saveq);
3743 	ulp_context = get_job_ulpcontext(phba, saveq);
3744 	if (phba->sli_rev == LPFC_SLI_REV4)
3745 		iotag = get_wqe_reqtag(saveq);
3746 	else
3747 		iotag = saveq->iocb.ulpIoTag;
3748 
3749 	if (cmdiocbp) {
3750 		ulp_command = get_job_cmnd(phba, cmdiocbp);
3751 		if (cmdiocbp->cmd_cmpl) {
3752 			/*
3753 			 * If an ELS command failed send an event to mgmt
3754 			 * application.
3755 			 */
3756 			if (ulp_status &&
3757 			     (pring->ringno == LPFC_ELS_RING) &&
3758 			     (ulp_command == CMD_ELS_REQUEST64_CR))
3759 				lpfc_send_els_failure_event(phba,
3760 					cmdiocbp, saveq);
3761 
3762 			/*
3763 			 * Post all ELS completions to the worker thread.
3764 			 * All other are passed to the completion callback.
3765 			 */
3766 			if (pring->ringno == LPFC_ELS_RING) {
3767 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3768 				    (cmdiocbp->cmd_flag &
3769 							LPFC_DRIVER_ABORTED)) {
3770 					spin_lock_irqsave(&phba->hbalock,
3771 							  iflag);
3772 					cmdiocbp->cmd_flag &=
3773 						~LPFC_DRIVER_ABORTED;
3774 					spin_unlock_irqrestore(&phba->hbalock,
3775 							       iflag);
3776 					saveq->iocb.ulpStatus =
3777 						IOSTAT_LOCAL_REJECT;
3778 					saveq->iocb.un.ulpWord[4] =
3779 						IOERR_SLI_ABORTED;
3780 
3781 					/* Firmware could still be in progress
3782 					 * of DMAing payload, so don't free data
3783 					 * buffer till after a hbeat.
3784 					 */
3785 					spin_lock_irqsave(&phba->hbalock,
3786 							  iflag);
3787 					saveq->cmd_flag |= LPFC_DELAY_MEM_FREE;
3788 					spin_unlock_irqrestore(&phba->hbalock,
3789 							       iflag);
3790 				}
3791 				if (phba->sli_rev == LPFC_SLI_REV4) {
3792 					if (saveq->cmd_flag &
3793 					    LPFC_EXCHANGE_BUSY) {
3794 						/* Set cmdiocb flag for the
3795 						 * exchange busy so sgl (xri)
3796 						 * will not be released until
3797 						 * the abort xri is received
3798 						 * from hba.
3799 						 */
3800 						spin_lock_irqsave(
3801 							&phba->hbalock, iflag);
3802 						cmdiocbp->cmd_flag |=
3803 							LPFC_EXCHANGE_BUSY;
3804 						spin_unlock_irqrestore(
3805 							&phba->hbalock, iflag);
3806 					}
3807 					if (cmdiocbp->cmd_flag &
3808 					    LPFC_DRIVER_ABORTED) {
3809 						/*
3810 						 * Clear LPFC_DRIVER_ABORTED
3811 						 * bit in case it was driver
3812 						 * initiated abort.
3813 						 */
3814 						spin_lock_irqsave(
3815 							&phba->hbalock, iflag);
3816 						cmdiocbp->cmd_flag &=
3817 							~LPFC_DRIVER_ABORTED;
3818 						spin_unlock_irqrestore(
3819 							&phba->hbalock, iflag);
3820 						set_job_ulpstatus(cmdiocbp,
3821 								  IOSTAT_LOCAL_REJECT);
3822 						set_job_ulpword4(cmdiocbp,
3823 								 IOERR_ABORT_REQUESTED);
3824 						/*
3825 						 * For SLI4, irspiocb contains
3826 						 * NO_XRI in sli_xritag, it
3827 						 * shall not affect releasing
3828 						 * sgl (xri) process.
3829 						 */
3830 						set_job_ulpstatus(saveq,
3831 								  IOSTAT_LOCAL_REJECT);
3832 						set_job_ulpword4(saveq,
3833 								 IOERR_SLI_ABORTED);
3834 						spin_lock_irqsave(
3835 							&phba->hbalock, iflag);
3836 						saveq->cmd_flag |=
3837 							LPFC_DELAY_MEM_FREE;
3838 						spin_unlock_irqrestore(
3839 							&phba->hbalock, iflag);
3840 					}
3841 				}
3842 			}
3843 			cmdiocbp->cmd_cmpl(phba, cmdiocbp, saveq);
3844 		} else
3845 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3846 	} else {
3847 		/*
3848 		 * Unknown initiating command based on the response iotag.
3849 		 * This could be the case on the ELS ring because of
3850 		 * lpfc_els_abort().
3851 		 */
3852 		if (pring->ringno != LPFC_ELS_RING) {
3853 			/*
3854 			 * Ring <ringno> handler: unexpected completion IoTag
3855 			 * <IoTag>
3856 			 */
3857 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3858 					 "0322 Ring %d handler: "
3859 					 "unexpected completion IoTag x%x "
3860 					 "Data: x%x x%x x%x x%x\n",
3861 					 pring->ringno, iotag, ulp_status,
3862 					 ulp_word4, ulp_command, ulp_context);
3863 		}
3864 	}
3865 
3866 	return 1;
3867 }
3868 
3869 /**
3870  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3871  * @phba: Pointer to HBA context object.
3872  * @pring: Pointer to driver SLI ring object.
3873  *
3874  * This function is called from the iocb ring event handlers when
3875  * put pointer is ahead of the get pointer for a ring. This function signal
3876  * an error attention condition to the worker thread and the worker
3877  * thread will transition the HBA to offline state.
3878  **/
3879 static void
3880 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3881 {
3882 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3883 	/*
3884 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3885 	 * rsp ring <portRspMax>
3886 	 */
3887 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3888 			"0312 Ring %d handler: portRspPut %d "
3889 			"is bigger than rsp ring %d\n",
3890 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3891 			pring->sli.sli3.numRiocb);
3892 
3893 	phba->link_state = LPFC_HBA_ERROR;
3894 
3895 	/*
3896 	 * All error attention handlers are posted to
3897 	 * worker thread
3898 	 */
3899 	phba->work_ha |= HA_ERATT;
3900 	phba->work_hs = HS_FFER3;
3901 
3902 	lpfc_worker_wake_up(phba);
3903 
3904 	return;
3905 }
3906 
3907 /**
3908  * lpfc_poll_eratt - Error attention polling timer timeout handler
3909  * @t: Context to fetch pointer to address of HBA context object from.
3910  *
3911  * This function is invoked by the Error Attention polling timer when the
3912  * timer times out. It will check the SLI Error Attention register for
3913  * possible attention events. If so, it will post an Error Attention event
3914  * and wake up worker thread to process it. Otherwise, it will set up the
3915  * Error Attention polling timer for the next poll.
3916  **/
3917 void lpfc_poll_eratt(struct timer_list *t)
3918 {
3919 	struct lpfc_hba *phba;
3920 	uint32_t eratt = 0;
3921 	uint64_t sli_intr, cnt;
3922 
3923 	phba = timer_container_of(phba, t, eratt_poll);
3924 
3925 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
3926 		return;
3927 
3928 	if (phba->sli_rev == LPFC_SLI_REV4 &&
3929 	    !test_bit(HBA_SETUP, &phba->hba_flag)) {
3930 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3931 				"0663 HBA still initializing 0x%lx, restart "
3932 				"timer\n",
3933 				phba->hba_flag);
3934 		goto restart_timer;
3935 	}
3936 
3937 	/* Here we will also keep track of interrupts per sec of the hba */
3938 	sli_intr = phba->sli.slistat.sli_intr;
3939 
3940 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3941 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3942 			sli_intr);
3943 	else
3944 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3945 
3946 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3947 	do_div(cnt, phba->eratt_poll_interval);
3948 	phba->sli.slistat.sli_ips = cnt;
3949 
3950 	phba->sli.slistat.sli_prev_intr = sli_intr;
3951 
3952 	/* Check chip HA register for error event */
3953 	eratt = lpfc_sli_check_eratt(phba);
3954 
3955 	if (eratt) {
3956 		/* Tell the worker thread there is work to do */
3957 		lpfc_worker_wake_up(phba);
3958 		return;
3959 	}
3960 
3961 restart_timer:
3962 	/* Restart the timer for next eratt poll */
3963 	mod_timer(&phba->eratt_poll,
3964 		  jiffies + secs_to_jiffies(phba->eratt_poll_interval));
3965 	return;
3966 }
3967 
3968 
3969 /**
3970  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3971  * @phba: Pointer to HBA context object.
3972  * @pring: Pointer to driver SLI ring object.
3973  * @mask: Host attention register mask for this ring.
3974  *
3975  * This function is called from the interrupt context when there is a ring
3976  * event for the fcp ring. The caller does not hold any lock.
3977  * The function processes each response iocb in the response ring until it
3978  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3979  * LE bit set. The function will call the completion handler of the command iocb
3980  * if the response iocb indicates a completion for a command iocb or it is
3981  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3982  * function if this is an unsolicited iocb.
3983  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3984  * to check it explicitly.
3985  */
3986 int
3987 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3988 				struct lpfc_sli_ring *pring, uint32_t mask)
3989 {
3990 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3991 	IOCB_t *irsp = NULL;
3992 	IOCB_t *entry = NULL;
3993 	struct lpfc_iocbq *cmdiocbq = NULL;
3994 	struct lpfc_iocbq rspiocbq;
3995 	uint32_t status;
3996 	uint32_t portRspPut, portRspMax;
3997 	int rc = 1;
3998 	lpfc_iocb_type type;
3999 	unsigned long iflag;
4000 	uint32_t rsp_cmpl = 0;
4001 
4002 	spin_lock_irqsave(&phba->hbalock, iflag);
4003 	pring->stats.iocb_event++;
4004 
4005 	/*
4006 	 * The next available response entry should never exceed the maximum
4007 	 * entries.  If it does, treat it as an adapter hardware error.
4008 	 */
4009 	portRspMax = pring->sli.sli3.numRiocb;
4010 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4011 	if (unlikely(portRspPut >= portRspMax)) {
4012 		lpfc_sli_rsp_pointers_error(phba, pring);
4013 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4014 		return 1;
4015 	}
4016 	if (phba->fcp_ring_in_use) {
4017 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4018 		return 1;
4019 	} else
4020 		phba->fcp_ring_in_use = 1;
4021 
4022 	rmb();
4023 	while (pring->sli.sli3.rspidx != portRspPut) {
4024 		/*
4025 		 * Fetch an entry off the ring and copy it into a local data
4026 		 * structure.  The copy involves a byte-swap since the
4027 		 * network byte order and pci byte orders are different.
4028 		 */
4029 		entry = lpfc_resp_iocb(phba, pring);
4030 		phba->last_completion_time = jiffies;
4031 
4032 		if (++pring->sli.sli3.rspidx >= portRspMax)
4033 			pring->sli.sli3.rspidx = 0;
4034 
4035 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
4036 				      (uint32_t *) &rspiocbq.iocb,
4037 				      phba->iocb_rsp_size);
4038 		INIT_LIST_HEAD(&(rspiocbq.list));
4039 		irsp = &rspiocbq.iocb;
4040 
4041 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
4042 		pring->stats.iocb_rsp++;
4043 		rsp_cmpl++;
4044 
4045 		if (unlikely(irsp->ulpStatus)) {
4046 			/*
4047 			 * If resource errors reported from HBA, reduce
4048 			 * queuedepths of the SCSI device.
4049 			 */
4050 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
4051 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
4052 			     IOERR_NO_RESOURCES)) {
4053 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4054 				phba->lpfc_rampdown_queue_depth(phba);
4055 				spin_lock_irqsave(&phba->hbalock, iflag);
4056 			}
4057 
4058 			/* Rsp ring <ringno> error: IOCB */
4059 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4060 					"0336 Rsp Ring %d error: IOCB Data: "
4061 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
4062 					pring->ringno,
4063 					irsp->un.ulpWord[0],
4064 					irsp->un.ulpWord[1],
4065 					irsp->un.ulpWord[2],
4066 					irsp->un.ulpWord[3],
4067 					irsp->un.ulpWord[4],
4068 					irsp->un.ulpWord[5],
4069 					*(uint32_t *)&irsp->un1,
4070 					*((uint32_t *)&irsp->un1 + 1));
4071 		}
4072 
4073 		switch (type) {
4074 		case LPFC_ABORT_IOCB:
4075 		case LPFC_SOL_IOCB:
4076 			/*
4077 			 * Idle exchange closed via ABTS from port.  No iocb
4078 			 * resources need to be recovered.
4079 			 */
4080 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
4081 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4082 						"0333 IOCB cmd 0x%x"
4083 						" processed. Skipping"
4084 						" completion\n",
4085 						irsp->ulpCommand);
4086 				break;
4087 			}
4088 
4089 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
4090 							 &rspiocbq);
4091 			if (unlikely(!cmdiocbq))
4092 				break;
4093 			if (cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED)
4094 				cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
4095 			if (cmdiocbq->cmd_cmpl) {
4096 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4097 				cmdiocbq->cmd_cmpl(phba, cmdiocbq, &rspiocbq);
4098 				spin_lock_irqsave(&phba->hbalock, iflag);
4099 			}
4100 			break;
4101 		case LPFC_UNSOL_IOCB:
4102 			spin_unlock_irqrestore(&phba->hbalock, iflag);
4103 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
4104 			spin_lock_irqsave(&phba->hbalock, iflag);
4105 			break;
4106 		default:
4107 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
4108 				char adaptermsg[LPFC_MAX_ADPTMSG];
4109 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4110 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
4111 				       MAX_MSG_DATA);
4112 				dev_warn(&((phba->pcidev)->dev),
4113 					 "lpfc%d: %s\n",
4114 					 phba->brd_no, adaptermsg);
4115 			} else {
4116 				/* Unknown IOCB command */
4117 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4118 						"0334 Unknown IOCB command "
4119 						"Data: x%x, x%x x%x x%x x%x\n",
4120 						type, irsp->ulpCommand,
4121 						irsp->ulpStatus,
4122 						irsp->ulpIoTag,
4123 						irsp->ulpContext);
4124 			}
4125 			break;
4126 		}
4127 
4128 		/*
4129 		 * The response IOCB has been processed.  Update the ring
4130 		 * pointer in SLIM.  If the port response put pointer has not
4131 		 * been updated, sync the pgp->rspPutInx and fetch the new port
4132 		 * response put pointer.
4133 		 */
4134 		writel(pring->sli.sli3.rspidx,
4135 			&phba->host_gp[pring->ringno].rspGetInx);
4136 
4137 		if (pring->sli.sli3.rspidx == portRspPut)
4138 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4139 	}
4140 
4141 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
4142 		pring->stats.iocb_rsp_full++;
4143 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4144 		writel(status, phba->CAregaddr);
4145 		readl(phba->CAregaddr);
4146 	}
4147 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4148 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4149 		pring->stats.iocb_cmd_empty++;
4150 
4151 		/* Force update of the local copy of cmdGetInx */
4152 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4153 		lpfc_sli_resume_iocb(phba, pring);
4154 
4155 		if ((pring->lpfc_sli_cmd_available))
4156 			(pring->lpfc_sli_cmd_available) (phba, pring);
4157 
4158 	}
4159 
4160 	phba->fcp_ring_in_use = 0;
4161 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4162 	return rc;
4163 }
4164 
4165 /**
4166  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
4167  * @phba: Pointer to HBA context object.
4168  * @pring: Pointer to driver SLI ring object.
4169  * @rspiocbp: Pointer to driver response IOCB object.
4170  *
4171  * This function is called from the worker thread when there is a slow-path
4172  * response IOCB to process. This function chains all the response iocbs until
4173  * seeing the iocb with the LE bit set. The function will call
4174  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
4175  * completion of a command iocb. The function will call the
4176  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
4177  * The function frees the resources or calls the completion handler if this
4178  * iocb is an abort completion. The function returns NULL when the response
4179  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
4180  * this function shall chain the iocb on to the iocb_continueq and return the
4181  * response iocb passed in.
4182  **/
4183 static struct lpfc_iocbq *
4184 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
4185 			struct lpfc_iocbq *rspiocbp)
4186 {
4187 	struct lpfc_iocbq *saveq;
4188 	struct lpfc_iocbq *cmdiocb;
4189 	struct lpfc_iocbq *next_iocb;
4190 	IOCB_t *irsp;
4191 	uint32_t free_saveq;
4192 	u8 cmd_type;
4193 	lpfc_iocb_type type;
4194 	unsigned long iflag;
4195 	u32 ulp_status = get_job_ulpstatus(phba, rspiocbp);
4196 	u32 ulp_word4 = get_job_word4(phba, rspiocbp);
4197 	u32 ulp_command = get_job_cmnd(phba, rspiocbp);
4198 	int rc;
4199 
4200 	spin_lock_irqsave(&phba->hbalock, iflag);
4201 	/* First add the response iocb to the countinueq list */
4202 	list_add_tail(&rspiocbp->list, &pring->iocb_continueq);
4203 	pring->iocb_continueq_cnt++;
4204 
4205 	/*
4206 	 * By default, the driver expects to free all resources
4207 	 * associated with this iocb completion.
4208 	 */
4209 	free_saveq = 1;
4210 	saveq = list_get_first(&pring->iocb_continueq,
4211 			       struct lpfc_iocbq, list);
4212 	list_del_init(&pring->iocb_continueq);
4213 	pring->iocb_continueq_cnt = 0;
4214 
4215 	pring->stats.iocb_rsp++;
4216 
4217 	/*
4218 	 * If resource errors reported from HBA, reduce
4219 	 * queuedepths of the SCSI device.
4220 	 */
4221 	if (ulp_status == IOSTAT_LOCAL_REJECT &&
4222 	    ((ulp_word4 & IOERR_PARAM_MASK) ==
4223 	     IOERR_NO_RESOURCES)) {
4224 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4225 		phba->lpfc_rampdown_queue_depth(phba);
4226 		spin_lock_irqsave(&phba->hbalock, iflag);
4227 	}
4228 
4229 	if (ulp_status) {
4230 		/* Rsp ring <ringno> error: IOCB */
4231 		if (phba->sli_rev < LPFC_SLI_REV4) {
4232 			irsp = &rspiocbp->iocb;
4233 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4234 					"0328 Rsp Ring %d error: ulp_status x%x "
4235 					"IOCB Data: "
4236 					"x%08x x%08x x%08x x%08x "
4237 					"x%08x x%08x x%08x x%08x "
4238 					"x%08x x%08x x%08x x%08x "
4239 					"x%08x x%08x x%08x x%08x\n",
4240 					pring->ringno, ulp_status,
4241 					get_job_ulpword(rspiocbp, 0),
4242 					get_job_ulpword(rspiocbp, 1),
4243 					get_job_ulpword(rspiocbp, 2),
4244 					get_job_ulpword(rspiocbp, 3),
4245 					get_job_ulpword(rspiocbp, 4),
4246 					get_job_ulpword(rspiocbp, 5),
4247 					*(((uint32_t *)irsp) + 6),
4248 					*(((uint32_t *)irsp) + 7),
4249 					*(((uint32_t *)irsp) + 8),
4250 					*(((uint32_t *)irsp) + 9),
4251 					*(((uint32_t *)irsp) + 10),
4252 					*(((uint32_t *)irsp) + 11),
4253 					*(((uint32_t *)irsp) + 12),
4254 					*(((uint32_t *)irsp) + 13),
4255 					*(((uint32_t *)irsp) + 14),
4256 					*(((uint32_t *)irsp) + 15));
4257 		} else {
4258 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4259 					"0321 Rsp Ring %d error: "
4260 					"IOCB Data: "
4261 					"x%x x%x x%x x%x\n",
4262 					pring->ringno,
4263 					rspiocbp->wcqe_cmpl.word0,
4264 					rspiocbp->wcqe_cmpl.total_data_placed,
4265 					rspiocbp->wcqe_cmpl.parameter,
4266 					rspiocbp->wcqe_cmpl.word3);
4267 		}
4268 	}
4269 
4270 
4271 	/*
4272 	 * Fetch the iocb command type and call the correct completion
4273 	 * routine. Solicited and Unsolicited IOCBs on the ELS ring
4274 	 * get freed back to the lpfc_iocb_list by the discovery
4275 	 * kernel thread.
4276 	 */
4277 	cmd_type = ulp_command & CMD_IOCB_MASK;
4278 	type = lpfc_sli_iocb_cmd_type(cmd_type);
4279 	switch (type) {
4280 	case LPFC_SOL_IOCB:
4281 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4282 		rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
4283 		spin_lock_irqsave(&phba->hbalock, iflag);
4284 		break;
4285 	case LPFC_UNSOL_IOCB:
4286 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4287 		rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
4288 		spin_lock_irqsave(&phba->hbalock, iflag);
4289 		if (!rc)
4290 			free_saveq = 0;
4291 		break;
4292 	case LPFC_ABORT_IOCB:
4293 		cmdiocb = NULL;
4294 		if (ulp_command != CMD_XRI_ABORTED_CX)
4295 			cmdiocb = lpfc_sli_iocbq_lookup(phba, pring,
4296 							saveq);
4297 		if (cmdiocb) {
4298 			/* Call the specified completion routine */
4299 			if (cmdiocb->cmd_cmpl) {
4300 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4301 				cmdiocb->cmd_cmpl(phba, cmdiocb, saveq);
4302 				spin_lock_irqsave(&phba->hbalock, iflag);
4303 			} else {
4304 				__lpfc_sli_release_iocbq(phba, cmdiocb);
4305 			}
4306 		}
4307 		break;
4308 	case LPFC_UNKNOWN_IOCB:
4309 		if (ulp_command == CMD_ADAPTER_MSG) {
4310 			char adaptermsg[LPFC_MAX_ADPTMSG];
4311 
4312 			memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4313 			memcpy(&adaptermsg[0], (uint8_t *)&rspiocbp->wqe,
4314 			       MAX_MSG_DATA);
4315 			dev_warn(&((phba->pcidev)->dev),
4316 				 "lpfc%d: %s\n",
4317 				 phba->brd_no, adaptermsg);
4318 		} else {
4319 			/* Unknown command */
4320 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4321 					"0335 Unknown IOCB "
4322 					"command Data: x%x "
4323 					"x%x x%x x%x\n",
4324 					ulp_command,
4325 					ulp_status,
4326 					get_wqe_reqtag(rspiocbp),
4327 					get_job_ulpcontext(phba, rspiocbp));
4328 		}
4329 		break;
4330 	}
4331 
4332 	if (free_saveq) {
4333 		list_for_each_entry_safe(rspiocbp, next_iocb,
4334 					 &saveq->list, list) {
4335 			list_del_init(&rspiocbp->list);
4336 			__lpfc_sli_release_iocbq(phba, rspiocbp);
4337 		}
4338 		__lpfc_sli_release_iocbq(phba, saveq);
4339 	}
4340 	rspiocbp = NULL;
4341 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4342 	return rspiocbp;
4343 }
4344 
4345 /**
4346  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
4347  * @phba: Pointer to HBA context object.
4348  * @pring: Pointer to driver SLI ring object.
4349  * @mask: Host attention register mask for this ring.
4350  *
4351  * This routine wraps the actual slow_ring event process routine from the
4352  * API jump table function pointer from the lpfc_hba struct.
4353  **/
4354 void
4355 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
4356 				struct lpfc_sli_ring *pring, uint32_t mask)
4357 {
4358 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
4359 }
4360 
4361 /**
4362  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
4363  * @phba: Pointer to HBA context object.
4364  * @pring: Pointer to driver SLI ring object.
4365  * @mask: Host attention register mask for this ring.
4366  *
4367  * This function is called from the worker thread when there is a ring event
4368  * for non-fcp rings. The caller does not hold any lock. The function will
4369  * remove each response iocb in the response ring and calls the handle
4370  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4371  **/
4372 static void
4373 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
4374 				   struct lpfc_sli_ring *pring, uint32_t mask)
4375 {
4376 	struct lpfc_pgp *pgp;
4377 	IOCB_t *entry;
4378 	IOCB_t *irsp = NULL;
4379 	struct lpfc_iocbq *rspiocbp = NULL;
4380 	uint32_t portRspPut, portRspMax;
4381 	unsigned long iflag;
4382 	uint32_t status;
4383 
4384 	pgp = &phba->port_gp[pring->ringno];
4385 	spin_lock_irqsave(&phba->hbalock, iflag);
4386 	pring->stats.iocb_event++;
4387 
4388 	/*
4389 	 * The next available response entry should never exceed the maximum
4390 	 * entries.  If it does, treat it as an adapter hardware error.
4391 	 */
4392 	portRspMax = pring->sli.sli3.numRiocb;
4393 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4394 	if (portRspPut >= portRspMax) {
4395 		/*
4396 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
4397 		 * rsp ring <portRspMax>
4398 		 */
4399 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4400 				"0303 Ring %d handler: portRspPut %d "
4401 				"is bigger than rsp ring %d\n",
4402 				pring->ringno, portRspPut, portRspMax);
4403 
4404 		phba->link_state = LPFC_HBA_ERROR;
4405 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4406 
4407 		phba->work_hs = HS_FFER3;
4408 		lpfc_handle_eratt(phba);
4409 
4410 		return;
4411 	}
4412 
4413 	rmb();
4414 	while (pring->sli.sli3.rspidx != portRspPut) {
4415 		/*
4416 		 * Build a completion list and call the appropriate handler.
4417 		 * The process is to get the next available response iocb, get
4418 		 * a free iocb from the list, copy the response data into the
4419 		 * free iocb, insert to the continuation list, and update the
4420 		 * next response index to slim.  This process makes response
4421 		 * iocb's in the ring available to DMA as fast as possible but
4422 		 * pays a penalty for a copy operation.  Since the iocb is
4423 		 * only 32 bytes, this penalty is considered small relative to
4424 		 * the PCI reads for register values and a slim write.  When
4425 		 * the ulpLe field is set, the entire Command has been
4426 		 * received.
4427 		 */
4428 		entry = lpfc_resp_iocb(phba, pring);
4429 
4430 		phba->last_completion_time = jiffies;
4431 		rspiocbp = __lpfc_sli_get_iocbq(phba);
4432 		if (rspiocbp == NULL) {
4433 			printk(KERN_ERR "%s: out of buffers! Failing "
4434 			       "completion.\n", __func__);
4435 			break;
4436 		}
4437 
4438 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
4439 				      phba->iocb_rsp_size);
4440 		irsp = &rspiocbp->iocb;
4441 
4442 		if (++pring->sli.sli3.rspidx >= portRspMax)
4443 			pring->sli.sli3.rspidx = 0;
4444 
4445 		if (pring->ringno == LPFC_ELS_RING) {
4446 			lpfc_debugfs_slow_ring_trc(phba,
4447 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
4448 				*(((uint32_t *) irsp) + 4),
4449 				*(((uint32_t *) irsp) + 6),
4450 				*(((uint32_t *) irsp) + 7));
4451 		}
4452 
4453 		writel(pring->sli.sli3.rspidx,
4454 			&phba->host_gp[pring->ringno].rspGetInx);
4455 
4456 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4457 		/* Handle the response IOCB */
4458 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
4459 		spin_lock_irqsave(&phba->hbalock, iflag);
4460 
4461 		/*
4462 		 * If the port response put pointer has not been updated, sync
4463 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
4464 		 * response put pointer.
4465 		 */
4466 		if (pring->sli.sli3.rspidx == portRspPut) {
4467 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4468 		}
4469 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
4470 
4471 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
4472 		/* At least one response entry has been freed */
4473 		pring->stats.iocb_rsp_full++;
4474 		/* SET RxRE_RSP in Chip Att register */
4475 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4476 		writel(status, phba->CAregaddr);
4477 		readl(phba->CAregaddr); /* flush */
4478 	}
4479 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4480 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4481 		pring->stats.iocb_cmd_empty++;
4482 
4483 		/* Force update of the local copy of cmdGetInx */
4484 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4485 		lpfc_sli_resume_iocb(phba, pring);
4486 
4487 		if ((pring->lpfc_sli_cmd_available))
4488 			(pring->lpfc_sli_cmd_available) (phba, pring);
4489 
4490 	}
4491 
4492 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4493 	return;
4494 }
4495 
4496 /**
4497  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
4498  * @phba: Pointer to HBA context object.
4499  * @pring: Pointer to driver SLI ring object.
4500  * @mask: Host attention register mask for this ring.
4501  *
4502  * This function is called from the worker thread when there is a pending
4503  * ELS response iocb on the driver internal slow-path response iocb worker
4504  * queue. The caller does not hold any lock. The function will remove each
4505  * response iocb from the response worker queue and calls the handle
4506  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4507  **/
4508 static void
4509 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4510 				   struct lpfc_sli_ring *pring, uint32_t mask)
4511 {
4512 	struct lpfc_iocbq *irspiocbq;
4513 	struct hbq_dmabuf *dmabuf;
4514 	struct lpfc_cq_event *cq_event;
4515 	unsigned long iflag;
4516 	int count = 0;
4517 
4518 	clear_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
4519 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4520 		/* Get the response iocb from the head of work queue */
4521 		spin_lock_irqsave(&phba->hbalock, iflag);
4522 		list_remove_head(&phba->sli4_hba.sp_queue_event,
4523 				 cq_event, struct lpfc_cq_event, list);
4524 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4525 
4526 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4527 		case CQE_CODE_COMPL_WQE:
4528 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4529 						 cq_event);
4530 			/* Translate ELS WCQE to response IOCBQ */
4531 			irspiocbq = lpfc_sli4_els_preprocess_rspiocbq(phba,
4532 								      irspiocbq);
4533 			if (irspiocbq)
4534 				lpfc_sli_sp_handle_rspiocb(phba, pring,
4535 							   irspiocbq);
4536 			count++;
4537 			break;
4538 		case CQE_CODE_RECEIVE:
4539 		case CQE_CODE_RECEIVE_V1:
4540 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
4541 					      cq_event);
4542 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
4543 			count++;
4544 			break;
4545 		default:
4546 			break;
4547 		}
4548 
4549 		/* Limit the number of events to 64 to avoid soft lockups */
4550 		if (count == 64)
4551 			break;
4552 	}
4553 }
4554 
4555 /**
4556  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4557  * @phba: Pointer to HBA context object.
4558  * @pring: Pointer to driver SLI ring object.
4559  *
4560  * This function aborts all iocbs in the given ring and frees all the iocb
4561  * objects in txq. This function issues an abort iocb for all the iocb commands
4562  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4563  * the return of this function. The caller is not required to hold any locks.
4564  **/
4565 void
4566 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4567 {
4568 	LIST_HEAD(tx_completions);
4569 	spinlock_t *plock;		/* for transmit queue access */
4570 	struct lpfc_iocbq *iocb, *next_iocb;
4571 	int offline;
4572 
4573 	if (phba->sli_rev >= LPFC_SLI_REV4)
4574 		plock = &pring->ring_lock;
4575 	else
4576 		plock = &phba->hbalock;
4577 
4578 	if (pring->ringno == LPFC_ELS_RING)
4579 		lpfc_fabric_abort_hba(phba);
4580 
4581 	offline = pci_channel_offline(phba->pcidev);
4582 
4583 	/* Cancel everything on txq */
4584 	spin_lock_irq(plock);
4585 	list_splice_init(&pring->txq, &tx_completions);
4586 	pring->txq_cnt = 0;
4587 
4588 	if (offline) {
4589 		/* Cancel everything on txcmplq */
4590 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4591 			iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4592 		list_splice_init(&pring->txcmplq, &tx_completions);
4593 		pring->txcmplq_cnt = 0;
4594 	} else {
4595 		/* Issue ABTS for everything on the txcmplq */
4596 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4597 			lpfc_sli_issue_abort_iotag(phba, pring, iocb, NULL);
4598 	}
4599 	spin_unlock_irq(plock);
4600 
4601 	if (!offline)
4602 		lpfc_issue_hb_tmo(phba);
4603 
4604 	/* Cancel all the IOCBs from the completions list */
4605 	lpfc_sli_cancel_iocbs(phba, &tx_completions, IOSTAT_LOCAL_REJECT,
4606 			      IOERR_SLI_ABORTED);
4607 }
4608 
4609 /**
4610  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4611  * @phba: Pointer to HBA context object.
4612  *
4613  * This function aborts all iocbs in FCP rings and frees all the iocb
4614  * objects in txq. This function issues an abort iocb for all the iocb commands
4615  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4616  * the return of this function. The caller is not required to hold any locks.
4617  **/
4618 void
4619 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4620 {
4621 	struct lpfc_sli *psli = &phba->sli;
4622 	struct lpfc_sli_ring  *pring;
4623 	uint32_t i;
4624 
4625 	/* Look on all the FCP Rings for the iotag */
4626 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4627 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4628 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4629 			lpfc_sli_abort_iocb_ring(phba, pring);
4630 		}
4631 	} else {
4632 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4633 		lpfc_sli_abort_iocb_ring(phba, pring);
4634 	}
4635 }
4636 
4637 /**
4638  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4639  * @phba: Pointer to HBA context object.
4640  *
4641  * This function flushes all iocbs in the IO ring and frees all the iocb
4642  * objects in txq and txcmplq. This function will not issue abort iocbs
4643  * for all the iocb commands in txcmplq, they will just be returned with
4644  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4645  * slot has been permanently disabled.
4646  **/
4647 void
4648 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4649 {
4650 	LIST_HEAD(txq);
4651 	LIST_HEAD(txcmplq);
4652 	struct lpfc_sli *psli = &phba->sli;
4653 	struct lpfc_sli_ring  *pring;
4654 	uint32_t i;
4655 	struct lpfc_iocbq *piocb, *next_iocb;
4656 
4657 	/* Indicate the I/O queues are flushed */
4658 	set_bit(HBA_IOQ_FLUSH, &phba->hba_flag);
4659 
4660 	/* Look on all the FCP Rings for the iotag */
4661 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4662 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4663 			if (!phba->sli4_hba.hdwq ||
4664 			    !phba->sli4_hba.hdwq[i].io_wq) {
4665 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4666 						"7777 hdwq's deleted %lx "
4667 						"%lx %x %x\n",
4668 						phba->pport->load_flag,
4669 						phba->hba_flag,
4670 						phba->link_state,
4671 						phba->sli.sli_flag);
4672 				return;
4673 			}
4674 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4675 
4676 			spin_lock_irq(&pring->ring_lock);
4677 			/* Retrieve everything on txq */
4678 			list_splice_init(&pring->txq, &txq);
4679 			list_for_each_entry_safe(piocb, next_iocb,
4680 						 &pring->txcmplq, list)
4681 				piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4682 			/* Retrieve everything on the txcmplq */
4683 			list_splice_init(&pring->txcmplq, &txcmplq);
4684 			pring->txq_cnt = 0;
4685 			pring->txcmplq_cnt = 0;
4686 			spin_unlock_irq(&pring->ring_lock);
4687 
4688 			/* Flush the txq */
4689 			lpfc_sli_cancel_iocbs(phba, &txq,
4690 					      IOSTAT_LOCAL_REJECT,
4691 					      IOERR_SLI_DOWN);
4692 			/* Flush the txcmplq */
4693 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4694 					      IOSTAT_LOCAL_REJECT,
4695 					      IOERR_SLI_DOWN);
4696 			if (unlikely(pci_channel_offline(phba->pcidev)))
4697 				lpfc_sli4_io_xri_aborted(phba, NULL, 0);
4698 		}
4699 	} else {
4700 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4701 
4702 		spin_lock_irq(&phba->hbalock);
4703 		/* Retrieve everything on txq */
4704 		list_splice_init(&pring->txq, &txq);
4705 		list_for_each_entry_safe(piocb, next_iocb,
4706 					 &pring->txcmplq, list)
4707 			piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4708 		/* Retrieve everything on the txcmplq */
4709 		list_splice_init(&pring->txcmplq, &txcmplq);
4710 		pring->txq_cnt = 0;
4711 		pring->txcmplq_cnt = 0;
4712 		spin_unlock_irq(&phba->hbalock);
4713 
4714 		/* Flush the txq */
4715 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4716 				      IOERR_SLI_DOWN);
4717 		/* Flush the txcmpq */
4718 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4719 				      IOERR_SLI_DOWN);
4720 	}
4721 }
4722 
4723 /**
4724  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4725  * @phba: Pointer to HBA context object.
4726  * @mask: Bit mask to be checked.
4727  *
4728  * This function reads the host status register and compares
4729  * with the provided bit mask to check if HBA completed
4730  * the restart. This function will wait in a loop for the
4731  * HBA to complete restart. If the HBA does not restart within
4732  * 15 iterations, the function will reset the HBA again. The
4733  * function returns 1 when HBA fail to restart otherwise returns
4734  * zero.
4735  **/
4736 static int
4737 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4738 {
4739 	uint32_t status;
4740 	int i = 0;
4741 	int retval = 0;
4742 
4743 	/* Read the HBA Host Status Register */
4744 	if (lpfc_readl(phba->HSregaddr, &status))
4745 		return 1;
4746 
4747 	set_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
4748 
4749 	/*
4750 	 * Check status register every 100ms for 5 retries, then every
4751 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4752 	 * every 2.5 sec for 4.
4753 	 * Break our of the loop if errors occurred during init.
4754 	 */
4755 	while (((status & mask) != mask) &&
4756 	       !(status & HS_FFERM) &&
4757 	       i++ < 20) {
4758 
4759 		if (i <= 5)
4760 			msleep(10);
4761 		else if (i <= 10)
4762 			msleep(500);
4763 		else
4764 			msleep(2500);
4765 
4766 		if (i == 15) {
4767 				/* Do post */
4768 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4769 			lpfc_sli_brdrestart(phba);
4770 		}
4771 		/* Read the HBA Host Status Register */
4772 		if (lpfc_readl(phba->HSregaddr, &status)) {
4773 			retval = 1;
4774 			break;
4775 		}
4776 	}
4777 
4778 	/* Check to see if any errors occurred during init */
4779 	if ((status & HS_FFERM) || (i >= 20)) {
4780 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4781 				"2751 Adapter failed to restart, "
4782 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4783 				status,
4784 				readl(phba->MBslimaddr + 0xa8),
4785 				readl(phba->MBslimaddr + 0xac));
4786 		phba->link_state = LPFC_HBA_ERROR;
4787 		retval = 1;
4788 	}
4789 
4790 	return retval;
4791 }
4792 
4793 /**
4794  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4795  * @phba: Pointer to HBA context object.
4796  * @mask: Bit mask to be checked.
4797  *
4798  * This function checks the host status register to check if HBA is
4799  * ready. This function will wait in a loop for the HBA to be ready
4800  * If the HBA is not ready , the function will will reset the HBA PCI
4801  * function again. The function returns 1 when HBA fail to be ready
4802  * otherwise returns zero.
4803  **/
4804 static int
4805 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4806 {
4807 	uint32_t status;
4808 	int retval = 0;
4809 
4810 	/* Read the HBA Host Status Register */
4811 	status = lpfc_sli4_post_status_check(phba);
4812 
4813 	if (status) {
4814 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4815 		lpfc_sli_brdrestart(phba);
4816 		status = lpfc_sli4_post_status_check(phba);
4817 	}
4818 
4819 	/* Check to see if any errors occurred during init */
4820 	if (status) {
4821 		phba->link_state = LPFC_HBA_ERROR;
4822 		retval = 1;
4823 	} else
4824 		phba->sli4_hba.intr_enable = 0;
4825 
4826 	clear_bit(HBA_SETUP, &phba->hba_flag);
4827 	return retval;
4828 }
4829 
4830 /**
4831  * lpfc_sli_brdready - Wrapper func for checking the hba readiness
4832  * @phba: Pointer to HBA context object.
4833  * @mask: Bit mask to be checked.
4834  *
4835  * This routine wraps the actual SLI3 or SLI4 hba readiness check routine
4836  * from the API jump table function pointer from the lpfc_hba struct.
4837  **/
4838 int
4839 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4840 {
4841 	return phba->lpfc_sli_brdready(phba, mask);
4842 }
4843 
4844 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4845 
4846 /**
4847  * lpfc_reset_barrier - Make HBA ready for HBA reset
4848  * @phba: Pointer to HBA context object.
4849  *
4850  * This function is called before resetting an HBA. This function is called
4851  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4852  **/
4853 void lpfc_reset_barrier(struct lpfc_hba *phba)
4854 {
4855 	uint32_t __iomem *resp_buf;
4856 	uint32_t __iomem *mbox_buf;
4857 	volatile struct MAILBOX_word0 mbox;
4858 	uint32_t hc_copy, ha_copy, resp_data;
4859 	int  i;
4860 	uint8_t hdrtype;
4861 
4862 	lockdep_assert_held(&phba->hbalock);
4863 
4864 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4865 	if (hdrtype != PCI_HEADER_TYPE_MFD ||
4866 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4867 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4868 		return;
4869 
4870 	/*
4871 	 * Tell the other part of the chip to suspend temporarily all
4872 	 * its DMA activity.
4873 	 */
4874 	resp_buf = phba->MBslimaddr;
4875 
4876 	/* Disable the error attention */
4877 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4878 		return;
4879 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4880 	readl(phba->HCregaddr); /* flush */
4881 	phba->link_flag |= LS_IGNORE_ERATT;
4882 
4883 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4884 		return;
4885 	if (ha_copy & HA_ERATT) {
4886 		/* Clear Chip error bit */
4887 		writel(HA_ERATT, phba->HAregaddr);
4888 		phba->pport->stopped = 1;
4889 	}
4890 
4891 	mbox.word0 = 0;
4892 	mbox.mbxCommand = MBX_KILL_BOARD;
4893 	mbox.mbxOwner = OWN_CHIP;
4894 
4895 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4896 	mbox_buf = phba->MBslimaddr;
4897 	writel(mbox.word0, mbox_buf);
4898 
4899 	for (i = 0; i < 50; i++) {
4900 		if (lpfc_readl((resp_buf + 1), &resp_data))
4901 			return;
4902 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4903 			mdelay(1);
4904 		else
4905 			break;
4906 	}
4907 	resp_data = 0;
4908 	if (lpfc_readl((resp_buf + 1), &resp_data))
4909 		return;
4910 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4911 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4912 		    phba->pport->stopped)
4913 			goto restore_hc;
4914 		else
4915 			goto clear_errat;
4916 	}
4917 
4918 	mbox.mbxOwner = OWN_HOST;
4919 	resp_data = 0;
4920 	for (i = 0; i < 500; i++) {
4921 		if (lpfc_readl(resp_buf, &resp_data))
4922 			return;
4923 		if (resp_data != mbox.word0)
4924 			mdelay(1);
4925 		else
4926 			break;
4927 	}
4928 
4929 clear_errat:
4930 
4931 	while (++i < 500) {
4932 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4933 			return;
4934 		if (!(ha_copy & HA_ERATT))
4935 			mdelay(1);
4936 		else
4937 			break;
4938 	}
4939 
4940 	if (readl(phba->HAregaddr) & HA_ERATT) {
4941 		writel(HA_ERATT, phba->HAregaddr);
4942 		phba->pport->stopped = 1;
4943 	}
4944 
4945 restore_hc:
4946 	phba->link_flag &= ~LS_IGNORE_ERATT;
4947 	writel(hc_copy, phba->HCregaddr);
4948 	readl(phba->HCregaddr); /* flush */
4949 }
4950 
4951 /**
4952  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4953  * @phba: Pointer to HBA context object.
4954  *
4955  * This function issues a kill_board mailbox command and waits for
4956  * the error attention interrupt. This function is called for stopping
4957  * the firmware processing. The caller is not required to hold any
4958  * locks. This function calls lpfc_hba_down_post function to free
4959  * any pending commands after the kill. The function will return 1 when it
4960  * fails to kill the board else will return 0.
4961  **/
4962 int
4963 lpfc_sli_brdkill(struct lpfc_hba *phba)
4964 {
4965 	struct lpfc_sli *psli;
4966 	LPFC_MBOXQ_t *pmb;
4967 	uint32_t status;
4968 	uint32_t ha_copy;
4969 	int retval;
4970 	int i = 0;
4971 
4972 	psli = &phba->sli;
4973 
4974 	/* Kill HBA */
4975 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4976 			"0329 Kill HBA Data: x%x x%x\n",
4977 			phba->pport->port_state, psli->sli_flag);
4978 
4979 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4980 	if (!pmb)
4981 		return 1;
4982 
4983 	/* Disable the error attention */
4984 	spin_lock_irq(&phba->hbalock);
4985 	if (lpfc_readl(phba->HCregaddr, &status)) {
4986 		spin_unlock_irq(&phba->hbalock);
4987 		mempool_free(pmb, phba->mbox_mem_pool);
4988 		return 1;
4989 	}
4990 	status &= ~HC_ERINT_ENA;
4991 	writel(status, phba->HCregaddr);
4992 	readl(phba->HCregaddr); /* flush */
4993 	phba->link_flag |= LS_IGNORE_ERATT;
4994 	spin_unlock_irq(&phba->hbalock);
4995 
4996 	lpfc_kill_board(phba, pmb);
4997 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4998 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4999 
5000 	if (retval != MBX_SUCCESS) {
5001 		if (retval != MBX_BUSY)
5002 			mempool_free(pmb, phba->mbox_mem_pool);
5003 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5004 				"2752 KILL_BOARD command failed retval %d\n",
5005 				retval);
5006 		spin_lock_irq(&phba->hbalock);
5007 		phba->link_flag &= ~LS_IGNORE_ERATT;
5008 		spin_unlock_irq(&phba->hbalock);
5009 		return 1;
5010 	}
5011 
5012 	spin_lock_irq(&phba->hbalock);
5013 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
5014 	spin_unlock_irq(&phba->hbalock);
5015 
5016 	mempool_free(pmb, phba->mbox_mem_pool);
5017 
5018 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
5019 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
5020 	 * 3 seconds we still set HBA_ERROR state because the status of the
5021 	 * board is now undefined.
5022 	 */
5023 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
5024 		return 1;
5025 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
5026 		mdelay(100);
5027 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
5028 			return 1;
5029 	}
5030 
5031 	timer_delete_sync(&psli->mbox_tmo);
5032 	if (ha_copy & HA_ERATT) {
5033 		writel(HA_ERATT, phba->HAregaddr);
5034 		phba->pport->stopped = 1;
5035 	}
5036 	spin_lock_irq(&phba->hbalock);
5037 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5038 	psli->mbox_active = NULL;
5039 	phba->link_flag &= ~LS_IGNORE_ERATT;
5040 	spin_unlock_irq(&phba->hbalock);
5041 
5042 	lpfc_hba_down_post(phba);
5043 	phba->link_state = LPFC_HBA_ERROR;
5044 
5045 	return ha_copy & HA_ERATT ? 0 : 1;
5046 }
5047 
5048 /**
5049  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
5050  * @phba: Pointer to HBA context object.
5051  *
5052  * This function resets the HBA by writing HC_INITFF to the control
5053  * register. After the HBA resets, this function resets all the iocb ring
5054  * indices. This function disables PCI layer parity checking during
5055  * the reset.
5056  * This function returns 0 always.
5057  * The caller is not required to hold any locks.
5058  **/
5059 int
5060 lpfc_sli_brdreset(struct lpfc_hba *phba)
5061 {
5062 	struct lpfc_sli *psli;
5063 	struct lpfc_sli_ring *pring;
5064 	uint16_t cfg_value;
5065 	int i;
5066 
5067 	psli = &phba->sli;
5068 
5069 	/* Reset HBA */
5070 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5071 			"0325 Reset HBA Data: x%x x%x\n",
5072 			(phba->pport) ? phba->pport->port_state : 0,
5073 			psli->sli_flag);
5074 
5075 	/* perform board reset */
5076 	phba->fc_eventTag = 0;
5077 	phba->link_events = 0;
5078 	set_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
5079 	if (phba->pport) {
5080 		phba->pport->fc_myDID = 0;
5081 		phba->pport->fc_prevDID = 0;
5082 	}
5083 
5084 	/* Turn off parity checking and serr during the physical reset */
5085 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
5086 		return -EIO;
5087 
5088 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
5089 			      (cfg_value &
5090 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5091 
5092 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
5093 
5094 	/* Now toggle INITFF bit in the Host Control Register */
5095 	writel(HC_INITFF, phba->HCregaddr);
5096 	mdelay(1);
5097 	readl(phba->HCregaddr); /* flush */
5098 	writel(0, phba->HCregaddr);
5099 	readl(phba->HCregaddr); /* flush */
5100 
5101 	/* Restore PCI cmd register */
5102 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5103 
5104 	/* Initialize relevant SLI info */
5105 	for (i = 0; i < psli->num_rings; i++) {
5106 		pring = &psli->sli3_ring[i];
5107 		pring->flag = 0;
5108 		pring->sli.sli3.rspidx = 0;
5109 		pring->sli.sli3.next_cmdidx  = 0;
5110 		pring->sli.sli3.local_getidx = 0;
5111 		pring->sli.sli3.cmdidx = 0;
5112 		pring->missbufcnt = 0;
5113 	}
5114 
5115 	phba->link_state = LPFC_WARM_START;
5116 	return 0;
5117 }
5118 
5119 /**
5120  * lpfc_sli4_brdreset - Reset a sli-4 HBA
5121  * @phba: Pointer to HBA context object.
5122  *
5123  * This function resets a SLI4 HBA. This function disables PCI layer parity
5124  * checking during resets the device. The caller is not required to hold
5125  * any locks.
5126  *
5127  * This function returns 0 on success else returns negative error code.
5128  **/
5129 int
5130 lpfc_sli4_brdreset(struct lpfc_hba *phba)
5131 {
5132 	struct lpfc_sli *psli = &phba->sli;
5133 	uint16_t cfg_value;
5134 	int rc = 0;
5135 
5136 	/* Reset HBA */
5137 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5138 			"0295 Reset HBA Data: x%x x%x x%lx\n",
5139 			phba->pport->port_state, psli->sli_flag,
5140 			phba->hba_flag);
5141 
5142 	/* perform board reset */
5143 	phba->fc_eventTag = 0;
5144 	phba->link_events = 0;
5145 	phba->pport->fc_myDID = 0;
5146 	phba->pport->fc_prevDID = 0;
5147 
5148 	spin_lock_irq(&phba->hbalock);
5149 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
5150 	phba->fcf.fcf_flag = 0;
5151 	spin_unlock_irq(&phba->hbalock);
5152 
5153 	/* Now physically reset the device */
5154 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5155 			"0389 Performing PCI function reset!\n");
5156 
5157 	/* Turn off parity checking and serr during the physical reset */
5158 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
5159 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5160 				"3205 PCI read Config failed\n");
5161 		return -EIO;
5162 	}
5163 
5164 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
5165 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5166 
5167 	/* Perform FCoE PCI function reset before freeing queue memory */
5168 	rc = lpfc_pci_function_reset(phba);
5169 
5170 	/* Restore PCI cmd register */
5171 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5172 
5173 	return rc;
5174 }
5175 
5176 /**
5177  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
5178  * @phba: Pointer to HBA context object.
5179  *
5180  * This function is called in the SLI initialization code path to
5181  * restart the HBA. The caller is not required to hold any lock.
5182  * This function writes MBX_RESTART mailbox command to the SLIM and
5183  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
5184  * function to free any pending commands. The function enables
5185  * POST only during the first initialization. The function returns zero.
5186  * The function does not guarantee completion of MBX_RESTART mailbox
5187  * command before the return of this function.
5188  **/
5189 static int
5190 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
5191 {
5192 	volatile struct MAILBOX_word0 mb;
5193 	struct lpfc_sli *psli;
5194 	void __iomem *to_slim;
5195 
5196 	spin_lock_irq(&phba->hbalock);
5197 
5198 	psli = &phba->sli;
5199 
5200 	/* Restart HBA */
5201 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5202 			"0337 Restart HBA Data: x%x x%x\n",
5203 			(phba->pport) ? phba->pport->port_state : 0,
5204 			psli->sli_flag);
5205 
5206 	mb.word0 = 0;
5207 	mb.mbxCommand = MBX_RESTART;
5208 	mb.mbxHc = 1;
5209 
5210 	lpfc_reset_barrier(phba);
5211 
5212 	to_slim = phba->MBslimaddr;
5213 	writel(mb.word0, to_slim);
5214 	readl(to_slim); /* flush */
5215 
5216 	/* Only skip post after fc_ffinit is completed */
5217 	if (phba->pport && phba->pport->port_state)
5218 		mb.word0 = 1;	/* This is really setting up word1 */
5219 	else
5220 		mb.word0 = 0;	/* This is really setting up word1 */
5221 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
5222 	writel(mb.word0, to_slim);
5223 	readl(to_slim); /* flush */
5224 
5225 	lpfc_sli_brdreset(phba);
5226 	if (phba->pport)
5227 		phba->pport->stopped = 0;
5228 	phba->link_state = LPFC_INIT_START;
5229 	phba->hba_flag = 0;
5230 	spin_unlock_irq(&phba->hbalock);
5231 
5232 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5233 	psli->stats_start = ktime_get_seconds();
5234 
5235 	/* Give the INITFF and Post time to settle. */
5236 	mdelay(100);
5237 
5238 	lpfc_hba_down_post(phba);
5239 
5240 	return 0;
5241 }
5242 
5243 /**
5244  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
5245  * @phba: Pointer to HBA context object.
5246  *
5247  * This function is called in the SLI initialization code path to restart
5248  * a SLI4 HBA. The caller is not required to hold any lock.
5249  * At the end of the function, it calls lpfc_hba_down_post function to
5250  * free any pending commands.
5251  **/
5252 static int
5253 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
5254 {
5255 	struct lpfc_sli *psli = &phba->sli;
5256 	int rc;
5257 
5258 	/* Restart HBA */
5259 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5260 			"0296 Restart HBA Data: x%x x%x\n",
5261 			phba->pport->port_state, psli->sli_flag);
5262 
5263 	clear_bit(HBA_SETUP, &phba->hba_flag);
5264 	lpfc_sli4_queue_unset(phba);
5265 
5266 	rc = lpfc_sli4_brdreset(phba);
5267 	if (rc) {
5268 		phba->link_state = LPFC_HBA_ERROR;
5269 		goto hba_down_queue;
5270 	}
5271 
5272 	spin_lock_irq(&phba->hbalock);
5273 	phba->pport->stopped = 0;
5274 	phba->link_state = LPFC_INIT_START;
5275 	phba->hba_flag = 0;
5276 	/* Preserve FA-PWWN expectation */
5277 	phba->sli4_hba.fawwpn_flag &= LPFC_FAWWPN_FABRIC;
5278 	spin_unlock_irq(&phba->hbalock);
5279 
5280 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5281 	psli->stats_start = ktime_get_seconds();
5282 
5283 hba_down_queue:
5284 	lpfc_hba_down_post(phba);
5285 	lpfc_sli4_queue_destroy(phba);
5286 
5287 	return rc;
5288 }
5289 
5290 /**
5291  * lpfc_sli_brdrestart - Wrapper func for restarting hba
5292  * @phba: Pointer to HBA context object.
5293  *
5294  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
5295  * API jump table function pointer from the lpfc_hba struct.
5296 **/
5297 int
5298 lpfc_sli_brdrestart(struct lpfc_hba *phba)
5299 {
5300 	return phba->lpfc_sli_brdrestart(phba);
5301 }
5302 
5303 /**
5304  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
5305  * @phba: Pointer to HBA context object.
5306  *
5307  * This function is called after a HBA restart to wait for successful
5308  * restart of the HBA. Successful restart of the HBA is indicated by
5309  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
5310  * iteration, the function will restart the HBA again. The function returns
5311  * zero if HBA successfully restarted else returns negative error code.
5312  **/
5313 int
5314 lpfc_sli_chipset_init(struct lpfc_hba *phba)
5315 {
5316 	uint32_t status, i = 0;
5317 
5318 	/* Read the HBA Host Status Register */
5319 	if (lpfc_readl(phba->HSregaddr, &status))
5320 		return -EIO;
5321 
5322 	/* Check status register to see what current state is */
5323 	i = 0;
5324 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
5325 
5326 		/* Check every 10ms for 10 retries, then every 100ms for 90
5327 		 * retries, then every 1 sec for 50 retires for a total of
5328 		 * ~60 seconds before reset the board again and check every
5329 		 * 1 sec for 50 retries. The up to 60 seconds before the
5330 		 * board ready is required by the Falcon FIPS zeroization
5331 		 * complete, and any reset the board in between shall cause
5332 		 * restart of zeroization, further delay the board ready.
5333 		 */
5334 		if (i++ >= 200) {
5335 			/* Adapter failed to init, timeout, status reg
5336 			   <status> */
5337 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5338 					"0436 Adapter failed to init, "
5339 					"timeout, status reg x%x, "
5340 					"FW Data: A8 x%x AC x%x\n", status,
5341 					readl(phba->MBslimaddr + 0xa8),
5342 					readl(phba->MBslimaddr + 0xac));
5343 			phba->link_state = LPFC_HBA_ERROR;
5344 			return -ETIMEDOUT;
5345 		}
5346 
5347 		/* Check to see if any errors occurred during init */
5348 		if (status & HS_FFERM) {
5349 			/* ERROR: During chipset initialization */
5350 			/* Adapter failed to init, chipset, status reg
5351 			   <status> */
5352 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5353 					"0437 Adapter failed to init, "
5354 					"chipset, status reg x%x, "
5355 					"FW Data: A8 x%x AC x%x\n", status,
5356 					readl(phba->MBslimaddr + 0xa8),
5357 					readl(phba->MBslimaddr + 0xac));
5358 			phba->link_state = LPFC_HBA_ERROR;
5359 			return -EIO;
5360 		}
5361 
5362 		if (i <= 10)
5363 			msleep(10);
5364 		else if (i <= 100)
5365 			msleep(100);
5366 		else
5367 			msleep(1000);
5368 
5369 		if (i == 150) {
5370 			/* Do post */
5371 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5372 			lpfc_sli_brdrestart(phba);
5373 		}
5374 		/* Read the HBA Host Status Register */
5375 		if (lpfc_readl(phba->HSregaddr, &status))
5376 			return -EIO;
5377 	}
5378 
5379 	/* Check to see if any errors occurred during init */
5380 	if (status & HS_FFERM) {
5381 		/* ERROR: During chipset initialization */
5382 		/* Adapter failed to init, chipset, status reg <status> */
5383 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5384 				"0438 Adapter failed to init, chipset, "
5385 				"status reg x%x, "
5386 				"FW Data: A8 x%x AC x%x\n", status,
5387 				readl(phba->MBslimaddr + 0xa8),
5388 				readl(phba->MBslimaddr + 0xac));
5389 		phba->link_state = LPFC_HBA_ERROR;
5390 		return -EIO;
5391 	}
5392 
5393 	set_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
5394 
5395 	/* Clear all interrupt enable conditions */
5396 	writel(0, phba->HCregaddr);
5397 	readl(phba->HCregaddr); /* flush */
5398 
5399 	/* setup host attn register */
5400 	writel(0xffffffff, phba->HAregaddr);
5401 	readl(phba->HAregaddr); /* flush */
5402 	return 0;
5403 }
5404 
5405 /**
5406  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5407  *
5408  * This function calculates and returns the number of HBQs required to be
5409  * configured.
5410  **/
5411 int
5412 lpfc_sli_hbq_count(void)
5413 {
5414 	return ARRAY_SIZE(lpfc_hbq_defs);
5415 }
5416 
5417 /**
5418  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5419  *
5420  * This function adds the number of hbq entries in every HBQ to get
5421  * the total number of hbq entries required for the HBA and returns
5422  * the total count.
5423  **/
5424 static int
5425 lpfc_sli_hbq_entry_count(void)
5426 {
5427 	int  hbq_count = lpfc_sli_hbq_count();
5428 	int  count = 0;
5429 	int  i;
5430 
5431 	for (i = 0; i < hbq_count; ++i)
5432 		count += lpfc_hbq_defs[i]->entry_count;
5433 	return count;
5434 }
5435 
5436 /**
5437  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5438  *
5439  * This function calculates amount of memory required for all hbq entries
5440  * to be configured and returns the total memory required.
5441  **/
5442 int
5443 lpfc_sli_hbq_size(void)
5444 {
5445 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5446 }
5447 
5448 /**
5449  * lpfc_sli_hbq_setup - configure and initialize HBQs
5450  * @phba: Pointer to HBA context object.
5451  *
5452  * This function is called during the SLI initialization to configure
5453  * all the HBQs and post buffers to the HBQ. The caller is not
5454  * required to hold any locks. This function will return zero if successful
5455  * else it will return negative error code.
5456  **/
5457 static int
5458 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5459 {
5460 	int  hbq_count = lpfc_sli_hbq_count();
5461 	LPFC_MBOXQ_t *pmb;
5462 	MAILBOX_t *pmbox;
5463 	uint32_t hbqno;
5464 	uint32_t hbq_entry_index;
5465 
5466 				/* Get a Mailbox buffer to setup mailbox
5467 				 * commands for HBA initialization
5468 				 */
5469 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5470 
5471 	if (!pmb)
5472 		return -ENOMEM;
5473 
5474 	pmbox = &pmb->u.mb;
5475 
5476 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
5477 	phba->link_state = LPFC_INIT_MBX_CMDS;
5478 	phba->hbq_in_use = 1;
5479 
5480 	hbq_entry_index = 0;
5481 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5482 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
5483 		phba->hbqs[hbqno].hbqPutIdx      = 0;
5484 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5485 		phba->hbqs[hbqno].entry_count =
5486 			lpfc_hbq_defs[hbqno]->entry_count;
5487 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5488 			hbq_entry_index, pmb);
5489 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
5490 
5491 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5492 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5493 			   mbxStatus <status>, ring <num> */
5494 
5495 			lpfc_printf_log(phba, KERN_ERR,
5496 					LOG_SLI | LOG_VPORT,
5497 					"1805 Adapter failed to init. "
5498 					"Data: x%x x%x x%x\n",
5499 					pmbox->mbxCommand,
5500 					pmbox->mbxStatus, hbqno);
5501 
5502 			phba->link_state = LPFC_HBA_ERROR;
5503 			mempool_free(pmb, phba->mbox_mem_pool);
5504 			return -ENXIO;
5505 		}
5506 	}
5507 	phba->hbq_count = hbq_count;
5508 
5509 	mempool_free(pmb, phba->mbox_mem_pool);
5510 
5511 	/* Initially populate or replenish the HBQs */
5512 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5513 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5514 	return 0;
5515 }
5516 
5517 /**
5518  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5519  * @phba: Pointer to HBA context object.
5520  *
5521  * This function is called during the SLI initialization to configure
5522  * all the HBQs and post buffers to the HBQ. The caller is not
5523  * required to hold any locks. This function will return zero if successful
5524  * else it will return negative error code.
5525  **/
5526 static int
5527 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5528 {
5529 	phba->hbq_in_use = 1;
5530 	/**
5531 	 * Specific case when the MDS diagnostics is enabled and supported.
5532 	 * The receive buffer count is truncated to manage the incoming
5533 	 * traffic.
5534 	 **/
5535 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5536 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5537 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5538 	else
5539 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5540 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5541 	phba->hbq_count = 1;
5542 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5543 	/* Initially populate or replenish the HBQs */
5544 	return 0;
5545 }
5546 
5547 /**
5548  * lpfc_sli_config_port - Issue config port mailbox command
5549  * @phba: Pointer to HBA context object.
5550  * @sli_mode: sli mode - 2/3
5551  *
5552  * This function is called by the sli initialization code path
5553  * to issue config_port mailbox command. This function restarts the
5554  * HBA firmware and issues a config_port mailbox command to configure
5555  * the SLI interface in the sli mode specified by sli_mode
5556  * variable. The caller is not required to hold any locks.
5557  * The function returns 0 if successful, else returns negative error
5558  * code.
5559  **/
5560 int
5561 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5562 {
5563 	LPFC_MBOXQ_t *pmb;
5564 	uint32_t resetcount = 0, rc = 0, done = 0;
5565 
5566 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5567 	if (!pmb) {
5568 		phba->link_state = LPFC_HBA_ERROR;
5569 		return -ENOMEM;
5570 	}
5571 
5572 	phba->sli_rev = sli_mode;
5573 	while (resetcount < 2 && !done) {
5574 		spin_lock_irq(&phba->hbalock);
5575 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5576 		spin_unlock_irq(&phba->hbalock);
5577 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5578 		lpfc_sli_brdrestart(phba);
5579 		rc = lpfc_sli_chipset_init(phba);
5580 		if (rc)
5581 			break;
5582 
5583 		spin_lock_irq(&phba->hbalock);
5584 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5585 		spin_unlock_irq(&phba->hbalock);
5586 		resetcount++;
5587 
5588 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5589 		 * value of 0 means the call was successful.  Any other
5590 		 * nonzero value is a failure, but if ERESTART is returned,
5591 		 * the driver may reset the HBA and try again.
5592 		 */
5593 		rc = lpfc_config_port_prep(phba);
5594 		if (rc == -ERESTART) {
5595 			phba->link_state = LPFC_LINK_UNKNOWN;
5596 			continue;
5597 		} else if (rc)
5598 			break;
5599 
5600 		phba->link_state = LPFC_INIT_MBX_CMDS;
5601 		lpfc_config_port(phba, pmb);
5602 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5603 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5604 					LPFC_SLI3_HBQ_ENABLED |
5605 					LPFC_SLI3_CRP_ENABLED |
5606 					LPFC_SLI3_DSS_ENABLED);
5607 		if (rc != MBX_SUCCESS) {
5608 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5609 				"0442 Adapter failed to init, mbxCmd x%x "
5610 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5611 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5612 			spin_lock_irq(&phba->hbalock);
5613 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5614 			spin_unlock_irq(&phba->hbalock);
5615 			rc = -ENXIO;
5616 		} else {
5617 			/* Allow asynchronous mailbox command to go through */
5618 			spin_lock_irq(&phba->hbalock);
5619 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5620 			spin_unlock_irq(&phba->hbalock);
5621 			done = 1;
5622 
5623 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5624 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5625 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5626 					"3110 Port did not grant ASABT\n");
5627 		}
5628 	}
5629 	if (!done) {
5630 		rc = -EINVAL;
5631 		goto do_prep_failed;
5632 	}
5633 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5634 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5635 			rc = -ENXIO;
5636 			goto do_prep_failed;
5637 		}
5638 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5639 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5640 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5641 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5642 				phba->max_vpi : phba->max_vports;
5643 
5644 		} else
5645 			phba->max_vpi = 0;
5646 		if (pmb->u.mb.un.varCfgPort.gerbm)
5647 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5648 		if (pmb->u.mb.un.varCfgPort.gcrp)
5649 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5650 
5651 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5652 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5653 
5654 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5655 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5656 				phba->cfg_enable_bg = 0;
5657 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5658 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5659 						"0443 Adapter did not grant "
5660 						"BlockGuard\n");
5661 			}
5662 		}
5663 	} else {
5664 		phba->hbq_get = NULL;
5665 		phba->port_gp = phba->mbox->us.s2.port;
5666 		phba->max_vpi = 0;
5667 	}
5668 do_prep_failed:
5669 	mempool_free(pmb, phba->mbox_mem_pool);
5670 	return rc;
5671 }
5672 
5673 
5674 /**
5675  * lpfc_sli_hba_setup - SLI initialization function
5676  * @phba: Pointer to HBA context object.
5677  *
5678  * This function is the main SLI initialization function. This function
5679  * is called by the HBA initialization code, HBA reset code and HBA
5680  * error attention handler code. Caller is not required to hold any
5681  * locks. This function issues config_port mailbox command to configure
5682  * the SLI, setup iocb rings and HBQ rings. In the end the function
5683  * calls the config_port_post function to issue init_link mailbox
5684  * command and to start the discovery. The function will return zero
5685  * if successful, else it will return negative error code.
5686  **/
5687 int
5688 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5689 {
5690 	uint32_t rc;
5691 	int  i;
5692 	int longs;
5693 
5694 	/* Enable ISR already does config_port because of config_msi mbx */
5695 	if (test_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag)) {
5696 		rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5697 		if (rc)
5698 			return -EIO;
5699 		clear_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
5700 	}
5701 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5702 
5703 	if (phba->sli_rev == 3) {
5704 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5705 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5706 	} else {
5707 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5708 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5709 		phba->sli3_options = 0;
5710 	}
5711 
5712 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5713 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5714 			phba->sli_rev, phba->max_vpi);
5715 	rc = lpfc_sli_ring_map(phba);
5716 
5717 	if (rc)
5718 		goto lpfc_sli_hba_setup_error;
5719 
5720 	/* Initialize VPIs. */
5721 	if (phba->sli_rev == LPFC_SLI_REV3) {
5722 		/*
5723 		 * The VPI bitmask and physical ID array are allocated
5724 		 * and initialized once only - at driver load.  A port
5725 		 * reset doesn't need to reinitialize this memory.
5726 		 */
5727 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5728 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5729 			phba->vpi_bmask = kcalloc(longs,
5730 						  sizeof(unsigned long),
5731 						  GFP_KERNEL);
5732 			if (!phba->vpi_bmask) {
5733 				rc = -ENOMEM;
5734 				goto lpfc_sli_hba_setup_error;
5735 			}
5736 
5737 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5738 						sizeof(uint16_t),
5739 						GFP_KERNEL);
5740 			if (!phba->vpi_ids) {
5741 				kfree(phba->vpi_bmask);
5742 				rc = -ENOMEM;
5743 				goto lpfc_sli_hba_setup_error;
5744 			}
5745 			for (i = 0; i < phba->max_vpi; i++)
5746 				phba->vpi_ids[i] = i;
5747 		}
5748 	}
5749 
5750 	/* Init HBQs */
5751 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5752 		rc = lpfc_sli_hbq_setup(phba);
5753 		if (rc)
5754 			goto lpfc_sli_hba_setup_error;
5755 	}
5756 	spin_lock_irq(&phba->hbalock);
5757 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5758 	spin_unlock_irq(&phba->hbalock);
5759 
5760 	rc = lpfc_config_port_post(phba);
5761 	if (rc)
5762 		goto lpfc_sli_hba_setup_error;
5763 
5764 	return rc;
5765 
5766 lpfc_sli_hba_setup_error:
5767 	phba->link_state = LPFC_HBA_ERROR;
5768 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5769 			"0445 Firmware initialization failed\n");
5770 	return rc;
5771 }
5772 
5773 /**
5774  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5775  * @phba: Pointer to HBA context object.
5776  *
5777  * This function issue a dump mailbox command to read config region
5778  * 23 and parse the records in the region and populate driver
5779  * data structure.
5780  **/
5781 static int
5782 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5783 {
5784 	LPFC_MBOXQ_t *mboxq;
5785 	struct lpfc_dmabuf *mp;
5786 	struct lpfc_mqe *mqe;
5787 	uint32_t data_length;
5788 	int rc;
5789 
5790 	/* Program the default value of vlan_id and fc_map */
5791 	phba->valid_vlan = 0;
5792 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5793 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5794 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5795 
5796 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5797 	if (!mboxq)
5798 		return -ENOMEM;
5799 
5800 	mqe = &mboxq->u.mqe;
5801 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5802 		rc = -ENOMEM;
5803 		goto out_free_mboxq;
5804 	}
5805 
5806 	mp = mboxq->ctx_buf;
5807 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5808 
5809 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5810 			"(%d):2571 Mailbox cmd x%x Status x%x "
5811 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5812 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5813 			"CQ: x%x x%x x%x x%x\n",
5814 			mboxq->vport ? mboxq->vport->vpi : 0,
5815 			bf_get(lpfc_mqe_command, mqe),
5816 			bf_get(lpfc_mqe_status, mqe),
5817 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5818 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5819 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5820 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5821 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5822 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5823 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5824 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5825 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5826 			mboxq->mcqe.word0,
5827 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5828 			mboxq->mcqe.trailer);
5829 
5830 	if (rc) {
5831 		rc = -EIO;
5832 		goto out_free_mboxq;
5833 	}
5834 	data_length = mqe->un.mb_words[5];
5835 	if (data_length > DMP_RGN23_SIZE) {
5836 		rc = -EIO;
5837 		goto out_free_mboxq;
5838 	}
5839 
5840 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5841 	rc = 0;
5842 
5843 out_free_mboxq:
5844 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
5845 	return rc;
5846 }
5847 
5848 /**
5849  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5850  * @phba: pointer to lpfc hba data structure.
5851  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5852  * @vpd: pointer to the memory to hold resulting port vpd data.
5853  * @vpd_size: On input, the number of bytes allocated to @vpd.
5854  *	      On output, the number of data bytes in @vpd.
5855  *
5856  * This routine executes a READ_REV SLI4 mailbox command.  In
5857  * addition, this routine gets the port vpd data.
5858  *
5859  * Return codes
5860  * 	0 - successful
5861  * 	-ENOMEM - could not allocated memory.
5862  **/
5863 static int
5864 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5865 		    uint8_t *vpd, uint32_t *vpd_size)
5866 {
5867 	int rc = 0;
5868 	uint32_t dma_size;
5869 	struct lpfc_dmabuf *dmabuf;
5870 	struct lpfc_mqe *mqe;
5871 
5872 	dmabuf = kzalloc_obj(struct lpfc_dmabuf);
5873 	if (!dmabuf)
5874 		return -ENOMEM;
5875 
5876 	/*
5877 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5878 	 * mailbox command.
5879 	 */
5880 	dma_size = *vpd_size;
5881 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5882 					  &dmabuf->phys, GFP_KERNEL);
5883 	if (!dmabuf->virt) {
5884 		kfree(dmabuf);
5885 		return -ENOMEM;
5886 	}
5887 
5888 	/*
5889 	 * The SLI4 implementation of READ_REV conflicts at word1,
5890 	 * bits 31:16 and SLI4 adds vpd functionality not present
5891 	 * in SLI3.  This code corrects the conflicts.
5892 	 */
5893 	lpfc_read_rev(phba, mboxq);
5894 	mqe = &mboxq->u.mqe;
5895 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5896 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5897 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5898 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5899 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5900 
5901 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5902 	if (rc) {
5903 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5904 				  dmabuf->virt, dmabuf->phys);
5905 		kfree(dmabuf);
5906 		return -EIO;
5907 	}
5908 
5909 	/*
5910 	 * The available vpd length cannot be bigger than the
5911 	 * DMA buffer passed to the port.  Catch the less than
5912 	 * case and update the caller's size.
5913 	 */
5914 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5915 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5916 
5917 	memcpy(vpd, dmabuf->virt, *vpd_size);
5918 
5919 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5920 			  dmabuf->virt, dmabuf->phys);
5921 	kfree(dmabuf);
5922 	return 0;
5923 }
5924 
5925 /**
5926  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5927  * @phba: pointer to lpfc hba data structure.
5928  *
5929  * This routine retrieves SLI4 device physical port name this PCI function
5930  * is attached to.
5931  *
5932  * Return codes
5933  *      0 - successful
5934  *      otherwise - failed to retrieve controller attributes
5935  **/
5936 static int
5937 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5938 {
5939 	LPFC_MBOXQ_t *mboxq;
5940 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5941 	struct lpfc_controller_attribute *cntl_attr;
5942 	void *virtaddr = NULL;
5943 	uint32_t alloclen, reqlen;
5944 	uint32_t shdr_status, shdr_add_status;
5945 	union lpfc_sli4_cfg_shdr *shdr;
5946 	int rc;
5947 
5948 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5949 	if (!mboxq)
5950 		return -ENOMEM;
5951 
5952 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5953 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5954 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5955 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5956 			LPFC_SLI4_MBX_NEMBED);
5957 
5958 	if (alloclen < reqlen) {
5959 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5960 				"3084 Allocated DMA memory size (%d) is "
5961 				"less than the requested DMA memory size "
5962 				"(%d)\n", alloclen, reqlen);
5963 		rc = -ENOMEM;
5964 		goto out_free_mboxq;
5965 	}
5966 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5967 	virtaddr = mboxq->sge_array->addr[0];
5968 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5969 	shdr = &mbx_cntl_attr->cfg_shdr;
5970 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5971 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5972 	if (shdr_status || shdr_add_status || rc) {
5973 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5974 				"3085 Mailbox x%x (x%x/x%x) failed, "
5975 				"rc:x%x, status:x%x, add_status:x%x\n",
5976 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5977 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5978 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5979 				rc, shdr_status, shdr_add_status);
5980 		rc = -ENXIO;
5981 		goto out_free_mboxq;
5982 	}
5983 
5984 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5985 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5986 	phba->sli4_hba.lnk_info.lnk_tp =
5987 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5988 	phba->sli4_hba.lnk_info.lnk_no =
5989 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5990 	phba->sli4_hba.flash_id = bf_get(lpfc_cntl_attr_flash_id, cntl_attr);
5991 	phba->sli4_hba.asic_rev = bf_get(lpfc_cntl_attr_asic_rev, cntl_attr);
5992 
5993 	memcpy(phba->BIOSVersion, cntl_attr->bios_ver_str,
5994 		sizeof(phba->BIOSVersion));
5995 	phba->BIOSVersion[sizeof(phba->BIOSVersion) - 1] = '\0';
5996 
5997 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5998 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s, "
5999 			"flash_id: x%02x, asic_rev: x%02x\n",
6000 			phba->sli4_hba.lnk_info.lnk_tp,
6001 			phba->sli4_hba.lnk_info.lnk_no,
6002 			phba->BIOSVersion, phba->sli4_hba.flash_id,
6003 			phba->sli4_hba.asic_rev);
6004 out_free_mboxq:
6005 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6006 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6007 	else
6008 		mempool_free(mboxq, phba->mbox_mem_pool);
6009 	return rc;
6010 }
6011 
6012 /**
6013  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
6014  * @phba: pointer to lpfc hba data structure.
6015  *
6016  * This routine retrieves SLI4 device physical port name this PCI function
6017  * is attached to.
6018  *
6019  * Return codes
6020  *      0 - successful
6021  *      otherwise - failed to retrieve physical port name
6022  **/
6023 static int
6024 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
6025 {
6026 	LPFC_MBOXQ_t *mboxq;
6027 	struct lpfc_mbx_get_port_name *get_port_name;
6028 	uint32_t shdr_status, shdr_add_status;
6029 	union lpfc_sli4_cfg_shdr *shdr;
6030 	char cport_name = 0;
6031 	int rc;
6032 
6033 	/* We assume nothing at this point */
6034 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6035 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
6036 
6037 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6038 	if (!mboxq)
6039 		return -ENOMEM;
6040 	/* obtain link type and link number via READ_CONFIG */
6041 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6042 	lpfc_sli4_read_config(phba);
6043 
6044 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG)
6045 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
6046 
6047 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
6048 		goto retrieve_ppname;
6049 
6050 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
6051 	rc = lpfc_sli4_get_ctl_attr(phba);
6052 	if (rc)
6053 		goto out_free_mboxq;
6054 
6055 retrieve_ppname:
6056 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
6057 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
6058 		sizeof(struct lpfc_mbx_get_port_name) -
6059 		sizeof(struct lpfc_sli4_cfg_mhdr),
6060 		LPFC_SLI4_MBX_EMBED);
6061 	get_port_name = &mboxq->u.mqe.un.get_port_name;
6062 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
6063 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
6064 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
6065 		phba->sli4_hba.lnk_info.lnk_tp);
6066 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6067 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6068 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6069 	if (shdr_status || shdr_add_status || rc) {
6070 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6071 				"3087 Mailbox x%x (x%x/x%x) failed: "
6072 				"rc:x%x, status:x%x, add_status:x%x\n",
6073 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6074 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6075 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6076 				rc, shdr_status, shdr_add_status);
6077 		rc = -ENXIO;
6078 		goto out_free_mboxq;
6079 	}
6080 	switch (phba->sli4_hba.lnk_info.lnk_no) {
6081 	case LPFC_LINK_NUMBER_0:
6082 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
6083 				&get_port_name->u.response);
6084 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6085 		break;
6086 	case LPFC_LINK_NUMBER_1:
6087 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
6088 				&get_port_name->u.response);
6089 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6090 		break;
6091 	case LPFC_LINK_NUMBER_2:
6092 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
6093 				&get_port_name->u.response);
6094 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6095 		break;
6096 	case LPFC_LINK_NUMBER_3:
6097 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
6098 				&get_port_name->u.response);
6099 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6100 		break;
6101 	default:
6102 		break;
6103 	}
6104 
6105 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
6106 		phba->Port[0] = cport_name;
6107 		phba->Port[1] = '\0';
6108 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6109 				"3091 SLI get port name: %s\n", phba->Port);
6110 	}
6111 
6112 out_free_mboxq:
6113 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6114 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6115 	else
6116 		mempool_free(mboxq, phba->mbox_mem_pool);
6117 	return rc;
6118 }
6119 
6120 /**
6121  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
6122  * @phba: pointer to lpfc hba data structure.
6123  *
6124  * This routine is called to explicitly arm the SLI4 device's completion and
6125  * event queues
6126  **/
6127 static void
6128 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
6129 {
6130 	int qidx;
6131 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
6132 	struct lpfc_sli4_hdw_queue *qp;
6133 	struct lpfc_queue *eq;
6134 
6135 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
6136 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
6137 	if (sli4_hba->nvmels_cq)
6138 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
6139 					   LPFC_QUEUE_REARM);
6140 
6141 	if (sli4_hba->hdwq) {
6142 		/* Loop thru all Hardware Queues */
6143 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
6144 			qp = &sli4_hba->hdwq[qidx];
6145 			/* ARM the corresponding CQ */
6146 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
6147 						LPFC_QUEUE_REARM);
6148 		}
6149 
6150 		/* Loop thru all IRQ vectors */
6151 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
6152 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
6153 			/* ARM the corresponding EQ */
6154 			sli4_hba->sli4_write_eq_db(phba, eq,
6155 						   0, LPFC_QUEUE_REARM);
6156 		}
6157 	}
6158 
6159 	if (phba->nvmet_support) {
6160 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
6161 			sli4_hba->sli4_write_cq_db(phba,
6162 				sli4_hba->nvmet_cqset[qidx], 0,
6163 				LPFC_QUEUE_REARM);
6164 		}
6165 	}
6166 }
6167 
6168 /**
6169  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
6170  * @phba: Pointer to HBA context object.
6171  * @type: The resource extent type.
6172  * @extnt_count: buffer to hold port available extent count.
6173  * @extnt_size: buffer to hold element count per extent.
6174  *
6175  * This function calls the port and retrievs the number of available
6176  * extents and their size for a particular extent type.
6177  *
6178  * Returns: 0 if successful.  Nonzero otherwise.
6179  **/
6180 int
6181 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
6182 			       uint16_t *extnt_count, uint16_t *extnt_size)
6183 {
6184 	int rc = 0;
6185 	uint32_t length;
6186 	uint32_t mbox_tmo;
6187 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
6188 	LPFC_MBOXQ_t *mbox;
6189 
6190 	*extnt_count = 0;
6191 	*extnt_size = 0;
6192 
6193 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6194 	if (!mbox)
6195 		return -ENOMEM;
6196 
6197 	/* Find out how many extents are available for this resource type */
6198 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
6199 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6200 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6201 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
6202 			 length, LPFC_SLI4_MBX_EMBED);
6203 
6204 	/* Send an extents count of 0 - the GET doesn't use it. */
6205 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6206 					LPFC_SLI4_MBX_EMBED);
6207 	if (unlikely(rc)) {
6208 		rc = -EIO;
6209 		goto err_exit;
6210 	}
6211 
6212 	if (!phba->sli4_hba.intr_enable)
6213 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6214 	else {
6215 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6216 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6217 	}
6218 	if (unlikely(rc)) {
6219 		rc = -EIO;
6220 		goto err_exit;
6221 	}
6222 
6223 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
6224 	if (bf_get(lpfc_mbox_hdr_status,
6225 		   &rsrc_info->header.cfg_shdr.response)) {
6226 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6227 				"2930 Failed to get resource extents "
6228 				"Status 0x%x Add'l Status 0x%x\n",
6229 				bf_get(lpfc_mbox_hdr_status,
6230 				       &rsrc_info->header.cfg_shdr.response),
6231 				bf_get(lpfc_mbox_hdr_add_status,
6232 				       &rsrc_info->header.cfg_shdr.response));
6233 		rc = -EIO;
6234 		goto err_exit;
6235 	}
6236 
6237 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
6238 			      &rsrc_info->u.rsp);
6239 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
6240 			     &rsrc_info->u.rsp);
6241 
6242 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6243 			"3162 Retrieved extents type-%d from port: count:%d, "
6244 			"size:%d\n", type, *extnt_count, *extnt_size);
6245 
6246 err_exit:
6247 	mempool_free(mbox, phba->mbox_mem_pool);
6248 	return rc;
6249 }
6250 
6251 /**
6252  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
6253  * @phba: Pointer to HBA context object.
6254  * @type: The extent type to check.
6255  *
6256  * This function reads the current available extents from the port and checks
6257  * if the extent count or extent size has changed since the last access.
6258  * Callers use this routine post port reset to understand if there is a
6259  * extent reprovisioning requirement.
6260  *
6261  * Returns:
6262  *   -Error: error indicates problem.
6263  *   1: Extent count or size has changed.
6264  *   0: No changes.
6265  **/
6266 static int
6267 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
6268 {
6269 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
6270 	uint16_t size_diff, rsrc_ext_size;
6271 	int rc = 0;
6272 	struct lpfc_rsrc_blks *rsrc_entry;
6273 	struct list_head *rsrc_blk_list = NULL;
6274 
6275 	size_diff = 0;
6276 	curr_ext_cnt = 0;
6277 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6278 					    &rsrc_ext_cnt,
6279 					    &rsrc_ext_size);
6280 	if (unlikely(rc))
6281 		return -EIO;
6282 
6283 	switch (type) {
6284 	case LPFC_RSC_TYPE_FCOE_RPI:
6285 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6286 		break;
6287 	case LPFC_RSC_TYPE_FCOE_VPI:
6288 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
6289 		break;
6290 	case LPFC_RSC_TYPE_FCOE_XRI:
6291 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6292 		break;
6293 	case LPFC_RSC_TYPE_FCOE_VFI:
6294 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6295 		break;
6296 	default:
6297 		break;
6298 	}
6299 
6300 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
6301 		curr_ext_cnt++;
6302 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
6303 			size_diff++;
6304 	}
6305 
6306 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
6307 		rc = 1;
6308 
6309 	return rc;
6310 }
6311 
6312 /**
6313  * lpfc_sli4_cfg_post_extnts -
6314  * @phba: Pointer to HBA context object.
6315  * @extnt_cnt: number of available extents.
6316  * @type: the extent type (rpi, xri, vfi, vpi).
6317  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
6318  * @mbox: pointer to the caller's allocated mailbox structure.
6319  *
6320  * This function executes the extents allocation request.  It also
6321  * takes care of the amount of memory needed to allocate or get the
6322  * allocated extents. It is the caller's responsibility to evaluate
6323  * the response.
6324  *
6325  * Returns:
6326  *   -Error:  Error value describes the condition found.
6327  *   0: if successful
6328  **/
6329 static int
6330 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6331 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6332 {
6333 	int rc = 0;
6334 	uint32_t req_len;
6335 	uint32_t emb_len;
6336 	uint32_t alloc_len, mbox_tmo;
6337 
6338 	/* Calculate the total requested length of the dma memory */
6339 	req_len = extnt_cnt * sizeof(uint16_t);
6340 
6341 	/*
6342 	 * Calculate the size of an embedded mailbox.  The uint32_t
6343 	 * accounts for extents-specific word.
6344 	 */
6345 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6346 		sizeof(uint32_t);
6347 
6348 	/*
6349 	 * Presume the allocation and response will fit into an embedded
6350 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6351 	 */
6352 	*emb = LPFC_SLI4_MBX_EMBED;
6353 	if (req_len > emb_len) {
6354 		req_len = extnt_cnt * sizeof(uint16_t) +
6355 			sizeof(union lpfc_sli4_cfg_shdr) +
6356 			sizeof(uint32_t);
6357 		*emb = LPFC_SLI4_MBX_NEMBED;
6358 	}
6359 
6360 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6361 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6362 				     req_len, *emb);
6363 	if (alloc_len < req_len) {
6364 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6365 			"2982 Allocated DMA memory size (x%x) is "
6366 			"less than the requested DMA memory "
6367 			"size (x%x)\n", alloc_len, req_len);
6368 		return -ENOMEM;
6369 	}
6370 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6371 	if (unlikely(rc))
6372 		return -EIO;
6373 
6374 	if (!phba->sli4_hba.intr_enable)
6375 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6376 	else {
6377 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6378 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6379 	}
6380 
6381 	if (unlikely(rc))
6382 		rc = -EIO;
6383 	return rc;
6384 }
6385 
6386 /**
6387  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6388  * @phba: Pointer to HBA context object.
6389  * @type:  The resource extent type to allocate.
6390  *
6391  * This function allocates the number of elements for the specified
6392  * resource type.
6393  **/
6394 static int
6395 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6396 {
6397 	bool emb = false;
6398 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6399 	uint16_t rsrc_id, rsrc_start, j, k;
6400 	uint16_t *ids;
6401 	int i, rc;
6402 	unsigned long longs;
6403 	unsigned long *bmask;
6404 	struct lpfc_rsrc_blks *rsrc_blks;
6405 	LPFC_MBOXQ_t *mbox;
6406 	uint32_t length;
6407 	struct lpfc_id_range *id_array = NULL;
6408 	void *virtaddr = NULL;
6409 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6410 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6411 	struct list_head *ext_blk_list;
6412 
6413 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6414 					    &rsrc_cnt,
6415 					    &rsrc_size);
6416 	if (unlikely(rc))
6417 		return -EIO;
6418 
6419 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6420 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6421 			"3009 No available Resource Extents "
6422 			"for resource type 0x%x: Count: 0x%x, "
6423 			"Size 0x%x\n", type, rsrc_cnt,
6424 			rsrc_size);
6425 		return -ENOMEM;
6426 	}
6427 
6428 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6429 			"2903 Post resource extents type-0x%x: "
6430 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6431 
6432 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6433 	if (!mbox)
6434 		return -ENOMEM;
6435 
6436 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6437 	if (unlikely(rc)) {
6438 		rc = -EIO;
6439 		goto err_exit;
6440 	}
6441 
6442 	/*
6443 	 * Figure out where the response is located.  Then get local pointers
6444 	 * to the response data.  The port does not guarantee to respond to
6445 	 * all extents counts request so update the local variable with the
6446 	 * allocated count from the port.
6447 	 */
6448 	if (emb == LPFC_SLI4_MBX_EMBED) {
6449 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6450 		id_array = &rsrc_ext->u.rsp.id[0];
6451 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6452 	} else {
6453 		virtaddr = mbox->sge_array->addr[0];
6454 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6455 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6456 		id_array = &n_rsrc->id;
6457 	}
6458 
6459 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6460 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6461 
6462 	/*
6463 	 * Based on the resource size and count, correct the base and max
6464 	 * resource values.
6465 	 */
6466 	length = sizeof(struct lpfc_rsrc_blks);
6467 	switch (type) {
6468 	case LPFC_RSC_TYPE_FCOE_RPI:
6469 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6470 						   sizeof(unsigned long),
6471 						   GFP_KERNEL);
6472 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6473 			rc = -ENOMEM;
6474 			goto err_exit;
6475 		}
6476 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6477 						 sizeof(uint16_t),
6478 						 GFP_KERNEL);
6479 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6480 			kfree(phba->sli4_hba.rpi_bmask);
6481 			rc = -ENOMEM;
6482 			goto err_exit;
6483 		}
6484 
6485 		/*
6486 		 * The next_rpi was initialized with the maximum available
6487 		 * count but the port may allocate a smaller number.  Catch
6488 		 * that case and update the next_rpi.
6489 		 */
6490 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6491 
6492 		/* Initialize local ptrs for common extent processing later. */
6493 		bmask = phba->sli4_hba.rpi_bmask;
6494 		ids = phba->sli4_hba.rpi_ids;
6495 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6496 		break;
6497 	case LPFC_RSC_TYPE_FCOE_VPI:
6498 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6499 					  GFP_KERNEL);
6500 		if (unlikely(!phba->vpi_bmask)) {
6501 			rc = -ENOMEM;
6502 			goto err_exit;
6503 		}
6504 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6505 					 GFP_KERNEL);
6506 		if (unlikely(!phba->vpi_ids)) {
6507 			kfree(phba->vpi_bmask);
6508 			rc = -ENOMEM;
6509 			goto err_exit;
6510 		}
6511 
6512 		/* Initialize local ptrs for common extent processing later. */
6513 		bmask = phba->vpi_bmask;
6514 		ids = phba->vpi_ids;
6515 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6516 		break;
6517 	case LPFC_RSC_TYPE_FCOE_XRI:
6518 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6519 						   sizeof(unsigned long),
6520 						   GFP_KERNEL);
6521 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6522 			rc = -ENOMEM;
6523 			goto err_exit;
6524 		}
6525 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6526 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6527 						 sizeof(uint16_t),
6528 						 GFP_KERNEL);
6529 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6530 			kfree(phba->sli4_hba.xri_bmask);
6531 			rc = -ENOMEM;
6532 			goto err_exit;
6533 		}
6534 
6535 		/* Initialize local ptrs for common extent processing later. */
6536 		bmask = phba->sli4_hba.xri_bmask;
6537 		ids = phba->sli4_hba.xri_ids;
6538 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6539 		break;
6540 	case LPFC_RSC_TYPE_FCOE_VFI:
6541 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6542 						   sizeof(unsigned long),
6543 						   GFP_KERNEL);
6544 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6545 			rc = -ENOMEM;
6546 			goto err_exit;
6547 		}
6548 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6549 						 sizeof(uint16_t),
6550 						 GFP_KERNEL);
6551 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6552 			kfree(phba->sli4_hba.vfi_bmask);
6553 			rc = -ENOMEM;
6554 			goto err_exit;
6555 		}
6556 
6557 		/* Initialize local ptrs for common extent processing later. */
6558 		bmask = phba->sli4_hba.vfi_bmask;
6559 		ids = phba->sli4_hba.vfi_ids;
6560 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6561 		break;
6562 	default:
6563 		/* Unsupported Opcode.  Fail call. */
6564 		id_array = NULL;
6565 		bmask = NULL;
6566 		ids = NULL;
6567 		ext_blk_list = NULL;
6568 		goto err_exit;
6569 	}
6570 
6571 	/*
6572 	 * Complete initializing the extent configuration with the
6573 	 * allocated ids assigned to this function.  The bitmask serves
6574 	 * as an index into the array and manages the available ids.  The
6575 	 * array just stores the ids communicated to the port via the wqes.
6576 	 */
6577 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6578 		if ((i % 2) == 0)
6579 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6580 					 &id_array[k]);
6581 		else
6582 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6583 					 &id_array[k]);
6584 
6585 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6586 		if (unlikely(!rsrc_blks)) {
6587 			rc = -ENOMEM;
6588 			kfree(bmask);
6589 			kfree(ids);
6590 			goto err_exit;
6591 		}
6592 		rsrc_blks->rsrc_start = rsrc_id;
6593 		rsrc_blks->rsrc_size = rsrc_size;
6594 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6595 		rsrc_start = rsrc_id;
6596 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6597 			phba->sli4_hba.io_xri_start = rsrc_start +
6598 				lpfc_sli4_get_iocb_cnt(phba);
6599 		}
6600 
6601 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6602 			ids[j] = rsrc_id;
6603 			rsrc_id++;
6604 			j++;
6605 		}
6606 		/* Entire word processed.  Get next word.*/
6607 		if ((i % 2) == 1)
6608 			k++;
6609 	}
6610  err_exit:
6611 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6612 	return rc;
6613 }
6614 
6615 
6616 
6617 /**
6618  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6619  * @phba: Pointer to HBA context object.
6620  * @type: the extent's type.
6621  *
6622  * This function deallocates all extents of a particular resource type.
6623  * SLI4 does not allow for deallocating a particular extent range.  It
6624  * is the caller's responsibility to release all kernel memory resources.
6625  **/
6626 static int
6627 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6628 {
6629 	int rc;
6630 	uint32_t length, mbox_tmo = 0;
6631 	LPFC_MBOXQ_t *mbox;
6632 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6633 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6634 
6635 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6636 	if (!mbox)
6637 		return -ENOMEM;
6638 
6639 	/*
6640 	 * This function sends an embedded mailbox because it only sends the
6641 	 * the resource type.  All extents of this type are released by the
6642 	 * port.
6643 	 */
6644 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6645 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6646 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6647 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6648 			 length, LPFC_SLI4_MBX_EMBED);
6649 
6650 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6651 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6652 					LPFC_SLI4_MBX_EMBED);
6653 	if (unlikely(rc)) {
6654 		rc = -EIO;
6655 		goto out_free_mbox;
6656 	}
6657 	if (!phba->sli4_hba.intr_enable)
6658 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6659 	else {
6660 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6661 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6662 	}
6663 	if (unlikely(rc)) {
6664 		rc = -EIO;
6665 		goto out_free_mbox;
6666 	}
6667 
6668 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6669 	if (bf_get(lpfc_mbox_hdr_status,
6670 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6671 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6672 				"2919 Failed to release resource extents "
6673 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6674 				"Resource memory not released.\n",
6675 				type,
6676 				bf_get(lpfc_mbox_hdr_status,
6677 				    &dealloc_rsrc->header.cfg_shdr.response),
6678 				bf_get(lpfc_mbox_hdr_add_status,
6679 				    &dealloc_rsrc->header.cfg_shdr.response));
6680 		rc = -EIO;
6681 		goto out_free_mbox;
6682 	}
6683 
6684 	/* Release kernel memory resources for the specific type. */
6685 	switch (type) {
6686 	case LPFC_RSC_TYPE_FCOE_VPI:
6687 		kfree(phba->vpi_bmask);
6688 		kfree(phba->vpi_ids);
6689 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6690 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6691 				    &phba->lpfc_vpi_blk_list, list) {
6692 			list_del_init(&rsrc_blk->list);
6693 			kfree(rsrc_blk);
6694 		}
6695 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6696 		break;
6697 	case LPFC_RSC_TYPE_FCOE_XRI:
6698 		kfree(phba->sli4_hba.xri_bmask);
6699 		kfree(phba->sli4_hba.xri_ids);
6700 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6701 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6702 			list_del_init(&rsrc_blk->list);
6703 			kfree(rsrc_blk);
6704 		}
6705 		break;
6706 	case LPFC_RSC_TYPE_FCOE_VFI:
6707 		kfree(phba->sli4_hba.vfi_bmask);
6708 		kfree(phba->sli4_hba.vfi_ids);
6709 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6710 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6711 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6712 			list_del_init(&rsrc_blk->list);
6713 			kfree(rsrc_blk);
6714 		}
6715 		break;
6716 	case LPFC_RSC_TYPE_FCOE_RPI:
6717 		/* RPI bitmask and physical id array are cleaned up earlier. */
6718 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6719 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6720 			list_del_init(&rsrc_blk->list);
6721 			kfree(rsrc_blk);
6722 		}
6723 		break;
6724 	default:
6725 		break;
6726 	}
6727 
6728 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6729 
6730  out_free_mbox:
6731 	mempool_free(mbox, phba->mbox_mem_pool);
6732 	return rc;
6733 }
6734 
6735 static void
6736 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6737 		  uint32_t feature)
6738 {
6739 	uint32_t len;
6740 	u32 sig_freq = 0;
6741 
6742 	len = sizeof(struct lpfc_mbx_set_feature) -
6743 		sizeof(struct lpfc_sli4_cfg_mhdr);
6744 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6745 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6746 			 LPFC_SLI4_MBX_EMBED);
6747 
6748 	switch (feature) {
6749 	case LPFC_SET_UE_RECOVERY:
6750 		bf_set(lpfc_mbx_set_feature_UER,
6751 		       &mbox->u.mqe.un.set_feature, 1);
6752 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6753 		mbox->u.mqe.un.set_feature.param_len = 8;
6754 		break;
6755 	case LPFC_SET_MDS_DIAGS:
6756 		bf_set(lpfc_mbx_set_feature_mds,
6757 		       &mbox->u.mqe.un.set_feature, 1);
6758 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6759 		       &mbox->u.mqe.un.set_feature, 1);
6760 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6761 		mbox->u.mqe.un.set_feature.param_len = 8;
6762 		break;
6763 	case LPFC_SET_CGN_SIGNAL:
6764 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6765 			sig_freq = 0;
6766 		else
6767 			sig_freq = phba->cgn_sig_freq;
6768 
6769 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6770 			bf_set(lpfc_mbx_set_feature_CGN_alarm_freq,
6771 			       &mbox->u.mqe.un.set_feature, sig_freq);
6772 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6773 			       &mbox->u.mqe.un.set_feature, sig_freq);
6774 		}
6775 
6776 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY)
6777 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6778 			       &mbox->u.mqe.un.set_feature, sig_freq);
6779 
6780 		if (phba->cmf_active_mode == LPFC_CFG_OFF ||
6781 		    phba->cgn_reg_signal == EDC_CG_SIG_NOTSUPPORTED)
6782 			sig_freq = 0;
6783 		else
6784 			sig_freq = lpfc_acqe_cgn_frequency;
6785 
6786 		bf_set(lpfc_mbx_set_feature_CGN_acqe_freq,
6787 		       &mbox->u.mqe.un.set_feature, sig_freq);
6788 
6789 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_CGN_SIGNAL;
6790 		mbox->u.mqe.un.set_feature.param_len = 12;
6791 		break;
6792 	case LPFC_SET_DUAL_DUMP:
6793 		bf_set(lpfc_mbx_set_feature_dd,
6794 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6795 		bf_set(lpfc_mbx_set_feature_ddquery,
6796 		       &mbox->u.mqe.un.set_feature, 0);
6797 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6798 		mbox->u.mqe.un.set_feature.param_len = 4;
6799 		break;
6800 	case LPFC_SET_ENABLE_MI:
6801 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_MI;
6802 		mbox->u.mqe.un.set_feature.param_len = 4;
6803 		bf_set(lpfc_mbx_set_feature_milunq, &mbox->u.mqe.un.set_feature,
6804 		       phba->pport->cfg_lun_queue_depth);
6805 		bf_set(lpfc_mbx_set_feature_mi, &mbox->u.mqe.un.set_feature,
6806 		       phba->sli4_hba.pc_sli4_params.mi_ver);
6807 		break;
6808 	case LPFC_SET_LD_SIGNAL:
6809 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_LD_SIGNAL;
6810 		mbox->u.mqe.un.set_feature.param_len = 16;
6811 		bf_set(lpfc_mbx_set_feature_lds_qry,
6812 		       &mbox->u.mqe.un.set_feature, LPFC_QUERY_LDS_OP);
6813 		break;
6814 	case LPFC_SET_ENABLE_CMF:
6815 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_CMF;
6816 		mbox->u.mqe.un.set_feature.param_len = 4;
6817 		bf_set(lpfc_mbx_set_feature_cmf,
6818 		       &mbox->u.mqe.un.set_feature, 1);
6819 		break;
6820 	}
6821 	return;
6822 }
6823 
6824 /**
6825  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6826  * @phba: Pointer to HBA context object.
6827  *
6828  * Disable FW logging into host memory on the adapter. To
6829  * be done before reading logs from the host memory.
6830  **/
6831 void
6832 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6833 {
6834 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6835 
6836 	spin_lock_irq(&phba->ras_fwlog_lock);
6837 	ras_fwlog->state = INACTIVE;
6838 	spin_unlock_irq(&phba->ras_fwlog_lock);
6839 
6840 	/* Disable FW logging to host memory */
6841 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6842 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6843 
6844 	/* Wait 10ms for firmware to stop using DMA buffer */
6845 	usleep_range(10 * 1000, 20 * 1000);
6846 }
6847 
6848 /**
6849  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6850  * @phba: Pointer to HBA context object.
6851  *
6852  * This function is called to free memory allocated for RAS FW logging
6853  * support in the driver.
6854  **/
6855 void
6856 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6857 {
6858 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6859 	struct lpfc_dmabuf *dmabuf, *next;
6860 
6861 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6862 		list_for_each_entry_safe(dmabuf, next,
6863 				    &ras_fwlog->fwlog_buff_list,
6864 				    list) {
6865 			list_del(&dmabuf->list);
6866 			dma_free_coherent(&phba->pcidev->dev,
6867 					  LPFC_RAS_MAX_ENTRY_SIZE,
6868 					  dmabuf->virt, dmabuf->phys);
6869 			kfree(dmabuf);
6870 		}
6871 	}
6872 
6873 	if (ras_fwlog->lwpd.virt) {
6874 		dma_free_coherent(&phba->pcidev->dev,
6875 				  sizeof(uint32_t) * 2,
6876 				  ras_fwlog->lwpd.virt,
6877 				  ras_fwlog->lwpd.phys);
6878 		ras_fwlog->lwpd.virt = NULL;
6879 	}
6880 
6881 	spin_lock_irq(&phba->ras_fwlog_lock);
6882 	ras_fwlog->state = INACTIVE;
6883 	spin_unlock_irq(&phba->ras_fwlog_lock);
6884 }
6885 
6886 /**
6887  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6888  * @phba: Pointer to HBA context object.
6889  * @fwlog_buff_count: Count of buffers to be created.
6890  *
6891  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6892  * to update FW log is posted to the adapter.
6893  * Buffer count is calculated based on module param ras_fwlog_buffsize
6894  * Size of each buffer posted to FW is 64K.
6895  **/
6896 
6897 static int
6898 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6899 			uint32_t fwlog_buff_count)
6900 {
6901 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6902 	struct lpfc_dmabuf *dmabuf;
6903 	int rc = 0, i = 0;
6904 
6905 	/* Initialize List */
6906 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6907 
6908 	/* Allocate memory for the LWPD */
6909 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6910 					    sizeof(uint32_t) * 2,
6911 					    &ras_fwlog->lwpd.phys,
6912 					    GFP_KERNEL);
6913 	if (!ras_fwlog->lwpd.virt) {
6914 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6915 				"6185 LWPD Memory Alloc Failed\n");
6916 
6917 		return -ENOMEM;
6918 	}
6919 
6920 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6921 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6922 		dmabuf = kzalloc_obj(struct lpfc_dmabuf);
6923 		if (!dmabuf) {
6924 			rc = -ENOMEM;
6925 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6926 					"6186 Memory Alloc failed FW logging");
6927 			goto free_mem;
6928 		}
6929 
6930 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6931 						  LPFC_RAS_MAX_ENTRY_SIZE,
6932 						  &dmabuf->phys, GFP_KERNEL);
6933 		if (!dmabuf->virt) {
6934 			kfree(dmabuf);
6935 			rc = -ENOMEM;
6936 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6937 					"6187 DMA Alloc Failed FW logging");
6938 			goto free_mem;
6939 		}
6940 		dmabuf->buffer_tag = i;
6941 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6942 	}
6943 
6944 free_mem:
6945 	if (rc)
6946 		lpfc_sli4_ras_dma_free(phba);
6947 
6948 	return rc;
6949 }
6950 
6951 /**
6952  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6953  * @phba: pointer to lpfc hba data structure.
6954  * @pmb: pointer to the driver internal queue element for mailbox command.
6955  *
6956  * Completion handler for driver's RAS MBX command to the device.
6957  **/
6958 static void
6959 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6960 {
6961 	MAILBOX_t *mb;
6962 	union lpfc_sli4_cfg_shdr *shdr;
6963 	uint32_t shdr_status, shdr_add_status;
6964 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6965 
6966 	mb = &pmb->u.mb;
6967 
6968 	shdr = (union lpfc_sli4_cfg_shdr *)
6969 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6970 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6971 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6972 
6973 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6974 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6975 				"6188 FW LOG mailbox "
6976 				"completed with status x%x add_status x%x,"
6977 				" mbx status x%x\n",
6978 				shdr_status, shdr_add_status, mb->mbxStatus);
6979 
6980 		ras_fwlog->ras_hwsupport = false;
6981 		goto disable_ras;
6982 	}
6983 
6984 	spin_lock_irq(&phba->ras_fwlog_lock);
6985 	ras_fwlog->state = ACTIVE;
6986 	spin_unlock_irq(&phba->ras_fwlog_lock);
6987 	mempool_free(pmb, phba->mbox_mem_pool);
6988 
6989 	return;
6990 
6991 disable_ras:
6992 	/* Free RAS DMA memory */
6993 	lpfc_sli4_ras_dma_free(phba);
6994 	mempool_free(pmb, phba->mbox_mem_pool);
6995 }
6996 
6997 /**
6998  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
6999  * @phba: pointer to lpfc hba data structure.
7000  * @fwlog_level: Logging verbosity level.
7001  * @fwlog_enable: Enable/Disable logging.
7002  *
7003  * Initialize memory and post mailbox command to enable FW logging in host
7004  * memory.
7005  **/
7006 int
7007 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
7008 			 uint32_t fwlog_level,
7009 			 uint32_t fwlog_enable)
7010 {
7011 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
7012 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
7013 	struct lpfc_dmabuf *dmabuf;
7014 	LPFC_MBOXQ_t *mbox;
7015 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
7016 	int rc = 0;
7017 
7018 	spin_lock_irq(&phba->ras_fwlog_lock);
7019 	ras_fwlog->state = INACTIVE;
7020 	spin_unlock_irq(&phba->ras_fwlog_lock);
7021 
7022 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
7023 			  phba->cfg_ras_fwlog_buffsize);
7024 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
7025 
7026 	/*
7027 	 * If re-enabling FW logging support use earlier allocated
7028 	 * DMA buffers while posting MBX command.
7029 	 **/
7030 	if (!ras_fwlog->lwpd.virt) {
7031 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
7032 		if (rc) {
7033 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7034 					"6189 FW Log Memory Allocation Failed");
7035 			return rc;
7036 		}
7037 	}
7038 
7039 	/* Setup Mailbox command */
7040 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7041 	if (!mbox) {
7042 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7043 				"6190 RAS MBX Alloc Failed");
7044 		rc = -ENOMEM;
7045 		goto mem_free;
7046 	}
7047 
7048 	ras_fwlog->fw_loglevel = fwlog_level;
7049 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
7050 		sizeof(struct lpfc_sli4_cfg_mhdr));
7051 
7052 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
7053 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
7054 			 len, LPFC_SLI4_MBX_EMBED);
7055 
7056 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
7057 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
7058 	       fwlog_enable);
7059 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
7060 	       ras_fwlog->fw_loglevel);
7061 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
7062 	       ras_fwlog->fw_buffcount);
7063 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
7064 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
7065 
7066 	/* Update DMA buffer address */
7067 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
7068 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
7069 
7070 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
7071 			putPaddrLow(dmabuf->phys);
7072 
7073 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
7074 			putPaddrHigh(dmabuf->phys);
7075 	}
7076 
7077 	/* Update LPWD address */
7078 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
7079 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
7080 
7081 	spin_lock_irq(&phba->ras_fwlog_lock);
7082 	ras_fwlog->state = REG_INPROGRESS;
7083 	spin_unlock_irq(&phba->ras_fwlog_lock);
7084 	mbox->vport = phba->pport;
7085 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
7086 
7087 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
7088 
7089 	if (rc == MBX_NOT_FINISHED) {
7090 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7091 				"6191 FW-Log Mailbox failed. "
7092 				"status %d mbxStatus : x%x", rc,
7093 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
7094 		mempool_free(mbox, phba->mbox_mem_pool);
7095 		rc = -EIO;
7096 		goto mem_free;
7097 	} else
7098 		rc = 0;
7099 mem_free:
7100 	if (rc)
7101 		lpfc_sli4_ras_dma_free(phba);
7102 
7103 	return rc;
7104 }
7105 
7106 /**
7107  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
7108  * @phba: Pointer to HBA context object.
7109  *
7110  * Check if RAS is supported on the adapter and initialize it.
7111  **/
7112 void
7113 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
7114 {
7115 	/* Check RAS FW Log needs to be enabled or not */
7116 	if (lpfc_check_fwlog_support(phba))
7117 		return;
7118 
7119 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
7120 				 LPFC_RAS_ENABLE_LOGGING);
7121 }
7122 
7123 /**
7124  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
7125  * @phba: Pointer to HBA context object.
7126  *
7127  * This function allocates all SLI4 resource identifiers.
7128  **/
7129 int
7130 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
7131 {
7132 	int i, rc, error = 0;
7133 	uint16_t count, base;
7134 	unsigned long longs;
7135 
7136 	if (!phba->sli4_hba.rpi_hdrs_in_use)
7137 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
7138 	if (phba->sli4_hba.extents_in_use) {
7139 		/*
7140 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
7141 		 * resource extent count must be read and allocated before
7142 		 * provisioning the resource id arrays.
7143 		 */
7144 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7145 		    LPFC_IDX_RSRC_RDY) {
7146 			/*
7147 			 * Extent-based resources are set - the driver could
7148 			 * be in a port reset. Figure out if any corrective
7149 			 * actions need to be taken.
7150 			 */
7151 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7152 						 LPFC_RSC_TYPE_FCOE_VFI);
7153 			if (rc != 0)
7154 				error++;
7155 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7156 						 LPFC_RSC_TYPE_FCOE_VPI);
7157 			if (rc != 0)
7158 				error++;
7159 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7160 						 LPFC_RSC_TYPE_FCOE_XRI);
7161 			if (rc != 0)
7162 				error++;
7163 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7164 						 LPFC_RSC_TYPE_FCOE_RPI);
7165 			if (rc != 0)
7166 				error++;
7167 
7168 			/*
7169 			 * It's possible that the number of resources
7170 			 * provided to this port instance changed between
7171 			 * resets.  Detect this condition and reallocate
7172 			 * resources.  Otherwise, there is no action.
7173 			 */
7174 			if (error) {
7175 				lpfc_printf_log(phba, KERN_INFO,
7176 						LOG_MBOX | LOG_INIT,
7177 						"2931 Detected extent resource "
7178 						"change.  Reallocating all "
7179 						"extents.\n");
7180 				rc = lpfc_sli4_dealloc_extent(phba,
7181 						 LPFC_RSC_TYPE_FCOE_VFI);
7182 				rc = lpfc_sli4_dealloc_extent(phba,
7183 						 LPFC_RSC_TYPE_FCOE_VPI);
7184 				rc = lpfc_sli4_dealloc_extent(phba,
7185 						 LPFC_RSC_TYPE_FCOE_XRI);
7186 				rc = lpfc_sli4_dealloc_extent(phba,
7187 						 LPFC_RSC_TYPE_FCOE_RPI);
7188 			} else
7189 				return 0;
7190 		}
7191 
7192 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7193 		if (unlikely(rc))
7194 			goto err_exit;
7195 
7196 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7197 		if (unlikely(rc))
7198 			goto err_exit;
7199 
7200 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7201 		if (unlikely(rc))
7202 			goto err_exit;
7203 
7204 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7205 		if (unlikely(rc))
7206 			goto err_exit;
7207 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7208 		       LPFC_IDX_RSRC_RDY);
7209 		return rc;
7210 	} else {
7211 		/*
7212 		 * The port does not support resource extents.  The XRI, VPI,
7213 		 * VFI, RPI resource ids were determined from READ_CONFIG.
7214 		 * Just allocate the bitmasks and provision the resource id
7215 		 * arrays.  If a port reset is active, the resources don't
7216 		 * need any action - just exit.
7217 		 */
7218 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7219 		    LPFC_IDX_RSRC_RDY) {
7220 			lpfc_sli4_dealloc_resource_identifiers(phba);
7221 			lpfc_sli4_remove_rpis(phba);
7222 		}
7223 		/* RPIs. */
7224 		count = phba->sli4_hba.max_cfg_param.max_rpi;
7225 		if (count <= 0) {
7226 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7227 					"3279 Invalid provisioning of "
7228 					"rpi:%d\n", count);
7229 			rc = -EINVAL;
7230 			goto err_exit;
7231 		}
7232 		base = phba->sli4_hba.max_cfg_param.rpi_base;
7233 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7234 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
7235 						   sizeof(unsigned long),
7236 						   GFP_KERNEL);
7237 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
7238 			rc = -ENOMEM;
7239 			goto err_exit;
7240 		}
7241 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
7242 						 GFP_KERNEL);
7243 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
7244 			rc = -ENOMEM;
7245 			goto free_rpi_bmask;
7246 		}
7247 
7248 		for (i = 0; i < count; i++)
7249 			phba->sli4_hba.rpi_ids[i] = base + i;
7250 
7251 		/* VPIs. */
7252 		count = phba->sli4_hba.max_cfg_param.max_vpi;
7253 		if (count <= 0) {
7254 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7255 					"3280 Invalid provisioning of "
7256 					"vpi:%d\n", count);
7257 			rc = -EINVAL;
7258 			goto free_rpi_ids;
7259 		}
7260 		base = phba->sli4_hba.max_cfg_param.vpi_base;
7261 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7262 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
7263 					  GFP_KERNEL);
7264 		if (unlikely(!phba->vpi_bmask)) {
7265 			rc = -ENOMEM;
7266 			goto free_rpi_ids;
7267 		}
7268 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
7269 					GFP_KERNEL);
7270 		if (unlikely(!phba->vpi_ids)) {
7271 			rc = -ENOMEM;
7272 			goto free_vpi_bmask;
7273 		}
7274 
7275 		for (i = 0; i < count; i++)
7276 			phba->vpi_ids[i] = base + i;
7277 
7278 		/* XRIs. */
7279 		count = phba->sli4_hba.max_cfg_param.max_xri;
7280 		if (count <= 0) {
7281 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7282 					"3281 Invalid provisioning of "
7283 					"xri:%d\n", count);
7284 			rc = -EINVAL;
7285 			goto free_vpi_ids;
7286 		}
7287 		base = phba->sli4_hba.max_cfg_param.xri_base;
7288 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7289 		phba->sli4_hba.xri_bmask = kcalloc(longs,
7290 						   sizeof(unsigned long),
7291 						   GFP_KERNEL);
7292 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
7293 			rc = -ENOMEM;
7294 			goto free_vpi_ids;
7295 		}
7296 		phba->sli4_hba.max_cfg_param.xri_used = 0;
7297 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
7298 						 GFP_KERNEL);
7299 		if (unlikely(!phba->sli4_hba.xri_ids)) {
7300 			rc = -ENOMEM;
7301 			goto free_xri_bmask;
7302 		}
7303 
7304 		for (i = 0; i < count; i++)
7305 			phba->sli4_hba.xri_ids[i] = base + i;
7306 
7307 		/* VFIs. */
7308 		count = phba->sli4_hba.max_cfg_param.max_vfi;
7309 		if (count <= 0) {
7310 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7311 					"3282 Invalid provisioning of "
7312 					"vfi:%d\n", count);
7313 			rc = -EINVAL;
7314 			goto free_xri_ids;
7315 		}
7316 		base = phba->sli4_hba.max_cfg_param.vfi_base;
7317 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7318 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
7319 						   sizeof(unsigned long),
7320 						   GFP_KERNEL);
7321 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
7322 			rc = -ENOMEM;
7323 			goto free_xri_ids;
7324 		}
7325 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
7326 						 GFP_KERNEL);
7327 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
7328 			rc = -ENOMEM;
7329 			goto free_vfi_bmask;
7330 		}
7331 
7332 		for (i = 0; i < count; i++)
7333 			phba->sli4_hba.vfi_ids[i] = base + i;
7334 
7335 		/*
7336 		 * Mark all resources ready.  An HBA reset doesn't need
7337 		 * to reset the initialization.
7338 		 */
7339 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7340 		       LPFC_IDX_RSRC_RDY);
7341 		return 0;
7342 	}
7343 
7344  free_vfi_bmask:
7345 	kfree(phba->sli4_hba.vfi_bmask);
7346 	phba->sli4_hba.vfi_bmask = NULL;
7347  free_xri_ids:
7348 	kfree(phba->sli4_hba.xri_ids);
7349 	phba->sli4_hba.xri_ids = NULL;
7350  free_xri_bmask:
7351 	kfree(phba->sli4_hba.xri_bmask);
7352 	phba->sli4_hba.xri_bmask = NULL;
7353  free_vpi_ids:
7354 	kfree(phba->vpi_ids);
7355 	phba->vpi_ids = NULL;
7356  free_vpi_bmask:
7357 	kfree(phba->vpi_bmask);
7358 	phba->vpi_bmask = NULL;
7359  free_rpi_ids:
7360 	kfree(phba->sli4_hba.rpi_ids);
7361 	phba->sli4_hba.rpi_ids = NULL;
7362  free_rpi_bmask:
7363 	kfree(phba->sli4_hba.rpi_bmask);
7364 	phba->sli4_hba.rpi_bmask = NULL;
7365  err_exit:
7366 	return rc;
7367 }
7368 
7369 /**
7370  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
7371  * @phba: Pointer to HBA context object.
7372  *
7373  * This function allocates the number of elements for the specified
7374  * resource type.
7375  **/
7376 int
7377 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7378 {
7379 	if (phba->sli4_hba.extents_in_use) {
7380 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7381 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7382 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7383 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7384 	} else {
7385 		kfree(phba->vpi_bmask);
7386 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
7387 		kfree(phba->vpi_ids);
7388 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7389 		kfree(phba->sli4_hba.xri_bmask);
7390 		kfree(phba->sli4_hba.xri_ids);
7391 		kfree(phba->sli4_hba.vfi_bmask);
7392 		kfree(phba->sli4_hba.vfi_ids);
7393 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7394 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7395 	}
7396 
7397 	return 0;
7398 }
7399 
7400 /**
7401  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7402  * @phba: Pointer to HBA context object.
7403  * @type: The resource extent type.
7404  * @extnt_cnt: buffer to hold port extent count response
7405  * @extnt_size: buffer to hold port extent size response.
7406  *
7407  * This function calls the port to read the host allocated extents
7408  * for a particular type.
7409  **/
7410 int
7411 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7412 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
7413 {
7414 	bool emb;
7415 	int rc = 0;
7416 	uint16_t curr_blks = 0;
7417 	uint32_t req_len, emb_len;
7418 	uint32_t alloc_len, mbox_tmo;
7419 	struct list_head *blk_list_head;
7420 	struct lpfc_rsrc_blks *rsrc_blk;
7421 	LPFC_MBOXQ_t *mbox;
7422 	void *virtaddr = NULL;
7423 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7424 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7425 	union  lpfc_sli4_cfg_shdr *shdr;
7426 
7427 	switch (type) {
7428 	case LPFC_RSC_TYPE_FCOE_VPI:
7429 		blk_list_head = &phba->lpfc_vpi_blk_list;
7430 		break;
7431 	case LPFC_RSC_TYPE_FCOE_XRI:
7432 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7433 		break;
7434 	case LPFC_RSC_TYPE_FCOE_VFI:
7435 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7436 		break;
7437 	case LPFC_RSC_TYPE_FCOE_RPI:
7438 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7439 		break;
7440 	default:
7441 		return -EIO;
7442 	}
7443 
7444 	/* Count the number of extents currently allocatd for this type. */
7445 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
7446 		if (curr_blks == 0) {
7447 			/*
7448 			 * The GET_ALLOCATED mailbox does not return the size,
7449 			 * just the count.  The size should be just the size
7450 			 * stored in the current allocated block and all sizes
7451 			 * for an extent type are the same so set the return
7452 			 * value now.
7453 			 */
7454 			*extnt_size = rsrc_blk->rsrc_size;
7455 		}
7456 		curr_blks++;
7457 	}
7458 
7459 	/*
7460 	 * Calculate the size of an embedded mailbox.  The uint32_t
7461 	 * accounts for extents-specific word.
7462 	 */
7463 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7464 		sizeof(uint32_t);
7465 
7466 	/*
7467 	 * Presume the allocation and response will fit into an embedded
7468 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7469 	 */
7470 	emb = LPFC_SLI4_MBX_EMBED;
7471 	req_len = emb_len;
7472 	if (req_len > emb_len) {
7473 		req_len = curr_blks * sizeof(uint16_t) +
7474 			sizeof(union lpfc_sli4_cfg_shdr) +
7475 			sizeof(uint32_t);
7476 		emb = LPFC_SLI4_MBX_NEMBED;
7477 	}
7478 
7479 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7480 	if (!mbox)
7481 		return -ENOMEM;
7482 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7483 
7484 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7485 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7486 				     req_len, emb);
7487 	if (alloc_len < req_len) {
7488 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7489 			"2983 Allocated DMA memory size (x%x) is "
7490 			"less than the requested DMA memory "
7491 			"size (x%x)\n", alloc_len, req_len);
7492 		rc = -ENOMEM;
7493 		goto err_exit;
7494 	}
7495 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7496 	if (unlikely(rc)) {
7497 		rc = -EIO;
7498 		goto err_exit;
7499 	}
7500 
7501 	if (!phba->sli4_hba.intr_enable)
7502 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7503 	else {
7504 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7505 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7506 	}
7507 
7508 	if (unlikely(rc)) {
7509 		rc = -EIO;
7510 		goto err_exit;
7511 	}
7512 
7513 	/*
7514 	 * Figure out where the response is located.  Then get local pointers
7515 	 * to the response data.  The port does not guarantee to respond to
7516 	 * all extents counts request so update the local variable with the
7517 	 * allocated count from the port.
7518 	 */
7519 	if (emb == LPFC_SLI4_MBX_EMBED) {
7520 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7521 		shdr = &rsrc_ext->header.cfg_shdr;
7522 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7523 	} else {
7524 		virtaddr = mbox->sge_array->addr[0];
7525 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7526 		shdr = &n_rsrc->cfg_shdr;
7527 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7528 	}
7529 
7530 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7531 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7532 			"2984 Failed to read allocated resources "
7533 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7534 			type,
7535 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7536 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7537 		rc = -EIO;
7538 		goto err_exit;
7539 	}
7540  err_exit:
7541 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7542 	return rc;
7543 }
7544 
7545 /**
7546  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7547  * @phba: pointer to lpfc hba data structure.
7548  * @sgl_list: linked link of sgl buffers to post
7549  * @cnt: number of linked list buffers
7550  *
7551  * This routine walks the list of buffers that have been allocated and
7552  * repost them to the port by using SGL block post. This is needed after a
7553  * pci_function_reset/warm_start or start. It attempts to construct blocks
7554  * of buffer sgls which contains contiguous xris and uses the non-embedded
7555  * SGL block post mailbox commands to post them to the port. For single
7556  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7557  * mailbox command for posting.
7558  *
7559  * Returns: 0 = success, non-zero failure.
7560  **/
7561 static int
7562 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7563 			  struct list_head *sgl_list, int cnt)
7564 {
7565 	struct lpfc_sglq *sglq_entry = NULL;
7566 	struct lpfc_sglq *sglq_entry_next = NULL;
7567 	struct lpfc_sglq *sglq_entry_first = NULL;
7568 	int status = 0, total_cnt;
7569 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7570 	int last_xritag = NO_XRI;
7571 	LIST_HEAD(prep_sgl_list);
7572 	LIST_HEAD(blck_sgl_list);
7573 	LIST_HEAD(allc_sgl_list);
7574 	LIST_HEAD(post_sgl_list);
7575 	LIST_HEAD(free_sgl_list);
7576 
7577 	spin_lock_irq(&phba->hbalock);
7578 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7579 	list_splice_init(sgl_list, &allc_sgl_list);
7580 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7581 	spin_unlock_irq(&phba->hbalock);
7582 
7583 	total_cnt = cnt;
7584 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7585 				 &allc_sgl_list, list) {
7586 		list_del_init(&sglq_entry->list);
7587 		block_cnt++;
7588 		if ((last_xritag != NO_XRI) &&
7589 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7590 			/* a hole in xri block, form a sgl posting block */
7591 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7592 			post_cnt = block_cnt - 1;
7593 			/* prepare list for next posting block */
7594 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7595 			block_cnt = 1;
7596 		} else {
7597 			/* prepare list for next posting block */
7598 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7599 			/* enough sgls for non-embed sgl mbox command */
7600 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7601 				list_splice_init(&prep_sgl_list,
7602 						 &blck_sgl_list);
7603 				post_cnt = block_cnt;
7604 				block_cnt = 0;
7605 			}
7606 		}
7607 		num_posted++;
7608 
7609 		/* keep track of last sgl's xritag */
7610 		last_xritag = sglq_entry->sli4_xritag;
7611 
7612 		/* end of repost sgl list condition for buffers */
7613 		if (num_posted == total_cnt) {
7614 			if (post_cnt == 0) {
7615 				list_splice_init(&prep_sgl_list,
7616 						 &blck_sgl_list);
7617 				post_cnt = block_cnt;
7618 			} else if (block_cnt == 1) {
7619 				status = lpfc_sli4_post_sgl(phba,
7620 						sglq_entry->phys, 0,
7621 						sglq_entry->sli4_xritag);
7622 				if (!status) {
7623 					/* successful, put sgl to posted list */
7624 					list_add_tail(&sglq_entry->list,
7625 						      &post_sgl_list);
7626 				} else {
7627 					/* Failure, put sgl to free list */
7628 					lpfc_printf_log(phba, KERN_WARNING,
7629 						LOG_SLI,
7630 						"3159 Failed to post "
7631 						"sgl, xritag:x%x\n",
7632 						sglq_entry->sli4_xritag);
7633 					list_add_tail(&sglq_entry->list,
7634 						      &free_sgl_list);
7635 					total_cnt--;
7636 				}
7637 			}
7638 		}
7639 
7640 		/* continue until a nembed page worth of sgls */
7641 		if (post_cnt == 0)
7642 			continue;
7643 
7644 		/* post the buffer list sgls as a block */
7645 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7646 						 post_cnt);
7647 
7648 		if (!status) {
7649 			/* success, put sgl list to posted sgl list */
7650 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7651 		} else {
7652 			/* Failure, put sgl list to free sgl list */
7653 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7654 							    struct lpfc_sglq,
7655 							    list);
7656 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7657 					"3160 Failed to post sgl-list, "
7658 					"xritag:x%x-x%x\n",
7659 					sglq_entry_first->sli4_xritag,
7660 					(sglq_entry_first->sli4_xritag +
7661 					 post_cnt - 1));
7662 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7663 			total_cnt -= post_cnt;
7664 		}
7665 
7666 		/* don't reset xirtag due to hole in xri block */
7667 		if (block_cnt == 0)
7668 			last_xritag = NO_XRI;
7669 
7670 		/* reset sgl post count for next round of posting */
7671 		post_cnt = 0;
7672 	}
7673 
7674 	/* free the sgls failed to post */
7675 	lpfc_free_sgl_list(phba, &free_sgl_list);
7676 
7677 	/* push sgls posted to the available list */
7678 	if (!list_empty(&post_sgl_list)) {
7679 		spin_lock_irq(&phba->hbalock);
7680 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7681 		list_splice_init(&post_sgl_list, sgl_list);
7682 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7683 		spin_unlock_irq(&phba->hbalock);
7684 	} else {
7685 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7686 				"3161 Failure to post sgl to port,status %x "
7687 				"blkcnt %d totalcnt %d postcnt %d\n",
7688 				status, block_cnt, total_cnt, post_cnt);
7689 		return -EIO;
7690 	}
7691 
7692 	/* return the number of XRIs actually posted */
7693 	return total_cnt;
7694 }
7695 
7696 /**
7697  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7698  * @phba: pointer to lpfc hba data structure.
7699  *
7700  * This routine walks the list of nvme buffers that have been allocated and
7701  * repost them to the port by using SGL block post. This is needed after a
7702  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7703  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7704  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7705  *
7706  * Returns: 0 = success, non-zero failure.
7707  **/
7708 static int
7709 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7710 {
7711 	LIST_HEAD(post_nblist);
7712 	int num_posted, rc = 0;
7713 
7714 	/* get all NVME buffers need to repost to a local list */
7715 	lpfc_io_buf_flush(phba, &post_nblist);
7716 
7717 	/* post the list of nvme buffer sgls to port if available */
7718 	if (!list_empty(&post_nblist)) {
7719 		num_posted = lpfc_sli4_post_io_sgl_list(
7720 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7721 		/* failed to post any nvme buffer, return error */
7722 		if (num_posted == 0)
7723 			rc = -EIO;
7724 	}
7725 	return rc;
7726 }
7727 
7728 static void
7729 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7730 {
7731 	uint32_t len;
7732 
7733 	len = sizeof(struct lpfc_mbx_set_host_data) -
7734 		sizeof(struct lpfc_sli4_cfg_mhdr);
7735 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7736 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7737 			 LPFC_SLI4_MBX_EMBED);
7738 
7739 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7740 	mbox->u.mqe.un.set_host_data.param_len =
7741 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7742 	snprintf(mbox->u.mqe.un.set_host_data.un.data,
7743 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7744 		 "Linux %s v"LPFC_DRIVER_VERSION,
7745 		 test_bit(HBA_FCOE_MODE, &phba->hba_flag) ? "FCoE" : "FC");
7746 }
7747 
7748 int
7749 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7750 		    struct lpfc_queue *drq, int count, int idx)
7751 {
7752 	int rc, i;
7753 	struct lpfc_rqe hrqe;
7754 	struct lpfc_rqe drqe;
7755 	struct lpfc_rqb *rqbp;
7756 	unsigned long flags;
7757 	struct rqb_dmabuf *rqb_buffer;
7758 	LIST_HEAD(rqb_buf_list);
7759 
7760 	rqbp = hrq->rqbp;
7761 	for (i = 0; i < count; i++) {
7762 		spin_lock_irqsave(&phba->hbalock, flags);
7763 		/* IF RQ is already full, don't bother */
7764 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7765 			spin_unlock_irqrestore(&phba->hbalock, flags);
7766 			break;
7767 		}
7768 		spin_unlock_irqrestore(&phba->hbalock, flags);
7769 
7770 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7771 		if (!rqb_buffer)
7772 			break;
7773 		rqb_buffer->hrq = hrq;
7774 		rqb_buffer->drq = drq;
7775 		rqb_buffer->idx = idx;
7776 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7777 	}
7778 
7779 	spin_lock_irqsave(&phba->hbalock, flags);
7780 	while (!list_empty(&rqb_buf_list)) {
7781 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7782 				 hbuf.list);
7783 
7784 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7785 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7786 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7787 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7788 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7789 		if (rc < 0) {
7790 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7791 					"6421 Cannot post to HRQ %d: %x %x %x "
7792 					"DRQ %x %x\n",
7793 					hrq->queue_id,
7794 					hrq->host_index,
7795 					hrq->hba_index,
7796 					hrq->entry_count,
7797 					drq->host_index,
7798 					drq->hba_index);
7799 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7800 		} else {
7801 			list_add_tail(&rqb_buffer->hbuf.list,
7802 				      &rqbp->rqb_buffer_list);
7803 			rqbp->buffer_count++;
7804 		}
7805 	}
7806 	spin_unlock_irqrestore(&phba->hbalock, flags);
7807 	return 1;
7808 }
7809 
7810 static void
7811 lpfc_mbx_cmpl_read_lds_params(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7812 {
7813 	union lpfc_sli4_cfg_shdr *shdr;
7814 	u32 shdr_status, shdr_add_status;
7815 
7816 	shdr = (union lpfc_sli4_cfg_shdr *)
7817 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7818 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7819 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7820 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7821 		lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT | LOG_MBOX,
7822 				"4622 SET_FEATURE (x%x) mbox failed, "
7823 				"status x%x add_status x%x, mbx status x%x\n",
7824 				LPFC_SET_LD_SIGNAL, shdr_status,
7825 				shdr_add_status, pmb->u.mb.mbxStatus);
7826 		phba->degrade_activate_threshold = 0;
7827 		phba->degrade_deactivate_threshold = 0;
7828 		phba->fec_degrade_interval = 0;
7829 		goto out;
7830 	}
7831 
7832 	phba->degrade_activate_threshold = pmb->u.mqe.un.set_feature.word7;
7833 	phba->degrade_deactivate_threshold = pmb->u.mqe.un.set_feature.word8;
7834 	phba->fec_degrade_interval = pmb->u.mqe.un.set_feature.word10;
7835 
7836 	lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT,
7837 			"4624 Success: da x%x dd x%x interval x%x\n",
7838 			phba->degrade_activate_threshold,
7839 			phba->degrade_deactivate_threshold,
7840 			phba->fec_degrade_interval);
7841 out:
7842 	mempool_free(pmb, phba->mbox_mem_pool);
7843 }
7844 
7845 int
7846 lpfc_read_lds_params(struct lpfc_hba *phba)
7847 {
7848 	LPFC_MBOXQ_t *mboxq;
7849 	int rc;
7850 
7851 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7852 	if (!mboxq)
7853 		return -ENOMEM;
7854 
7855 	lpfc_set_features(phba, mboxq, LPFC_SET_LD_SIGNAL);
7856 	mboxq->vport = phba->pport;
7857 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_lds_params;
7858 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7859 	if (rc == MBX_NOT_FINISHED) {
7860 		mempool_free(mboxq, phba->mbox_mem_pool);
7861 		return -EIO;
7862 	}
7863 	return 0;
7864 }
7865 
7866 static void
7867 lpfc_mbx_cmpl_cgn_set_ftrs(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7868 {
7869 	struct lpfc_vport *vport = pmb->vport;
7870 	union lpfc_sli4_cfg_shdr *shdr;
7871 	u32 shdr_status, shdr_add_status;
7872 	u32 sig, acqe;
7873 
7874 	/* Two outcomes. (1) Set featurs was successul and EDC negotiation
7875 	 * is done. (2) Mailbox failed and send FPIN support only.
7876 	 */
7877 	shdr = (union lpfc_sli4_cfg_shdr *)
7878 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7879 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7880 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7881 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7882 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
7883 				"2516 CGN SET_FEATURE mbox failed with "
7884 				"status x%x add_status x%x, mbx status x%x "
7885 				"Reset Congestion to FPINs only\n",
7886 				shdr_status, shdr_add_status,
7887 				pmb->u.mb.mbxStatus);
7888 		/* If there is a mbox error, move on to RDF */
7889 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7890 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7891 		goto out;
7892 	}
7893 
7894 	/* Zero out Congestion Signal ACQE counter */
7895 	phba->cgn_acqe_cnt = 0;
7896 
7897 	acqe = bf_get(lpfc_mbx_set_feature_CGN_acqe_freq,
7898 		      &pmb->u.mqe.un.set_feature);
7899 	sig = bf_get(lpfc_mbx_set_feature_CGN_warn_freq,
7900 		     &pmb->u.mqe.un.set_feature);
7901 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7902 			"4620 SET_FEATURES Success: Freq: %ds %dms "
7903 			" Reg: x%x x%x\n", acqe, sig,
7904 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7905 out:
7906 	mempool_free(pmb, phba->mbox_mem_pool);
7907 
7908 	/* Register for FPIN events from the fabric now that the
7909 	 * EDC common_set_features has completed.
7910 	 */
7911 	lpfc_issue_els_rdf(vport, 0);
7912 }
7913 
7914 int
7915 lpfc_config_cgn_signal(struct lpfc_hba *phba)
7916 {
7917 	LPFC_MBOXQ_t *mboxq;
7918 	u32 rc;
7919 
7920 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7921 	if (!mboxq)
7922 		goto out_rdf;
7923 
7924 	lpfc_set_features(phba, mboxq, LPFC_SET_CGN_SIGNAL);
7925 	mboxq->vport = phba->pport;
7926 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_cgn_set_ftrs;
7927 
7928 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7929 			"4621 SET_FEATURES: FREQ sig x%x acqe x%x: "
7930 			"Reg: x%x x%x\n",
7931 			phba->cgn_sig_freq, lpfc_acqe_cgn_frequency,
7932 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7933 
7934 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7935 	if (rc == MBX_NOT_FINISHED)
7936 		goto out;
7937 	return 0;
7938 
7939 out:
7940 	mempool_free(mboxq, phba->mbox_mem_pool);
7941 out_rdf:
7942 	/* If there is a mbox error, move on to RDF */
7943 	phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7944 	phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7945 	lpfc_issue_els_rdf(phba->pport, 0);
7946 	return -EIO;
7947 }
7948 
7949 /**
7950  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7951  * @phba: pointer to lpfc hba data structure.
7952  *
7953  * This routine initializes the per-eq idle_stat to dynamically dictate
7954  * polling decisions.
7955  *
7956  * Return codes:
7957  *   None
7958  **/
7959 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
7960 {
7961 	int i;
7962 	struct lpfc_sli4_hdw_queue *hdwq;
7963 	struct lpfc_queue *eq;
7964 	struct lpfc_idle_stat *idle_stat;
7965 	u64 wall;
7966 
7967 	for_each_present_cpu(i) {
7968 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
7969 		eq = hdwq->hba_eq;
7970 
7971 		/* Skip if we've already handled this eq's primary CPU */
7972 		if (eq->chann != i)
7973 			continue;
7974 
7975 		idle_stat = &phba->sli4_hba.idle_stat[i];
7976 
7977 		idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
7978 		idle_stat->prev_wall = wall;
7979 
7980 		if (phba->nvmet_support ||
7981 		    phba->cmf_active_mode != LPFC_CFG_OFF ||
7982 		    phba->intr_type != MSIX)
7983 			eq->poll_mode = LPFC_QUEUE_WORK;
7984 		else
7985 			eq->poll_mode = LPFC_THREADED_IRQ;
7986 	}
7987 
7988 	if (!phba->nvmet_support && phba->intr_type == MSIX)
7989 		schedule_delayed_work(&phba->idle_stat_delay_work,
7990 				      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
7991 }
7992 
7993 static void lpfc_sli4_dip(struct lpfc_hba *phba)
7994 {
7995 	uint32_t if_type;
7996 
7997 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
7998 	if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
7999 	    if_type == LPFC_SLI_INTF_IF_TYPE_6) {
8000 		struct lpfc_register reg_data;
8001 
8002 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
8003 			       &reg_data.word0))
8004 			return;
8005 
8006 		if (bf_get(lpfc_sliport_status_dip, &reg_data))
8007 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8008 					"2904 Firmware Dump Image Present"
8009 					" on Adapter");
8010 	}
8011 }
8012 
8013 /**
8014  * lpfc_rx_monitor_create_ring - Initialize ring buffer for rx_monitor
8015  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8016  * @entries: Number of rx_info_entry objects to allocate in ring
8017  *
8018  * Return:
8019  * 0 - Success
8020  * ENOMEM - Failure to kmalloc
8021  **/
8022 int lpfc_rx_monitor_create_ring(struct lpfc_rx_info_monitor *rx_monitor,
8023 				u32 entries)
8024 {
8025 	rx_monitor->ring = kmalloc_objs(struct rx_info_entry, entries);
8026 	if (!rx_monitor->ring)
8027 		return -ENOMEM;
8028 
8029 	rx_monitor->head_idx = 0;
8030 	rx_monitor->tail_idx = 0;
8031 	spin_lock_init(&rx_monitor->lock);
8032 	rx_monitor->entries = entries;
8033 
8034 	return 0;
8035 }
8036 
8037 /**
8038  * lpfc_rx_monitor_destroy_ring - Free ring buffer for rx_monitor
8039  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8040  *
8041  * Called after cancellation of cmf_timer.
8042  **/
8043 void lpfc_rx_monitor_destroy_ring(struct lpfc_rx_info_monitor *rx_monitor)
8044 {
8045 	kfree(rx_monitor->ring);
8046 	rx_monitor->ring = NULL;
8047 	rx_monitor->entries = 0;
8048 	rx_monitor->head_idx = 0;
8049 	rx_monitor->tail_idx = 0;
8050 }
8051 
8052 /**
8053  * lpfc_rx_monitor_record - Insert an entry into rx_monitor's ring
8054  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8055  * @entry: Pointer to rx_info_entry
8056  *
8057  * Used to insert an rx_info_entry into rx_monitor's ring.  Note that this is a
8058  * deep copy of rx_info_entry not a shallow copy of the rx_info_entry ptr.
8059  *
8060  * This is called from lpfc_cmf_timer, which is in timer/softirq context.
8061  *
8062  * In cases of old data overflow, we do a best effort of FIFO order.
8063  **/
8064 void lpfc_rx_monitor_record(struct lpfc_rx_info_monitor *rx_monitor,
8065 			    struct rx_info_entry *entry)
8066 {
8067 	struct rx_info_entry *ring = rx_monitor->ring;
8068 	u32 *head_idx = &rx_monitor->head_idx;
8069 	u32 *tail_idx = &rx_monitor->tail_idx;
8070 	spinlock_t *ring_lock = &rx_monitor->lock;
8071 	u32 ring_size = rx_monitor->entries;
8072 
8073 	spin_lock(ring_lock);
8074 	memcpy(&ring[*tail_idx], entry, sizeof(*entry));
8075 	*tail_idx = (*tail_idx + 1) % ring_size;
8076 
8077 	/* Best effort of FIFO saved data */
8078 	if (*tail_idx == *head_idx)
8079 		*head_idx = (*head_idx + 1) % ring_size;
8080 
8081 	spin_unlock(ring_lock);
8082 }
8083 
8084 /**
8085  * lpfc_rx_monitor_report - Read out rx_monitor's ring
8086  * @phba: Pointer to lpfc_hba object
8087  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8088  * @buf: Pointer to char buffer that will contain rx monitor info data
8089  * @buf_len: Length buf including null char
8090  * @max_read_entries: Maximum number of entries to read out of ring
8091  *
8092  * Used to dump/read what's in rx_monitor's ring buffer.
8093  *
8094  * If buf is NULL || buf_len == 0, then it is implied that we want to log the
8095  * information to kmsg instead of filling out buf.
8096  *
8097  * Return:
8098  * Number of entries read out of the ring
8099  **/
8100 u32 lpfc_rx_monitor_report(struct lpfc_hba *phba,
8101 			   struct lpfc_rx_info_monitor *rx_monitor, char *buf,
8102 			   u32 buf_len, u32 max_read_entries)
8103 {
8104 	struct rx_info_entry *ring = rx_monitor->ring;
8105 	struct rx_info_entry *entry;
8106 	u32 *head_idx = &rx_monitor->head_idx;
8107 	u32 *tail_idx = &rx_monitor->tail_idx;
8108 	spinlock_t *ring_lock = &rx_monitor->lock;
8109 	u32 ring_size = rx_monitor->entries;
8110 	u32 cnt = 0;
8111 	bool log_to_kmsg = (!buf || !buf_len) ? true : false;
8112 	struct seq_buf s;
8113 
8114 	if (!log_to_kmsg) {
8115 		/* clear the buffer to be sure */
8116 		memset(buf, 0, buf_len);
8117 
8118 		seq_buf_init(&s, buf, buf_len);
8119 		seq_buf_printf(&s, "\t%-16s%-16s%-16s%-16s%-8s%-8s%-8s%-8s%-8s%-8s%-16s\n",
8120 			       "MaxBPI", "Tot_Data_CMF",
8121 			       "Tot_Data_Cmd", "Tot_Data_Cmpl",
8122 			       "Lat(us)", "Avg_IO", "Max_IO", "Bsy",
8123 			       "IO_cnt", "Info", "BWutil(ms)");
8124 	}
8125 
8126 	/* Needs to be _irq because record is called from timer interrupt
8127 	 * context
8128 	 */
8129 	spin_lock_irq(ring_lock);
8130 	while (*head_idx != *tail_idx) {
8131 		entry = &ring[*head_idx];
8132 
8133 		/* Read out this entry's data. */
8134 		if (!log_to_kmsg) {
8135 			unsigned int len;
8136 
8137 			/* A header that did not fit leaves no room. */
8138 			if (seq_buf_has_overflowed(&s))
8139 				break;
8140 			len = seq_buf_used(&s);
8141 
8142 			seq_buf_printf(&s,
8143 				       "%03d:\t%-16llu%-16llu%-16llu%-16llu%-8llu%-8llu%-8llu%-8u%-8u%-8u%u(%u)\n",
8144 				       *head_idx,
8145 				       entry->max_bytes_per_interval,
8146 				       entry->cmf_bytes,
8147 				       entry->total_bytes,
8148 				       entry->rcv_bytes,
8149 				       entry->avg_io_latency,
8150 				       entry->avg_io_size,
8151 				       entry->max_read_cnt,
8152 				       entry->cmf_busy, entry->io_cnt,
8153 				       entry->cmf_info,
8154 				       entry->timer_utilization,
8155 				       entry->timer_interval);
8156 
8157 			/*
8158 			 * Drop a record whole if it does not fit, without
8159 			 * consuming its ring entry: the reader takes the
8160 			 * string up to its NUL.
8161 			 */
8162 			if (seq_buf_has_overflowed(&s)) {
8163 				buf[len] = '\0';
8164 				break;
8165 			}
8166 		} else {
8167 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
8168 					"4410 %02u: MBPI %llu Xmit %llu "
8169 					"Cmpl %llu Lat %llu ASz %llu Info %02u "
8170 					"BWUtil %u Int %u slot %u\n",
8171 					cnt, entry->max_bytes_per_interval,
8172 					entry->total_bytes, entry->rcv_bytes,
8173 					entry->avg_io_latency,
8174 					entry->avg_io_size, entry->cmf_info,
8175 					entry->timer_utilization,
8176 					entry->timer_interval, *head_idx);
8177 		}
8178 
8179 		*head_idx = (*head_idx + 1) % ring_size;
8180 
8181 		/* Don't feed more than max_read_entries */
8182 		cnt++;
8183 		if (cnt >= max_read_entries)
8184 			break;
8185 	}
8186 	spin_unlock_irq(ring_lock);
8187 
8188 	return cnt;
8189 }
8190 
8191 /**
8192  * lpfc_cmf_setup - Initialize idle_stat tracking
8193  * @phba: Pointer to HBA context object.
8194  *
8195  * This is called from HBA setup during driver load or when the HBA
8196  * comes online. this does all the initialization to support CMF and MI.
8197  **/
8198 static int
8199 lpfc_cmf_setup(struct lpfc_hba *phba)
8200 {
8201 	LPFC_MBOXQ_t *mboxq;
8202 	struct lpfc_dmabuf *mp;
8203 	struct lpfc_pc_sli4_params *sli4_params;
8204 	int rc, cmf, mi_ver;
8205 
8206 	rc = lpfc_sli4_refresh_params(phba);
8207 	if (unlikely(rc))
8208 		return rc;
8209 
8210 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8211 	if (!mboxq)
8212 		return -ENOMEM;
8213 
8214 	sli4_params = &phba->sli4_hba.pc_sli4_params;
8215 
8216 	/* Always try to enable MI feature if we can */
8217 	if (sli4_params->mi_ver) {
8218 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_MI);
8219 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8220 		mi_ver = bf_get(lpfc_mbx_set_feature_mi,
8221 				 &mboxq->u.mqe.un.set_feature);
8222 
8223 		if (rc == MBX_SUCCESS) {
8224 			if (mi_ver) {
8225 				lpfc_printf_log(phba,
8226 						KERN_WARNING, LOG_CGN_MGMT,
8227 						"6215 MI is enabled\n");
8228 				sli4_params->mi_ver = mi_ver;
8229 			} else {
8230 				lpfc_printf_log(phba,
8231 						KERN_WARNING, LOG_CGN_MGMT,
8232 						"6338 MI is disabled\n");
8233 				sli4_params->mi_ver = 0;
8234 			}
8235 		} else {
8236 			/* mi_ver is already set from GET_SLI4_PARAMETERS */
8237 			lpfc_printf_log(phba, KERN_INFO,
8238 					LOG_CGN_MGMT | LOG_INIT,
8239 					"6245 Enable MI Mailbox x%x (x%x/x%x) "
8240 					"failed, rc:x%x mi:x%x\n",
8241 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8242 					lpfc_sli_config_mbox_subsys_get
8243 						(phba, mboxq),
8244 					lpfc_sli_config_mbox_opcode_get
8245 						(phba, mboxq),
8246 					rc, sli4_params->mi_ver);
8247 		}
8248 	} else {
8249 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8250 				"6217 MI is disabled\n");
8251 	}
8252 
8253 	/* Ensure FDMI is enabled for MI if enable_mi is set */
8254 	if (sli4_params->mi_ver)
8255 		phba->cfg_fdmi_on = LPFC_FDMI_SUPPORT;
8256 
8257 	/* Always try to enable CMF feature if we can */
8258 	if (sli4_params->cmf) {
8259 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_CMF);
8260 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8261 		cmf = bf_get(lpfc_mbx_set_feature_cmf,
8262 			     &mboxq->u.mqe.un.set_feature);
8263 		if (rc == MBX_SUCCESS && cmf) {
8264 			lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8265 					"6218 CMF is enabled: mode %d\n",
8266 					phba->cmf_active_mode);
8267 		} else {
8268 			lpfc_printf_log(phba, KERN_WARNING,
8269 					LOG_CGN_MGMT | LOG_INIT,
8270 					"6219 Enable CMF Mailbox x%x (x%x/x%x) "
8271 					"failed, rc:x%x dd:x%x\n",
8272 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8273 					lpfc_sli_config_mbox_subsys_get
8274 						(phba, mboxq),
8275 					lpfc_sli_config_mbox_opcode_get
8276 						(phba, mboxq),
8277 					rc, cmf);
8278 			sli4_params->cmf = 0;
8279 			phba->cmf_active_mode = LPFC_CFG_OFF;
8280 			goto no_cmf;
8281 		}
8282 
8283 		/* Allocate Congestion Information Buffer */
8284 		if (!phba->cgn_i) {
8285 			mp = kmalloc_obj(*mp);
8286 			if (mp)
8287 				mp->virt = dma_alloc_coherent
8288 						(&phba->pcidev->dev,
8289 						sizeof(struct lpfc_cgn_info),
8290 						&mp->phys, GFP_KERNEL);
8291 			if (!mp || !mp->virt) {
8292 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8293 						"2640 Failed to alloc memory "
8294 						"for Congestion Info\n");
8295 				kfree(mp);
8296 				sli4_params->cmf = 0;
8297 				phba->cmf_active_mode = LPFC_CFG_OFF;
8298 				goto no_cmf;
8299 			}
8300 			phba->cgn_i = mp;
8301 
8302 			/* initialize congestion buffer info */
8303 			lpfc_init_congestion_buf(phba);
8304 			lpfc_init_congestion_stat(phba);
8305 
8306 			/* Zero out Congestion Signal counters */
8307 			atomic64_set(&phba->cgn_acqe_stat.alarm, 0);
8308 			atomic64_set(&phba->cgn_acqe_stat.warn, 0);
8309 		}
8310 
8311 		rc = lpfc_sli4_cgn_params_read(phba);
8312 		if (rc < 0) {
8313 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8314 					"6242 Error reading Cgn Params (%d)\n",
8315 					rc);
8316 			/* Ensure CGN Mode is off */
8317 			sli4_params->cmf = 0;
8318 		} else if (!rc) {
8319 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8320 					"6243 CGN Event empty object.\n");
8321 			/* Ensure CGN Mode is off */
8322 			sli4_params->cmf = 0;
8323 		}
8324 	} else {
8325 no_cmf:
8326 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8327 				"6220 CMF is disabled\n");
8328 	}
8329 
8330 	/* Only register congestion buffer with firmware if BOTH
8331 	 * CMF and E2E are enabled.
8332 	 */
8333 	if (sli4_params->cmf && sli4_params->mi_ver) {
8334 		rc = lpfc_reg_congestion_buf(phba);
8335 		if (rc) {
8336 			dma_free_coherent(&phba->pcidev->dev,
8337 					  sizeof(struct lpfc_cgn_info),
8338 					  phba->cgn_i->virt, phba->cgn_i->phys);
8339 			kfree(phba->cgn_i);
8340 			phba->cgn_i = NULL;
8341 			/* Ensure CGN Mode is off */
8342 			phba->cmf_active_mode = LPFC_CFG_OFF;
8343 			sli4_params->cmf = 0;
8344 			return 0;
8345 		}
8346 	}
8347 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8348 			"6470 Setup MI version %d CMF %d mode %d\n",
8349 			sli4_params->mi_ver, sli4_params->cmf,
8350 			phba->cmf_active_mode);
8351 
8352 	mempool_free(mboxq, phba->mbox_mem_pool);
8353 
8354 	/* Initialize atomic counters */
8355 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
8356 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
8357 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
8358 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
8359 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
8360 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
8361 	atomic64_set(&phba->cgn_latency_evt, 0);
8362 
8363 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
8364 
8365 	/* Allocate RX Monitor Buffer */
8366 	if (!phba->rx_monitor) {
8367 		phba->rx_monitor = kzalloc_obj(*phba->rx_monitor);
8368 
8369 		if (!phba->rx_monitor) {
8370 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8371 					"2644 Failed to alloc memory "
8372 					"for RX Monitor Buffer\n");
8373 			return -ENOMEM;
8374 		}
8375 
8376 		/* Instruct the rx_monitor object to instantiate its ring */
8377 		if (lpfc_rx_monitor_create_ring(phba->rx_monitor,
8378 						LPFC_MAX_RXMONITOR_ENTRY)) {
8379 			kfree(phba->rx_monitor);
8380 			phba->rx_monitor = NULL;
8381 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8382 					"2645 Failed to alloc memory "
8383 					"for RX Monitor's Ring\n");
8384 			return -ENOMEM;
8385 		}
8386 	}
8387 
8388 	return 0;
8389 }
8390 
8391 static int
8392 lpfc_set_host_tm(struct lpfc_hba *phba)
8393 {
8394 	LPFC_MBOXQ_t *mboxq;
8395 	uint32_t len, rc;
8396 	struct timespec64 cur_time;
8397 	struct tm broken;
8398 	uint32_t month, day, year;
8399 	uint32_t hour, minute, second;
8400 	struct lpfc_mbx_set_host_date_time *tm;
8401 
8402 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8403 	if (!mboxq)
8404 		return -ENOMEM;
8405 
8406 	len = sizeof(struct lpfc_mbx_set_host_data) -
8407 		sizeof(struct lpfc_sli4_cfg_mhdr);
8408 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
8409 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
8410 			 LPFC_SLI4_MBX_EMBED);
8411 
8412 	mboxq->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_DATE_TIME;
8413 	mboxq->u.mqe.un.set_host_data.param_len =
8414 			sizeof(struct lpfc_mbx_set_host_date_time);
8415 	tm = &mboxq->u.mqe.un.set_host_data.un.tm;
8416 	ktime_get_real_ts64(&cur_time);
8417 	time64_to_tm(cur_time.tv_sec, 0, &broken);
8418 	month = broken.tm_mon + 1;
8419 	day = broken.tm_mday;
8420 	year = broken.tm_year - 100;
8421 	hour = broken.tm_hour;
8422 	minute = broken.tm_min;
8423 	second = broken.tm_sec;
8424 	bf_set(lpfc_mbx_set_host_month, tm, month);
8425 	bf_set(lpfc_mbx_set_host_day, tm, day);
8426 	bf_set(lpfc_mbx_set_host_year, tm, year);
8427 	bf_set(lpfc_mbx_set_host_hour, tm, hour);
8428 	bf_set(lpfc_mbx_set_host_min, tm, minute);
8429 	bf_set(lpfc_mbx_set_host_sec, tm, second);
8430 
8431 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8432 	mempool_free(mboxq, phba->mbox_mem_pool);
8433 	return rc;
8434 }
8435 
8436 /**
8437  * lpfc_get_platform_uuid - Attempts to extract a platform uuid
8438  * @phba: pointer to lpfc hba data structure.
8439  *
8440  * This routine attempts to first read SMBIOS DMI data for the System
8441  * Information structure offset 08h called System UUID.  Else, no platform
8442  * UUID will be advertised.
8443  **/
8444 static void
8445 lpfc_get_platform_uuid(struct lpfc_hba *phba)
8446 {
8447 	int rc;
8448 	const char *uuid;
8449 	char pni[17] = {0}; /* 16 characters + '\0' */
8450 	bool is_ff = true, is_00 = true;
8451 	u8 i;
8452 
8453 	/* First attempt SMBIOS DMI */
8454 	uuid = dmi_get_system_info(DMI_PRODUCT_UUID);
8455 	if (uuid) {
8456 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8457 				"2088 SMBIOS UUID %s\n",
8458 				uuid);
8459 	} else {
8460 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8461 				"2099 Could not extract UUID\n");
8462 	}
8463 
8464 	if (uuid && uuid_is_valid(uuid)) {
8465 		/* Generate PNI from UUID format.
8466 		 *
8467 		 * 1.) Extract lower 64 bits from UUID format.
8468 		 * 2.) Set 3h for NAA Locally Assigned Name Identifier format.
8469 		 *
8470 		 * e.g. xxxxxxxx-xxxx-xxxx-yyyy-yyyyyyyyyyyy
8471 		 *
8472 		 * extract the yyyy-yyyyyyyyyyyy portion
8473 		 * final PNI   3yyyyyyyyyyyyyyy
8474 		 */
8475 		scnprintf(pni, sizeof(pni), "3%c%c%c%s",
8476 			  uuid[20], uuid[21], uuid[22], &uuid[24]);
8477 
8478 		/* Sanitize the converted PNI */
8479 		for (i = 1; i < 16 && (is_ff || is_00); i++) {
8480 			if (pni[i] != '0')
8481 				is_00 = false;
8482 			if (pni[i] != 'f' && pni[i] != 'F')
8483 				is_ff = false;
8484 		}
8485 
8486 		/* Convert from char* to unsigned long */
8487 		rc = kstrtoul(pni, 16, &phba->pni);
8488 		if (!rc && !is_ff && !is_00) {
8489 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8490 					"2100 PNI 0x%016lx\n", phba->pni);
8491 		} else {
8492 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8493 					"2101 PNI %s generation status %d\n",
8494 					pni, rc);
8495 			phba->pni = 0;
8496 		}
8497 	}
8498 }
8499 
8500 /**
8501  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
8502  * @phba: Pointer to HBA context object.
8503  *
8504  * This function is the main SLI4 device initialization PCI function. This
8505  * function is called by the HBA initialization code, HBA reset code and
8506  * HBA error attention handler code. Caller is not required to hold any
8507  * locks.
8508  **/
8509 int
8510 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
8511 {
8512 	int rc, i, cnt, len, dd;
8513 	LPFC_MBOXQ_t *mboxq;
8514 	struct lpfc_mqe *mqe;
8515 	uint8_t *vpd;
8516 	uint32_t vpd_size;
8517 	uint32_t ftr_rsp = 0;
8518 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
8519 	struct lpfc_vport *vport = phba->pport;
8520 	struct lpfc_dmabuf *mp;
8521 	struct lpfc_rqb *rqbp;
8522 	u32 flg;
8523 
8524 	/* Perform a PCI function reset to start from clean */
8525 	rc = lpfc_pci_function_reset(phba);
8526 	if (unlikely(rc))
8527 		return -ENODEV;
8528 
8529 	/* Check the HBA Host Status Register for readiness */
8530 	rc = lpfc_sli4_post_status_check(phba);
8531 	if (unlikely(rc))
8532 		return -ENODEV;
8533 	else {
8534 		spin_lock_irq(&phba->hbalock);
8535 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
8536 		flg = phba->sli.sli_flag;
8537 		spin_unlock_irq(&phba->hbalock);
8538 		/* Allow a little time after setting SLI_ACTIVE for any polled
8539 		 * MBX commands to complete via BSG.
8540 		 */
8541 		for (i = 0; i < 50 && (flg & LPFC_SLI_MBOX_ACTIVE); i++) {
8542 			msleep(20);
8543 			spin_lock_irq(&phba->hbalock);
8544 			flg = phba->sli.sli_flag;
8545 			spin_unlock_irq(&phba->hbalock);
8546 		}
8547 	}
8548 	clear_bit(HBA_SETUP, &phba->hba_flag);
8549 
8550 	lpfc_sli4_dip(phba);
8551 
8552 	/*
8553 	 * Allocate a single mailbox container for initializing the
8554 	 * port.
8555 	 */
8556 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8557 	if (!mboxq)
8558 		return -ENOMEM;
8559 
8560 	/* Issue READ_REV to collect vpd and FW information. */
8561 	vpd_size = SLI4_PAGE_SIZE;
8562 	vpd = kzalloc(vpd_size, GFP_KERNEL);
8563 	if (!vpd) {
8564 		rc = -ENOMEM;
8565 		goto out_free_mbox;
8566 	}
8567 
8568 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
8569 	if (unlikely(rc)) {
8570 		kfree(vpd);
8571 		goto out_free_mbox;
8572 	}
8573 
8574 	mqe = &mboxq->u.mqe;
8575 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
8576 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
8577 		set_bit(HBA_FCOE_MODE, &phba->hba_flag);
8578 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
8579 	} else {
8580 		clear_bit(HBA_FCOE_MODE, &phba->hba_flag);
8581 	}
8582 
8583 	/* Obtain platform UUID, only for SLI4 FC adapters */
8584 	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag))
8585 		lpfc_get_platform_uuid(phba);
8586 
8587 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
8588 		LPFC_DCBX_CEE_MODE)
8589 		set_bit(HBA_FIP_SUPPORT, &phba->hba_flag);
8590 	else
8591 		clear_bit(HBA_FIP_SUPPORT, &phba->hba_flag);
8592 
8593 	clear_bit(HBA_IOQ_FLUSH, &phba->hba_flag);
8594 
8595 	if (phba->sli_rev != LPFC_SLI_REV4) {
8596 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8597 			"0376 READ_REV Error. SLI Level %d "
8598 			"FCoE enabled %d\n",
8599 			phba->sli_rev,
8600 			test_bit(HBA_FCOE_MODE, &phba->hba_flag) ? 1 : 0);
8601 		rc = -EIO;
8602 		kfree(vpd);
8603 		goto out_free_mbox;
8604 	}
8605 
8606 	rc = lpfc_set_host_tm(phba);
8607 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
8608 			"6468 Set host date / time: Status x%x:\n", rc);
8609 
8610 	/*
8611 	 * Continue initialization with default values even if driver failed
8612 	 * to read FCoE param config regions, only read parameters if the
8613 	 * board is FCoE
8614 	 */
8615 	if (test_bit(HBA_FCOE_MODE, &phba->hba_flag) &&
8616 	    lpfc_sli4_read_fcoe_params(phba))
8617 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
8618 			"2570 Failed to read FCoE parameters\n");
8619 
8620 	/*
8621 	 * Retrieve sli4 device physical port name, failure of doing it
8622 	 * is considered as non-fatal.
8623 	 */
8624 	rc = lpfc_sli4_retrieve_pport_name(phba);
8625 	if (!rc)
8626 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8627 				"3080 Successful retrieving SLI4 device "
8628 				"physical port name: %s.\n", phba->Port);
8629 
8630 	rc = lpfc_sli4_get_ctl_attr(phba);
8631 	if (!rc)
8632 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8633 				"8351 Successful retrieving SLI4 device "
8634 				"CTL ATTR\n");
8635 
8636 	/*
8637 	 * Evaluate the read rev and vpd data. Populate the driver
8638 	 * state with the results. If this routine fails, the failure
8639 	 * is not fatal as the driver will use generic values.
8640 	 */
8641 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
8642 	if (unlikely(!rc))
8643 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8644 				"0377 Error %d parsing vpd. "
8645 				"Using defaults.\n", rc);
8646 	kfree(vpd);
8647 
8648 	/* Save information as VPD data */
8649 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
8650 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
8651 
8652 	/*
8653 	 * This is because first G7 ASIC doesn't support the standard
8654 	 * 0x5a NVME cmd descriptor type/subtype
8655 	 */
8656 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8657 			LPFC_SLI_INTF_IF_TYPE_6) &&
8658 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
8659 	    (phba->vpd.rev.smRev == 0) &&
8660 	    (phba->cfg_nvme_embed_cmd == 1))
8661 		phba->cfg_nvme_embed_cmd = 0;
8662 
8663 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
8664 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
8665 					 &mqe->un.read_rev);
8666 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
8667 				       &mqe->un.read_rev);
8668 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
8669 					    &mqe->un.read_rev);
8670 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
8671 					   &mqe->un.read_rev);
8672 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
8673 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
8674 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
8675 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
8676 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
8677 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
8678 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8679 			"(%d):0380 READ_REV Status x%x "
8680 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
8681 			mboxq->vport ? mboxq->vport->vpi : 0,
8682 			bf_get(lpfc_mqe_status, mqe),
8683 			phba->vpd.rev.opFwName,
8684 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
8685 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
8686 
8687 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8688 	    LPFC_SLI_INTF_IF_TYPE_0) {
8689 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
8690 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8691 		if (rc == MBX_SUCCESS) {
8692 			set_bit(HBA_RECOVERABLE_UE, &phba->hba_flag);
8693 			/* Set 1Sec interval to detect UE */
8694 			phba->eratt_poll_interval = 1;
8695 			phba->sli4_hba.ue_to_sr = bf_get(
8696 					lpfc_mbx_set_feature_UESR,
8697 					&mboxq->u.mqe.un.set_feature);
8698 			phba->sli4_hba.ue_to_rp = bf_get(
8699 					lpfc_mbx_set_feature_UERP,
8700 					&mboxq->u.mqe.un.set_feature);
8701 		}
8702 	}
8703 
8704 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
8705 		/* Enable MDS Diagnostics only if the SLI Port supports it */
8706 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
8707 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8708 		if (rc != MBX_SUCCESS)
8709 			phba->mds_diags_support = 0;
8710 	}
8711 
8712 	/*
8713 	 * Discover the port's supported feature set and match it against the
8714 	 * hosts requests.
8715 	 */
8716 	lpfc_request_features(phba, mboxq);
8717 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8718 	if (unlikely(rc)) {
8719 		rc = -EIO;
8720 		goto out_free_mbox;
8721 	}
8722 
8723 	/* Disable VMID if app header is not supported */
8724 	if (phba->cfg_vmid_app_header && !(bf_get(lpfc_mbx_rq_ftr_rsp_ashdr,
8725 						  &mqe->un.req_ftrs))) {
8726 		bf_set(lpfc_ftr_ashdr, &phba->sli4_hba.sli4_flags, 0);
8727 		phba->cfg_vmid_app_header = 0;
8728 		lpfc_printf_log(phba, KERN_DEBUG, LOG_SLI,
8729 				"1242 vmid feature not supported\n");
8730 	}
8731 
8732 	/*
8733 	 * The port must support FCP initiator mode as this is the
8734 	 * only mode running in the host.
8735 	 */
8736 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
8737 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8738 				"0378 No support for fcpi mode.\n");
8739 		ftr_rsp++;
8740 	}
8741 
8742 	/*
8743 	 * If the port cannot support the host's requested features
8744 	 * then turn off the global config parameters to disable the
8745 	 * feature in the driver.  This is not a fatal error.
8746 	 */
8747 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8748 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
8749 			phba->cfg_enable_bg = 0;
8750 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
8751 			ftr_rsp++;
8752 		}
8753 	}
8754 
8755 	if (phba->max_vpi && phba->cfg_enable_npiv &&
8756 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8757 		ftr_rsp++;
8758 
8759 	if (ftr_rsp) {
8760 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8761 				"0379 Feature Mismatch Data: x%08x %08x "
8762 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
8763 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
8764 				phba->cfg_enable_npiv, phba->max_vpi);
8765 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
8766 			phba->cfg_enable_bg = 0;
8767 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8768 			phba->cfg_enable_npiv = 0;
8769 	}
8770 
8771 	/* These SLI3 features are assumed in SLI4 */
8772 	spin_lock_irq(&phba->hbalock);
8773 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
8774 	spin_unlock_irq(&phba->hbalock);
8775 
8776 	/* Always try to enable dual dump feature if we can */
8777 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
8778 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8779 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
8780 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
8781 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8782 				"6448 Dual Dump is enabled\n");
8783 	else
8784 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
8785 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
8786 				"rc:x%x dd:x%x\n",
8787 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8788 				lpfc_sli_config_mbox_subsys_get(
8789 					phba, mboxq),
8790 				lpfc_sli_config_mbox_opcode_get(
8791 					phba, mboxq),
8792 				rc, dd);
8793 
8794 	/*
8795 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
8796 	 * calls depends on these resources to complete port setup.
8797 	 */
8798 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
8799 	if (rc) {
8800 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8801 				"2920 Failed to alloc Resource IDs "
8802 				"rc = x%x\n", rc);
8803 		goto out_free_mbox;
8804 	}
8805 
8806 	lpfc_sli4_node_rpi_restore(phba);
8807 
8808 	lpfc_set_host_data(phba, mboxq);
8809 
8810 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8811 	if (rc) {
8812 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8813 				"2134 Failed to set host os driver version %x",
8814 				rc);
8815 	}
8816 
8817 	/* Read the port's service parameters. */
8818 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
8819 	if (rc) {
8820 		phba->link_state = LPFC_HBA_ERROR;
8821 		rc = -ENOMEM;
8822 		goto out_free_mbox;
8823 	}
8824 
8825 	mboxq->vport = vport;
8826 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8827 	mp = mboxq->ctx_buf;
8828 	if (rc == MBX_SUCCESS) {
8829 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
8830 		rc = 0;
8831 	}
8832 
8833 	/*
8834 	 * This memory was allocated by the lpfc_read_sparam routine but is
8835 	 * no longer needed.  It is released and ctx_buf NULLed to prevent
8836 	 * unintended pointer access as the mbox is reused.
8837 	 */
8838 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
8839 	kfree(mp);
8840 	mboxq->ctx_buf = NULL;
8841 	if (unlikely(rc)) {
8842 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8843 				"0382 READ_SPARAM command failed "
8844 				"status %d, mbxStatus x%x\n",
8845 				rc, bf_get(lpfc_mqe_status, mqe));
8846 		phba->link_state = LPFC_HBA_ERROR;
8847 		rc = -EIO;
8848 		goto out_free_mbox;
8849 	}
8850 
8851 	lpfc_update_vport_wwn(vport);
8852 
8853 	/* Update the fc_host data structures with new wwn. */
8854 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
8855 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
8856 
8857 	/* Create all the SLI4 queues */
8858 	rc = lpfc_sli4_queue_create(phba);
8859 	if (rc) {
8860 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8861 				"3089 Failed to allocate queues\n");
8862 		rc = -ENODEV;
8863 		goto out_free_mbox;
8864 	}
8865 	/* Set up all the queues to the device */
8866 	rc = lpfc_sli4_queue_setup(phba);
8867 	if (unlikely(rc)) {
8868 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8869 				"0381 Error %d during queue setup.\n", rc);
8870 		goto out_destroy_queue;
8871 	}
8872 	/* Initialize the driver internal SLI layer lists. */
8873 	lpfc_sli4_setup(phba);
8874 	lpfc_sli4_queue_init(phba);
8875 
8876 	/* update host els xri-sgl sizes and mappings */
8877 	rc = lpfc_sli4_els_sgl_update(phba);
8878 	if (unlikely(rc)) {
8879 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8880 				"1400 Failed to update xri-sgl size and "
8881 				"mapping: %d\n", rc);
8882 		goto out_destroy_queue;
8883 	}
8884 
8885 	/* register the els sgl pool to the port */
8886 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
8887 				       phba->sli4_hba.els_xri_cnt);
8888 	if (unlikely(rc < 0)) {
8889 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8890 				"0582 Error %d during els sgl post "
8891 				"operation\n", rc);
8892 		rc = -ENODEV;
8893 		goto out_destroy_queue;
8894 	}
8895 	phba->sli4_hba.els_xri_cnt = rc;
8896 
8897 	if (phba->nvmet_support) {
8898 		/* update host nvmet xri-sgl sizes and mappings */
8899 		rc = lpfc_sli4_nvmet_sgl_update(phba);
8900 		if (unlikely(rc)) {
8901 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8902 					"6308 Failed to update nvmet-sgl size "
8903 					"and mapping: %d\n", rc);
8904 			goto out_destroy_queue;
8905 		}
8906 
8907 		/* register the nvmet sgl pool to the port */
8908 		rc = lpfc_sli4_repost_sgl_list(
8909 			phba,
8910 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
8911 			phba->sli4_hba.nvmet_xri_cnt);
8912 		if (unlikely(rc < 0)) {
8913 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8914 					"3117 Error %d during nvmet "
8915 					"sgl post\n", rc);
8916 			rc = -ENODEV;
8917 			goto out_destroy_queue;
8918 		}
8919 		phba->sli4_hba.nvmet_xri_cnt = rc;
8920 
8921 		/* We allocate an iocbq for every receive context SGL.
8922 		 * The additional allocation is for abort and ls handling.
8923 		 */
8924 		cnt = phba->sli4_hba.nvmet_xri_cnt +
8925 			phba->sli4_hba.max_cfg_param.max_xri;
8926 	} else {
8927 		/* update host common xri-sgl sizes and mappings */
8928 		rc = lpfc_sli4_io_sgl_update(phba);
8929 		if (unlikely(rc)) {
8930 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8931 					"6082 Failed to update nvme-sgl size "
8932 					"and mapping: %d\n", rc);
8933 			goto out_destroy_queue;
8934 		}
8935 
8936 		/* register the allocated common sgl pool to the port */
8937 		rc = lpfc_sli4_repost_io_sgl_list(phba);
8938 		if (unlikely(rc)) {
8939 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8940 					"6116 Error %d during nvme sgl post "
8941 					"operation\n", rc);
8942 			/* Some NVME buffers were moved to abort nvme list */
8943 			/* A pci function reset will repost them */
8944 			rc = -ENODEV;
8945 			goto out_destroy_queue;
8946 		}
8947 		/* Each lpfc_io_buf job structure has an iocbq element.
8948 		 * This cnt provides for abort, els, ct and ls requests.
8949 		 */
8950 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
8951 	}
8952 
8953 	if (!phba->sli.iocbq_lookup) {
8954 		/* Initialize and populate the iocb list per host */
8955 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8956 				"2821 initialize iocb list with %d entries\n",
8957 				cnt);
8958 		rc = lpfc_init_iocb_list(phba, cnt);
8959 		if (rc) {
8960 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8961 					"1413 Failed to init iocb list.\n");
8962 			goto out_destroy_queue;
8963 		}
8964 	}
8965 
8966 	if (phba->nvmet_support)
8967 		lpfc_nvmet_create_targetport(phba);
8968 
8969 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
8970 		/* Post initial buffers to all RQs created */
8971 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
8972 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
8973 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
8974 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
8975 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
8976 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
8977 			rqbp->buffer_count = 0;
8978 
8979 			lpfc_post_rq_buffer(
8980 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
8981 				phba->sli4_hba.nvmet_mrq_data[i],
8982 				phba->cfg_nvmet_mrq_post, i);
8983 		}
8984 	}
8985 
8986 	/* Post the rpi header region to the device. */
8987 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
8988 	if (unlikely(rc)) {
8989 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8990 				"0393 Error %d during rpi post operation\n",
8991 				rc);
8992 		rc = -ENODEV;
8993 		goto out_free_iocblist;
8994 	}
8995 
8996 	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag)) {
8997 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
8998 			/*
8999 			 * The FC Port needs to register FCFI (index 0)
9000 			 */
9001 			lpfc_reg_fcfi(phba, mboxq);
9002 			mboxq->vport = phba->pport;
9003 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9004 			if (rc != MBX_SUCCESS)
9005 				goto out_unset_queue;
9006 			rc = 0;
9007 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
9008 						&mboxq->u.mqe.un.reg_fcfi);
9009 		} else {
9010 			/* We are a NVME Target mode with MRQ > 1 */
9011 
9012 			/* First register the FCFI */
9013 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
9014 			mboxq->vport = phba->pport;
9015 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9016 			if (rc != MBX_SUCCESS)
9017 				goto out_unset_queue;
9018 			rc = 0;
9019 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
9020 						&mboxq->u.mqe.un.reg_fcfi_mrq);
9021 
9022 			/* Next register the MRQs */
9023 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
9024 			mboxq->vport = phba->pport;
9025 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9026 			if (rc != MBX_SUCCESS)
9027 				goto out_unset_queue;
9028 			rc = 0;
9029 		}
9030 		/* Check if the port is configured to be disabled */
9031 		lpfc_sli_read_link_ste(phba);
9032 	}
9033 
9034 	/* Don't post more new bufs if repost already recovered
9035 	 * the nvme sgls.
9036 	 */
9037 	if (phba->nvmet_support == 0) {
9038 		if (phba->sli4_hba.io_xri_cnt == 0) {
9039 			len = lpfc_new_io_buf(
9040 					      phba, phba->sli4_hba.io_xri_max);
9041 			if (len == 0) {
9042 				rc = -ENOMEM;
9043 				goto out_unset_queue;
9044 			}
9045 
9046 			if (phba->cfg_xri_rebalancing)
9047 				lpfc_create_multixri_pools(phba);
9048 		}
9049 	} else {
9050 		phba->cfg_xri_rebalancing = 0;
9051 	}
9052 
9053 	/* Allow asynchronous mailbox command to go through */
9054 	spin_lock_irq(&phba->hbalock);
9055 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9056 	spin_unlock_irq(&phba->hbalock);
9057 
9058 	/* Post receive buffers to the device */
9059 	lpfc_sli4_rb_setup(phba);
9060 
9061 	/* Reset HBA FCF states after HBA reset */
9062 	phba->fcf.fcf_flag = 0;
9063 	phba->fcf.current_rec.flag = 0;
9064 
9065 	/* Start the ELS watchdog timer */
9066 	mod_timer(&vport->els_tmofunc,
9067 			jiffies + secs_to_jiffies(phba->fc_ratov * 2));
9068 
9069 	/* Start heart beat timer */
9070 	mod_timer(&phba->hb_tmofunc,
9071 		  jiffies + secs_to_jiffies(LPFC_HB_MBOX_INTERVAL));
9072 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
9073 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
9074 	phba->last_completion_time = jiffies;
9075 
9076 	/* start eq_delay heartbeat */
9077 	if (phba->cfg_auto_imax)
9078 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
9079 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
9080 
9081 	/* start per phba idle_stat_delay heartbeat */
9082 	lpfc_init_idle_stat_hb(phba);
9083 
9084 	/* Start error attention (ERATT) polling timer */
9085 	mod_timer(&phba->eratt_poll,
9086 		  jiffies + secs_to_jiffies(phba->eratt_poll_interval));
9087 
9088 	/*
9089 	 * The port is ready, set the host's link state to LINK_DOWN
9090 	 * in preparation for link interrupts.
9091 	 */
9092 	spin_lock_irq(&phba->hbalock);
9093 	phba->link_state = LPFC_LINK_DOWN;
9094 
9095 	/* Check if physical ports are trunked */
9096 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
9097 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
9098 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
9099 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
9100 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
9101 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
9102 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
9103 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
9104 	spin_unlock_irq(&phba->hbalock);
9105 
9106 	/* Arm the CQs and then EQs on device */
9107 	lpfc_sli4_arm_cqeq_intr(phba);
9108 
9109 	/* Indicate device interrupt mode */
9110 	phba->sli4_hba.intr_enable = 1;
9111 
9112 	/* Setup CMF after HBA is initialized */
9113 	lpfc_cmf_setup(phba);
9114 
9115 	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag) &&
9116 	    test_bit(LINK_DISABLED, &phba->hba_flag)) {
9117 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9118 				"3103 Adapter Link is disabled.\n");
9119 		lpfc_down_link(phba, mboxq);
9120 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9121 		if (rc != MBX_SUCCESS) {
9122 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9123 					"3104 Adapter failed to issue "
9124 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
9125 			goto out_io_buff_free;
9126 		}
9127 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
9128 		/* don't perform init_link on SLI4 FC port loopback test */
9129 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
9130 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
9131 			if (rc)
9132 				goto out_io_buff_free;
9133 		}
9134 	}
9135 	mempool_free(mboxq, phba->mbox_mem_pool);
9136 
9137 	/* Enable RAS FW log support */
9138 	lpfc_sli4_ras_setup(phba);
9139 
9140 	set_bit(HBA_SETUP, &phba->hba_flag);
9141 	return rc;
9142 
9143 out_io_buff_free:
9144 	/* Free allocated IO Buffers */
9145 	lpfc_io_free(phba);
9146 out_unset_queue:
9147 	/* Unset all the queues set up in this routine when error out */
9148 	lpfc_sli4_queue_unset(phba);
9149 out_free_iocblist:
9150 	lpfc_free_iocb_list(phba);
9151 out_destroy_queue:
9152 	lpfc_sli4_queue_destroy(phba);
9153 	lpfc_stop_hba_timers(phba);
9154 out_free_mbox:
9155 	mempool_free(mboxq, phba->mbox_mem_pool);
9156 	return rc;
9157 }
9158 
9159 /**
9160  * lpfc_mbox_timeout - Timeout call back function for mbox timer
9161  * @t: Context to fetch pointer to hba structure from.
9162  *
9163  * This is the callback function for mailbox timer. The mailbox
9164  * timer is armed when a new mailbox command is issued and the timer
9165  * is deleted when the mailbox complete. The function is called by
9166  * the kernel timer code when a mailbox does not complete within
9167  * expected time. This function wakes up the worker thread to
9168  * process the mailbox timeout and returns. All the processing is
9169  * done by the worker thread function lpfc_mbox_timeout_handler.
9170  **/
9171 void
9172 lpfc_mbox_timeout(struct timer_list *t)
9173 {
9174 	struct lpfc_hba  *phba = timer_container_of(phba, t, sli.mbox_tmo);
9175 	unsigned long iflag;
9176 	uint32_t tmo_posted;
9177 
9178 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
9179 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
9180 	if (!tmo_posted)
9181 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
9182 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
9183 
9184 	if (!tmo_posted)
9185 		lpfc_worker_wake_up(phba);
9186 	return;
9187 }
9188 
9189 /**
9190  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
9191  *                                    are pending
9192  * @phba: Pointer to HBA context object.
9193  *
9194  * This function checks if any mailbox completions are present on the mailbox
9195  * completion queue.
9196  **/
9197 static bool
9198 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
9199 {
9200 
9201 	uint32_t idx;
9202 	struct lpfc_queue *mcq;
9203 	struct lpfc_mcqe *mcqe;
9204 	bool pending_completions = false;
9205 	uint8_t	qe_valid;
9206 
9207 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9208 		return false;
9209 
9210 	/* Check for completions on mailbox completion queue */
9211 
9212 	mcq = phba->sli4_hba.mbx_cq;
9213 	idx = mcq->hba_index;
9214 	qe_valid = mcq->qe_valid;
9215 	while (bf_get_le32(lpfc_cqe_valid,
9216 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
9217 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
9218 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
9219 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
9220 			pending_completions = true;
9221 			break;
9222 		}
9223 		idx = (idx + 1) % mcq->entry_count;
9224 		if (mcq->hba_index == idx)
9225 			break;
9226 
9227 		/* if the index wrapped around, toggle the valid bit */
9228 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
9229 			qe_valid = (qe_valid) ? 0 : 1;
9230 	}
9231 	return pending_completions;
9232 
9233 }
9234 
9235 /**
9236  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
9237  *					      that were missed.
9238  * @phba: Pointer to HBA context object.
9239  *
9240  * For sli4, it is possible to miss an interrupt. As such mbox completions
9241  * maybe missed causing erroneous mailbox timeouts to occur. This function
9242  * checks to see if mbox completions are on the mailbox completion queue
9243  * and will process all the completions associated with the eq for the
9244  * mailbox completion queue.
9245  **/
9246 static bool
9247 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
9248 {
9249 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
9250 	uint32_t eqidx;
9251 	struct lpfc_queue *fpeq = NULL;
9252 	struct lpfc_queue *eq;
9253 	bool mbox_pending;
9254 
9255 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9256 		return false;
9257 
9258 	/* Find the EQ associated with the mbox CQ */
9259 	if (sli4_hba->hdwq) {
9260 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
9261 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
9262 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
9263 				fpeq = eq;
9264 				break;
9265 			}
9266 		}
9267 	}
9268 	if (!fpeq)
9269 		return false;
9270 
9271 	/* Turn off interrupts from this EQ */
9272 
9273 	sli4_hba->sli4_eq_clr_intr(fpeq);
9274 
9275 	/* Check to see if a mbox completion is pending */
9276 
9277 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
9278 
9279 	/*
9280 	 * If a mbox completion is pending, process all the events on EQ
9281 	 * associated with the mbox completion queue (this could include
9282 	 * mailbox commands, async events, els commands, receive queue data
9283 	 * and fcp commands)
9284 	 */
9285 
9286 	if (mbox_pending)
9287 		/* process and rearm the EQ */
9288 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
9289 				     LPFC_QUEUE_WORK);
9290 	else
9291 		/* Always clear and re-arm the EQ */
9292 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
9293 
9294 	return mbox_pending;
9295 
9296 }
9297 
9298 /**
9299  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
9300  * @phba: Pointer to HBA context object.
9301  *
9302  * This function is called from worker thread when a mailbox command times out.
9303  * The caller is not required to hold any locks. This function will reset the
9304  * HBA and recover all the pending commands.
9305  **/
9306 void
9307 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
9308 {
9309 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
9310 	MAILBOX_t *mb = NULL;
9311 
9312 	struct lpfc_sli *psli = &phba->sli;
9313 
9314 	/* If the mailbox completed, process the completion */
9315 	lpfc_sli4_process_missed_mbox_completions(phba);
9316 
9317 	if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
9318 		return;
9319 
9320 	if (pmbox != NULL)
9321 		mb = &pmbox->u.mb;
9322 	/* Check the pmbox pointer first.  There is a race condition
9323 	 * between the mbox timeout handler getting executed in the
9324 	 * worklist and the mailbox actually completing. When this
9325 	 * race condition occurs, the mbox_active will be NULL.
9326 	 */
9327 	spin_lock_irq(&phba->hbalock);
9328 	if (pmbox == NULL) {
9329 		lpfc_printf_log(phba, KERN_WARNING,
9330 				LOG_MBOX | LOG_SLI,
9331 				"0353 Active Mailbox cleared - mailbox timeout "
9332 				"exiting\n");
9333 		spin_unlock_irq(&phba->hbalock);
9334 		return;
9335 	}
9336 
9337 	/* Mbox cmd <mbxCommand> timeout */
9338 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9339 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
9340 			mb->mbxCommand,
9341 			phba->pport->port_state,
9342 			phba->sli.sli_flag,
9343 			phba->sli.mbox_active);
9344 	spin_unlock_irq(&phba->hbalock);
9345 
9346 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
9347 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
9348 	 * it to fail all outstanding SCSI IO.
9349 	 */
9350 	set_bit(MBX_TMO_ERR, &phba->bit_flags);
9351 	spin_lock_irq(&phba->pport->work_port_lock);
9352 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9353 	spin_unlock_irq(&phba->pport->work_port_lock);
9354 	spin_lock_irq(&phba->hbalock);
9355 	phba->link_state = LPFC_LINK_UNKNOWN;
9356 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
9357 	spin_unlock_irq(&phba->hbalock);
9358 
9359 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9360 			"0345 Resetting board due to mailbox timeout\n");
9361 
9362 	/* Reset the HBA device */
9363 	lpfc_reset_hba(phba);
9364 }
9365 
9366 /**
9367  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
9368  * @phba: Pointer to HBA context object.
9369  * @pmbox: Pointer to mailbox object.
9370  * @flag: Flag indicating how the mailbox need to be processed.
9371  *
9372  * This function is called by discovery code and HBA management code
9373  * to submit a mailbox command to firmware with SLI-3 interface spec. This
9374  * function gets the hbalock to protect the data structures.
9375  * The mailbox command can be submitted in polling mode, in which case
9376  * this function will wait in a polling loop for the completion of the
9377  * mailbox.
9378  * If the mailbox is submitted in no_wait mode (not polling) the
9379  * function will submit the command and returns immediately without waiting
9380  * for the mailbox completion. The no_wait is supported only when HBA
9381  * is in SLI2/SLI3 mode - interrupts are enabled.
9382  * The SLI interface allows only one mailbox pending at a time. If the
9383  * mailbox is issued in polling mode and there is already a mailbox
9384  * pending, then the function will return an error. If the mailbox is issued
9385  * in NO_WAIT mode and there is a mailbox pending already, the function
9386  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
9387  * The sli layer owns the mailbox object until the completion of mailbox
9388  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
9389  * return codes the caller owns the mailbox command after the return of
9390  * the function.
9391  **/
9392 static int
9393 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
9394 		       uint32_t flag)
9395 {
9396 	MAILBOX_t *mbx;
9397 	struct lpfc_sli *psli = &phba->sli;
9398 	uint32_t status, evtctr;
9399 	uint32_t ha_copy, hc_copy;
9400 	int i;
9401 	unsigned long timeout;
9402 	unsigned long drvr_flag = 0;
9403 	uint32_t word0, ldata;
9404 	void __iomem *to_slim;
9405 	int processing_queue = 0;
9406 
9407 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
9408 	if (!pmbox) {
9409 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9410 		/* processing mbox queue from intr_handler */
9411 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9412 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9413 			return MBX_SUCCESS;
9414 		}
9415 		processing_queue = 1;
9416 		pmbox = lpfc_mbox_get(phba);
9417 		if (!pmbox) {
9418 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9419 			return MBX_SUCCESS;
9420 		}
9421 	}
9422 
9423 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
9424 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
9425 		if(!pmbox->vport) {
9426 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9427 			lpfc_printf_log(phba, KERN_ERR,
9428 					LOG_MBOX | LOG_VPORT,
9429 					"1806 Mbox x%x failed. No vport\n",
9430 					pmbox->u.mb.mbxCommand);
9431 			dump_stack();
9432 			goto out_not_finished;
9433 		}
9434 	}
9435 
9436 	/* If the PCI channel is in offline state, do not post mbox. */
9437 	if (unlikely(pci_channel_offline(phba->pcidev))) {
9438 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9439 		goto out_not_finished;
9440 	}
9441 
9442 	/* If HBA has a deferred error attention, fail the iocb. */
9443 	if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag))) {
9444 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9445 		goto out_not_finished;
9446 	}
9447 
9448 	psli = &phba->sli;
9449 
9450 	mbx = &pmbox->u.mb;
9451 	status = MBX_SUCCESS;
9452 
9453 	if (phba->link_state == LPFC_HBA_ERROR) {
9454 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9455 
9456 		/* Mbox command <mbxCommand> cannot issue */
9457 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9458 				"(%d):0311 Mailbox command x%x cannot "
9459 				"issue Data: x%x x%x\n",
9460 				pmbox->vport ? pmbox->vport->vpi : 0,
9461 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9462 		goto out_not_finished;
9463 	}
9464 
9465 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
9466 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
9467 			!(hc_copy & HC_MBINT_ENA)) {
9468 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9469 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9470 				"(%d):2528 Mailbox command x%x cannot "
9471 				"issue Data: x%x x%x\n",
9472 				pmbox->vport ? pmbox->vport->vpi : 0,
9473 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9474 			goto out_not_finished;
9475 		}
9476 	}
9477 
9478 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9479 		/* Polling for a mbox command when another one is already active
9480 		 * is not allowed in SLI. Also, the driver must have established
9481 		 * SLI2 mode to queue and process multiple mbox commands.
9482 		 */
9483 
9484 		if (flag & MBX_POLL) {
9485 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9486 
9487 			/* Mbox command <mbxCommand> cannot issue */
9488 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9489 					"(%d):2529 Mailbox command x%x "
9490 					"cannot issue Data: x%x x%x\n",
9491 					pmbox->vport ? pmbox->vport->vpi : 0,
9492 					pmbox->u.mb.mbxCommand,
9493 					psli->sli_flag, flag);
9494 			goto out_not_finished;
9495 		}
9496 
9497 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
9498 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9499 			/* Mbox command <mbxCommand> cannot issue */
9500 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9501 					"(%d):2530 Mailbox command x%x "
9502 					"cannot issue Data: x%x x%x\n",
9503 					pmbox->vport ? pmbox->vport->vpi : 0,
9504 					pmbox->u.mb.mbxCommand,
9505 					psli->sli_flag, flag);
9506 			goto out_not_finished;
9507 		}
9508 
9509 		/* Another mailbox command is still being processed, queue this
9510 		 * command to be processed later.
9511 		 */
9512 		lpfc_mbox_put(phba, pmbox);
9513 
9514 		/* Mbox cmd issue - BUSY */
9515 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9516 				"(%d):0308 Mbox cmd issue - BUSY Data: "
9517 				"x%x x%x x%x x%x\n",
9518 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
9519 				mbx->mbxCommand,
9520 				phba->pport ? phba->pport->port_state : 0xff,
9521 				psli->sli_flag, flag);
9522 
9523 		psli->slistat.mbox_busy++;
9524 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9525 
9526 		if (pmbox->vport) {
9527 			lpfc_debugfs_disc_trc(pmbox->vport,
9528 				LPFC_DISC_TRC_MBOX_VPORT,
9529 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
9530 				(uint32_t)mbx->mbxCommand,
9531 				mbx->un.varWords[0], mbx->un.varWords[1]);
9532 		}
9533 		else {
9534 			lpfc_debugfs_disc_trc(phba->pport,
9535 				LPFC_DISC_TRC_MBOX,
9536 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
9537 				(uint32_t)mbx->mbxCommand,
9538 				mbx->un.varWords[0], mbx->un.varWords[1]);
9539 		}
9540 
9541 		return MBX_BUSY;
9542 	}
9543 
9544 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9545 
9546 	/* If we are not polling, we MUST be in SLI2 mode */
9547 	if (flag != MBX_POLL) {
9548 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
9549 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
9550 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9551 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9552 			/* Mbox command <mbxCommand> cannot issue */
9553 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9554 					"(%d):2531 Mailbox command x%x "
9555 					"cannot issue Data: x%x x%x\n",
9556 					pmbox->vport ? pmbox->vport->vpi : 0,
9557 					pmbox->u.mb.mbxCommand,
9558 					psli->sli_flag, flag);
9559 			goto out_not_finished;
9560 		}
9561 		/* timeout active mbox command */
9562 		timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox));
9563 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
9564 	}
9565 
9566 	/* Mailbox cmd <cmd> issue */
9567 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9568 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
9569 			"x%x\n",
9570 			pmbox->vport ? pmbox->vport->vpi : 0,
9571 			mbx->mbxCommand,
9572 			phba->pport ? phba->pport->port_state : 0xff,
9573 			psli->sli_flag, flag);
9574 
9575 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
9576 		if (pmbox->vport) {
9577 			lpfc_debugfs_disc_trc(pmbox->vport,
9578 				LPFC_DISC_TRC_MBOX_VPORT,
9579 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9580 				(uint32_t)mbx->mbxCommand,
9581 				mbx->un.varWords[0], mbx->un.varWords[1]);
9582 		}
9583 		else {
9584 			lpfc_debugfs_disc_trc(phba->pport,
9585 				LPFC_DISC_TRC_MBOX,
9586 				"MBOX Send:       cmd:x%x mb:x%x x%x",
9587 				(uint32_t)mbx->mbxCommand,
9588 				mbx->un.varWords[0], mbx->un.varWords[1]);
9589 		}
9590 	}
9591 
9592 	psli->slistat.mbox_cmd++;
9593 	evtctr = psli->slistat.mbox_event;
9594 
9595 	/* next set own bit for the adapter and copy over command word */
9596 	mbx->mbxOwner = OWN_CHIP;
9597 
9598 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9599 		/* Populate mbox extension offset word. */
9600 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
9601 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9602 				= (uint8_t *)phba->mbox_ext
9603 				  - (uint8_t *)phba->mbox;
9604 		}
9605 
9606 		/* Copy the mailbox extension data */
9607 		if (pmbox->in_ext_byte_len && pmbox->ext_buf) {
9608 			lpfc_sli_pcimem_bcopy(pmbox->ext_buf,
9609 					      (uint8_t *)phba->mbox_ext,
9610 					      pmbox->in_ext_byte_len);
9611 		}
9612 		/* Copy command data to host SLIM area */
9613 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
9614 	} else {
9615 		/* Populate mbox extension offset word. */
9616 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
9617 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9618 				= MAILBOX_HBA_EXT_OFFSET;
9619 
9620 		/* Copy the mailbox extension data */
9621 		if (pmbox->in_ext_byte_len && pmbox->ext_buf)
9622 			lpfc_memcpy_to_slim(phba->MBslimaddr +
9623 				MAILBOX_HBA_EXT_OFFSET,
9624 				pmbox->ext_buf, pmbox->in_ext_byte_len);
9625 
9626 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9627 			/* copy command data into host mbox for cmpl */
9628 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
9629 					      MAILBOX_CMD_SIZE);
9630 
9631 		/* First copy mbox command data to HBA SLIM, skip past first
9632 		   word */
9633 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
9634 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
9635 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
9636 
9637 		/* Next copy over first word, with mbxOwner set */
9638 		ldata = *((uint32_t *)mbx);
9639 		to_slim = phba->MBslimaddr;
9640 		writel(ldata, to_slim);
9641 		readl(to_slim); /* flush */
9642 
9643 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9644 			/* switch over to host mailbox */
9645 			psli->sli_flag |= LPFC_SLI_ACTIVE;
9646 	}
9647 
9648 	wmb();
9649 
9650 	switch (flag) {
9651 	case MBX_NOWAIT:
9652 		/* Set up reference to mailbox command */
9653 		psli->mbox_active = pmbox;
9654 		/* Interrupt board to do it */
9655 		writel(CA_MBATT, phba->CAregaddr);
9656 		readl(phba->CAregaddr); /* flush */
9657 		/* Don't wait for it to finish, just return */
9658 		break;
9659 
9660 	case MBX_POLL:
9661 		/* Set up null reference to mailbox command */
9662 		psli->mbox_active = NULL;
9663 		/* Interrupt board to do it */
9664 		writel(CA_MBATT, phba->CAregaddr);
9665 		readl(phba->CAregaddr); /* flush */
9666 
9667 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9668 			/* First read mbox status word */
9669 			word0 = *((uint32_t *)phba->mbox);
9670 			word0 = le32_to_cpu(word0);
9671 		} else {
9672 			/* First read mbox status word */
9673 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
9674 				spin_unlock_irqrestore(&phba->hbalock,
9675 						       drvr_flag);
9676 				goto out_not_finished;
9677 			}
9678 		}
9679 
9680 		/* Read the HBA Host Attention Register */
9681 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9682 			spin_unlock_irqrestore(&phba->hbalock,
9683 						       drvr_flag);
9684 			goto out_not_finished;
9685 		}
9686 		timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox)) + jiffies;
9687 		i = 0;
9688 		/* Wait for command to complete */
9689 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
9690 		       (!(ha_copy & HA_MBATT) &&
9691 			(phba->link_state > LPFC_WARM_START))) {
9692 			if (time_after(jiffies, timeout)) {
9693 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9694 				spin_unlock_irqrestore(&phba->hbalock,
9695 						       drvr_flag);
9696 				goto out_not_finished;
9697 			}
9698 
9699 			/* Check if we took a mbox interrupt while we were
9700 			   polling */
9701 			if (((word0 & OWN_CHIP) != OWN_CHIP)
9702 			    && (evtctr != psli->slistat.mbox_event))
9703 				break;
9704 
9705 			if (i++ > 10) {
9706 				spin_unlock_irqrestore(&phba->hbalock,
9707 						       drvr_flag);
9708 				msleep(1);
9709 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
9710 			}
9711 
9712 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9713 				/* First copy command data */
9714 				word0 = *((uint32_t *)phba->mbox);
9715 				word0 = le32_to_cpu(word0);
9716 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
9717 					MAILBOX_t *slimmb;
9718 					uint32_t slimword0;
9719 					/* Check real SLIM for any errors */
9720 					slimword0 = readl(phba->MBslimaddr);
9721 					slimmb = (MAILBOX_t *) & slimword0;
9722 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
9723 					    && slimmb->mbxStatus) {
9724 						psli->sli_flag &=
9725 						    ~LPFC_SLI_ACTIVE;
9726 						word0 = slimword0;
9727 					}
9728 				}
9729 			} else {
9730 				/* First copy command data */
9731 				word0 = readl(phba->MBslimaddr);
9732 			}
9733 			/* Read the HBA Host Attention Register */
9734 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9735 				spin_unlock_irqrestore(&phba->hbalock,
9736 						       drvr_flag);
9737 				goto out_not_finished;
9738 			}
9739 		}
9740 
9741 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9742 			/* copy results back to user */
9743 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
9744 						MAILBOX_CMD_SIZE);
9745 			/* Copy the mailbox extension data */
9746 			if (pmbox->out_ext_byte_len && pmbox->ext_buf) {
9747 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
9748 						      pmbox->ext_buf,
9749 						      pmbox->out_ext_byte_len);
9750 			}
9751 		} else {
9752 			/* First copy command data */
9753 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
9754 						MAILBOX_CMD_SIZE);
9755 			/* Copy the mailbox extension data */
9756 			if (pmbox->out_ext_byte_len && pmbox->ext_buf) {
9757 				lpfc_memcpy_from_slim(
9758 					pmbox->ext_buf,
9759 					phba->MBslimaddr +
9760 					MAILBOX_HBA_EXT_OFFSET,
9761 					pmbox->out_ext_byte_len);
9762 			}
9763 		}
9764 
9765 		writel(HA_MBATT, phba->HAregaddr);
9766 		readl(phba->HAregaddr); /* flush */
9767 
9768 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9769 		status = mbx->mbxStatus;
9770 	}
9771 
9772 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9773 	return status;
9774 
9775 out_not_finished:
9776 	if (processing_queue) {
9777 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
9778 		lpfc_mbox_cmpl_put(phba, pmbox);
9779 	}
9780 	return MBX_NOT_FINISHED;
9781 }
9782 
9783 /**
9784  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
9785  * @phba: Pointer to HBA context object.
9786  *
9787  * The function blocks the posting of SLI4 asynchronous mailbox commands from
9788  * the driver internal pending mailbox queue. It will then try to wait out the
9789  * possible outstanding mailbox command before return.
9790  *
9791  * Returns:
9792  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
9793  * 	the outstanding mailbox command timed out.
9794  **/
9795 static int
9796 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
9797 {
9798 	struct lpfc_sli *psli = &phba->sli;
9799 	LPFC_MBOXQ_t *mboxq;
9800 	int rc = 0;
9801 	unsigned long timeout = 0;
9802 	u32 sli_flag;
9803 	u8 cmd, subsys, opcode;
9804 
9805 	/* Mark the asynchronous mailbox command posting as blocked */
9806 	spin_lock_irq(&phba->hbalock);
9807 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
9808 	/* Determine how long we might wait for the active mailbox
9809 	 * command to be gracefully completed by firmware.
9810 	 */
9811 	if (phba->sli.mbox_active)
9812 		timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba,
9813 						phba->sli.mbox_active)) + jiffies;
9814 	spin_unlock_irq(&phba->hbalock);
9815 
9816 	/* Make sure the mailbox is really active */
9817 	if (timeout)
9818 		lpfc_sli4_process_missed_mbox_completions(phba);
9819 
9820 	/* Wait for the outstanding mailbox command to complete */
9821 	while (phba->sli.mbox_active) {
9822 		/* Check active mailbox complete status every 2ms */
9823 		msleep(2);
9824 		if (time_after(jiffies, timeout)) {
9825 			/* Timeout, mark the outstanding cmd not complete */
9826 
9827 			/* Sanity check sli.mbox_active has not completed or
9828 			 * cancelled from another context during last 2ms sleep,
9829 			 * so take hbalock to be sure before logging.
9830 			 */
9831 			spin_lock_irq(&phba->hbalock);
9832 			if (phba->sli.mbox_active) {
9833 				mboxq = phba->sli.mbox_active;
9834 				cmd = mboxq->u.mb.mbxCommand;
9835 				subsys = lpfc_sli_config_mbox_subsys_get(phba,
9836 									 mboxq);
9837 				opcode = lpfc_sli_config_mbox_opcode_get(phba,
9838 									 mboxq);
9839 				sli_flag = psli->sli_flag;
9840 				spin_unlock_irq(&phba->hbalock);
9841 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9842 						"2352 Mailbox command x%x "
9843 						"(x%x/x%x) sli_flag x%x could "
9844 						"not complete\n",
9845 						cmd, subsys, opcode,
9846 						sli_flag);
9847 			} else {
9848 				spin_unlock_irq(&phba->hbalock);
9849 			}
9850 
9851 			rc = 1;
9852 			break;
9853 		}
9854 	}
9855 
9856 	/* Can not cleanly block async mailbox command, fails it */
9857 	if (rc) {
9858 		spin_lock_irq(&phba->hbalock);
9859 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9860 		spin_unlock_irq(&phba->hbalock);
9861 	}
9862 	return rc;
9863 }
9864 
9865 /**
9866  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
9867  * @phba: Pointer to HBA context object.
9868  *
9869  * The function unblocks and resume posting of SLI4 asynchronous mailbox
9870  * commands from the driver internal pending mailbox queue. It makes sure
9871  * that there is no outstanding mailbox command before resuming posting
9872  * asynchronous mailbox commands. If, for any reason, there is outstanding
9873  * mailbox command, it will try to wait it out before resuming asynchronous
9874  * mailbox command posting.
9875  **/
9876 static void
9877 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
9878 {
9879 	struct lpfc_sli *psli = &phba->sli;
9880 
9881 	spin_lock_irq(&phba->hbalock);
9882 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9883 		/* Asynchronous mailbox posting is not blocked, do nothing */
9884 		spin_unlock_irq(&phba->hbalock);
9885 		return;
9886 	}
9887 
9888 	/* Outstanding synchronous mailbox command is guaranteed to be done,
9889 	 * successful or timeout, after timing-out the outstanding mailbox
9890 	 * command shall always be removed, so just unblock posting async
9891 	 * mailbox command and resume
9892 	 */
9893 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9894 	spin_unlock_irq(&phba->hbalock);
9895 
9896 	/* wake up worker thread to post asynchronous mailbox command */
9897 	lpfc_worker_wake_up(phba);
9898 }
9899 
9900 /**
9901  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
9902  * @phba: Pointer to HBA context object.
9903  * @mboxq: Pointer to mailbox object.
9904  *
9905  * The function waits for the bootstrap mailbox register ready bit from
9906  * port for twice the regular mailbox command timeout value.
9907  *
9908  *      0 - no timeout on waiting for bootstrap mailbox register ready.
9909  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out or port
9910  *                     is in an unrecoverable state.
9911  **/
9912 static int
9913 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9914 {
9915 	uint32_t db_ready;
9916 	unsigned long timeout;
9917 	struct lpfc_register bmbx_reg;
9918 	struct lpfc_register portstat_reg = {-1};
9919 
9920 	/* Sanity check - there is no point to wait if the port is in an
9921 	 * unrecoverable state.
9922 	 */
9923 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
9924 	    LPFC_SLI_INTF_IF_TYPE_2) {
9925 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9926 			       &portstat_reg.word0) ||
9927 		    lpfc_sli4_unrecoverable_port(&portstat_reg)) {
9928 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9929 					"3858 Skipping bmbx ready because "
9930 					"Port Status x%x\n",
9931 					portstat_reg.word0);
9932 			return MBXERR_ERROR;
9933 		}
9934 	}
9935 
9936 	timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)) + jiffies;
9937 
9938 	do {
9939 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
9940 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
9941 		if (!db_ready)
9942 			mdelay(2);
9943 
9944 		if (time_after(jiffies, timeout))
9945 			return MBXERR_ERROR;
9946 	} while (!db_ready);
9947 
9948 	return 0;
9949 }
9950 
9951 /**
9952  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
9953  * @phba: Pointer to HBA context object.
9954  * @mboxq: Pointer to mailbox object.
9955  *
9956  * The function posts a mailbox to the port.  The mailbox is expected
9957  * to be comletely filled in and ready for the port to operate on it.
9958  * This routine executes a synchronous completion operation on the
9959  * mailbox by polling for its completion.
9960  *
9961  * The caller must not be holding any locks when calling this routine.
9962  *
9963  * Returns:
9964  *	MBX_SUCCESS - mailbox posted successfully
9965  *	Any of the MBX error values.
9966  **/
9967 static int
9968 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9969 {
9970 	int rc = MBX_SUCCESS;
9971 	unsigned long iflag;
9972 	uint32_t mcqe_status;
9973 	uint32_t mbx_cmnd;
9974 	struct lpfc_sli *psli = &phba->sli;
9975 	struct lpfc_mqe *mb = &mboxq->u.mqe;
9976 	struct lpfc_bmbx_create *mbox_rgn;
9977 	struct dma_address *dma_address;
9978 
9979 	/*
9980 	 * Only one mailbox can be active to the bootstrap mailbox region
9981 	 * at a time and there is no queueing provided.
9982 	 */
9983 	spin_lock_irqsave(&phba->hbalock, iflag);
9984 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9985 		spin_unlock_irqrestore(&phba->hbalock, iflag);
9986 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9987 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
9988 				"cannot issue Data: x%x x%x\n",
9989 				mboxq->vport ? mboxq->vport->vpi : 0,
9990 				mboxq->u.mb.mbxCommand,
9991 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9992 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9993 				psli->sli_flag, MBX_POLL);
9994 		return MBXERR_ERROR;
9995 	}
9996 	/* The server grabs the token and owns it until release */
9997 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9998 	phba->sli.mbox_active = mboxq;
9999 	spin_unlock_irqrestore(&phba->hbalock, iflag);
10000 
10001 	/* wait for bootstrap mbox register for readiness */
10002 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
10003 	if (rc)
10004 		goto exit;
10005 	/*
10006 	 * Initialize the bootstrap memory region to avoid stale data areas
10007 	 * in the mailbox post.  Then copy the caller's mailbox contents to
10008 	 * the bmbx mailbox region.
10009 	 */
10010 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
10011 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
10012 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
10013 			       sizeof(struct lpfc_mqe));
10014 
10015 	/* Post the high mailbox dma address to the port and wait for ready. */
10016 	dma_address = &phba->sli4_hba.bmbx.dma_address;
10017 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
10018 
10019 	/* wait for bootstrap mbox register for hi-address write done */
10020 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
10021 	if (rc)
10022 		goto exit;
10023 
10024 	/* Post the low mailbox dma address to the port. */
10025 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
10026 
10027 	/* wait for bootstrap mbox register for low address write done */
10028 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
10029 	if (rc)
10030 		goto exit;
10031 
10032 	/*
10033 	 * Read the CQ to ensure the mailbox has completed.
10034 	 * If so, update the mailbox status so that the upper layers
10035 	 * can complete the request normally.
10036 	 */
10037 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
10038 			       sizeof(struct lpfc_mqe));
10039 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
10040 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
10041 			       sizeof(struct lpfc_mcqe));
10042 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
10043 	/*
10044 	 * When the CQE status indicates a failure and the mailbox status
10045 	 * indicates success then copy the CQE status into the mailbox status
10046 	 * (and prefix it with x4000).
10047 	 */
10048 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
10049 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
10050 			bf_set(lpfc_mqe_status, mb,
10051 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
10052 		rc = MBXERR_ERROR;
10053 	} else
10054 		lpfc_sli4_swap_str(phba, mboxq);
10055 
10056 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10057 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
10058 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
10059 			" x%x x%x CQ: x%x x%x x%x x%x\n",
10060 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10061 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10062 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10063 			bf_get(lpfc_mqe_status, mb),
10064 			mb->un.mb_words[0], mb->un.mb_words[1],
10065 			mb->un.mb_words[2], mb->un.mb_words[3],
10066 			mb->un.mb_words[4], mb->un.mb_words[5],
10067 			mb->un.mb_words[6], mb->un.mb_words[7],
10068 			mb->un.mb_words[8], mb->un.mb_words[9],
10069 			mb->un.mb_words[10], mb->un.mb_words[11],
10070 			mb->un.mb_words[12], mboxq->mcqe.word0,
10071 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
10072 			mboxq->mcqe.trailer);
10073 exit:
10074 	/* We are holding the token, no needed for lock when release */
10075 	spin_lock_irqsave(&phba->hbalock, iflag);
10076 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10077 	phba->sli.mbox_active = NULL;
10078 	spin_unlock_irqrestore(&phba->hbalock, iflag);
10079 	return rc;
10080 }
10081 
10082 /**
10083  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
10084  * @phba: Pointer to HBA context object.
10085  * @mboxq: Pointer to mailbox object.
10086  * @flag: Flag indicating how the mailbox need to be processed.
10087  *
10088  * This function is called by discovery code and HBA management code to submit
10089  * a mailbox command to firmware with SLI-4 interface spec.
10090  *
10091  * Return codes the caller owns the mailbox command after the return of the
10092  * function.
10093  **/
10094 static int
10095 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
10096 		       uint32_t flag)
10097 {
10098 	struct lpfc_sli *psli = &phba->sli;
10099 	unsigned long iflags;
10100 	int rc;
10101 
10102 	/* dump from issue mailbox command if setup */
10103 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
10104 
10105 	rc = lpfc_mbox_dev_check(phba);
10106 	if (unlikely(rc)) {
10107 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10108 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
10109 				"cannot issue Data: x%x x%x\n",
10110 				mboxq->vport ? mboxq->vport->vpi : 0,
10111 				mboxq->u.mb.mbxCommand,
10112 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10113 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10114 				psli->sli_flag, flag);
10115 		goto out_not_finished;
10116 	}
10117 
10118 	/* Detect polling mode and jump to a handler */
10119 	if (!phba->sli4_hba.intr_enable) {
10120 		if (flag == MBX_POLL)
10121 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10122 		else
10123 			rc = -EIO;
10124 		if (rc != MBX_SUCCESS)
10125 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10126 					"(%d):2541 Mailbox command x%x "
10127 					"(x%x/x%x) failure: "
10128 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
10129 					"Data: x%x x%x\n",
10130 					mboxq->vport ? mboxq->vport->vpi : 0,
10131 					mboxq->u.mb.mbxCommand,
10132 					lpfc_sli_config_mbox_subsys_get(phba,
10133 									mboxq),
10134 					lpfc_sli_config_mbox_opcode_get(phba,
10135 									mboxq),
10136 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10137 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10138 					bf_get(lpfc_mcqe_ext_status,
10139 					       &mboxq->mcqe),
10140 					psli->sli_flag, flag);
10141 		return rc;
10142 	} else if (flag == MBX_POLL) {
10143 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10144 				"(%d):2542 Try to issue mailbox command "
10145 				"x%x (x%x/x%x) synchronously ahead of async "
10146 				"mailbox command queue: x%x x%x\n",
10147 				mboxq->vport ? mboxq->vport->vpi : 0,
10148 				mboxq->u.mb.mbxCommand,
10149 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10150 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10151 				psli->sli_flag, flag);
10152 		/* Try to block the asynchronous mailbox posting */
10153 		rc = lpfc_sli4_async_mbox_block(phba);
10154 		if (!rc) {
10155 			/* Successfully blocked, now issue sync mbox cmd */
10156 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10157 			if (rc != MBX_SUCCESS)
10158 				lpfc_printf_log(phba, KERN_WARNING,
10159 					LOG_MBOX | LOG_SLI,
10160 					"(%d):2597 Sync Mailbox command "
10161 					"x%x (x%x/x%x) failure: "
10162 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
10163 					"Data: x%x x%x\n",
10164 					mboxq->vport ? mboxq->vport->vpi : 0,
10165 					mboxq->u.mb.mbxCommand,
10166 					lpfc_sli_config_mbox_subsys_get(phba,
10167 									mboxq),
10168 					lpfc_sli_config_mbox_opcode_get(phba,
10169 									mboxq),
10170 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10171 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10172 					bf_get(lpfc_mcqe_ext_status,
10173 					       &mboxq->mcqe),
10174 					psli->sli_flag, flag);
10175 			/* Unblock the async mailbox posting afterward */
10176 			lpfc_sli4_async_mbox_unblock(phba);
10177 		}
10178 		return rc;
10179 	}
10180 
10181 	/* Now, interrupt mode asynchronous mailbox command */
10182 	rc = lpfc_mbox_cmd_check(phba, mboxq);
10183 	if (rc) {
10184 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10185 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
10186 				"cannot issue Data: x%x x%x\n",
10187 				mboxq->vport ? mboxq->vport->vpi : 0,
10188 				mboxq->u.mb.mbxCommand,
10189 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10190 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10191 				psli->sli_flag, flag);
10192 		goto out_not_finished;
10193 	}
10194 
10195 	/* Put the mailbox command to the driver internal FIFO */
10196 	psli->slistat.mbox_busy++;
10197 	spin_lock_irqsave(&phba->hbalock, iflags);
10198 	lpfc_mbox_put(phba, mboxq);
10199 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10200 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10201 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
10202 			"x%x (x%x/x%x) x%x x%x x%x x%x\n",
10203 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
10204 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
10205 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10206 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10207 			mboxq->u.mb.un.varUnregLogin.rpi,
10208 			phba->pport->port_state,
10209 			psli->sli_flag, MBX_NOWAIT);
10210 	/* Wake up worker thread to transport mailbox command from head */
10211 	lpfc_worker_wake_up(phba);
10212 
10213 	return MBX_BUSY;
10214 
10215 out_not_finished:
10216 	return MBX_NOT_FINISHED;
10217 }
10218 
10219 /**
10220  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
10221  * @phba: Pointer to HBA context object.
10222  *
10223  * This function is called by worker thread to send a mailbox command to
10224  * SLI4 HBA firmware.
10225  *
10226  **/
10227 int
10228 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
10229 {
10230 	struct lpfc_sli *psli = &phba->sli;
10231 	LPFC_MBOXQ_t *mboxq;
10232 	int rc = MBX_SUCCESS;
10233 	unsigned long iflags;
10234 	struct lpfc_mqe *mqe;
10235 	uint32_t mbx_cmnd;
10236 
10237 	/* Check interrupt mode before post async mailbox command */
10238 	if (unlikely(!phba->sli4_hba.intr_enable))
10239 		return MBX_NOT_FINISHED;
10240 
10241 	/* Check for mailbox command service token */
10242 	spin_lock_irqsave(&phba->hbalock, iflags);
10243 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
10244 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10245 		return MBX_NOT_FINISHED;
10246 	}
10247 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
10248 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10249 		return MBX_NOT_FINISHED;
10250 	}
10251 	if (unlikely(phba->sli.mbox_active)) {
10252 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10253 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10254 				"0384 There is pending active mailbox cmd\n");
10255 		return MBX_NOT_FINISHED;
10256 	}
10257 	/* Take the mailbox command service token */
10258 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
10259 
10260 	/* Get the next mailbox command from head of queue */
10261 	mboxq = lpfc_mbox_get(phba);
10262 
10263 	/* If no more mailbox command waiting for post, we're done */
10264 	if (!mboxq) {
10265 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10266 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10267 		return MBX_SUCCESS;
10268 	}
10269 	phba->sli.mbox_active = mboxq;
10270 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10271 
10272 	/* Check device readiness for posting mailbox command */
10273 	rc = lpfc_mbox_dev_check(phba);
10274 	if (unlikely(rc))
10275 		/* Driver clean routine will clean up pending mailbox */
10276 		goto out_not_finished;
10277 
10278 	/* Prepare the mbox command to be posted */
10279 	mqe = &mboxq->u.mqe;
10280 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
10281 
10282 	/* Start timer for the mbox_tmo and log some mailbox post messages */
10283 	mod_timer(&psli->mbox_tmo, (jiffies +
10284 		  secs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq))));
10285 
10286 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10287 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
10288 			"x%x x%x\n",
10289 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10290 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10291 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10292 			phba->pport->port_state, psli->sli_flag);
10293 
10294 	if (mbx_cmnd != MBX_HEARTBEAT) {
10295 		if (mboxq->vport) {
10296 			lpfc_debugfs_disc_trc(mboxq->vport,
10297 				LPFC_DISC_TRC_MBOX_VPORT,
10298 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
10299 				mbx_cmnd, mqe->un.mb_words[0],
10300 				mqe->un.mb_words[1]);
10301 		} else {
10302 			lpfc_debugfs_disc_trc(phba->pport,
10303 				LPFC_DISC_TRC_MBOX,
10304 				"MBOX Send: cmd:x%x mb:x%x x%x",
10305 				mbx_cmnd, mqe->un.mb_words[0],
10306 				mqe->un.mb_words[1]);
10307 		}
10308 	}
10309 	psli->slistat.mbox_cmd++;
10310 
10311 	/* Post the mailbox command to the port */
10312 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
10313 	if (rc != MBX_SUCCESS) {
10314 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10315 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
10316 				"cannot issue Data: x%x x%x\n",
10317 				mboxq->vport ? mboxq->vport->vpi : 0,
10318 				mboxq->u.mb.mbxCommand,
10319 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10320 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10321 				psli->sli_flag, MBX_NOWAIT);
10322 		goto out_not_finished;
10323 	}
10324 
10325 	return rc;
10326 
10327 out_not_finished:
10328 	spin_lock_irqsave(&phba->hbalock, iflags);
10329 	if (phba->sli.mbox_active) {
10330 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
10331 		__lpfc_mbox_cmpl_put(phba, mboxq);
10332 		/* Release the token */
10333 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10334 		phba->sli.mbox_active = NULL;
10335 	}
10336 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10337 
10338 	return MBX_NOT_FINISHED;
10339 }
10340 
10341 /**
10342  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
10343  * @phba: Pointer to HBA context object.
10344  * @pmbox: Pointer to mailbox object.
10345  * @flag: Flag indicating how the mailbox need to be processed.
10346  *
10347  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
10348  * the API jump table function pointer from the lpfc_hba struct.
10349  *
10350  * Return codes the caller owns the mailbox command after the return of the
10351  * function.
10352  **/
10353 int
10354 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
10355 {
10356 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
10357 }
10358 
10359 /**
10360  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
10361  * @phba: The hba struct for which this call is being executed.
10362  * @dev_grp: The HBA PCI-Device group number.
10363  *
10364  * This routine sets up the mbox interface API function jump table in @phba
10365  * struct.
10366  * Returns: 0 - success, -ENODEV - failure.
10367  **/
10368 int
10369 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10370 {
10371 
10372 	switch (dev_grp) {
10373 	case LPFC_PCI_DEV_LP:
10374 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
10375 		phba->lpfc_sli_handle_slow_ring_event =
10376 				lpfc_sli_handle_slow_ring_event_s3;
10377 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
10378 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
10379 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
10380 		break;
10381 	case LPFC_PCI_DEV_OC:
10382 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
10383 		phba->lpfc_sli_handle_slow_ring_event =
10384 				lpfc_sli_handle_slow_ring_event_s4;
10385 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
10386 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
10387 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
10388 		break;
10389 	default:
10390 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10391 				"1420 Invalid HBA PCI-device group: 0x%x\n",
10392 				dev_grp);
10393 		return -ENODEV;
10394 	}
10395 	return 0;
10396 }
10397 
10398 /**
10399  * __lpfc_sli_ringtx_put - Add an iocb to the txq
10400  * @phba: Pointer to HBA context object.
10401  * @pring: Pointer to driver SLI ring object.
10402  * @piocb: Pointer to address of newly added command iocb.
10403  *
10404  * This function is called with hbalock held for SLI3 ports or
10405  * the ring lock held for SLI4 ports to add a command
10406  * iocb to the txq when SLI layer cannot submit the command iocb
10407  * to the ring.
10408  **/
10409 void
10410 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10411 		    struct lpfc_iocbq *piocb)
10412 {
10413 	if (phba->sli_rev == LPFC_SLI_REV4)
10414 		lockdep_assert_held(&pring->ring_lock);
10415 	else
10416 		lockdep_assert_held(&phba->hbalock);
10417 	/* Insert the caller's iocb in the txq tail for later processing. */
10418 	list_add_tail(&piocb->list, &pring->txq);
10419 }
10420 
10421 /**
10422  * lpfc_sli_next_iocb - Get the next iocb in the txq
10423  * @phba: Pointer to HBA context object.
10424  * @pring: Pointer to driver SLI ring object.
10425  * @piocb: Pointer to address of newly added command iocb.
10426  *
10427  * This function is called with hbalock held before a new
10428  * iocb is submitted to the firmware. This function checks
10429  * txq to flush the iocbs in txq to Firmware before
10430  * submitting new iocbs to the Firmware.
10431  * If there are iocbs in the txq which need to be submitted
10432  * to firmware, lpfc_sli_next_iocb returns the first element
10433  * of the txq after dequeuing it from txq.
10434  * If there is no iocb in the txq then the function will return
10435  * *piocb and *piocb is set to NULL. Caller needs to check
10436  * *piocb to find if there are more commands in the txq.
10437  **/
10438 static struct lpfc_iocbq *
10439 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10440 		   struct lpfc_iocbq **piocb)
10441 {
10442 	struct lpfc_iocbq * nextiocb;
10443 
10444 	lockdep_assert_held(&phba->hbalock);
10445 
10446 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
10447 	if (!nextiocb) {
10448 		nextiocb = *piocb;
10449 		*piocb = NULL;
10450 	}
10451 
10452 	return nextiocb;
10453 }
10454 
10455 /**
10456  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
10457  * @phba: Pointer to HBA context object.
10458  * @ring_number: SLI ring number to issue iocb on.
10459  * @piocb: Pointer to command iocb.
10460  * @flag: Flag indicating if this command can be put into txq.
10461  *
10462  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
10463  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
10464  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
10465  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
10466  * this function allows only iocbs for posting buffers. This function finds
10467  * next available slot in the command ring and posts the command to the
10468  * available slot and writes the port attention register to request HBA start
10469  * processing new iocb. If there is no slot available in the ring and
10470  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
10471  * the function returns IOCB_BUSY.
10472  *
10473  * This function is called with hbalock held. The function will return success
10474  * after it successfully submit the iocb to firmware or after adding to the
10475  * txq.
10476  **/
10477 static int
10478 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
10479 		    struct lpfc_iocbq *piocb, uint32_t flag)
10480 {
10481 	struct lpfc_iocbq *nextiocb;
10482 	IOCB_t *iocb;
10483 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
10484 
10485 	lockdep_assert_held(&phba->hbalock);
10486 
10487 	if (piocb->cmd_cmpl && (!piocb->vport) &&
10488 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
10489 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
10490 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10491 				"1807 IOCB x%x failed. No vport\n",
10492 				piocb->iocb.ulpCommand);
10493 		dump_stack();
10494 		return IOCB_ERROR;
10495 	}
10496 
10497 
10498 	/* If the PCI channel is in offline state, do not post iocbs. */
10499 	if (unlikely(pci_channel_offline(phba->pcidev)))
10500 		return IOCB_ERROR;
10501 
10502 	/* If HBA has a deferred error attention, fail the iocb. */
10503 	if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag)))
10504 		return IOCB_ERROR;
10505 
10506 	/*
10507 	 * We should never get an IOCB if we are in a < LINK_DOWN state
10508 	 */
10509 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
10510 		return IOCB_ERROR;
10511 
10512 	/*
10513 	 * Check to see if we are blocking IOCB processing because of a
10514 	 * outstanding event.
10515 	 */
10516 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
10517 		goto iocb_busy;
10518 
10519 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
10520 		/*
10521 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
10522 		 * can be issued if the link is not up.
10523 		 */
10524 		switch (piocb->iocb.ulpCommand) {
10525 		case CMD_QUE_RING_BUF_CN:
10526 		case CMD_QUE_RING_BUF64_CN:
10527 			/*
10528 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
10529 			 * completion, cmd_cmpl MUST be 0.
10530 			 */
10531 			if (piocb->cmd_cmpl)
10532 				piocb->cmd_cmpl = NULL;
10533 			fallthrough;
10534 		case CMD_CREATE_XRI_CR:
10535 		case CMD_CLOSE_XRI_CN:
10536 		case CMD_CLOSE_XRI_CX:
10537 			break;
10538 		default:
10539 			goto iocb_busy;
10540 		}
10541 
10542 	/*
10543 	 * For FCP commands, we must be in a state where we can process link
10544 	 * attention events.
10545 	 */
10546 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
10547 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
10548 		goto iocb_busy;
10549 	}
10550 
10551 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
10552 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
10553 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
10554 
10555 	if (iocb)
10556 		lpfc_sli_update_ring(phba, pring);
10557 	else
10558 		lpfc_sli_update_full_ring(phba, pring);
10559 
10560 	if (!piocb)
10561 		return IOCB_SUCCESS;
10562 
10563 	goto out_busy;
10564 
10565  iocb_busy:
10566 	pring->stats.iocb_cmd_delay++;
10567 
10568  out_busy:
10569 
10570 	if (!(flag & SLI_IOCB_RET_IOCB)) {
10571 		__lpfc_sli_ringtx_put(phba, pring, piocb);
10572 		return IOCB_SUCCESS;
10573 	}
10574 
10575 	return IOCB_BUSY;
10576 }
10577 
10578 /**
10579  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10580  * @phba: Pointer to HBA context object.
10581  * @ring_number: SLI ring number to issue wqe on.
10582  * @piocb: Pointer to command iocb.
10583  * @flag: Flag indicating if this command can be put into txq.
10584  *
10585  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10586  * send  an iocb command to an HBA with SLI-3 interface spec.
10587  *
10588  * This function takes the hbalock before invoking the lockless version.
10589  * The function will return success after it successfully submit the wqe to
10590  * firmware or after adding to the txq.
10591  **/
10592 static int
10593 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10594 			   struct lpfc_iocbq *piocb, uint32_t flag)
10595 {
10596 	unsigned long iflags;
10597 	int rc;
10598 
10599 	spin_lock_irqsave(&phba->hbalock, iflags);
10600 	rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10601 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10602 
10603 	return rc;
10604 }
10605 
10606 /**
10607  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10608  * @phba: Pointer to HBA context object.
10609  * @ring_number: SLI ring number to issue wqe on.
10610  * @piocb: Pointer to command iocb.
10611  * @flag: Flag indicating if this command can be put into txq.
10612  *
10613  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10614  * an wqe command to an HBA with SLI-4 interface spec.
10615  *
10616  * This function is a lockless version. The function will return success
10617  * after it successfully submit the wqe to firmware or after adding to the
10618  * txq.
10619  **/
10620 static int
10621 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10622 			   struct lpfc_iocbq *piocb, uint32_t flag)
10623 {
10624 	struct lpfc_io_buf *lpfc_cmd = piocb->io_buf;
10625 
10626 	lpfc_prep_embed_io(phba, lpfc_cmd);
10627 	return lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
10628 }
10629 
10630 void
10631 lpfc_prep_embed_io(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
10632 {
10633 	struct lpfc_iocbq *piocb = &lpfc_cmd->cur_iocbq;
10634 	union lpfc_wqe128 *wqe = &lpfc_cmd->cur_iocbq.wqe;
10635 	struct sli4_sge_le *sgl;
10636 	u32 type_size;
10637 
10638 	/* 128 byte wqe support here */
10639 	sgl = (struct sli4_sge_le *)lpfc_cmd->dma_sgl;
10640 
10641 	if (phba->fcp_embed_io) {
10642 		struct fcp_cmnd *fcp_cmnd;
10643 		u32 *ptr;
10644 
10645 		fcp_cmnd = lpfc_cmd->fcp_cmnd;
10646 
10647 		/* Word 0-2 - FCP_CMND */
10648 		type_size = le32_to_cpu(sgl->sge_len);
10649 		type_size |= ULP_BDE64_TYPE_BDE_IMMED;
10650 		wqe->generic.bde.tus.w = type_size;
10651 		wqe->generic.bde.addrHigh = 0;
10652 		wqe->generic.bde.addrLow =  72;  /* Word 18 */
10653 
10654 		bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10655 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10656 
10657 		/* Word 18-29  FCP CMND Payload */
10658 		ptr = &wqe->words[18];
10659 		lpfc_sli_pcimem_bcopy(fcp_cmnd, ptr, le32_to_cpu(sgl->sge_len));
10660 	} else {
10661 		/* Word 0-2 - Inline BDE */
10662 		wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
10663 		wqe->generic.bde.tus.f.bdeSize = le32_to_cpu(sgl->sge_len);
10664 		wqe->generic.bde.addrHigh = le32_to_cpu(sgl->addr_hi);
10665 		wqe->generic.bde.addrLow = le32_to_cpu(sgl->addr_lo);
10666 
10667 		/* Word 10 */
10668 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10669 		bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
10670 	}
10671 
10672 	/* add the VMID tags as per switch response */
10673 	if (unlikely(piocb->cmd_flag & LPFC_IO_VMID)) {
10674 		if (phba->pport->vmid_flag & LPFC_VMID_TYPE_PRIO) {
10675 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
10676 			bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10677 					(piocb->vmid_tag.cs_ctl_vmid));
10678 		} else if (phba->cfg_vmid_app_header) {
10679 			bf_set(wqe_appid, &wqe->fcp_iwrite.wqe_com, 1);
10680 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10681 			wqe->words[31] = piocb->vmid_tag.app_id;
10682 		}
10683 	}
10684 }
10685 
10686 /**
10687  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10688  * @phba: Pointer to HBA context object.
10689  * @ring_number: SLI ring number to issue iocb on.
10690  * @piocb: Pointer to command iocb.
10691  * @flag: Flag indicating if this command can be put into txq.
10692  *
10693  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10694  * an iocb command to an HBA with SLI-4 interface spec.
10695  *
10696  * This function is called with ringlock held. The function will return success
10697  * after it successfully submit the iocb to firmware or after adding to the
10698  * txq.
10699  **/
10700 static int
10701 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10702 			 struct lpfc_iocbq *piocb, uint32_t flag)
10703 {
10704 	struct lpfc_sglq *sglq;
10705 	union lpfc_wqe128 *wqe;
10706 	struct lpfc_queue *wq;
10707 	struct lpfc_sli_ring *pring;
10708 	u32 ulp_command = get_job_cmnd(phba, piocb);
10709 
10710 	/* Get the WQ */
10711 	if ((piocb->cmd_flag & LPFC_IO_FCP) ||
10712 	    (piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
10713 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10714 	} else {
10715 		wq = phba->sli4_hba.els_wq;
10716 	}
10717 
10718 	/* Get corresponding ring */
10719 	pring = wq->pring;
10720 
10721 	/*
10722 	 * The WQE can be either 64 or 128 bytes,
10723 	 */
10724 
10725 	lockdep_assert_held(&pring->ring_lock);
10726 	wqe = &piocb->wqe;
10727 	if (piocb->sli4_xritag == NO_XRI) {
10728 		if (ulp_command == CMD_ABORT_XRI_CX)
10729 			sglq = NULL;
10730 		else {
10731 			sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10732 			if (!sglq) {
10733 				if (!(flag & SLI_IOCB_RET_IOCB)) {
10734 					__lpfc_sli_ringtx_put(phba,
10735 							pring,
10736 							piocb);
10737 					return IOCB_SUCCESS;
10738 				} else {
10739 					return IOCB_BUSY;
10740 				}
10741 			}
10742 		}
10743 	} else if (piocb->cmd_flag &  LPFC_IO_FCP) {
10744 		/* These IO's already have an XRI and a mapped sgl. */
10745 		sglq = NULL;
10746 	}
10747 	else {
10748 		/*
10749 		 * This is a continuation of a commandi,(CX) so this
10750 		 * sglq is on the active list
10751 		 */
10752 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10753 		if (!sglq)
10754 			return IOCB_ERROR;
10755 	}
10756 
10757 	if (sglq) {
10758 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10759 		piocb->sli4_xritag = sglq->sli4_xritag;
10760 
10761 		/* ABTS sent by initiator to CT exchange, the
10762 		 * RX_ID field will be filled with the newly
10763 		 * allocated responder XRI.
10764 		 */
10765 		if (ulp_command == CMD_XMIT_BLS_RSP64_CX &&
10766 		    piocb->abort_bls == LPFC_ABTS_UNSOL_INT)
10767 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10768 			       piocb->sli4_xritag);
10769 
10770 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com,
10771 		       piocb->sli4_xritag);
10772 
10773 		if (lpfc_wqe_bpl2sgl(phba, piocb, sglq) == NO_XRI)
10774 			return IOCB_ERROR;
10775 	}
10776 
10777 	if (lpfc_sli4_wq_put(wq, wqe))
10778 		return IOCB_ERROR;
10779 
10780 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10781 
10782 	return 0;
10783 }
10784 
10785 /*
10786  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
10787  *
10788  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
10789  * or IOCB for sli-3  function.
10790  * pointer from the lpfc_hba struct.
10791  *
10792  * Return codes:
10793  * IOCB_ERROR - Error
10794  * IOCB_SUCCESS - Success
10795  * IOCB_BUSY - Busy
10796  **/
10797 int
10798 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
10799 		      struct lpfc_iocbq *piocb, uint32_t flag)
10800 {
10801 	return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
10802 }
10803 
10804 /*
10805  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10806  *
10807  * This routine wraps the actual lockless version for issusing IOCB function
10808  * pointer from the lpfc_hba struct.
10809  *
10810  * Return codes:
10811  * IOCB_ERROR - Error
10812  * IOCB_SUCCESS - Success
10813  * IOCB_BUSY - Busy
10814  **/
10815 int
10816 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10817 		struct lpfc_iocbq *piocb, uint32_t flag)
10818 {
10819 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10820 }
10821 
10822 static void
10823 __lpfc_sli_prep_els_req_rsp_s3(struct lpfc_iocbq *cmdiocbq,
10824 			       struct lpfc_vport *vport,
10825 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10826 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10827 {
10828 	struct lpfc_hba *phba = vport->phba;
10829 	IOCB_t *cmd;
10830 
10831 	cmd = &cmdiocbq->iocb;
10832 	memset(cmd, 0, sizeof(*cmd));
10833 
10834 	cmd->un.elsreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10835 	cmd->un.elsreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10836 	cmd->un.elsreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10837 
10838 	if (expect_rsp) {
10839 		cmd->un.elsreq64.bdl.bdeSize = (2 * sizeof(struct ulp_bde64));
10840 		cmd->un.elsreq64.remoteID = did; /* DID */
10841 		cmd->ulpCommand = CMD_ELS_REQUEST64_CR;
10842 		cmd->ulpTimeout = tmo;
10843 	} else {
10844 		cmd->un.elsreq64.bdl.bdeSize = sizeof(struct ulp_bde64);
10845 		cmd->un.genreq64.xmit_els_remoteID = did; /* DID */
10846 		cmd->ulpCommand = CMD_XMIT_ELS_RSP64_CX;
10847 		cmd->ulpPU = PARM_NPIV_DID;
10848 	}
10849 	cmd->ulpBdeCount = 1;
10850 	cmd->ulpLe = 1;
10851 	cmd->ulpClass = CLASS3;
10852 
10853 	/* If we have NPIV enabled, we want to send ELS traffic by VPI. */
10854 	if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) {
10855 		if (expect_rsp) {
10856 			cmd->un.elsreq64.myID = vport->fc_myDID;
10857 
10858 			/* For ELS_REQUEST64_CR, use the VPI by default */
10859 			cmd->ulpContext = phba->vpi_ids[vport->vpi];
10860 		}
10861 
10862 		cmd->ulpCt_h = 0;
10863 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10864 		if (elscmd == ELS_CMD_ECHO)
10865 			cmd->ulpCt_l = 0; /* context = invalid RPI */
10866 		else
10867 			cmd->ulpCt_l = 1; /* context = VPI */
10868 	}
10869 }
10870 
10871 static void
10872 __lpfc_sli_prep_els_req_rsp_s4(struct lpfc_iocbq *cmdiocbq,
10873 			       struct lpfc_vport *vport,
10874 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10875 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10876 {
10877 	struct lpfc_hba  *phba = vport->phba;
10878 	union lpfc_wqe128 *wqe;
10879 	struct ulp_bde64_le *bde;
10880 	u8 els_id;
10881 
10882 	wqe = &cmdiocbq->wqe;
10883 	memset(wqe, 0, sizeof(*wqe));
10884 
10885 	/* Word 0 - 2 BDE */
10886 	bde = (struct ulp_bde64_le *)&wqe->generic.bde;
10887 	bde->addr_low = cpu_to_le32(putPaddrLow(bmp->phys));
10888 	bde->addr_high = cpu_to_le32(putPaddrHigh(bmp->phys));
10889 	bde->type_size = cpu_to_le32(cmd_size);
10890 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10891 
10892 	if (expect_rsp) {
10893 		bf_set(wqe_cmnd, &wqe->els_req.wqe_com, CMD_ELS_REQUEST64_WQE);
10894 
10895 		/* Transfer length */
10896 		wqe->els_req.payload_len = cmd_size;
10897 		wqe->els_req.max_response_payload_len = FCELSSIZE;
10898 
10899 		/* DID */
10900 		bf_set(wqe_els_did, &wqe->els_req.wqe_dest, did);
10901 
10902 		/* Word 11 - ELS_ID */
10903 		switch (elscmd) {
10904 		case ELS_CMD_PLOGI:
10905 			els_id = LPFC_ELS_ID_PLOGI;
10906 			break;
10907 		case ELS_CMD_FLOGI:
10908 			els_id = LPFC_ELS_ID_FLOGI;
10909 			break;
10910 		case ELS_CMD_LOGO:
10911 			els_id = LPFC_ELS_ID_LOGO;
10912 			break;
10913 		case ELS_CMD_FDISC:
10914 			if (!vport->fc_myDID) {
10915 				els_id = LPFC_ELS_ID_FDISC;
10916 				break;
10917 			}
10918 			fallthrough;
10919 		default:
10920 			els_id = LPFC_ELS_ID_DEFAULT;
10921 			break;
10922 		}
10923 
10924 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
10925 	} else {
10926 		/* DID */
10927 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest, did);
10928 
10929 		/* Transfer length */
10930 		wqe->xmit_els_rsp.response_payload_len = cmd_size;
10931 
10932 		bf_set(wqe_cmnd, &wqe->xmit_els_rsp.wqe_com,
10933 		       CMD_XMIT_ELS_RSP64_WQE);
10934 	}
10935 
10936 	bf_set(wqe_tmo, &wqe->generic.wqe_com, tmo);
10937 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, cmdiocbq->iotag);
10938 	bf_set(wqe_class, &wqe->generic.wqe_com, CLASS3);
10939 
10940 	/* If we have NPIV enabled, we want to send ELS traffic by VPI.
10941 	 * For SLI4, since the driver controls VPIs we also want to include
10942 	 * all ELS pt2pt protocol traffic as well.
10943 	 */
10944 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) ||
10945 	    test_bit(FC_PT2PT, &vport->fc_flag)) {
10946 		if (expect_rsp) {
10947 			bf_set(els_req64_sid, &wqe->els_req, vport->fc_myDID);
10948 
10949 			/* For ELS_REQUEST64_WQE, use the VPI by default */
10950 			bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10951 			       phba->vpi_ids[vport->vpi]);
10952 		}
10953 
10954 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10955 		if (elscmd == ELS_CMD_ECHO)
10956 			bf_set(wqe_ct, &wqe->generic.wqe_com, 0);
10957 		else
10958 			bf_set(wqe_ct, &wqe->generic.wqe_com, 1);
10959 	}
10960 }
10961 
10962 void
10963 lpfc_sli_prep_els_req_rsp(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
10964 			  struct lpfc_vport *vport, struct lpfc_dmabuf *bmp,
10965 			  u16 cmd_size, u32 did, u32 elscmd, u8 tmo,
10966 			  u8 expect_rsp)
10967 {
10968 	phba->__lpfc_sli_prep_els_req_rsp(cmdiocbq, vport, bmp, cmd_size, did,
10969 					  elscmd, tmo, expect_rsp);
10970 }
10971 
10972 static void
10973 __lpfc_sli_prep_gen_req_s3(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10974 			   u16 rpi, u32 num_entry, u8 tmo)
10975 {
10976 	IOCB_t *cmd;
10977 
10978 	cmd = &cmdiocbq->iocb;
10979 	memset(cmd, 0, sizeof(*cmd));
10980 
10981 	cmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10982 	cmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10983 	cmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10984 	cmd->un.genreq64.bdl.bdeSize = num_entry * sizeof(struct ulp_bde64);
10985 
10986 	cmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
10987 	cmd->un.genreq64.w5.hcsw.Type = FC_TYPE_CT;
10988 	cmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
10989 
10990 	cmd->ulpContext = rpi;
10991 	cmd->ulpClass = CLASS3;
10992 	cmd->ulpCommand = CMD_GEN_REQUEST64_CR;
10993 	cmd->ulpBdeCount = 1;
10994 	cmd->ulpLe = 1;
10995 	cmd->ulpOwner = OWN_CHIP;
10996 	cmd->ulpTimeout = tmo;
10997 }
10998 
10999 static void
11000 __lpfc_sli_prep_gen_req_s4(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
11001 			   u16 rpi, u32 num_entry, u8 tmo)
11002 {
11003 	union lpfc_wqe128 *cmdwqe;
11004 	struct ulp_bde64_le *bde, *bpl;
11005 	u32 xmit_len = 0, total_len = 0, size, type, i;
11006 
11007 	cmdwqe = &cmdiocbq->wqe;
11008 	memset(cmdwqe, 0, sizeof(*cmdwqe));
11009 
11010 	/* Calculate total_len and xmit_len */
11011 	bpl = (struct ulp_bde64_le *)bmp->virt;
11012 	for (i = 0; i < num_entry; i++) {
11013 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
11014 		total_len += size;
11015 	}
11016 	for (i = 0; i < num_entry; i++) {
11017 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
11018 		type = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_TYPE_MASK;
11019 		if (type != ULP_BDE64_TYPE_BDE_64)
11020 			break;
11021 		xmit_len += size;
11022 	}
11023 
11024 	/* Words 0 - 2 */
11025 	bde = (struct ulp_bde64_le *)&cmdwqe->generic.bde;
11026 	bde->addr_low = bpl->addr_low;
11027 	bde->addr_high = bpl->addr_high;
11028 	bde->type_size = cpu_to_le32(xmit_len);
11029 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
11030 
11031 	/* Word 3 */
11032 	cmdwqe->gen_req.request_payload_len = xmit_len;
11033 
11034 	/* Word 5 */
11035 	bf_set(wqe_type, &cmdwqe->gen_req.wge_ctl, FC_TYPE_CT);
11036 	bf_set(wqe_rctl, &cmdwqe->gen_req.wge_ctl, FC_RCTL_DD_UNSOL_CTL);
11037 	bf_set(wqe_si, &cmdwqe->gen_req.wge_ctl, 1);
11038 	bf_set(wqe_la, &cmdwqe->gen_req.wge_ctl, 1);
11039 
11040 	/* Word 6 */
11041 	bf_set(wqe_ctxt_tag, &cmdwqe->gen_req.wqe_com, rpi);
11042 
11043 	/* Word 7 */
11044 	bf_set(wqe_tmo, &cmdwqe->gen_req.wqe_com, tmo);
11045 	bf_set(wqe_class, &cmdwqe->gen_req.wqe_com, CLASS3);
11046 	bf_set(wqe_cmnd, &cmdwqe->gen_req.wqe_com, CMD_GEN_REQUEST64_CR);
11047 	bf_set(wqe_ct, &cmdwqe->gen_req.wqe_com, SLI4_CT_RPI);
11048 
11049 	/* Word 12 */
11050 	cmdwqe->gen_req.max_response_payload_len = total_len - xmit_len;
11051 }
11052 
11053 void
11054 lpfc_sli_prep_gen_req(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11055 		      struct lpfc_dmabuf *bmp, u16 rpi, u32 num_entry, u8 tmo)
11056 {
11057 	phba->__lpfc_sli_prep_gen_req(cmdiocbq, bmp, rpi, num_entry, tmo);
11058 }
11059 
11060 static void
11061 __lpfc_sli_prep_xmit_seq64_s3(struct lpfc_iocbq *cmdiocbq,
11062 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11063 			      u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11064 {
11065 	IOCB_t *icmd;
11066 
11067 	icmd = &cmdiocbq->iocb;
11068 	memset(icmd, 0, sizeof(*icmd));
11069 
11070 	icmd->un.xseq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
11071 	icmd->un.xseq64.bdl.addrLow = putPaddrLow(bmp->phys);
11072 	icmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
11073 	icmd->un.xseq64.bdl.bdeSize = (num_entry * sizeof(struct ulp_bde64));
11074 	icmd->un.xseq64.w5.hcsw.Fctl = LA;
11075 	if (last_seq)
11076 		icmd->un.xseq64.w5.hcsw.Fctl |= LS;
11077 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
11078 	icmd->un.xseq64.w5.hcsw.Rctl = rctl;
11079 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
11080 
11081 	icmd->ulpBdeCount = 1;
11082 	icmd->ulpLe = 1;
11083 	icmd->ulpClass = CLASS3;
11084 
11085 	switch (cr_cx_cmd) {
11086 	case CMD_XMIT_SEQUENCE64_CR:
11087 		icmd->ulpContext = rpi;
11088 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CR;
11089 		break;
11090 	case CMD_XMIT_SEQUENCE64_CX:
11091 		icmd->ulpContext = ox_id;
11092 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CX;
11093 		break;
11094 	default:
11095 		break;
11096 	}
11097 }
11098 
11099 static void
11100 __lpfc_sli_prep_xmit_seq64_s4(struct lpfc_iocbq *cmdiocbq,
11101 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11102 			      u32 full_size, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11103 {
11104 	union lpfc_wqe128 *wqe;
11105 	struct ulp_bde64 *bpl;
11106 
11107 	wqe = &cmdiocbq->wqe;
11108 	memset(wqe, 0, sizeof(*wqe));
11109 
11110 	/* Words 0 - 2 */
11111 	bpl = (struct ulp_bde64 *)bmp->virt;
11112 	wqe->xmit_sequence.bde.addrHigh = bpl->addrHigh;
11113 	wqe->xmit_sequence.bde.addrLow = bpl->addrLow;
11114 	wqe->xmit_sequence.bde.tus.w = bpl->tus.w;
11115 
11116 	/* Word 5 */
11117 	bf_set(wqe_ls, &wqe->xmit_sequence.wge_ctl, last_seq);
11118 	bf_set(wqe_la, &wqe->xmit_sequence.wge_ctl, 1);
11119 	bf_set(wqe_dfctl, &wqe->xmit_sequence.wge_ctl, 0);
11120 	bf_set(wqe_rctl, &wqe->xmit_sequence.wge_ctl, rctl);
11121 	bf_set(wqe_type, &wqe->xmit_sequence.wge_ctl, FC_TYPE_CT);
11122 
11123 	/* Word 6 */
11124 	bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com, rpi);
11125 
11126 	bf_set(wqe_cmnd, &wqe->xmit_sequence.wqe_com,
11127 	       CMD_XMIT_SEQUENCE64_WQE);
11128 
11129 	/* Word 7 */
11130 	bf_set(wqe_class, &wqe->xmit_sequence.wqe_com, CLASS3);
11131 
11132 	/* Word 9 */
11133 	bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com, ox_id);
11134 
11135 	if (cmdiocbq->cmd_flag & (LPFC_IO_LIBDFC | LPFC_IO_LOOPBACK)) {
11136 		/* Word 10 */
11137 		if (cmdiocbq->cmd_flag & LPFC_IO_VMID) {
11138 			bf_set(wqe_appid, &wqe->xmit_sequence.wqe_com, 1);
11139 			bf_set(wqe_wqes, &wqe->xmit_sequence.wqe_com, 1);
11140 			wqe->words[31] = LOOPBACK_SRC_APPID;
11141 		}
11142 
11143 		/* Word 12 */
11144 		wqe->xmit_sequence.xmit_len = full_size;
11145 	}
11146 	else
11147 		wqe->xmit_sequence.xmit_len =
11148 			wqe->xmit_sequence.bde.tus.f.bdeSize;
11149 }
11150 
11151 void
11152 lpfc_sli_prep_xmit_seq64(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11153 			 struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11154 			 u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11155 {
11156 	phba->__lpfc_sli_prep_xmit_seq64(cmdiocbq, bmp, rpi, ox_id, num_entry,
11157 					 rctl, last_seq, cr_cx_cmd);
11158 }
11159 
11160 static void
11161 __lpfc_sli_prep_abort_xri_s3(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11162 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11163 			     bool wqec)
11164 {
11165 	IOCB_t *icmd = NULL;
11166 
11167 	icmd = &cmdiocbq->iocb;
11168 	memset(icmd, 0, sizeof(*icmd));
11169 
11170 	/* Word 5 */
11171 	icmd->un.acxri.abortContextTag = ulp_context;
11172 	icmd->un.acxri.abortIoTag = iotag;
11173 
11174 	if (ia) {
11175 		/* Word 7 */
11176 		icmd->ulpCommand = CMD_CLOSE_XRI_CN;
11177 	} else {
11178 		/* Word 3 */
11179 		icmd->un.acxri.abortType = ABORT_TYPE_ABTS;
11180 
11181 		/* Word 7 */
11182 		icmd->ulpClass = ulp_class;
11183 		icmd->ulpCommand = CMD_ABORT_XRI_CN;
11184 	}
11185 
11186 	/* Word 7 */
11187 	icmd->ulpLe = 1;
11188 }
11189 
11190 static void
11191 __lpfc_sli_prep_abort_xri_s4(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11192 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11193 			     bool wqec)
11194 {
11195 	union lpfc_wqe128 *wqe;
11196 
11197 	wqe = &cmdiocbq->wqe;
11198 	memset(wqe, 0, sizeof(*wqe));
11199 
11200 	/* Word 3 */
11201 	bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
11202 	if (ia)
11203 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
11204 	else
11205 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
11206 
11207 	/* Word 7 */
11208 	bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_WQE);
11209 
11210 	/* Word 8 */
11211 	wqe->abort_cmd.wqe_com.abort_tag = ulp_context;
11212 
11213 	/* Word 9 */
11214 	bf_set(wqe_reqtag, &wqe->abort_cmd.wqe_com, iotag);
11215 
11216 	/* Word 10 */
11217 	bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
11218 
11219 	/* Word 11 */
11220 	if (wqec)
11221 		bf_set(wqe_wqec, &wqe->abort_cmd.wqe_com, 1);
11222 	bf_set(wqe_cqid, &wqe->abort_cmd.wqe_com, cqid);
11223 	bf_set(wqe_cmd_type, &wqe->abort_cmd.wqe_com, OTHER_COMMAND);
11224 }
11225 
11226 void
11227 lpfc_sli_prep_abort_xri(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11228 			u16 ulp_context, u16 iotag, u8 ulp_class, u16 cqid,
11229 			bool ia, bool wqec)
11230 {
11231 	phba->__lpfc_sli_prep_abort_xri(cmdiocbq, ulp_context, iotag, ulp_class,
11232 					cqid, ia, wqec);
11233 }
11234 
11235 /**
11236  * lpfc_sli_api_table_setup - Set up sli api function jump table
11237  * @phba: The hba struct for which this call is being executed.
11238  * @dev_grp: The HBA PCI-Device group number.
11239  *
11240  * This routine sets up the SLI interface API function jump table in @phba
11241  * struct.
11242  * Returns: 0 - success, -ENODEV - failure.
11243  **/
11244 int
11245 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
11246 {
11247 
11248 	switch (dev_grp) {
11249 	case LPFC_PCI_DEV_LP:
11250 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
11251 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
11252 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
11253 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s3;
11254 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s3;
11255 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s3;
11256 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s3;
11257 		break;
11258 	case LPFC_PCI_DEV_OC:
11259 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
11260 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
11261 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
11262 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s4;
11263 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s4;
11264 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s4;
11265 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s4;
11266 		break;
11267 	default:
11268 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11269 				"1419 Invalid HBA PCI-device group: 0x%x\n",
11270 				dev_grp);
11271 		return -ENODEV;
11272 	}
11273 	return 0;
11274 }
11275 
11276 /**
11277  * lpfc_sli4_calc_ring - Calculates which ring to use
11278  * @phba: Pointer to HBA context object.
11279  * @piocb: Pointer to command iocb.
11280  *
11281  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
11282  * hba_wqidx, thus we need to calculate the corresponding ring.
11283  * Since ABORTS must go on the same WQ of the command they are
11284  * aborting, we use command's hba_wqidx.
11285  */
11286 struct lpfc_sli_ring *
11287 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
11288 {
11289 	struct lpfc_io_buf *lpfc_cmd;
11290 
11291 	if (piocb->cmd_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
11292 		if (unlikely(!phba->sli4_hba.hdwq))
11293 			return NULL;
11294 		/*
11295 		 * for abort iocb hba_wqidx should already
11296 		 * be setup based on what work queue we used.
11297 		 */
11298 		if (!(piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
11299 			lpfc_cmd = piocb->io_buf;
11300 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
11301 		}
11302 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
11303 	} else {
11304 		if (unlikely(!phba->sli4_hba.els_wq))
11305 			return NULL;
11306 		piocb->hba_wqidx = 0;
11307 		return phba->sli4_hba.els_wq->pring;
11308 	}
11309 }
11310 
11311 inline void lpfc_sli4_poll_eq(struct lpfc_queue *eq)
11312 {
11313 	struct lpfc_hba *phba = eq->phba;
11314 
11315 	/*
11316 	 * Unlocking an irq is one of the entry point to check
11317 	 * for re-schedule, but we are good for io submission
11318 	 * path as midlayer does a get_cpu to glue us in. Flush
11319 	 * out the invalidate queue so we can see the updated
11320 	 * value for flag.
11321 	 */
11322 	smp_rmb();
11323 
11324 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
11325 		/* We will not likely get the completion for the caller
11326 		 * during this iteration but i guess that's fine.
11327 		 * Future io's coming on this eq should be able to
11328 		 * pick it up.  As for the case of single io's, they
11329 		 * will be handled through a sched from polling timer
11330 		 * function which is currently triggered every 1msec.
11331 		 */
11332 		lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM,
11333 				     LPFC_QUEUE_WORK);
11334 }
11335 
11336 /**
11337  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
11338  * @phba: Pointer to HBA context object.
11339  * @ring_number: Ring number
11340  * @piocb: Pointer to command iocb.
11341  * @flag: Flag indicating if this command can be put into txq.
11342  *
11343  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
11344  * function. This function gets the hbalock and calls
11345  * __lpfc_sli_issue_iocb function and will return the error returned
11346  * by __lpfc_sli_issue_iocb function. This wrapper is used by
11347  * functions which do not hold hbalock.
11348  **/
11349 int
11350 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
11351 		    struct lpfc_iocbq *piocb, uint32_t flag)
11352 {
11353 	struct lpfc_sli_ring *pring;
11354 	struct lpfc_queue *eq;
11355 	unsigned long iflags;
11356 	int rc;
11357 
11358 	/* If the PCI channel is in offline state, do not post iocbs. */
11359 	if (unlikely(pci_channel_offline(phba->pcidev)))
11360 		return IOCB_ERROR;
11361 
11362 	if (phba->sli_rev == LPFC_SLI_REV4) {
11363 		lpfc_sli_prep_wqe(phba, piocb);
11364 
11365 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
11366 
11367 		pring = lpfc_sli4_calc_ring(phba, piocb);
11368 		if (unlikely(pring == NULL))
11369 			return IOCB_ERROR;
11370 
11371 		spin_lock_irqsave(&pring->ring_lock, iflags);
11372 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11373 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11374 
11375 		lpfc_sli4_poll_eq(eq);
11376 	} else {
11377 		/* For now, SLI2/3 will still use hbalock */
11378 		spin_lock_irqsave(&phba->hbalock, iflags);
11379 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11380 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11381 	}
11382 	return rc;
11383 }
11384 
11385 /**
11386  * lpfc_extra_ring_setup - Extra ring setup function
11387  * @phba: Pointer to HBA context object.
11388  *
11389  * This function is called while driver attaches with the
11390  * HBA to setup the extra ring. The extra ring is used
11391  * only when driver needs to support target mode functionality
11392  * or IP over FC functionalities.
11393  *
11394  * This function is called with no lock held. SLI3 only.
11395  **/
11396 static int
11397 lpfc_extra_ring_setup( struct lpfc_hba *phba)
11398 {
11399 	struct lpfc_sli *psli;
11400 	struct lpfc_sli_ring *pring;
11401 
11402 	psli = &phba->sli;
11403 
11404 	/* Adjust cmd/rsp ring iocb entries more evenly */
11405 
11406 	/* Take some away from the FCP ring */
11407 	pring = &psli->sli3_ring[LPFC_FCP_RING];
11408 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11409 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11410 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11411 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11412 
11413 	/* and give them to the extra ring */
11414 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
11415 
11416 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11417 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11418 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11419 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11420 
11421 	/* Setup default profile for this ring */
11422 	pring->iotag_max = 4096;
11423 	pring->num_mask = 1;
11424 	pring->prt[0].profile = 0;      /* Mask 0 */
11425 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
11426 	pring->prt[0].type = phba->cfg_multi_ring_type;
11427 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
11428 	return 0;
11429 }
11430 
11431 static void
11432 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
11433 			     struct lpfc_nodelist *ndlp)
11434 {
11435 	unsigned long iflags;
11436 	struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
11437 
11438 	/* Hold a node reference for outstanding queued work */
11439 	if (!lpfc_nlp_get(ndlp))
11440 		return;
11441 
11442 	spin_lock_irqsave(&phba->hbalock, iflags);
11443 	if (!list_empty(&evtp->evt_listp)) {
11444 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11445 		lpfc_nlp_put(ndlp);
11446 		return;
11447 	}
11448 
11449 	evtp->evt_arg1 = ndlp;
11450 	evtp->evt = LPFC_EVT_RECOVER_PORT;
11451 	list_add_tail(&evtp->evt_listp, &phba->work_list);
11452 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11453 
11454 	lpfc_worker_wake_up(phba);
11455 }
11456 
11457 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
11458  * @phba: Pointer to HBA context object.
11459  * @iocbq: Pointer to iocb object.
11460  *
11461  * The async_event handler calls this routine when it receives
11462  * an ASYNC_STATUS_CN event from the port.  The port generates
11463  * this event when an Abort Sequence request to an rport fails
11464  * twice in succession.  The abort could be originated by the
11465  * driver or by the port.  The ABTS could have been for an ELS
11466  * or FCP IO.  The port only generates this event when an ABTS
11467  * fails to complete after one retry.
11468  */
11469 static void
11470 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
11471 			  struct lpfc_iocbq *iocbq)
11472 {
11473 	struct lpfc_nodelist *ndlp = NULL;
11474 	uint16_t rpi = 0, vpi = 0;
11475 	struct lpfc_vport *vport = NULL;
11476 
11477 	/* The rpi in the ulpContext is vport-sensitive. */
11478 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
11479 	rpi = iocbq->iocb.ulpContext;
11480 
11481 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11482 			"3092 Port generated ABTS async event "
11483 			"on vpi %d rpi %d status 0x%x\n",
11484 			vpi, rpi, iocbq->iocb.ulpStatus);
11485 
11486 	vport = lpfc_find_vport_by_vpid(phba, vpi);
11487 	if (!vport)
11488 		goto err_exit;
11489 	ndlp = lpfc_findnode_rpi(vport, rpi);
11490 	if (!ndlp)
11491 		goto err_exit;
11492 
11493 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
11494 		lpfc_sli_abts_recover_port(vport, ndlp);
11495 	return;
11496 
11497  err_exit:
11498 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11499 			"3095 Event Context not found, no "
11500 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
11501 			vpi, rpi, iocbq->iocb.ulpStatus,
11502 			iocbq->iocb.ulpContext);
11503 }
11504 
11505 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
11506  * @phba: pointer to HBA context object.
11507  * @ndlp: nodelist pointer for the impacted rport.
11508  * @axri: pointer to the wcqe containing the failed exchange.
11509  *
11510  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
11511  * port.  The port generates this event when an abort exchange request to an
11512  * rport fails twice in succession with no reply.  The abort could be originated
11513  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
11514  */
11515 void
11516 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
11517 			   struct lpfc_nodelist *ndlp,
11518 			   struct sli4_wcqe_xri_aborted *axri)
11519 {
11520 	uint32_t ext_status = 0;
11521 
11522 	if (!ndlp) {
11523 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11524 				"3115 Node Context not found, driver "
11525 				"ignoring abts err event\n");
11526 		return;
11527 	}
11528 
11529 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11530 			"3116 Port generated FCP XRI ABORT event on "
11531 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
11532 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
11533 			bf_get(lpfc_wcqe_xa_xri, axri),
11534 			bf_get(lpfc_wcqe_xa_status, axri),
11535 			axri->parameter);
11536 
11537 	/*
11538 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
11539 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
11540 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
11541 	 */
11542 	ext_status = axri->parameter & IOERR_PARAM_MASK;
11543 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
11544 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
11545 		lpfc_sli_post_recovery_event(phba, ndlp);
11546 }
11547 
11548 /**
11549  * lpfc_sli_async_event_handler - ASYNC iocb handler function
11550  * @phba: Pointer to HBA context object.
11551  * @pring: Pointer to driver SLI ring object.
11552  * @iocbq: Pointer to iocb object.
11553  *
11554  * This function is called by the slow ring event handler
11555  * function when there is an ASYNC event iocb in the ring.
11556  * This function is called with no lock held.
11557  * Currently this function handles only temperature related
11558  * ASYNC events. The function decodes the temperature sensor
11559  * event message and posts events for the management applications.
11560  **/
11561 static void
11562 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
11563 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
11564 {
11565 	IOCB_t *icmd;
11566 	uint16_t evt_code;
11567 	struct temp_event temp_event_data;
11568 	struct Scsi_Host *shost;
11569 	uint32_t *iocb_w;
11570 
11571 	icmd = &iocbq->iocb;
11572 	evt_code = icmd->un.asyncstat.evt_code;
11573 
11574 	switch (evt_code) {
11575 	case ASYNC_TEMP_WARN:
11576 	case ASYNC_TEMP_SAFE:
11577 		temp_event_data.data = (uint32_t) icmd->ulpContext;
11578 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
11579 		if (evt_code == ASYNC_TEMP_WARN) {
11580 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
11581 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11582 				"0347 Adapter is very hot, please take "
11583 				"corrective action. temperature : %d Celsius\n",
11584 				(uint32_t) icmd->ulpContext);
11585 		} else {
11586 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
11587 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11588 				"0340 Adapter temperature is OK now. "
11589 				"temperature : %d Celsius\n",
11590 				(uint32_t) icmd->ulpContext);
11591 		}
11592 
11593 		/* Send temperature change event to applications */
11594 		shost = lpfc_shost_from_vport(phba->pport);
11595 		fc_host_post_vendor_event(shost, fc_get_event_number(),
11596 			sizeof(temp_event_data), (char *) &temp_event_data,
11597 			LPFC_NL_VENDOR_ID);
11598 		break;
11599 	case ASYNC_STATUS_CN:
11600 		lpfc_sli_abts_err_handler(phba, iocbq);
11601 		break;
11602 	default:
11603 		iocb_w = (uint32_t *) icmd;
11604 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11605 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
11606 			" evt_code 0x%x\n"
11607 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
11608 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
11609 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
11610 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
11611 			pring->ringno, icmd->un.asyncstat.evt_code,
11612 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
11613 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
11614 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
11615 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
11616 
11617 		break;
11618 	}
11619 }
11620 
11621 
11622 /**
11623  * lpfc_sli4_setup - SLI ring setup function
11624  * @phba: Pointer to HBA context object.
11625  *
11626  * lpfc_sli_setup sets up rings of the SLI interface with
11627  * number of iocbs per ring and iotags. This function is
11628  * called while driver attach to the HBA and before the
11629  * interrupts are enabled. So there is no need for locking.
11630  *
11631  * This function always returns 0.
11632  **/
11633 int
11634 lpfc_sli4_setup(struct lpfc_hba *phba)
11635 {
11636 	struct lpfc_sli_ring *pring;
11637 
11638 	pring = phba->sli4_hba.els_wq->pring;
11639 	pring->num_mask = LPFC_MAX_RING_MASK;
11640 	pring->prt[0].profile = 0;	/* Mask 0 */
11641 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11642 	pring->prt[0].type = FC_TYPE_ELS;
11643 	pring->prt[0].lpfc_sli_rcv_unsol_event =
11644 	    lpfc_els_unsol_event;
11645 	pring->prt[1].profile = 0;	/* Mask 1 */
11646 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
11647 	pring->prt[1].type = FC_TYPE_ELS;
11648 	pring->prt[1].lpfc_sli_rcv_unsol_event =
11649 	    lpfc_els_unsol_event;
11650 	pring->prt[2].profile = 0;	/* Mask 2 */
11651 	/* NameServer Inquiry */
11652 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11653 	/* NameServer */
11654 	pring->prt[2].type = FC_TYPE_CT;
11655 	pring->prt[2].lpfc_sli_rcv_unsol_event =
11656 	    lpfc_ct_unsol_event;
11657 	pring->prt[3].profile = 0;	/* Mask 3 */
11658 	/* NameServer response */
11659 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11660 	/* NameServer */
11661 	pring->prt[3].type = FC_TYPE_CT;
11662 	pring->prt[3].lpfc_sli_rcv_unsol_event =
11663 	    lpfc_ct_unsol_event;
11664 	return 0;
11665 }
11666 
11667 /**
11668  * lpfc_sli_setup - SLI ring setup function
11669  * @phba: Pointer to HBA context object.
11670  *
11671  * lpfc_sli_setup sets up rings of the SLI interface with
11672  * number of iocbs per ring and iotags. This function is
11673  * called while driver attach to the HBA and before the
11674  * interrupts are enabled. So there is no need for locking.
11675  *
11676  * This function always returns 0. SLI3 only.
11677  **/
11678 int
11679 lpfc_sli_setup(struct lpfc_hba *phba)
11680 {
11681 	int i, totiocbsize = 0;
11682 	struct lpfc_sli *psli = &phba->sli;
11683 	struct lpfc_sli_ring *pring;
11684 
11685 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
11686 	psli->sli_flag = 0;
11687 
11688 	psli->iocbq_lookup = NULL;
11689 	psli->iocbq_lookup_len = 0;
11690 	psli->last_iotag = 0;
11691 
11692 	for (i = 0; i < psli->num_rings; i++) {
11693 		pring = &psli->sli3_ring[i];
11694 		switch (i) {
11695 		case LPFC_FCP_RING:	/* ring 0 - FCP */
11696 			/* numCiocb and numRiocb are used in config_port */
11697 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
11698 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
11699 			pring->sli.sli3.numCiocb +=
11700 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11701 			pring->sli.sli3.numRiocb +=
11702 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11703 			pring->sli.sli3.numCiocb +=
11704 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11705 			pring->sli.sli3.numRiocb +=
11706 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11707 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11708 							SLI3_IOCB_CMD_SIZE :
11709 							SLI2_IOCB_CMD_SIZE;
11710 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11711 							SLI3_IOCB_RSP_SIZE :
11712 							SLI2_IOCB_RSP_SIZE;
11713 			pring->iotag_ctr = 0;
11714 			pring->iotag_max =
11715 			    (phba->cfg_hba_queue_depth * 2);
11716 			pring->fast_iotag = pring->iotag_max;
11717 			pring->num_mask = 0;
11718 			break;
11719 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
11720 			/* numCiocb and numRiocb are used in config_port */
11721 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
11722 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
11723 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11724 							SLI3_IOCB_CMD_SIZE :
11725 							SLI2_IOCB_CMD_SIZE;
11726 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11727 							SLI3_IOCB_RSP_SIZE :
11728 							SLI2_IOCB_RSP_SIZE;
11729 			pring->iotag_max = phba->cfg_hba_queue_depth;
11730 			pring->num_mask = 0;
11731 			break;
11732 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
11733 			/* numCiocb and numRiocb are used in config_port */
11734 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
11735 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
11736 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11737 							SLI3_IOCB_CMD_SIZE :
11738 							SLI2_IOCB_CMD_SIZE;
11739 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11740 							SLI3_IOCB_RSP_SIZE :
11741 							SLI2_IOCB_RSP_SIZE;
11742 			pring->fast_iotag = 0;
11743 			pring->iotag_ctr = 0;
11744 			pring->iotag_max = 4096;
11745 			pring->lpfc_sli_rcv_async_status =
11746 				lpfc_sli_async_event_handler;
11747 			pring->num_mask = LPFC_MAX_RING_MASK;
11748 			pring->prt[0].profile = 0;	/* Mask 0 */
11749 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11750 			pring->prt[0].type = FC_TYPE_ELS;
11751 			pring->prt[0].lpfc_sli_rcv_unsol_event =
11752 			    lpfc_els_unsol_event;
11753 			pring->prt[1].profile = 0;	/* Mask 1 */
11754 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
11755 			pring->prt[1].type = FC_TYPE_ELS;
11756 			pring->prt[1].lpfc_sli_rcv_unsol_event =
11757 			    lpfc_els_unsol_event;
11758 			pring->prt[2].profile = 0;	/* Mask 2 */
11759 			/* NameServer Inquiry */
11760 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11761 			/* NameServer */
11762 			pring->prt[2].type = FC_TYPE_CT;
11763 			pring->prt[2].lpfc_sli_rcv_unsol_event =
11764 			    lpfc_ct_unsol_event;
11765 			pring->prt[3].profile = 0;	/* Mask 3 */
11766 			/* NameServer response */
11767 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11768 			/* NameServer */
11769 			pring->prt[3].type = FC_TYPE_CT;
11770 			pring->prt[3].lpfc_sli_rcv_unsol_event =
11771 			    lpfc_ct_unsol_event;
11772 			break;
11773 		}
11774 		totiocbsize += (pring->sli.sli3.numCiocb *
11775 			pring->sli.sli3.sizeCiocb) +
11776 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
11777 	}
11778 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
11779 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
11780 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
11781 		       "SLI2 SLIM Data: x%x x%lx\n",
11782 		       phba->brd_no, totiocbsize,
11783 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
11784 	}
11785 	if (phba->cfg_multi_ring_support == 2)
11786 		lpfc_extra_ring_setup(phba);
11787 
11788 	return 0;
11789 }
11790 
11791 /**
11792  * lpfc_sli4_queue_init - Queue initialization function
11793  * @phba: Pointer to HBA context object.
11794  *
11795  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
11796  * ring. This function also initializes ring indices of each ring.
11797  * This function is called during the initialization of the SLI
11798  * interface of an HBA.
11799  * This function is called with no lock held and always returns
11800  * 1.
11801  **/
11802 void
11803 lpfc_sli4_queue_init(struct lpfc_hba *phba)
11804 {
11805 	struct lpfc_sli *psli;
11806 	struct lpfc_sli_ring *pring;
11807 	int i;
11808 
11809 	psli = &phba->sli;
11810 	spin_lock_irq(&phba->hbalock);
11811 	INIT_LIST_HEAD(&psli->mboxq);
11812 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11813 	/* Initialize list headers for txq and txcmplq as double linked lists */
11814 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
11815 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
11816 		pring->flag = 0;
11817 		pring->ringno = LPFC_FCP_RING;
11818 		pring->txcmplq_cnt = 0;
11819 		INIT_LIST_HEAD(&pring->txq);
11820 		INIT_LIST_HEAD(&pring->txcmplq);
11821 		INIT_LIST_HEAD(&pring->iocb_continueq);
11822 		spin_lock_init(&pring->ring_lock);
11823 	}
11824 	pring = phba->sli4_hba.els_wq->pring;
11825 	pring->flag = 0;
11826 	pring->ringno = LPFC_ELS_RING;
11827 	pring->txcmplq_cnt = 0;
11828 	INIT_LIST_HEAD(&pring->txq);
11829 	INIT_LIST_HEAD(&pring->txcmplq);
11830 	INIT_LIST_HEAD(&pring->iocb_continueq);
11831 	spin_lock_init(&pring->ring_lock);
11832 
11833 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11834 		pring = phba->sli4_hba.nvmels_wq->pring;
11835 		pring->flag = 0;
11836 		pring->ringno = LPFC_ELS_RING;
11837 		pring->txcmplq_cnt = 0;
11838 		INIT_LIST_HEAD(&pring->txq);
11839 		INIT_LIST_HEAD(&pring->txcmplq);
11840 		INIT_LIST_HEAD(&pring->iocb_continueq);
11841 		spin_lock_init(&pring->ring_lock);
11842 	}
11843 
11844 	spin_unlock_irq(&phba->hbalock);
11845 }
11846 
11847 /**
11848  * lpfc_sli_queue_init - Queue initialization function
11849  * @phba: Pointer to HBA context object.
11850  *
11851  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11852  * ring. This function also initializes ring indices of each ring.
11853  * This function is called during the initialization of the SLI
11854  * interface of an HBA.
11855  * This function is called with no lock held and always returns
11856  * 1.
11857  **/
11858 void
11859 lpfc_sli_queue_init(struct lpfc_hba *phba)
11860 {
11861 	struct lpfc_sli *psli;
11862 	struct lpfc_sli_ring *pring;
11863 	int i;
11864 
11865 	psli = &phba->sli;
11866 	spin_lock_irq(&phba->hbalock);
11867 	INIT_LIST_HEAD(&psli->mboxq);
11868 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11869 	/* Initialize list headers for txq and txcmplq as double linked lists */
11870 	for (i = 0; i < psli->num_rings; i++) {
11871 		pring = &psli->sli3_ring[i];
11872 		pring->ringno = i;
11873 		pring->sli.sli3.next_cmdidx  = 0;
11874 		pring->sli.sli3.local_getidx = 0;
11875 		pring->sli.sli3.cmdidx = 0;
11876 		INIT_LIST_HEAD(&pring->iocb_continueq);
11877 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11878 		INIT_LIST_HEAD(&pring->postbufq);
11879 		pring->flag = 0;
11880 		INIT_LIST_HEAD(&pring->txq);
11881 		INIT_LIST_HEAD(&pring->txcmplq);
11882 		spin_lock_init(&pring->ring_lock);
11883 	}
11884 	spin_unlock_irq(&phba->hbalock);
11885 }
11886 
11887 /**
11888  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11889  * @phba: Pointer to HBA context object.
11890  *
11891  * This routine flushes the mailbox command subsystem. It will unconditionally
11892  * flush all the mailbox commands in the three possible stages in the mailbox
11893  * command sub-system: pending mailbox command queue; the outstanding mailbox
11894  * command; and completed mailbox command queue. It is caller's responsibility
11895  * to make sure that the driver is in the proper state to flush the mailbox
11896  * command sub-system. Namely, the posting of mailbox commands into the
11897  * pending mailbox command queue from the various clients must be stopped;
11898  * either the HBA is in a state that it will never works on the outstanding
11899  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11900  * mailbox command has been completed.
11901  **/
11902 static void
11903 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11904 {
11905 	LIST_HEAD(completions);
11906 	struct lpfc_sli *psli = &phba->sli;
11907 	LPFC_MBOXQ_t *pmb;
11908 	unsigned long iflag;
11909 
11910 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11911 	local_bh_disable();
11912 
11913 	/* Flush all the mailbox commands in the mbox system */
11914 	spin_lock_irqsave(&phba->hbalock, iflag);
11915 
11916 	/* The pending mailbox command queue */
11917 	list_splice_init(&phba->sli.mboxq, &completions);
11918 	/* The outstanding active mailbox command */
11919 	if (psli->mbox_active) {
11920 		list_add_tail(&psli->mbox_active->list, &completions);
11921 		psli->mbox_active = NULL;
11922 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11923 	}
11924 	/* The completed mailbox command queue */
11925 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11926 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11927 
11928 	/* Enable softirqs again, done with phba->hbalock */
11929 	local_bh_enable();
11930 
11931 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11932 	while (!list_empty(&completions)) {
11933 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11934 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11935 		if (pmb->mbox_cmpl)
11936 			pmb->mbox_cmpl(phba, pmb);
11937 	}
11938 }
11939 
11940 /**
11941  * lpfc_sli_host_down - Vport cleanup function
11942  * @vport: Pointer to virtual port object.
11943  *
11944  * lpfc_sli_host_down is called to clean up the resources
11945  * associated with a vport before destroying virtual
11946  * port data structures.
11947  * This function does following operations:
11948  * - Free discovery resources associated with this virtual
11949  *   port.
11950  * - Free iocbs associated with this virtual port in
11951  *   the txq.
11952  * - Send abort for all iocb commands associated with this
11953  *   vport in txcmplq.
11954  *
11955  * This function is called with no lock held and always returns 1.
11956  **/
11957 int
11958 lpfc_sli_host_down(struct lpfc_vport *vport)
11959 {
11960 	LIST_HEAD(completions);
11961 	struct lpfc_hba *phba = vport->phba;
11962 	struct lpfc_sli *psli = &phba->sli;
11963 	struct lpfc_queue *qp = NULL;
11964 	struct lpfc_sli_ring *pring;
11965 	struct lpfc_iocbq *iocb, *next_iocb;
11966 	int i;
11967 	unsigned long flags = 0;
11968 	uint16_t prev_pring_flag;
11969 
11970 	lpfc_cleanup_discovery_resources(vport);
11971 
11972 	spin_lock_irqsave(&phba->hbalock, flags);
11973 
11974 	/*
11975 	 * Error everything on the txq since these iocbs
11976 	 * have not been given to the FW yet.
11977 	 * Also issue ABTS for everything on the txcmplq
11978 	 */
11979 	if (phba->sli_rev != LPFC_SLI_REV4) {
11980 		for (i = 0; i < psli->num_rings; i++) {
11981 			pring = &psli->sli3_ring[i];
11982 			prev_pring_flag = pring->flag;
11983 			/* Only slow rings */
11984 			if (pring->ringno == LPFC_ELS_RING) {
11985 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11986 				/* Set the lpfc data pending flag */
11987 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11988 			}
11989 			list_for_each_entry_safe(iocb, next_iocb,
11990 						 &pring->txq, list) {
11991 				if (iocb->vport != vport)
11992 					continue;
11993 				list_move_tail(&iocb->list, &completions);
11994 			}
11995 			list_for_each_entry_safe(iocb, next_iocb,
11996 						 &pring->txcmplq, list) {
11997 				if (iocb->vport != vport)
11998 					continue;
11999 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
12000 							   NULL);
12001 			}
12002 			pring->flag = prev_pring_flag;
12003 		}
12004 	} else {
12005 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12006 			pring = qp->pring;
12007 			if (!pring)
12008 				continue;
12009 			if (pring == phba->sli4_hba.els_wq->pring) {
12010 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12011 				/* Set the lpfc data pending flag */
12012 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12013 			}
12014 			prev_pring_flag = pring->flag;
12015 			spin_lock(&pring->ring_lock);
12016 			list_for_each_entry_safe(iocb, next_iocb,
12017 						 &pring->txq, list) {
12018 				if (iocb->vport != vport)
12019 					continue;
12020 				list_move_tail(&iocb->list, &completions);
12021 			}
12022 			spin_unlock(&pring->ring_lock);
12023 			list_for_each_entry_safe(iocb, next_iocb,
12024 						 &pring->txcmplq, list) {
12025 				if (iocb->vport != vport)
12026 					continue;
12027 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
12028 							   NULL);
12029 			}
12030 			pring->flag = prev_pring_flag;
12031 		}
12032 	}
12033 	spin_unlock_irqrestore(&phba->hbalock, flags);
12034 
12035 	/* Make sure HBA is alive */
12036 	lpfc_issue_hb_tmo(phba);
12037 
12038 	/* Cancel all the IOCBs from the completions list */
12039 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
12040 			      IOERR_SLI_DOWN);
12041 	return 1;
12042 }
12043 
12044 /**
12045  * lpfc_sli_hba_down - Resource cleanup function for the HBA
12046  * @phba: Pointer to HBA context object.
12047  *
12048  * This function cleans up all iocb, buffers, mailbox commands
12049  * while shutting down the HBA. This function is called with no
12050  * lock held and always returns 1.
12051  * This function does the following to cleanup driver resources:
12052  * - Free discovery resources for each virtual port
12053  * - Cleanup any pending fabric iocbs
12054  * - Iterate through the iocb txq and free each entry
12055  *   in the list.
12056  * - Free up any buffer posted to the HBA
12057  * - Free mailbox commands in the mailbox queue.
12058  **/
12059 int
12060 lpfc_sli_hba_down(struct lpfc_hba *phba)
12061 {
12062 	LIST_HEAD(completions);
12063 	struct lpfc_sli *psli = &phba->sli;
12064 	struct lpfc_queue *qp = NULL;
12065 	struct lpfc_sli_ring *pring;
12066 	struct lpfc_dmabuf *buf_ptr;
12067 	unsigned long flags = 0;
12068 	int i;
12069 
12070 	/* Shutdown the mailbox command sub-system */
12071 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
12072 
12073 	lpfc_hba_down_prep(phba);
12074 
12075 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12076 	local_bh_disable();
12077 
12078 	lpfc_fabric_abort_hba(phba);
12079 
12080 	spin_lock_irqsave(&phba->hbalock, flags);
12081 
12082 	/*
12083 	 * Error everything on the txq since these iocbs
12084 	 * have not been given to the FW yet.
12085 	 */
12086 	if (phba->sli_rev != LPFC_SLI_REV4) {
12087 		for (i = 0; i < psli->num_rings; i++) {
12088 			pring = &psli->sli3_ring[i];
12089 			/* Only slow rings */
12090 			if (pring->ringno == LPFC_ELS_RING) {
12091 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12092 				/* Set the lpfc data pending flag */
12093 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12094 			}
12095 			list_splice_init(&pring->txq, &completions);
12096 		}
12097 	} else {
12098 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12099 			pring = qp->pring;
12100 			if (!pring)
12101 				continue;
12102 			spin_lock(&pring->ring_lock);
12103 			list_splice_init(&pring->txq, &completions);
12104 			spin_unlock(&pring->ring_lock);
12105 			if (pring == phba->sli4_hba.els_wq->pring) {
12106 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12107 				/* Set the lpfc data pending flag */
12108 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12109 			}
12110 		}
12111 	}
12112 	spin_unlock_irqrestore(&phba->hbalock, flags);
12113 
12114 	/* Cancel all the IOCBs from the completions list */
12115 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
12116 			      IOERR_SLI_DOWN);
12117 
12118 	spin_lock_irqsave(&phba->hbalock, flags);
12119 	list_splice_init(&phba->elsbuf, &completions);
12120 	phba->elsbuf_cnt = 0;
12121 	phba->elsbuf_prev_cnt = 0;
12122 	spin_unlock_irqrestore(&phba->hbalock, flags);
12123 
12124 	while (!list_empty(&completions)) {
12125 		list_remove_head(&completions, buf_ptr,
12126 			struct lpfc_dmabuf, list);
12127 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
12128 		kfree(buf_ptr);
12129 	}
12130 
12131 	/* Enable softirqs again, done with phba->hbalock */
12132 	local_bh_enable();
12133 
12134 	/* Return any active mbox cmds */
12135 	timer_delete_sync(&psli->mbox_tmo);
12136 
12137 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
12138 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
12139 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
12140 
12141 	return 1;
12142 }
12143 
12144 /**
12145  * lpfc_sli_pcimem_bcopy - SLI memory copy function
12146  * @srcp: Source memory pointer.
12147  * @destp: Destination memory pointer.
12148  * @cnt: Number of words required to be copied.
12149  *
12150  * This function is used for copying data between driver memory
12151  * and the SLI memory. This function also changes the endianness
12152  * of each word if native endianness is different from SLI
12153  * endianness. This function can be called with or without
12154  * lock.
12155  **/
12156 void
12157 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
12158 {
12159 	uint32_t *src = srcp;
12160 	uint32_t *dest = destp;
12161 	uint32_t ldata;
12162 	int i;
12163 
12164 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
12165 		ldata = *src;
12166 		ldata = le32_to_cpu(ldata);
12167 		*dest = ldata;
12168 		src++;
12169 		dest++;
12170 	}
12171 }
12172 
12173 
12174 /**
12175  * lpfc_sli_bemem_bcopy - SLI memory copy function
12176  * @srcp: Source memory pointer.
12177  * @destp: Destination memory pointer.
12178  * @cnt: Number of words required to be copied.
12179  *
12180  * This function is used for copying data between a data structure
12181  * with big endian representation to local endianness.
12182  * This function can be called with or without lock.
12183  **/
12184 void
12185 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
12186 {
12187 	uint32_t *src = srcp;
12188 	uint32_t *dest = destp;
12189 	uint32_t ldata;
12190 	int i;
12191 
12192 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
12193 		ldata = *src;
12194 		ldata = be32_to_cpu(ldata);
12195 		*dest = ldata;
12196 		src++;
12197 		dest++;
12198 	}
12199 }
12200 
12201 /**
12202  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
12203  * @phba: Pointer to HBA context object.
12204  * @pring: Pointer to driver SLI ring object.
12205  * @mp: Pointer to driver buffer object.
12206  *
12207  * This function is called with no lock held.
12208  * It always return zero after adding the buffer to the postbufq
12209  * buffer list.
12210  **/
12211 int
12212 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12213 			 struct lpfc_dmabuf *mp)
12214 {
12215 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
12216 	   later */
12217 	spin_lock_irq(&phba->hbalock);
12218 	list_add_tail(&mp->list, &pring->postbufq);
12219 	pring->postbufq_cnt++;
12220 	spin_unlock_irq(&phba->hbalock);
12221 	return 0;
12222 }
12223 
12224 /**
12225  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
12226  * @phba: Pointer to HBA context object.
12227  *
12228  * When HBQ is enabled, buffers are searched based on tags. This function
12229  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
12230  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
12231  * does not conflict with tags of buffer posted for unsolicited events.
12232  * The function returns the allocated tag. The function is called with
12233  * no locks held.
12234  **/
12235 uint32_t
12236 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
12237 {
12238 	spin_lock_irq(&phba->hbalock);
12239 	phba->buffer_tag_count++;
12240 	/*
12241 	 * Always set the QUE_BUFTAG_BIT to distiguish between
12242 	 * a tag assigned by HBQ.
12243 	 */
12244 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
12245 	spin_unlock_irq(&phba->hbalock);
12246 	return phba->buffer_tag_count;
12247 }
12248 
12249 /**
12250  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
12251  * @phba: Pointer to HBA context object.
12252  * @pring: Pointer to driver SLI ring object.
12253  * @tag: Buffer tag.
12254  *
12255  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
12256  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
12257  * iocb is posted to the response ring with the tag of the buffer.
12258  * This function searches the pring->postbufq list using the tag
12259  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
12260  * iocb. If the buffer is found then lpfc_dmabuf object of the
12261  * buffer is returned to the caller else NULL is returned.
12262  * This function is called with no lock held.
12263  **/
12264 struct lpfc_dmabuf *
12265 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12266 			uint32_t tag)
12267 {
12268 	struct lpfc_dmabuf *mp, *next_mp;
12269 	struct list_head *slp = &pring->postbufq;
12270 
12271 	/* Search postbufq, from the beginning, looking for a match on tag */
12272 	spin_lock_irq(&phba->hbalock);
12273 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12274 		if (mp->buffer_tag == tag) {
12275 			list_del_init(&mp->list);
12276 			pring->postbufq_cnt--;
12277 			spin_unlock_irq(&phba->hbalock);
12278 			return mp;
12279 		}
12280 	}
12281 
12282 	spin_unlock_irq(&phba->hbalock);
12283 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12284 			"0402 Cannot find virtual addr for buffer tag on "
12285 			"ring %d Data x%lx x%px x%px x%x\n",
12286 			pring->ringno, (unsigned long) tag,
12287 			slp->next, slp->prev, pring->postbufq_cnt);
12288 
12289 	return NULL;
12290 }
12291 
12292 /**
12293  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
12294  * @phba: Pointer to HBA context object.
12295  * @pring: Pointer to driver SLI ring object.
12296  * @phys: DMA address of the buffer.
12297  *
12298  * This function searches the buffer list using the dma_address
12299  * of unsolicited event to find the driver's lpfc_dmabuf object
12300  * corresponding to the dma_address. The function returns the
12301  * lpfc_dmabuf object if a buffer is found else it returns NULL.
12302  * This function is called by the ct and els unsolicited event
12303  * handlers to get the buffer associated with the unsolicited
12304  * event.
12305  *
12306  * This function is called with no lock held.
12307  **/
12308 struct lpfc_dmabuf *
12309 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12310 			 dma_addr_t phys)
12311 {
12312 	struct lpfc_dmabuf *mp, *next_mp;
12313 	struct list_head *slp = &pring->postbufq;
12314 
12315 	/* Search postbufq, from the beginning, looking for a match on phys */
12316 	spin_lock_irq(&phba->hbalock);
12317 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12318 		if (mp->phys == phys) {
12319 			list_del_init(&mp->list);
12320 			pring->postbufq_cnt--;
12321 			spin_unlock_irq(&phba->hbalock);
12322 			return mp;
12323 		}
12324 	}
12325 
12326 	spin_unlock_irq(&phba->hbalock);
12327 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12328 			"0410 Cannot find virtual addr for mapped buf on "
12329 			"ring %d Data x%llx x%px x%px x%x\n",
12330 			pring->ringno, (unsigned long long)phys,
12331 			slp->next, slp->prev, pring->postbufq_cnt);
12332 	return NULL;
12333 }
12334 
12335 /**
12336  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
12337  * @phba: Pointer to HBA context object.
12338  * @cmdiocb: Pointer to driver command iocb object.
12339  * @rspiocb: Pointer to driver response iocb object.
12340  *
12341  * This function is the completion handler for the abort iocbs for
12342  * ELS commands. This function is called from the ELS ring event
12343  * handler with no lock held. This function frees memory resources
12344  * associated with the abort iocb.
12345  **/
12346 static void
12347 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12348 			struct lpfc_iocbq *rspiocb)
12349 {
12350 	u32 ulp_status = get_job_ulpstatus(phba, rspiocb);
12351 	u32 ulp_word4 = get_job_word4(phba, rspiocb);
12352 	u8 cmnd = get_job_cmnd(phba, cmdiocb);
12353 
12354 	if (ulp_status) {
12355 		/*
12356 		 * Assume that the port already completed and returned, or
12357 		 * will return the iocb. Just Log the message.
12358 		 */
12359 		if (phba->sli_rev < LPFC_SLI_REV4) {
12360 			if (cmnd == CMD_ABORT_XRI_CX &&
12361 			    ulp_status == IOSTAT_LOCAL_REJECT &&
12362 			    ulp_word4 == IOERR_ABORT_REQUESTED) {
12363 				goto release_iocb;
12364 			}
12365 		}
12366 	}
12367 
12368 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS | LOG_SLI,
12369 			"0327 Abort els iocb complete x%px with io cmd xri %x "
12370 			"abort tag x%x abort status %x abort code %x\n",
12371 			cmdiocb, get_job_abtsiotag(phba, cmdiocb),
12372 			(phba->sli_rev == LPFC_SLI_REV4) ?
12373 			get_wqe_reqtag(cmdiocb) :
12374 			cmdiocb->iocb.ulpIoTag,
12375 			ulp_status, ulp_word4);
12376 release_iocb:
12377 	lpfc_sli_release_iocbq(phba, cmdiocb);
12378 	return;
12379 }
12380 
12381 /**
12382  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
12383  * @phba: Pointer to HBA context object.
12384  * @cmdiocb: Pointer to driver command iocb object.
12385  * @rspiocb: Pointer to driver response iocb object.
12386  *
12387  * The function is called from SLI ring event handler with no
12388  * lock held. This function is the completion handler for ELS commands
12389  * which are aborted. The function frees memory resources used for
12390  * the aborted ELS commands.
12391  **/
12392 void
12393 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12394 		     struct lpfc_iocbq *rspiocb)
12395 {
12396 	struct lpfc_nodelist *ndlp = cmdiocb->ndlp;
12397 	IOCB_t *irsp;
12398 	LPFC_MBOXQ_t *mbox;
12399 	u32 ulp_command, ulp_status, ulp_word4, iotag;
12400 
12401 	ulp_command = get_job_cmnd(phba, cmdiocb);
12402 	ulp_status = get_job_ulpstatus(phba, rspiocb);
12403 	ulp_word4 = get_job_word4(phba, rspiocb);
12404 
12405 	if (phba->sli_rev == LPFC_SLI_REV4) {
12406 		iotag = get_wqe_reqtag(cmdiocb);
12407 	} else {
12408 		irsp = &rspiocb->iocb;
12409 		iotag = irsp->ulpIoTag;
12410 
12411 		/* It is possible a PLOGI_RJT for NPIV ports to get aborted.
12412 		 * The MBX_REG_LOGIN64 mbox command is freed back to the
12413 		 * mbox_mem_pool here.
12414 		 */
12415 		if (cmdiocb->context_un.mbox) {
12416 			mbox = cmdiocb->context_un.mbox;
12417 			lpfc_mbox_rsrc_cleanup(phba, mbox, MBOX_THD_UNLOCKED);
12418 			cmdiocb->context_un.mbox = NULL;
12419 		}
12420 	}
12421 
12422 	/* ELS cmd tag <ulpIoTag> completes */
12423 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
12424 			"0139 Ignoring ELS cmd code x%x ref cnt x%x Data: "
12425 			"x%x x%x x%x x%px\n",
12426 			ulp_command, kref_read(&cmdiocb->ndlp->kref),
12427 			ulp_status, ulp_word4, iotag, cmdiocb->ndlp);
12428 	/*
12429 	 * Deref the ndlp after free_iocb. sli_release_iocb will access the ndlp
12430 	 * if exchange is busy.
12431 	 */
12432 	if (ulp_command == CMD_GEN_REQUEST64_CR)
12433 		lpfc_ct_free_iocb(phba, cmdiocb);
12434 	else
12435 		lpfc_els_free_iocb(phba, cmdiocb);
12436 
12437 	lpfc_nlp_put(ndlp);
12438 }
12439 
12440 /**
12441  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
12442  * @phba: Pointer to HBA context object.
12443  * @pring: Pointer to driver SLI ring object.
12444  * @cmdiocb: Pointer to driver command iocb object.
12445  * @cmpl: completion function.
12446  *
12447  * This function issues an abort iocb for the provided command iocb. In case
12448  * of unloading, the abort iocb will not be issued to commands on the ELS
12449  * ring. Instead, the callback function shall be changed to those commands
12450  * so that nothing happens when them finishes. This function is called with
12451  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
12452  * when the command iocb is an abort request.
12453  *
12454  **/
12455 int
12456 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12457 			   struct lpfc_iocbq *cmdiocb, void *cmpl)
12458 {
12459 	struct lpfc_vport *vport = cmdiocb->vport;
12460 	struct lpfc_iocbq *abtsiocbp;
12461 	int retval = IOCB_ERROR;
12462 	unsigned long iflags;
12463 	struct lpfc_nodelist *ndlp = NULL;
12464 	u32 ulp_command = get_job_cmnd(phba, cmdiocb);
12465 	u16 ulp_context, iotag;
12466 	bool ia;
12467 
12468 	/*
12469 	 * There are certain command types we don't want to abort.  And we
12470 	 * don't want to abort commands that are already in the process of
12471 	 * being aborted.
12472 	 */
12473 	if (ulp_command == CMD_ABORT_XRI_WQE ||
12474 	    ulp_command == CMD_ABORT_XRI_CN ||
12475 	    ulp_command == CMD_CLOSE_XRI_CN ||
12476 	    cmdiocb->cmd_flag & LPFC_DRIVER_ABORTED)
12477 		return IOCB_ABORTING;
12478 
12479 	if (!pring) {
12480 		if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12481 			cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12482 		else
12483 			cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12484 		return retval;
12485 	}
12486 
12487 	/*
12488 	 * Always abort the outstanding WQE and set the IA bit correctly
12489 	 * for the context.  This is necessary for correctly removing
12490 	 * outstanding ndlp reference counts when the CQE completes with
12491 	 * the XB bit set.
12492 	 */
12493 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
12494 	if (abtsiocbp == NULL)
12495 		return IOCB_NORESOURCE;
12496 
12497 	/* This signals the response to set the correct status
12498 	 * before calling the completion handler
12499 	 */
12500 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
12501 
12502 	if (phba->sli_rev == LPFC_SLI_REV4) {
12503 		ulp_context = cmdiocb->sli4_xritag;
12504 		iotag = abtsiocbp->iotag;
12505 	} else {
12506 		iotag = cmdiocb->iocb.ulpIoTag;
12507 		if (pring->ringno == LPFC_ELS_RING) {
12508 			ndlp = cmdiocb->ndlp;
12509 			ulp_context = ndlp->nlp_rpi;
12510 		} else {
12511 			ulp_context = cmdiocb->iocb.ulpContext;
12512 		}
12513 	}
12514 
12515 	/* Just close the exchange under certain conditions. */
12516 	if (test_bit(FC_UNLOADING, &vport->load_flag) ||
12517 	    phba->link_state < LPFC_LINK_UP ||
12518 	    (phba->sli_rev == LPFC_SLI_REV4 &&
12519 	     phba->sli4_hba.link_state.status == LPFC_FC_LA_TYPE_LINK_DOWN) ||
12520 	    (phba->link_flag & LS_EXTERNAL_LOOPBACK))
12521 		ia = true;
12522 	else
12523 		ia = false;
12524 
12525 	lpfc_sli_prep_abort_xri(phba, abtsiocbp, ulp_context, iotag,
12526 				cmdiocb->iocb.ulpClass,
12527 				LPFC_WQE_CQ_ID_DEFAULT, ia, false);
12528 
12529 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12530 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
12531 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
12532 		abtsiocbp->cmd_flag |= (LPFC_IO_FCP | LPFC_USE_FCPWQIDX);
12533 
12534 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
12535 		abtsiocbp->cmd_flag |= LPFC_IO_FOF;
12536 
12537 	if (cmpl)
12538 		abtsiocbp->cmd_cmpl = cmpl;
12539 	else
12540 		abtsiocbp->cmd_cmpl = lpfc_sli_abort_els_cmpl;
12541 	abtsiocbp->vport = vport;
12542 
12543 	if (phba->sli_rev == LPFC_SLI_REV4) {
12544 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
12545 		if (unlikely(pring == NULL))
12546 			goto abort_iotag_exit;
12547 		/* Note: both hbalock and ring_lock need to be set here */
12548 		spin_lock_irqsave(&pring->ring_lock, iflags);
12549 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12550 			abtsiocbp, 0);
12551 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
12552 	} else {
12553 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12554 			abtsiocbp, 0);
12555 	}
12556 
12557 abort_iotag_exit:
12558 
12559 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
12560 			 "0339 Abort IO XRI x%x, Original iotag x%x, "
12561 			 "abort tag x%x Cmdjob : x%px Abortjob : x%px "
12562 			 "retval x%x : IA %d cmd_cmpl %ps\n",
12563 			 ulp_context, (phba->sli_rev == LPFC_SLI_REV4) ?
12564 			 cmdiocb->iotag : iotag, iotag, cmdiocb, abtsiocbp,
12565 			 retval, ia, abtsiocbp->cmd_cmpl);
12566 	if (retval) {
12567 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
12568 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
12569 	}
12570 
12571 	/*
12572 	 * Caller to this routine should check for IOCB_ERROR
12573 	 * and handle it properly.  This routine no longer removes
12574 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
12575 	 */
12576 	return retval;
12577 }
12578 
12579 /**
12580  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
12581  * @phba: pointer to lpfc HBA data structure.
12582  *
12583  * This routine will abort all pending and outstanding iocbs to an HBA.
12584  **/
12585 void
12586 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
12587 {
12588 	struct lpfc_sli *psli = &phba->sli;
12589 	struct lpfc_sli_ring *pring;
12590 	struct lpfc_queue *qp = NULL;
12591 	int i;
12592 
12593 	if (phba->sli_rev != LPFC_SLI_REV4) {
12594 		for (i = 0; i < psli->num_rings; i++) {
12595 			pring = &psli->sli3_ring[i];
12596 			lpfc_sli_abort_iocb_ring(phba, pring);
12597 		}
12598 		return;
12599 	}
12600 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12601 		pring = qp->pring;
12602 		if (!pring)
12603 			continue;
12604 		lpfc_sli_abort_iocb_ring(phba, pring);
12605 	}
12606 }
12607 
12608 /**
12609  * lpfc_sli_validate_fcp_iocb_for_abort - filter iocbs appropriate for FCP aborts
12610  * @iocbq: Pointer to iocb object.
12611  * @vport: Pointer to driver virtual port object.
12612  *
12613  * This function acts as an iocb filter for functions which abort FCP iocbs.
12614  *
12615  * Return values
12616  * -ENODEV, if a null iocb or vport ptr is encountered
12617  * -EINVAL, if the iocb is not an FCP I/O, not on the TX cmpl queue, premarked as
12618  *          driver already started the abort process, or is an abort iocb itself
12619  * 0, passes criteria for aborting the FCP I/O iocb
12620  **/
12621 static int
12622 lpfc_sli_validate_fcp_iocb_for_abort(struct lpfc_iocbq *iocbq,
12623 				     struct lpfc_vport *vport)
12624 {
12625 	u8 ulp_command;
12626 
12627 	/* No null ptr vports */
12628 	if (!iocbq || iocbq->vport != vport)
12629 		return -ENODEV;
12630 
12631 	/* iocb must be for FCP IO, already exists on the TX cmpl queue,
12632 	 * can't be premarked as driver aborted, nor be an ABORT iocb itself
12633 	 */
12634 	ulp_command = get_job_cmnd(vport->phba, iocbq);
12635 	if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12636 	    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ) ||
12637 	    (iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12638 	    (ulp_command == CMD_ABORT_XRI_CN ||
12639 	     ulp_command == CMD_CLOSE_XRI_CN ||
12640 	     ulp_command == CMD_ABORT_XRI_WQE))
12641 		return -EINVAL;
12642 
12643 	return 0;
12644 }
12645 
12646 /**
12647  * lpfc_sli_validate_fcp_iocb - validate commands associated with a SCSI target
12648  * @iocbq: Pointer to driver iocb object.
12649  * @vport: Pointer to driver virtual port object.
12650  * @tgt_id: SCSI ID of the target.
12651  * @lun_id: LUN ID of the scsi device.
12652  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
12653  *
12654  * This function acts as an iocb filter for validating a lun/SCSI target/SCSI
12655  * host.
12656  *
12657  * It will return
12658  * 0 if the filtering criteria is met for the given iocb and will return
12659  * 1 if the filtering criteria is not met.
12660  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
12661  * given iocb is for the SCSI device specified by vport, tgt_id and
12662  * lun_id parameter.
12663  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
12664  * given iocb is for the SCSI target specified by vport and tgt_id
12665  * parameters.
12666  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
12667  * given iocb is for the SCSI host associated with the given vport.
12668  * This function is called with no locks held.
12669  **/
12670 static int
12671 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
12672 			   uint16_t tgt_id, uint64_t lun_id,
12673 			   lpfc_ctx_cmd ctx_cmd)
12674 {
12675 	struct lpfc_io_buf *lpfc_cmd;
12676 	int rc = 1;
12677 
12678 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12679 
12680 	if (lpfc_cmd->pCmd == NULL)
12681 		return rc;
12682 
12683 	switch (ctx_cmd) {
12684 	case LPFC_CTX_LUN:
12685 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12686 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
12687 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
12688 			rc = 0;
12689 		break;
12690 	case LPFC_CTX_TGT:
12691 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12692 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
12693 			rc = 0;
12694 		break;
12695 	case LPFC_CTX_HOST:
12696 		rc = 0;
12697 		break;
12698 	default:
12699 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
12700 			__func__, ctx_cmd);
12701 		break;
12702 	}
12703 
12704 	return rc;
12705 }
12706 
12707 /**
12708  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
12709  * @vport: Pointer to virtual port.
12710  * @tgt_id: SCSI ID of the target.
12711  * @lun_id: LUN ID of the scsi device.
12712  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12713  *
12714  * This function returns number of FCP commands pending for the vport.
12715  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
12716  * commands pending on the vport associated with SCSI device specified
12717  * by tgt_id and lun_id parameters.
12718  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
12719  * commands pending on the vport associated with SCSI target specified
12720  * by tgt_id parameter.
12721  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
12722  * commands pending on the vport.
12723  * This function returns the number of iocbs which satisfy the filter.
12724  * This function is called without any lock held.
12725  **/
12726 int
12727 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
12728 		  lpfc_ctx_cmd ctx_cmd)
12729 {
12730 	struct lpfc_hba *phba = vport->phba;
12731 	struct lpfc_iocbq *iocbq;
12732 	int sum, i;
12733 	unsigned long iflags;
12734 	u8 ulp_command;
12735 
12736 	spin_lock_irqsave(&phba->hbalock, iflags);
12737 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
12738 		iocbq = phba->sli.iocbq_lookup[i];
12739 
12740 		if (!iocbq || iocbq->vport != vport)
12741 			continue;
12742 		if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12743 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ))
12744 			continue;
12745 
12746 		/* Include counting outstanding aborts */
12747 		ulp_command = get_job_cmnd(phba, iocbq);
12748 		if (ulp_command == CMD_ABORT_XRI_CN ||
12749 		    ulp_command == CMD_CLOSE_XRI_CN ||
12750 		    ulp_command == CMD_ABORT_XRI_WQE) {
12751 			sum++;
12752 			continue;
12753 		}
12754 
12755 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12756 					       ctx_cmd) == 0)
12757 			sum++;
12758 	}
12759 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12760 
12761 	return sum;
12762 }
12763 
12764 /**
12765  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
12766  * @phba: Pointer to HBA context object
12767  * @cmdiocb: Pointer to command iocb object.
12768  * @rspiocb: Pointer to response iocb object.
12769  *
12770  * This function is called when an aborted FCP iocb completes. This
12771  * function is called by the ring event handler with no lock held.
12772  * This function frees the iocb.
12773  **/
12774 void
12775 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12776 			struct lpfc_iocbq *rspiocb)
12777 {
12778 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12779 			"3096 ABORT_XRI_CX completing on rpi x%x "
12780 			"original iotag x%x, abort cmd iotag x%x "
12781 			"status 0x%x, reason 0x%x\n",
12782 			(phba->sli_rev == LPFC_SLI_REV4) ?
12783 			cmdiocb->sli4_xritag :
12784 			cmdiocb->iocb.un.acxri.abortContextTag,
12785 			get_job_abtsiotag(phba, cmdiocb),
12786 			cmdiocb->iotag, get_job_ulpstatus(phba, rspiocb),
12787 			get_job_word4(phba, rspiocb));
12788 	lpfc_sli_release_iocbq(phba, cmdiocb);
12789 	return;
12790 }
12791 
12792 /**
12793  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
12794  * @vport: Pointer to virtual port.
12795  * @tgt_id: SCSI ID of the target.
12796  * @lun_id: LUN ID of the scsi device.
12797  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12798  *
12799  * This function sends an abort command for every SCSI command
12800  * associated with the given virtual port pending on the ring
12801  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12802  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12803  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12804  * followed by lpfc_sli_validate_fcp_iocb.
12805  *
12806  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
12807  * FCP iocbs associated with lun specified by tgt_id and lun_id
12808  * parameters
12809  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
12810  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12811  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
12812  * FCP iocbs associated with virtual port.
12813  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
12814  * lpfc_sli4_calc_ring is used.
12815  * This function returns number of iocbs it failed to abort.
12816  * This function is called with no locks held.
12817  **/
12818 int
12819 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
12820 		    lpfc_ctx_cmd abort_cmd)
12821 {
12822 	struct lpfc_hba *phba = vport->phba;
12823 	struct lpfc_sli_ring *pring = NULL;
12824 	struct lpfc_iocbq *iocbq;
12825 	int errcnt = 0, ret_val = 0;
12826 	unsigned long iflags;
12827 	int i;
12828 
12829 	/* all I/Os are in process of being flushed */
12830 	if (test_bit(HBA_IOQ_FLUSH, &phba->hba_flag))
12831 		return errcnt;
12832 
12833 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12834 		iocbq = phba->sli.iocbq_lookup[i];
12835 
12836 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12837 			continue;
12838 
12839 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12840 					       abort_cmd) != 0)
12841 			continue;
12842 
12843 		spin_lock_irqsave(&phba->hbalock, iflags);
12844 		if (phba->sli_rev == LPFC_SLI_REV3) {
12845 			pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12846 		} else if (phba->sli_rev == LPFC_SLI_REV4) {
12847 			pring = lpfc_sli4_calc_ring(phba, iocbq);
12848 		}
12849 		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
12850 						     lpfc_sli_abort_fcp_cmpl);
12851 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12852 		if (ret_val != IOCB_SUCCESS)
12853 			errcnt++;
12854 	}
12855 
12856 	return errcnt;
12857 }
12858 
12859 /**
12860  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12861  * @vport: Pointer to virtual port.
12862  * @pring: Pointer to driver SLI ring object.
12863  * @tgt_id: SCSI ID of the target.
12864  * @lun_id: LUN ID of the scsi device.
12865  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12866  *
12867  * This function sends an abort command for every SCSI command
12868  * associated with the given virtual port pending on the ring
12869  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12870  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12871  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12872  * followed by lpfc_sli_validate_fcp_iocb.
12873  *
12874  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12875  * FCP iocbs associated with lun specified by tgt_id and lun_id
12876  * parameters
12877  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12878  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12879  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12880  * FCP iocbs associated with virtual port.
12881  * This function returns number of iocbs it aborted .
12882  * This function is called with no locks held right after a taskmgmt
12883  * command is sent.
12884  **/
12885 int
12886 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12887 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12888 {
12889 	struct lpfc_hba *phba = vport->phba;
12890 	struct lpfc_io_buf *lpfc_cmd;
12891 	struct lpfc_iocbq *abtsiocbq;
12892 	struct lpfc_nodelist *ndlp = NULL;
12893 	struct lpfc_iocbq *iocbq;
12894 	int sum, i, ret_val;
12895 	unsigned long iflags;
12896 	struct lpfc_sli_ring *pring_s4 = NULL;
12897 	u16 ulp_context, iotag, cqid = LPFC_WQE_CQ_ID_DEFAULT;
12898 	bool ia;
12899 
12900 	/* all I/Os are in process of being flushed */
12901 	if (test_bit(HBA_IOQ_FLUSH, &phba->hba_flag))
12902 		return 0;
12903 
12904 	sum = 0;
12905 
12906 	spin_lock_irqsave(&phba->hbalock, iflags);
12907 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12908 		iocbq = phba->sli.iocbq_lookup[i];
12909 
12910 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12911 			continue;
12912 
12913 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12914 					       cmd) != 0)
12915 			continue;
12916 
12917 		/* Guard against IO completion being called at same time */
12918 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12919 		spin_lock(&lpfc_cmd->buf_lock);
12920 
12921 		if (!lpfc_cmd->pCmd) {
12922 			spin_unlock(&lpfc_cmd->buf_lock);
12923 			continue;
12924 		}
12925 
12926 		if (phba->sli_rev == LPFC_SLI_REV4) {
12927 			pring_s4 =
12928 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12929 			if (!pring_s4) {
12930 				spin_unlock(&lpfc_cmd->buf_lock);
12931 				continue;
12932 			}
12933 			/* Note: both hbalock and ring_lock must be set here */
12934 			spin_lock(&pring_s4->ring_lock);
12935 		}
12936 
12937 		/*
12938 		 * If the iocbq is already being aborted, don't take a second
12939 		 * action, but do count it.
12940 		 */
12941 		if ((iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12942 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ)) {
12943 			if (phba->sli_rev == LPFC_SLI_REV4)
12944 				spin_unlock(&pring_s4->ring_lock);
12945 			spin_unlock(&lpfc_cmd->buf_lock);
12946 			continue;
12947 		}
12948 
12949 		/* issue ABTS for this IOCB based on iotag */
12950 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
12951 		if (!abtsiocbq) {
12952 			if (phba->sli_rev == LPFC_SLI_REV4)
12953 				spin_unlock(&pring_s4->ring_lock);
12954 			spin_unlock(&lpfc_cmd->buf_lock);
12955 			continue;
12956 		}
12957 
12958 		if (phba->sli_rev == LPFC_SLI_REV4) {
12959 			iotag = abtsiocbq->iotag;
12960 			ulp_context = iocbq->sli4_xritag;
12961 			cqid = lpfc_cmd->hdwq->io_cq_map;
12962 		} else {
12963 			iotag = iocbq->iocb.ulpIoTag;
12964 			if (pring->ringno == LPFC_ELS_RING) {
12965 				ndlp = iocbq->ndlp;
12966 				ulp_context = ndlp->nlp_rpi;
12967 			} else {
12968 				ulp_context = iocbq->iocb.ulpContext;
12969 			}
12970 		}
12971 
12972 		ndlp = lpfc_cmd->rdata->pnode;
12973 
12974 		if (lpfc_is_link_up(phba) &&
12975 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE) &&
12976 		    !(phba->link_flag & LS_EXTERNAL_LOOPBACK))
12977 			ia = false;
12978 		else
12979 			ia = true;
12980 
12981 		lpfc_sli_prep_abort_xri(phba, abtsiocbq, ulp_context, iotag,
12982 					iocbq->iocb.ulpClass, cqid,
12983 					ia, false);
12984 
12985 		abtsiocbq->vport = vport;
12986 
12987 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12988 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12989 		if (iocbq->cmd_flag & LPFC_IO_FCP)
12990 			abtsiocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
12991 		if (iocbq->cmd_flag & LPFC_IO_FOF)
12992 			abtsiocbq->cmd_flag |= LPFC_IO_FOF;
12993 
12994 		/* Setup callback routine and issue the command. */
12995 		abtsiocbq->cmd_cmpl = lpfc_sli_abort_fcp_cmpl;
12996 
12997 		/*
12998 		 * Indicate the IO is being aborted by the driver and set
12999 		 * the caller's flag into the aborted IO.
13000 		 */
13001 		iocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
13002 
13003 		if (phba->sli_rev == LPFC_SLI_REV4) {
13004 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
13005 							abtsiocbq, 0);
13006 			spin_unlock(&pring_s4->ring_lock);
13007 		} else {
13008 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
13009 							abtsiocbq, 0);
13010 		}
13011 
13012 		spin_unlock(&lpfc_cmd->buf_lock);
13013 
13014 		if (ret_val == IOCB_ERROR)
13015 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
13016 		else
13017 			sum++;
13018 	}
13019 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13020 	return sum;
13021 }
13022 
13023 /**
13024  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
13025  * @phba: Pointer to HBA context object.
13026  * @cmdiocbq: Pointer to command iocb.
13027  * @rspiocbq: Pointer to response iocb.
13028  *
13029  * This function is the completion handler for iocbs issued using
13030  * lpfc_sli_issue_iocb_wait function. This function is called by the
13031  * ring event handler function without any lock held. This function
13032  * can be called from both worker thread context and interrupt
13033  * context. This function also can be called from other thread which
13034  * cleans up the SLI layer objects.
13035  * This function copy the contents of the response iocb to the
13036  * response iocb memory object provided by the caller of
13037  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
13038  * sleeps for the iocb completion.
13039  **/
13040 static void
13041 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
13042 			struct lpfc_iocbq *cmdiocbq,
13043 			struct lpfc_iocbq *rspiocbq)
13044 {
13045 	wait_queue_head_t *pdone_q;
13046 	unsigned long iflags;
13047 	struct lpfc_io_buf *lpfc_cmd;
13048 	size_t offset = offsetof(struct lpfc_iocbq, wqe);
13049 
13050 	spin_lock_irqsave(&phba->hbalock, iflags);
13051 	if (cmdiocbq->cmd_flag & LPFC_IO_WAKE_TMO) {
13052 
13053 		/*
13054 		 * A time out has occurred for the iocb.  If a time out
13055 		 * completion handler has been supplied, call it.  Otherwise,
13056 		 * just free the iocbq.
13057 		 */
13058 
13059 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13060 		cmdiocbq->cmd_cmpl = cmdiocbq->wait_cmd_cmpl;
13061 		cmdiocbq->wait_cmd_cmpl = NULL;
13062 		if (cmdiocbq->cmd_cmpl)
13063 			cmdiocbq->cmd_cmpl(phba, cmdiocbq, NULL);
13064 		else
13065 			lpfc_sli_release_iocbq(phba, cmdiocbq);
13066 		return;
13067 	}
13068 
13069 	/* Copy the contents of the local rspiocb into the caller's buffer. */
13070 	cmdiocbq->cmd_flag |= LPFC_IO_WAKE;
13071 	if (cmdiocbq->rsp_iocb && rspiocbq)
13072 		memcpy((char *)cmdiocbq->rsp_iocb + offset,
13073 		       (char *)rspiocbq + offset, sizeof(*rspiocbq) - offset);
13074 
13075 	/* Set the exchange busy flag for task management commands */
13076 	if ((cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
13077 	    !(cmdiocbq->cmd_flag & LPFC_IO_LIBDFC)) {
13078 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
13079 					cur_iocbq);
13080 		if (rspiocbq && (rspiocbq->cmd_flag & LPFC_EXCHANGE_BUSY))
13081 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
13082 		else
13083 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
13084 	}
13085 
13086 	pdone_q = cmdiocbq->context_un.wait_queue;
13087 	if (pdone_q)
13088 		wake_up(pdone_q);
13089 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13090 	return;
13091 }
13092 
13093 /**
13094  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
13095  * @phba: Pointer to HBA context object..
13096  * @piocbq: Pointer to command iocb.
13097  * @flag: Flag to test.
13098  *
13099  * This routine grabs the hbalock and then test the cmd_flag to
13100  * see if the passed in flag is set.
13101  * Returns:
13102  * 1 if flag is set.
13103  * 0 if flag is not set.
13104  **/
13105 static int
13106 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
13107 		 struct lpfc_iocbq *piocbq, uint32_t flag)
13108 {
13109 	unsigned long iflags;
13110 	int ret;
13111 
13112 	spin_lock_irqsave(&phba->hbalock, iflags);
13113 	ret = piocbq->cmd_flag & flag;
13114 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13115 	return ret;
13116 
13117 }
13118 
13119 /**
13120  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
13121  * @phba: Pointer to HBA context object..
13122  * @ring_number: Ring number
13123  * @piocb: Pointer to command iocb.
13124  * @prspiocbq: Pointer to response iocb.
13125  * @timeout: Timeout in number of seconds.
13126  *
13127  * This function issues the iocb to firmware and waits for the
13128  * iocb to complete. The cmd_cmpl field of the shall be used
13129  * to handle iocbs which time out. If the field is NULL, the
13130  * function shall free the iocbq structure.  If more clean up is
13131  * needed, the caller is expected to provide a completion function
13132  * that will provide the needed clean up.  If the iocb command is
13133  * not completed within timeout seconds, the function will either
13134  * free the iocbq structure (if cmd_cmpl == NULL) or execute the
13135  * completion function set in the cmd_cmpl field and then return
13136  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
13137  * resources if this function returns IOCB_TIMEDOUT.
13138  * The function waits for the iocb completion using an
13139  * non-interruptible wait.
13140  * This function will sleep while waiting for iocb completion.
13141  * So, this function should not be called from any context which
13142  * does not allow sleeping. Due to the same reason, this function
13143  * cannot be called with interrupt disabled.
13144  * This function assumes that the iocb completions occur while
13145  * this function sleep. So, this function cannot be called from
13146  * the thread which process iocb completion for this ring.
13147  * This function clears the cmd_flag of the iocb object before
13148  * issuing the iocb and the iocb completion handler sets this
13149  * flag and wakes this thread when the iocb completes.
13150  * The contents of the response iocb will be copied to prspiocbq
13151  * by the completion handler when the command completes.
13152  * This function returns IOCB_SUCCESS when success.
13153  * This function is called with no lock held.
13154  **/
13155 int
13156 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
13157 			 uint32_t ring_number,
13158 			 struct lpfc_iocbq *piocb,
13159 			 struct lpfc_iocbq *prspiocbq,
13160 			 uint32_t timeout)
13161 {
13162 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
13163 	long timeleft, timeout_req = 0;
13164 	int retval = IOCB_SUCCESS;
13165 	uint32_t creg_val;
13166 	struct lpfc_iocbq *iocb;
13167 	int txq_cnt = 0;
13168 	int txcmplq_cnt = 0;
13169 	struct lpfc_sli_ring *pring;
13170 	unsigned long iflags;
13171 	bool iocb_completed = true;
13172 
13173 	if (phba->sli_rev >= LPFC_SLI_REV4) {
13174 		lpfc_sli_prep_wqe(phba, piocb);
13175 
13176 		pring = lpfc_sli4_calc_ring(phba, piocb);
13177 	} else
13178 		pring = &phba->sli.sli3_ring[ring_number];
13179 	/*
13180 	 * If the caller has provided a response iocbq buffer, then rsp_iocb
13181 	 * is NULL or its an error.
13182 	 */
13183 	if (prspiocbq) {
13184 		if (piocb->rsp_iocb)
13185 			return IOCB_ERROR;
13186 		piocb->rsp_iocb = prspiocbq;
13187 	}
13188 
13189 	piocb->wait_cmd_cmpl = piocb->cmd_cmpl;
13190 	piocb->cmd_cmpl = lpfc_sli_wake_iocb_wait;
13191 	piocb->context_un.wait_queue = &done_q;
13192 	piocb->cmd_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
13193 
13194 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13195 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13196 			return IOCB_ERROR;
13197 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
13198 		writel(creg_val, phba->HCregaddr);
13199 		readl(phba->HCregaddr); /* flush */
13200 	}
13201 
13202 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
13203 				     SLI_IOCB_RET_IOCB);
13204 	if (retval == IOCB_SUCCESS) {
13205 		timeout_req = secs_to_jiffies(timeout);
13206 		timeleft = wait_event_timeout(done_q,
13207 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
13208 				timeout_req);
13209 		spin_lock_irqsave(&phba->hbalock, iflags);
13210 		if (!(piocb->cmd_flag & LPFC_IO_WAKE)) {
13211 
13212 			/*
13213 			 * IOCB timed out.  Inform the wake iocb wait
13214 			 * completion function and set local status
13215 			 */
13216 
13217 			iocb_completed = false;
13218 			piocb->cmd_flag |= LPFC_IO_WAKE_TMO;
13219 		}
13220 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13221 		if (iocb_completed) {
13222 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13223 					"0331 IOCB wake signaled\n");
13224 			/* Note: we are not indicating if the IOCB has a success
13225 			 * status or not - that's for the caller to check.
13226 			 * IOCB_SUCCESS means just that the command was sent and
13227 			 * completed. Not that it completed successfully.
13228 			 * */
13229 		} else if (timeleft == 0) {
13230 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13231 					"0338 IOCB wait timeout error - no "
13232 					"wake response Data x%x\n", timeout);
13233 			retval = IOCB_TIMEDOUT;
13234 		} else {
13235 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13236 					"0330 IOCB wake NOT set, "
13237 					"Data x%x x%lx\n",
13238 					timeout, (timeleft / jiffies));
13239 			retval = IOCB_TIMEDOUT;
13240 		}
13241 	} else if (retval == IOCB_BUSY) {
13242 		if (phba->cfg_log_verbose & LOG_SLI) {
13243 			list_for_each_entry(iocb, &pring->txq, list) {
13244 				txq_cnt++;
13245 			}
13246 			list_for_each_entry(iocb, &pring->txcmplq, list) {
13247 				txcmplq_cnt++;
13248 			}
13249 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13250 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
13251 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
13252 		}
13253 		return retval;
13254 	} else {
13255 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13256 				"0332 IOCB wait issue failed, Data x%x\n",
13257 				retval);
13258 		retval = IOCB_ERROR;
13259 	}
13260 
13261 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13262 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13263 			return IOCB_ERROR;
13264 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
13265 		writel(creg_val, phba->HCregaddr);
13266 		readl(phba->HCregaddr); /* flush */
13267 	}
13268 
13269 	if (prspiocbq)
13270 		piocb->rsp_iocb = NULL;
13271 
13272 	piocb->context_un.wait_queue = NULL;
13273 	piocb->cmd_cmpl = NULL;
13274 	return retval;
13275 }
13276 
13277 /**
13278  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
13279  * @phba: Pointer to HBA context object.
13280  * @pmboxq: Pointer to driver mailbox object.
13281  * @timeout: Timeout in number of seconds.
13282  *
13283  * This function issues the mailbox to firmware and waits for the
13284  * mailbox command to complete. If the mailbox command is not
13285  * completed within timeout seconds, it returns MBX_TIMEOUT.
13286  * The function waits for the mailbox completion using an
13287  * interruptible wait. If the thread is woken up due to a
13288  * signal, MBX_TIMEOUT error is returned to the caller. Caller
13289  * should not free the mailbox resources, if this function returns
13290  * MBX_TIMEOUT.
13291  * This function will sleep while waiting for mailbox completion.
13292  * So, this function should not be called from any context which
13293  * does not allow sleeping. Due to the same reason, this function
13294  * cannot be called with interrupt disabled.
13295  * This function assumes that the mailbox completion occurs while
13296  * this function sleep. So, this function cannot be called from
13297  * the worker thread which processes mailbox completion.
13298  * This function is called in the context of HBA management
13299  * applications.
13300  * This function returns MBX_SUCCESS when successful.
13301  * This function is called with no lock held.
13302  **/
13303 int
13304 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
13305 			 uint32_t timeout)
13306 {
13307 	struct completion mbox_done;
13308 	int retval;
13309 	unsigned long flag;
13310 
13311 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
13312 	/* setup wake call as IOCB callback */
13313 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
13314 
13315 	/* setup ctx_u field to pass wait_queue pointer to wake function  */
13316 	init_completion(&mbox_done);
13317 	pmboxq->ctx_u.mbox_wait = &mbox_done;
13318 	/* now issue the command */
13319 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
13320 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
13321 		wait_for_completion_timeout(&mbox_done, secs_to_jiffies(timeout));
13322 
13323 		spin_lock_irqsave(&phba->hbalock, flag);
13324 		pmboxq->ctx_u.mbox_wait = NULL;
13325 		/*
13326 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
13327 		 * else do not free the resources.
13328 		 */
13329 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
13330 			retval = MBX_SUCCESS;
13331 		} else {
13332 			retval = MBX_TIMEOUT;
13333 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13334 		}
13335 		spin_unlock_irqrestore(&phba->hbalock, flag);
13336 	}
13337 	return retval;
13338 }
13339 
13340 /**
13341  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
13342  * @phba: Pointer to HBA context.
13343  * @mbx_action: Mailbox shutdown options.
13344  *
13345  * This function is called to shutdown the driver's mailbox sub-system.
13346  * It first marks the mailbox sub-system is in a block state to prevent
13347  * the asynchronous mailbox command from issued off the pending mailbox
13348  * command queue. If the mailbox command sub-system shutdown is due to
13349  * HBA error conditions such as EEH or ERATT, this routine shall invoke
13350  * the mailbox sub-system flush routine to forcefully bring down the
13351  * mailbox sub-system. Otherwise, if it is due to normal condition (such
13352  * as with offline or HBA function reset), this routine will wait for the
13353  * outstanding mailbox command to complete before invoking the mailbox
13354  * sub-system flush routine to gracefully bring down mailbox sub-system.
13355  **/
13356 void
13357 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
13358 {
13359 	struct lpfc_sli *psli = &phba->sli;
13360 	unsigned long timeout;
13361 
13362 	if (mbx_action == LPFC_MBX_NO_WAIT) {
13363 		/* delay 100ms for port state */
13364 		msleep(100);
13365 		lpfc_sli_mbox_sys_flush(phba);
13366 		return;
13367 	}
13368 	timeout = secs_to_jiffies(LPFC_MBOX_TMO) + jiffies;
13369 
13370 	/* Disable softirqs, including timers from obtaining phba->hbalock */
13371 	local_bh_disable();
13372 
13373 	spin_lock_irq(&phba->hbalock);
13374 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13375 
13376 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
13377 		/* Determine how long we might wait for the active mailbox
13378 		 * command to be gracefully completed by firmware.
13379 		 */
13380 		if (phba->sli.mbox_active)
13381 			timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba,
13382 						phba->sli.mbox_active)) + jiffies;
13383 		spin_unlock_irq(&phba->hbalock);
13384 
13385 		/* Enable softirqs again, done with phba->hbalock */
13386 		local_bh_enable();
13387 
13388 		while (phba->sli.mbox_active) {
13389 			/* Check active mailbox complete status every 2ms */
13390 			msleep(2);
13391 			if (time_after(jiffies, timeout))
13392 				/* Timeout, let the mailbox flush routine to
13393 				 * forcefully release active mailbox command
13394 				 */
13395 				break;
13396 		}
13397 	} else {
13398 		spin_unlock_irq(&phba->hbalock);
13399 
13400 		/* Enable softirqs again, done with phba->hbalock */
13401 		local_bh_enable();
13402 	}
13403 
13404 	lpfc_sli_mbox_sys_flush(phba);
13405 }
13406 
13407 /**
13408  * lpfc_sli_eratt_read - read sli-3 error attention events
13409  * @phba: Pointer to HBA context.
13410  *
13411  * This function is called to read the SLI3 device error attention registers
13412  * for possible error attention events. The caller must hold the hostlock
13413  * with spin_lock_irq().
13414  *
13415  * This function returns 1 when there is Error Attention in the Host Attention
13416  * Register and returns 0 otherwise.
13417  **/
13418 static int
13419 lpfc_sli_eratt_read(struct lpfc_hba *phba)
13420 {
13421 	uint32_t ha_copy;
13422 
13423 	/* Read chip Host Attention (HA) register */
13424 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
13425 		goto unplug_err;
13426 
13427 	if (ha_copy & HA_ERATT) {
13428 		/* Read host status register to retrieve error event */
13429 		if (lpfc_sli_read_hs(phba))
13430 			goto unplug_err;
13431 
13432 		/* Check if there is a deferred error condition is active */
13433 		if ((HS_FFER1 & phba->work_hs) &&
13434 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13435 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
13436 			set_bit(DEFER_ERATT, &phba->hba_flag);
13437 			/* Clear all interrupt enable conditions */
13438 			writel(0, phba->HCregaddr);
13439 			readl(phba->HCregaddr);
13440 		}
13441 
13442 		/* Set the driver HA work bitmap */
13443 		phba->work_ha |= HA_ERATT;
13444 		/* Indicate polling handles this ERATT */
13445 		set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13446 		return 1;
13447 	}
13448 	return 0;
13449 
13450 unplug_err:
13451 	/* Set the driver HS work bitmap */
13452 	phba->work_hs |= UNPLUG_ERR;
13453 	/* Set the driver HA work bitmap */
13454 	phba->work_ha |= HA_ERATT;
13455 	/* Indicate polling handles this ERATT */
13456 	set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13457 	return 1;
13458 }
13459 
13460 /**
13461  * lpfc_sli4_eratt_read - read sli-4 error attention events
13462  * @phba: Pointer to HBA context.
13463  *
13464  * This function is called to read the SLI4 device error attention registers
13465  * for possible error attention events. The caller must hold the hostlock
13466  * with spin_lock_irq().
13467  *
13468  * This function returns 1 when there is Error Attention in the Host Attention
13469  * Register and returns 0 otherwise.
13470  **/
13471 static int
13472 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
13473 {
13474 	uint32_t uerr_sta_hi, uerr_sta_lo;
13475 	uint32_t if_type, portsmphr;
13476 	struct lpfc_register portstat_reg;
13477 	u32 logmask;
13478 
13479 	/*
13480 	 * For now, use the SLI4 device internal unrecoverable error
13481 	 * registers for error attention. This can be changed later.
13482 	 */
13483 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
13484 	switch (if_type) {
13485 	case LPFC_SLI_INTF_IF_TYPE_0:
13486 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
13487 			&uerr_sta_lo) ||
13488 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
13489 			&uerr_sta_hi)) {
13490 			phba->work_hs |= UNPLUG_ERR;
13491 			phba->work_ha |= HA_ERATT;
13492 			set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13493 			return 1;
13494 		}
13495 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
13496 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
13497 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13498 					"1423 HBA Unrecoverable error: "
13499 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
13500 					"ue_mask_lo_reg=0x%x, "
13501 					"ue_mask_hi_reg=0x%x\n",
13502 					uerr_sta_lo, uerr_sta_hi,
13503 					phba->sli4_hba.ue_mask_lo,
13504 					phba->sli4_hba.ue_mask_hi);
13505 			phba->work_status[0] = uerr_sta_lo;
13506 			phba->work_status[1] = uerr_sta_hi;
13507 			phba->work_ha |= HA_ERATT;
13508 			set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13509 			return 1;
13510 		}
13511 		break;
13512 	case LPFC_SLI_INTF_IF_TYPE_2:
13513 	case LPFC_SLI_INTF_IF_TYPE_6:
13514 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
13515 			&portstat_reg.word0) ||
13516 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
13517 			&portsmphr)){
13518 			phba->work_hs |= UNPLUG_ERR;
13519 			phba->work_ha |= HA_ERATT;
13520 			set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13521 			return 1;
13522 		}
13523 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
13524 			phba->work_status[0] =
13525 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
13526 			phba->work_status[1] =
13527 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
13528 			logmask = LOG_TRACE_EVENT;
13529 			if (phba->work_status[0] ==
13530 				SLIPORT_ERR1_REG_ERR_CODE_2 &&
13531 			    phba->work_status[1] == SLIPORT_ERR2_REG_FW_RESTART)
13532 				logmask = LOG_SLI;
13533 			lpfc_printf_log(phba, KERN_ERR, logmask,
13534 					"2885 Port Status Event: "
13535 					"port status reg 0x%x, "
13536 					"port smphr reg 0x%x, "
13537 					"error 1=0x%x, error 2=0x%x\n",
13538 					portstat_reg.word0,
13539 					portsmphr,
13540 					phba->work_status[0],
13541 					phba->work_status[1]);
13542 			phba->work_ha |= HA_ERATT;
13543 			set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13544 			return 1;
13545 		}
13546 		break;
13547 	case LPFC_SLI_INTF_IF_TYPE_1:
13548 	default:
13549 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13550 				"2886 HBA Error Attention on unsupported "
13551 				"if type %d.", if_type);
13552 		return 1;
13553 	}
13554 
13555 	return 0;
13556 }
13557 
13558 /**
13559  * lpfc_sli_check_eratt - check error attention events
13560  * @phba: Pointer to HBA context.
13561  *
13562  * This function is called from timer soft interrupt context to check HBA's
13563  * error attention register bit for error attention events.
13564  *
13565  * This function returns 1 when there is Error Attention in the Host Attention
13566  * Register and returns 0 otherwise.
13567  **/
13568 int
13569 lpfc_sli_check_eratt(struct lpfc_hba *phba)
13570 {
13571 	uint32_t ha_copy;
13572 
13573 	/* If somebody is waiting to handle an eratt, don't process it
13574 	 * here. The brdkill function will do this.
13575 	 */
13576 	if (phba->link_flag & LS_IGNORE_ERATT)
13577 		return 0;
13578 
13579 	/* Check if interrupt handler handles this ERATT */
13580 	if (test_bit(HBA_ERATT_HANDLED, &phba->hba_flag))
13581 		/* Interrupt handler has handled ERATT */
13582 		return 0;
13583 
13584 	/*
13585 	 * If there is deferred error attention, do not check for error
13586 	 * attention
13587 	 */
13588 	if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag)))
13589 		return 0;
13590 
13591 	spin_lock_irq(&phba->hbalock);
13592 	/* If PCI channel is offline, don't process it */
13593 	if (unlikely(pci_channel_offline(phba->pcidev))) {
13594 		spin_unlock_irq(&phba->hbalock);
13595 		return 0;
13596 	}
13597 
13598 	switch (phba->sli_rev) {
13599 	case LPFC_SLI_REV2:
13600 	case LPFC_SLI_REV3:
13601 		/* Read chip Host Attention (HA) register */
13602 		ha_copy = lpfc_sli_eratt_read(phba);
13603 		break;
13604 	case LPFC_SLI_REV4:
13605 		/* Read device Uncoverable Error (UERR) registers */
13606 		ha_copy = lpfc_sli4_eratt_read(phba);
13607 		break;
13608 	default:
13609 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13610 				"0299 Invalid SLI revision (%d)\n",
13611 				phba->sli_rev);
13612 		ha_copy = 0;
13613 		break;
13614 	}
13615 	spin_unlock_irq(&phba->hbalock);
13616 
13617 	return ha_copy;
13618 }
13619 
13620 /**
13621  * lpfc_intr_state_check - Check device state for interrupt handling
13622  * @phba: Pointer to HBA context.
13623  *
13624  * This inline routine checks whether a device or its PCI slot is in a state
13625  * that the interrupt should be handled.
13626  *
13627  * This function returns 0 if the device or the PCI slot is in a state that
13628  * interrupt should be handled, otherwise -EIO.
13629  */
13630 static inline int
13631 lpfc_intr_state_check(struct lpfc_hba *phba)
13632 {
13633 	/* If the pci channel is offline, ignore all the interrupts */
13634 	if (unlikely(pci_channel_offline(phba->pcidev)))
13635 		return -EIO;
13636 
13637 	/* Update device level interrupt statistics */
13638 	phba->sli.slistat.sli_intr++;
13639 
13640 	/* Ignore all interrupts during initialization. */
13641 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
13642 		return -EIO;
13643 
13644 	return 0;
13645 }
13646 
13647 /**
13648  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
13649  * @irq: Interrupt number.
13650  * @dev_id: The device context pointer.
13651  *
13652  * This function is directly called from the PCI layer as an interrupt
13653  * service routine when device with SLI-3 interface spec is enabled with
13654  * MSI-X multi-message interrupt mode and there are slow-path events in
13655  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
13656  * interrupt mode, this function is called as part of the device-level
13657  * interrupt handler. When the PCI slot is in error recovery or the HBA
13658  * is undergoing initialization, the interrupt handler will not process
13659  * the interrupt. The link attention and ELS ring attention events are
13660  * handled by the worker thread. The interrupt handler signals the worker
13661  * thread and returns for these events. This function is called without
13662  * any lock held. It gets the hbalock to access and update SLI data
13663  * structures.
13664  *
13665  * This function returns IRQ_HANDLED when interrupt is handled else it
13666  * returns IRQ_NONE.
13667  **/
13668 irqreturn_t
13669 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
13670 {
13671 	struct lpfc_hba  *phba;
13672 	uint32_t ha_copy, hc_copy;
13673 	uint32_t work_ha_copy;
13674 	unsigned long status;
13675 	unsigned long iflag;
13676 	uint32_t control;
13677 
13678 	MAILBOX_t *mbox, *pmbox;
13679 	struct lpfc_vport *vport;
13680 	struct lpfc_nodelist *ndlp;
13681 	struct lpfc_dmabuf *mp;
13682 	LPFC_MBOXQ_t *pmb;
13683 	int rc;
13684 
13685 	/*
13686 	 * Get the driver's phba structure from the dev_id and
13687 	 * assume the HBA is not interrupting.
13688 	 */
13689 	phba = (struct lpfc_hba *)dev_id;
13690 
13691 	if (unlikely(!phba))
13692 		return IRQ_NONE;
13693 
13694 	/*
13695 	 * Stuff needs to be attented to when this function is invoked as an
13696 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13697 	 */
13698 	if (phba->intr_type == MSIX) {
13699 		/* Check device state for handling interrupt */
13700 		if (lpfc_intr_state_check(phba))
13701 			return IRQ_NONE;
13702 		/* Need to read HA REG for slow-path events */
13703 		spin_lock_irqsave(&phba->hbalock, iflag);
13704 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13705 			goto unplug_error;
13706 		/* If somebody is waiting to handle an eratt don't process it
13707 		 * here. The brdkill function will do this.
13708 		 */
13709 		if (phba->link_flag & LS_IGNORE_ERATT)
13710 			ha_copy &= ~HA_ERATT;
13711 		/* Check the need for handling ERATT in interrupt handler */
13712 		if (ha_copy & HA_ERATT) {
13713 			if (test_and_set_bit(HBA_ERATT_HANDLED,
13714 					     &phba->hba_flag))
13715 				/* ERATT polling has handled ERATT */
13716 				ha_copy &= ~HA_ERATT;
13717 		}
13718 
13719 		/*
13720 		 * If there is deferred error attention, do not check for any
13721 		 * interrupt.
13722 		 */
13723 		if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag))) {
13724 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13725 			return IRQ_NONE;
13726 		}
13727 
13728 		/* Clear up only attention source related to slow-path */
13729 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
13730 			goto unplug_error;
13731 
13732 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
13733 			HC_LAINT_ENA | HC_ERINT_ENA),
13734 			phba->HCregaddr);
13735 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
13736 			phba->HAregaddr);
13737 		writel(hc_copy, phba->HCregaddr);
13738 		readl(phba->HAregaddr); /* flush */
13739 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13740 	} else
13741 		ha_copy = phba->ha_copy;
13742 
13743 	work_ha_copy = ha_copy & phba->work_ha_mask;
13744 
13745 	if (work_ha_copy) {
13746 		if (work_ha_copy & HA_LATT) {
13747 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
13748 				/*
13749 				 * Turn off Link Attention interrupts
13750 				 * until CLEAR_LA done
13751 				 */
13752 				spin_lock_irqsave(&phba->hbalock, iflag);
13753 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
13754 				if (lpfc_readl(phba->HCregaddr, &control))
13755 					goto unplug_error;
13756 				control &= ~HC_LAINT_ENA;
13757 				writel(control, phba->HCregaddr);
13758 				readl(phba->HCregaddr); /* flush */
13759 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13760 			}
13761 			else
13762 				work_ha_copy &= ~HA_LATT;
13763 		}
13764 
13765 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
13766 			/*
13767 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
13768 			 * the only slow ring.
13769 			 */
13770 			status = (work_ha_copy &
13771 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
13772 			status >>= (4*LPFC_ELS_RING);
13773 			if (status & HA_RXMASK) {
13774 				spin_lock_irqsave(&phba->hbalock, iflag);
13775 				if (lpfc_readl(phba->HCregaddr, &control))
13776 					goto unplug_error;
13777 
13778 				lpfc_debugfs_slow_ring_trc(phba,
13779 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
13780 				control, status,
13781 				(uint32_t)phba->sli.slistat.sli_intr);
13782 
13783 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
13784 					lpfc_debugfs_slow_ring_trc(phba,
13785 						"ISR Disable ring:"
13786 						"pwork:x%x hawork:x%x wait:x%x",
13787 						phba->work_ha, work_ha_copy,
13788 						(uint32_t)((unsigned long)
13789 						&phba->work_waitq));
13790 
13791 					control &=
13792 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
13793 					writel(control, phba->HCregaddr);
13794 					readl(phba->HCregaddr); /* flush */
13795 				}
13796 				else {
13797 					lpfc_debugfs_slow_ring_trc(phba,
13798 						"ISR slow ring:   pwork:"
13799 						"x%x hawork:x%x wait:x%x",
13800 						phba->work_ha, work_ha_copy,
13801 						(uint32_t)((unsigned long)
13802 						&phba->work_waitq));
13803 				}
13804 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13805 			}
13806 		}
13807 		spin_lock_irqsave(&phba->hbalock, iflag);
13808 		if (work_ha_copy & HA_ERATT) {
13809 			if (lpfc_sli_read_hs(phba))
13810 				goto unplug_error;
13811 			/*
13812 			 * Check if there is a deferred error condition
13813 			 * is active
13814 			 */
13815 			if ((HS_FFER1 & phba->work_hs) &&
13816 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13817 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
13818 				  phba->work_hs)) {
13819 				set_bit(DEFER_ERATT, &phba->hba_flag);
13820 				/* Clear all interrupt enable conditions */
13821 				writel(0, phba->HCregaddr);
13822 				readl(phba->HCregaddr);
13823 			}
13824 		}
13825 
13826 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
13827 			pmb = phba->sli.mbox_active;
13828 			pmbox = &pmb->u.mb;
13829 			mbox = phba->mbox;
13830 			vport = pmb->vport;
13831 
13832 			/* First check out the status word */
13833 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
13834 			if (pmbox->mbxOwner != OWN_HOST) {
13835 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13836 				/*
13837 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
13838 				 * mbxStatus <status>
13839 				 */
13840 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13841 						"(%d):0304 Stray Mailbox "
13842 						"Interrupt mbxCommand x%x "
13843 						"mbxStatus x%x\n",
13844 						(vport ? vport->vpi : 0),
13845 						pmbox->mbxCommand,
13846 						pmbox->mbxStatus);
13847 				/* clear mailbox attention bit */
13848 				work_ha_copy &= ~HA_MBATT;
13849 			} else {
13850 				phba->sli.mbox_active = NULL;
13851 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13852 				phba->last_completion_time = jiffies;
13853 				timer_delete(&phba->sli.mbox_tmo);
13854 				if (pmb->mbox_cmpl) {
13855 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
13856 							MAILBOX_CMD_SIZE);
13857 					if (pmb->out_ext_byte_len &&
13858 						pmb->ext_buf)
13859 						lpfc_sli_pcimem_bcopy(
13860 						phba->mbox_ext,
13861 						pmb->ext_buf,
13862 						pmb->out_ext_byte_len);
13863 				}
13864 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13865 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13866 
13867 					lpfc_debugfs_disc_trc(vport,
13868 						LPFC_DISC_TRC_MBOX_VPORT,
13869 						"MBOX dflt rpi: : "
13870 						"status:x%x rpi:x%x",
13871 						(uint32_t)pmbox->mbxStatus,
13872 						pmbox->un.varWords[0], 0);
13873 
13874 					if (!pmbox->mbxStatus) {
13875 						mp = pmb->ctx_buf;
13876 						ndlp = pmb->ctx_ndlp;
13877 
13878 						/* Reg_LOGIN of dflt RPI was
13879 						 * successful. new lets get
13880 						 * rid of the RPI using the
13881 						 * same mbox buffer.
13882 						 */
13883 						lpfc_unreg_login(phba,
13884 							vport->vpi,
13885 							pmbox->un.varWords[0],
13886 							pmb);
13887 						pmb->mbox_cmpl =
13888 							lpfc_mbx_cmpl_dflt_rpi;
13889 						pmb->ctx_buf = mp;
13890 						pmb->ctx_ndlp = ndlp;
13891 						pmb->vport = vport;
13892 						rc = lpfc_sli_issue_mbox(phba,
13893 								pmb,
13894 								MBX_NOWAIT);
13895 						if (rc != MBX_BUSY)
13896 							lpfc_printf_log(phba,
13897 							KERN_ERR,
13898 							LOG_TRACE_EVENT,
13899 							"0350 rc should have"
13900 							"been MBX_BUSY\n");
13901 						if (rc != MBX_NOT_FINISHED)
13902 							goto send_current_mbox;
13903 					}
13904 				}
13905 				spin_lock_irqsave(
13906 						&phba->pport->work_port_lock,
13907 						iflag);
13908 				phba->pport->work_port_events &=
13909 					~WORKER_MBOX_TMO;
13910 				spin_unlock_irqrestore(
13911 						&phba->pport->work_port_lock,
13912 						iflag);
13913 
13914 				/* Do NOT queue MBX_HEARTBEAT to the worker
13915 				 * thread for processing.
13916 				 */
13917 				if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13918 					/* Process mbox now */
13919 					phba->sli.mbox_active = NULL;
13920 					phba->sli.sli_flag &=
13921 						~LPFC_SLI_MBOX_ACTIVE;
13922 					if (pmb->mbox_cmpl)
13923 						pmb->mbox_cmpl(phba, pmb);
13924 				} else {
13925 					/* Queue to worker thread to process */
13926 					lpfc_mbox_cmpl_put(phba, pmb);
13927 				}
13928 			}
13929 		} else
13930 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13931 
13932 		if ((work_ha_copy & HA_MBATT) &&
13933 		    (phba->sli.mbox_active == NULL)) {
13934 send_current_mbox:
13935 			/* Process next mailbox command if there is one */
13936 			do {
13937 				rc = lpfc_sli_issue_mbox(phba, NULL,
13938 							 MBX_NOWAIT);
13939 			} while (rc == MBX_NOT_FINISHED);
13940 			if (rc != MBX_SUCCESS)
13941 				lpfc_printf_log(phba, KERN_ERR,
13942 						LOG_TRACE_EVENT,
13943 						"0349 rc should be "
13944 						"MBX_SUCCESS\n");
13945 		}
13946 
13947 		spin_lock_irqsave(&phba->hbalock, iflag);
13948 		phba->work_ha |= work_ha_copy;
13949 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13950 		lpfc_worker_wake_up(phba);
13951 	}
13952 	return IRQ_HANDLED;
13953 unplug_error:
13954 	spin_unlock_irqrestore(&phba->hbalock, iflag);
13955 	return IRQ_HANDLED;
13956 
13957 } /* lpfc_sli_sp_intr_handler */
13958 
13959 /**
13960  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13961  * @irq: Interrupt number.
13962  * @dev_id: The device context pointer.
13963  *
13964  * This function is directly called from the PCI layer as an interrupt
13965  * service routine when device with SLI-3 interface spec is enabled with
13966  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13967  * ring event in the HBA. However, when the device is enabled with either
13968  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13969  * device-level interrupt handler. When the PCI slot is in error recovery
13970  * or the HBA is undergoing initialization, the interrupt handler will not
13971  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13972  * the interrupt context. This function is called without any lock held.
13973  * It gets the hbalock to access and update SLI data structures.
13974  *
13975  * This function returns IRQ_HANDLED when interrupt is handled else it
13976  * returns IRQ_NONE.
13977  **/
13978 irqreturn_t
13979 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13980 {
13981 	struct lpfc_hba  *phba;
13982 	uint32_t ha_copy;
13983 	unsigned long status;
13984 	unsigned long iflag;
13985 	struct lpfc_sli_ring *pring;
13986 
13987 	/* Get the driver's phba structure from the dev_id and
13988 	 * assume the HBA is not interrupting.
13989 	 */
13990 	phba = (struct lpfc_hba *) dev_id;
13991 
13992 	if (unlikely(!phba))
13993 		return IRQ_NONE;
13994 
13995 	/*
13996 	 * Stuff needs to be attented to when this function is invoked as an
13997 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13998 	 */
13999 	if (phba->intr_type == MSIX) {
14000 		/* Check device state for handling interrupt */
14001 		if (lpfc_intr_state_check(phba))
14002 			return IRQ_NONE;
14003 		/* Need to read HA REG for FCP ring and other ring events */
14004 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
14005 			return IRQ_HANDLED;
14006 
14007 		/*
14008 		 * If there is deferred error attention, do not check for
14009 		 * any interrupt.
14010 		 */
14011 		if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag)))
14012 			return IRQ_NONE;
14013 
14014 		/* Clear up only attention source related to fast-path */
14015 		spin_lock_irqsave(&phba->hbalock, iflag);
14016 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
14017 			phba->HAregaddr);
14018 		readl(phba->HAregaddr); /* flush */
14019 		spin_unlock_irqrestore(&phba->hbalock, iflag);
14020 	} else
14021 		ha_copy = phba->ha_copy;
14022 
14023 	/*
14024 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
14025 	 */
14026 	ha_copy &= ~(phba->work_ha_mask);
14027 
14028 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
14029 	status >>= (4*LPFC_FCP_RING);
14030 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
14031 	if (status & HA_RXMASK)
14032 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
14033 
14034 	if (phba->cfg_multi_ring_support == 2) {
14035 		/*
14036 		 * Process all events on extra ring. Take the optimized path
14037 		 * for extra ring IO.
14038 		 */
14039 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14040 		status >>= (4*LPFC_EXTRA_RING);
14041 		if (status & HA_RXMASK) {
14042 			lpfc_sli_handle_fast_ring_event(phba,
14043 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
14044 					status);
14045 		}
14046 	}
14047 	return IRQ_HANDLED;
14048 }  /* lpfc_sli_fp_intr_handler */
14049 
14050 /**
14051  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
14052  * @irq: Interrupt number.
14053  * @dev_id: The device context pointer.
14054  *
14055  * This function is the HBA device-level interrupt handler to device with
14056  * SLI-3 interface spec, called from the PCI layer when either MSI or
14057  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
14058  * requires driver attention. This function invokes the slow-path interrupt
14059  * attention handling function and fast-path interrupt attention handling
14060  * function in turn to process the relevant HBA attention events. This
14061  * function is called without any lock held. It gets the hbalock to access
14062  * and update SLI data structures.
14063  *
14064  * This function returns IRQ_HANDLED when interrupt is handled, else it
14065  * returns IRQ_NONE.
14066  **/
14067 irqreturn_t
14068 lpfc_sli_intr_handler(int irq, void *dev_id)
14069 {
14070 	struct lpfc_hba  *phba;
14071 	irqreturn_t sp_irq_rc, fp_irq_rc;
14072 	unsigned long status1, status2;
14073 	uint32_t hc_copy;
14074 
14075 	/*
14076 	 * Get the driver's phba structure from the dev_id and
14077 	 * assume the HBA is not interrupting.
14078 	 */
14079 	phba = (struct lpfc_hba *) dev_id;
14080 
14081 	if (unlikely(!phba))
14082 		return IRQ_NONE;
14083 
14084 	/* Check device state for handling interrupt */
14085 	if (lpfc_intr_state_check(phba))
14086 		return IRQ_NONE;
14087 
14088 	spin_lock(&phba->hbalock);
14089 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
14090 		spin_unlock(&phba->hbalock);
14091 		return IRQ_HANDLED;
14092 	}
14093 
14094 	if (unlikely(!phba->ha_copy)) {
14095 		spin_unlock(&phba->hbalock);
14096 		return IRQ_NONE;
14097 	} else if (phba->ha_copy & HA_ERATT) {
14098 		if (test_and_set_bit(HBA_ERATT_HANDLED, &phba->hba_flag))
14099 			/* ERATT polling has handled ERATT */
14100 			phba->ha_copy &= ~HA_ERATT;
14101 	}
14102 
14103 	/*
14104 	 * If there is deferred error attention, do not check for any interrupt.
14105 	 */
14106 	if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag))) {
14107 		spin_unlock(&phba->hbalock);
14108 		return IRQ_NONE;
14109 	}
14110 
14111 	/* Clear attention sources except link and error attentions */
14112 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
14113 		spin_unlock(&phba->hbalock);
14114 		return IRQ_HANDLED;
14115 	}
14116 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
14117 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
14118 		phba->HCregaddr);
14119 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
14120 	writel(hc_copy, phba->HCregaddr);
14121 	readl(phba->HAregaddr); /* flush */
14122 	spin_unlock(&phba->hbalock);
14123 
14124 	/*
14125 	 * Invokes slow-path host attention interrupt handling as appropriate.
14126 	 */
14127 
14128 	/* status of events with mailbox and link attention */
14129 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
14130 
14131 	/* status of events with ELS ring */
14132 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
14133 	status2 >>= (4*LPFC_ELS_RING);
14134 
14135 	if (status1 || (status2 & HA_RXMASK))
14136 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
14137 	else
14138 		sp_irq_rc = IRQ_NONE;
14139 
14140 	/*
14141 	 * Invoke fast-path host attention interrupt handling as appropriate.
14142 	 */
14143 
14144 	/* status of events with FCP ring */
14145 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
14146 	status1 >>= (4*LPFC_FCP_RING);
14147 
14148 	/* status of events with extra ring */
14149 	if (phba->cfg_multi_ring_support == 2) {
14150 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14151 		status2 >>= (4*LPFC_EXTRA_RING);
14152 	} else
14153 		status2 = 0;
14154 
14155 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
14156 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
14157 	else
14158 		fp_irq_rc = IRQ_NONE;
14159 
14160 	/* Return device-level interrupt handling status */
14161 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
14162 }  /* lpfc_sli_intr_handler */
14163 
14164 /**
14165  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
14166  * @phba: pointer to lpfc hba data structure.
14167  *
14168  * This routine is invoked by the worker thread to process all the pending
14169  * SLI4 els abort xri events.
14170  **/
14171 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
14172 {
14173 	struct lpfc_cq_event *cq_event;
14174 	unsigned long iflags;
14175 
14176 	/* First, declare the els xri abort event has been handled */
14177 	clear_bit(ELS_XRI_ABORT_EVENT, &phba->hba_flag);
14178 
14179 	/* Now, handle all the els xri abort events */
14180 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14181 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
14182 		/* Get the first event from the head of the event queue */
14183 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
14184 				 cq_event, struct lpfc_cq_event, list);
14185 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14186 				       iflags);
14187 		/* Notify aborted XRI for ELS work queue */
14188 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
14189 
14190 		/* Free the event processed back to the free pool */
14191 		lpfc_sli4_cq_event_release(phba, cq_event);
14192 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14193 				  iflags);
14194 	}
14195 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14196 }
14197 
14198 /**
14199  * lpfc_sli4_els_preprocess_rspiocbq - Get response iocbq from els wcqe
14200  * @phba: Pointer to HBA context object.
14201  * @irspiocbq: Pointer to work-queue completion queue entry.
14202  *
14203  * This routine handles an ELS work-queue completion event and construct
14204  * a pseudo response ELS IOCBQ from the SLI4 ELS WCQE for the common
14205  * discovery engine to handle.
14206  *
14207  * Return: Pointer to the receive IOCBQ, NULL otherwise.
14208  **/
14209 static struct lpfc_iocbq *
14210 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
14211 				  struct lpfc_iocbq *irspiocbq)
14212 {
14213 	struct lpfc_sli_ring *pring;
14214 	struct lpfc_iocbq *cmdiocbq;
14215 	struct lpfc_wcqe_complete *wcqe;
14216 	unsigned long iflags;
14217 
14218 	pring = lpfc_phba_elsring(phba);
14219 	if (unlikely(!pring))
14220 		return NULL;
14221 
14222 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
14223 	spin_lock_irqsave(&pring->ring_lock, iflags);
14224 	pring->stats.iocb_event++;
14225 	/* Look up the ELS command IOCB and create pseudo response IOCB */
14226 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14227 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14228 	if (unlikely(!cmdiocbq)) {
14229 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
14230 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14231 				"0386 ELS complete with no corresponding "
14232 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
14233 				wcqe->word0, wcqe->total_data_placed,
14234 				wcqe->parameter, wcqe->word3);
14235 		lpfc_sli_release_iocbq(phba, irspiocbq);
14236 		return NULL;
14237 	}
14238 
14239 	memcpy(&irspiocbq->wqe, &cmdiocbq->wqe, sizeof(union lpfc_wqe128));
14240 	memcpy(&irspiocbq->wcqe_cmpl, wcqe, sizeof(*wcqe));
14241 
14242 	/* Put the iocb back on the txcmplq */
14243 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
14244 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
14245 
14246 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
14247 		spin_lock_irqsave(&phba->hbalock, iflags);
14248 		irspiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
14249 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14250 	}
14251 
14252 	return irspiocbq;
14253 }
14254 
14255 inline struct lpfc_cq_event *
14256 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
14257 {
14258 	struct lpfc_cq_event *cq_event;
14259 
14260 	/* Allocate a new internal CQ_EVENT entry */
14261 	cq_event = lpfc_sli4_cq_event_alloc(phba);
14262 	if (!cq_event) {
14263 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14264 				"0602 Failed to alloc CQ_EVENT entry\n");
14265 		return NULL;
14266 	}
14267 
14268 	/* Move the CQE into the event */
14269 	memcpy(&cq_event->cqe, entry, size);
14270 	return cq_event;
14271 }
14272 
14273 /**
14274  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
14275  * @phba: Pointer to HBA context object.
14276  * @mcqe: Pointer to mailbox completion queue entry.
14277  *
14278  * This routine process a mailbox completion queue entry with asynchronous
14279  * event.
14280  *
14281  * Return: true if work posted to worker thread, otherwise false.
14282  **/
14283 static bool
14284 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14285 {
14286 	struct lpfc_cq_event *cq_event;
14287 	unsigned long iflags;
14288 
14289 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14290 			"0392 Async Event: word0:x%x, word1:x%x, "
14291 			"word2:x%x, word3:x%x\n", mcqe->word0,
14292 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
14293 
14294 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
14295 	if (!cq_event)
14296 		return false;
14297 
14298 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
14299 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
14300 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
14301 
14302 	/* Set the async event flag */
14303 	set_bit(ASYNC_EVENT, &phba->hba_flag);
14304 
14305 	return true;
14306 }
14307 
14308 /**
14309  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
14310  * @phba: Pointer to HBA context object.
14311  * @mcqe: Pointer to mailbox completion queue entry.
14312  *
14313  * This routine process a mailbox completion queue entry with mailbox
14314  * completion event.
14315  *
14316  * Return: true if work posted to worker thread, otherwise false.
14317  **/
14318 static bool
14319 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14320 {
14321 	uint32_t mcqe_status;
14322 	MAILBOX_t *mbox, *pmbox;
14323 	struct lpfc_mqe *mqe;
14324 	struct lpfc_vport *vport;
14325 	struct lpfc_nodelist *ndlp;
14326 	struct lpfc_dmabuf *mp;
14327 	unsigned long iflags;
14328 	LPFC_MBOXQ_t *pmb;
14329 	bool workposted = false;
14330 	int rc;
14331 
14332 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
14333 	if (!bf_get(lpfc_trailer_completed, mcqe))
14334 		goto out_no_mqe_complete;
14335 
14336 	/* Get the reference to the active mbox command */
14337 	spin_lock_irqsave(&phba->hbalock, iflags);
14338 	pmb = phba->sli.mbox_active;
14339 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14340 	if (unlikely(!pmb)) {
14341 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14342 				"1832 No pending MBOX command to handle, "
14343 				"mcqe: x%08x x%08x x%08x x%08x\n",
14344 				mcqe->word0, mcqe->mcqe_tag0,
14345 				mcqe->mcqe_tag1, mcqe->trailer);
14346 		goto out_no_mqe_complete;
14347 	}
14348 	mqe = &pmb->u.mqe;
14349 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
14350 	mbox = phba->mbox;
14351 	vport = pmb->vport;
14352 
14353 	/* Reset heartbeat timer */
14354 	phba->last_completion_time = jiffies;
14355 	timer_delete(&phba->sli.mbox_tmo);
14356 
14357 	/* Move mbox data to caller's mailbox region, do endian swapping */
14358 	if (pmb->mbox_cmpl && mbox)
14359 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
14360 
14361 	/*
14362 	 * For mcqe errors, conditionally move a modified error code to
14363 	 * the mbox so that the error will not be missed.
14364 	 */
14365 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
14366 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
14367 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
14368 			bf_set(lpfc_mqe_status, mqe,
14369 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
14370 	}
14371 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
14372 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
14373 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
14374 				      "MBOX dflt rpi: status:x%x rpi:x%x",
14375 				      mcqe_status,
14376 				      pmbox->un.varWords[0], 0);
14377 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
14378 			mp = pmb->ctx_buf;
14379 			ndlp = pmb->ctx_ndlp;
14380 
14381 			/* Reg_LOGIN of dflt RPI was successful. Mark the
14382 			 * node as having an UNREG_LOGIN in progress to stop
14383 			 * an unsolicited PLOGI from the same NPortId from
14384 			 * starting another mailbox transaction.
14385 			 */
14386 			set_bit(NLP_UNREG_INP, &ndlp->nlp_flag);
14387 			lpfc_unreg_login(phba, vport->vpi,
14388 					 pmbox->un.varWords[0], pmb);
14389 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
14390 			pmb->ctx_buf = mp;
14391 
14392 			/* No reference taken here.  This is a default
14393 			 * RPI reg/immediate unreg cycle. The reference was
14394 			 * taken in the reg rpi path and is released when
14395 			 * this mailbox completes.
14396 			 */
14397 			pmb->ctx_ndlp = ndlp;
14398 			pmb->vport = vport;
14399 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
14400 			if (rc != MBX_BUSY)
14401 				lpfc_printf_log(phba, KERN_ERR,
14402 						LOG_TRACE_EVENT,
14403 						"0385 rc should "
14404 						"have been MBX_BUSY\n");
14405 			if (rc != MBX_NOT_FINISHED)
14406 				goto send_current_mbox;
14407 		}
14408 	}
14409 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
14410 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
14411 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
14412 
14413 	/* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
14414 	if (pmbox->mbxCommand == MBX_HEARTBEAT) {
14415 		spin_lock_irqsave(&phba->hbalock, iflags);
14416 		/* Release the mailbox command posting token */
14417 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14418 		phba->sli.mbox_active = NULL;
14419 		if (bf_get(lpfc_trailer_consumed, mcqe))
14420 			lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14421 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14422 
14423 		/* Post the next mbox command, if there is one */
14424 		lpfc_sli4_post_async_mbox(phba);
14425 
14426 		/* Process cmpl now */
14427 		if (pmb->mbox_cmpl)
14428 			pmb->mbox_cmpl(phba, pmb);
14429 		return false;
14430 	}
14431 
14432 	/* There is mailbox completion work to queue to the worker thread */
14433 	spin_lock_irqsave(&phba->hbalock, iflags);
14434 	__lpfc_mbox_cmpl_put(phba, pmb);
14435 	phba->work_ha |= HA_MBATT;
14436 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14437 	workposted = true;
14438 
14439 send_current_mbox:
14440 	spin_lock_irqsave(&phba->hbalock, iflags);
14441 	/* Release the mailbox command posting token */
14442 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14443 	/* Setting active mailbox pointer need to be in sync to flag clear */
14444 	phba->sli.mbox_active = NULL;
14445 	if (bf_get(lpfc_trailer_consumed, mcqe))
14446 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14447 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14448 	/* Wake up worker thread to post the next pending mailbox command */
14449 	lpfc_worker_wake_up(phba);
14450 	return workposted;
14451 
14452 out_no_mqe_complete:
14453 	spin_lock_irqsave(&phba->hbalock, iflags);
14454 	if (bf_get(lpfc_trailer_consumed, mcqe))
14455 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14456 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14457 	return false;
14458 }
14459 
14460 /**
14461  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
14462  * @phba: Pointer to HBA context object.
14463  * @cq: Pointer to associated CQ
14464  * @cqe: Pointer to mailbox completion queue entry.
14465  *
14466  * This routine process a mailbox completion queue entry, it invokes the
14467  * proper mailbox complete handling or asynchronous event handling routine
14468  * according to the MCQE's async bit.
14469  *
14470  * Return: true if work posted to worker thread, otherwise false.
14471  **/
14472 static bool
14473 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14474 			 struct lpfc_cqe *cqe)
14475 {
14476 	struct lpfc_mcqe mcqe;
14477 	bool workposted;
14478 
14479 	cq->CQ_mbox++;
14480 
14481 	/* Copy the mailbox MCQE and convert endian order as needed */
14482 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
14483 
14484 	/* Invoke the proper event handling routine */
14485 	if (!bf_get(lpfc_trailer_async, &mcqe))
14486 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
14487 	else
14488 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
14489 	return workposted;
14490 }
14491 
14492 /**
14493  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
14494  * @phba: Pointer to HBA context object.
14495  * @cq: Pointer to associated CQ
14496  * @wcqe: Pointer to work-queue completion queue entry.
14497  *
14498  * This routine handles an ELS work-queue completion event.
14499  *
14500  * Return: true if work posted to worker thread, otherwise false.
14501  **/
14502 static bool
14503 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14504 			     struct lpfc_wcqe_complete *wcqe)
14505 {
14506 	struct lpfc_iocbq *irspiocbq;
14507 	unsigned long iflags;
14508 	struct lpfc_sli_ring *pring = cq->pring;
14509 	int txq_cnt = 0;
14510 	int txcmplq_cnt = 0;
14511 
14512 	/* Check for response status */
14513 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14514 		/* Log the error status */
14515 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14516 				"0357 ELS CQE error: status=x%x: "
14517 				"CQE: %08x %08x %08x %08x\n",
14518 				bf_get(lpfc_wcqe_c_status, wcqe),
14519 				wcqe->word0, wcqe->total_data_placed,
14520 				wcqe->parameter, wcqe->word3);
14521 	}
14522 
14523 	/* Get an irspiocbq for later ELS response processing use */
14524 	irspiocbq = lpfc_sli_get_iocbq(phba);
14525 	if (!irspiocbq) {
14526 		if (!list_empty(&pring->txq))
14527 			txq_cnt++;
14528 		if (!list_empty(&pring->txcmplq))
14529 			txcmplq_cnt++;
14530 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14531 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
14532 			"els_txcmplq_cnt=%d\n",
14533 			txq_cnt, phba->iocb_cnt,
14534 			txcmplq_cnt);
14535 		return false;
14536 	}
14537 
14538 	/* Save off the slow-path queue event for work thread to process */
14539 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
14540 	spin_lock_irqsave(&phba->hbalock, iflags);
14541 	list_add_tail(&irspiocbq->cq_event.list,
14542 		      &phba->sli4_hba.sp_queue_event);
14543 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14544 	set_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
14545 
14546 	return true;
14547 }
14548 
14549 /**
14550  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
14551  * @phba: Pointer to HBA context object.
14552  * @wcqe: Pointer to work-queue completion queue entry.
14553  *
14554  * This routine handles slow-path WQ entry consumed event by invoking the
14555  * proper WQ release routine to the slow-path WQ.
14556  **/
14557 static void
14558 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
14559 			     struct lpfc_wcqe_release *wcqe)
14560 {
14561 	/* sanity check on queue memory */
14562 	if (unlikely(!phba->sli4_hba.els_wq))
14563 		return;
14564 	/* Check for the slow-path ELS work queue */
14565 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
14566 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
14567 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14568 	else
14569 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14570 				"2579 Slow-path wqe consume event carries "
14571 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
14572 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
14573 				phba->sli4_hba.els_wq->queue_id);
14574 }
14575 
14576 /**
14577  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
14578  * @phba: Pointer to HBA context object.
14579  * @cq: Pointer to a WQ completion queue.
14580  * @wcqe: Pointer to work-queue completion queue entry.
14581  *
14582  * This routine handles an XRI abort event.
14583  *
14584  * Return: true if work posted to worker thread, otherwise false.
14585  **/
14586 static bool
14587 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
14588 				   struct lpfc_queue *cq,
14589 				   struct sli4_wcqe_xri_aborted *wcqe)
14590 {
14591 	bool workposted = false;
14592 	struct lpfc_cq_event *cq_event;
14593 	unsigned long iflags;
14594 
14595 	switch (cq->subtype) {
14596 	case LPFC_IO:
14597 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
14598 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14599 			/* Notify aborted XRI for NVME work queue */
14600 			if (phba->nvmet_support)
14601 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
14602 		}
14603 		workposted = false;
14604 		break;
14605 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
14606 	case LPFC_ELS:
14607 		cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
14608 		if (!cq_event) {
14609 			workposted = false;
14610 			break;
14611 		}
14612 		cq_event->hdwq = cq->hdwq;
14613 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14614 				  iflags);
14615 		list_add_tail(&cq_event->list,
14616 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
14617 		/* Set the els xri abort event flag */
14618 		set_bit(ELS_XRI_ABORT_EVENT, &phba->hba_flag);
14619 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14620 				       iflags);
14621 		workposted = true;
14622 		break;
14623 	default:
14624 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14625 				"0603 Invalid CQ subtype %d: "
14626 				"%08x %08x %08x %08x\n",
14627 				cq->subtype, wcqe->word0, wcqe->parameter,
14628 				wcqe->word2, wcqe->word3);
14629 		workposted = false;
14630 		break;
14631 	}
14632 	return workposted;
14633 }
14634 
14635 #define FC_RCTL_MDS_DIAGS	0xF4
14636 
14637 /**
14638  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
14639  * @phba: Pointer to HBA context object.
14640  * @rcqe: Pointer to receive-queue completion queue entry.
14641  *
14642  * This routine process a receive-queue completion queue entry.
14643  *
14644  * Return: true if work posted to worker thread, otherwise false.
14645  **/
14646 static bool
14647 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
14648 {
14649 	bool workposted = false;
14650 	struct fc_frame_header *fc_hdr;
14651 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
14652 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
14653 	struct lpfc_nvmet_tgtport *tgtp;
14654 	struct hbq_dmabuf *dma_buf;
14655 	uint32_t status, rq_id;
14656 	unsigned long iflags;
14657 
14658 	/* sanity check on queue memory */
14659 	if (unlikely(!hrq) || unlikely(!drq))
14660 		return workposted;
14661 
14662 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14663 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14664 	else
14665 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14666 	if (rq_id != hrq->queue_id)
14667 		goto out;
14668 
14669 	status = bf_get(lpfc_rcqe_status, rcqe);
14670 	switch (status) {
14671 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14672 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14673 				"2537 Receive Frame Truncated!!\n");
14674 		fallthrough;
14675 	case FC_STATUS_RQ_SUCCESS:
14676 		spin_lock_irqsave(&phba->hbalock, iflags);
14677 		lpfc_sli4_rq_release(hrq, drq);
14678 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14679 		if (!dma_buf) {
14680 			hrq->RQ_no_buf_found++;
14681 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14682 			goto out;
14683 		}
14684 		hrq->RQ_rcv_buf++;
14685 		hrq->RQ_buf_posted--;
14686 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
14687 
14688 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14689 
14690 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
14691 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
14692 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14693 			/* Handle MDS Loopback frames */
14694 			if  (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
14695 				lpfc_sli4_handle_mds_loopback(phba->pport,
14696 							      dma_buf);
14697 			else
14698 				lpfc_in_buf_free(phba, &dma_buf->dbuf);
14699 			break;
14700 		}
14701 
14702 		/* save off the frame for the work thread to process */
14703 		list_add_tail(&dma_buf->cq_event.list,
14704 			      &phba->sli4_hba.sp_queue_event);
14705 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14706 		/* Frame received */
14707 		set_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
14708 		workposted = true;
14709 		break;
14710 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14711 		if (phba->nvmet_support) {
14712 			tgtp = phba->targetport->private;
14713 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14714 					"6402 RQE Error x%x, posted %d err_cnt "
14715 					"%d: %x %x %x\n",
14716 					status, hrq->RQ_buf_posted,
14717 					hrq->RQ_no_posted_buf,
14718 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14719 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14720 					atomic_read(&tgtp->xmt_fcp_release));
14721 		}
14722 		hrq->RQ_discard_frm++;
14723 		fallthrough;
14724 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14725 		/* Unexpected event - bump the counter for support. */
14726 		hrq->RQ_no_posted_buf++;
14727 
14728 		lpfc_log_msg(phba, KERN_WARNING,
14729 			     LOG_ELS | LOG_DISCOVERY | LOG_SLI,
14730 			     "6423 RQE completion Status x%x, needed x%x "
14731 			     "discarded x%x\n", status,
14732 			     hrq->RQ_no_posted_buf - hrq->RQ_discard_frm,
14733 			     hrq->RQ_discard_frm);
14734 
14735 		/* For SLI3, post more buffers if possible. No action for SLI4.
14736 		 * SLI4 is reposting immediately after processing the RQE.
14737 		 */
14738 		set_bit(HBA_POST_RECEIVE_BUFFER, &phba->hba_flag);
14739 		workposted = true;
14740 		break;
14741 	case FC_STATUS_RQ_DMA_FAILURE:
14742 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14743 				"2564 RQE DMA Error x%x, x%08x x%08x x%08x "
14744 				"x%08x\n",
14745 				status, rcqe->word0, rcqe->word1,
14746 				rcqe->word2, rcqe->word3);
14747 
14748 		/* If IV set, no further recovery */
14749 		if (bf_get(lpfc_rcqe_iv, rcqe))
14750 			break;
14751 
14752 		/* recycle consumed resource */
14753 		spin_lock_irqsave(&phba->hbalock, iflags);
14754 		lpfc_sli4_rq_release(hrq, drq);
14755 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14756 		if (!dma_buf) {
14757 			hrq->RQ_no_buf_found++;
14758 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14759 			break;
14760 		}
14761 		hrq->RQ_rcv_buf++;
14762 		hrq->RQ_buf_posted--;
14763 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14764 		lpfc_in_buf_free(phba, &dma_buf->dbuf);
14765 		break;
14766 	default:
14767 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14768 				"2565 Unexpected RQE Status x%x, w0-3 x%08x "
14769 				"x%08x x%08x x%08x\n",
14770 				status, rcqe->word0, rcqe->word1,
14771 				rcqe->word2, rcqe->word3);
14772 		break;
14773 	}
14774 out:
14775 	return workposted;
14776 }
14777 
14778 /**
14779  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
14780  * @phba: Pointer to HBA context object.
14781  * @cq: Pointer to the completion queue.
14782  * @cqe: Pointer to a completion queue entry.
14783  *
14784  * This routine process a slow-path work-queue or receive queue completion queue
14785  * entry.
14786  *
14787  * Return: true if work posted to worker thread, otherwise false.
14788  **/
14789 static bool
14790 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14791 			 struct lpfc_cqe *cqe)
14792 {
14793 	struct lpfc_cqe cqevt;
14794 	bool workposted = false;
14795 
14796 	/* Copy the work queue CQE and convert endian order if needed */
14797 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14798 
14799 	/* Check and process for different type of WCQE and dispatch */
14800 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
14801 	case CQE_CODE_COMPL_WQE:
14802 		/* Process the WQ/RQ complete event */
14803 		phba->last_completion_time = jiffies;
14804 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14805 				(struct lpfc_wcqe_complete *)&cqevt);
14806 		break;
14807 	case CQE_CODE_RELEASE_WQE:
14808 		/* Process the WQ release event */
14809 		lpfc_sli4_sp_handle_rel_wcqe(phba,
14810 				(struct lpfc_wcqe_release *)&cqevt);
14811 		break;
14812 	case CQE_CODE_XRI_ABORTED:
14813 		/* Process the WQ XRI abort event */
14814 		phba->last_completion_time = jiffies;
14815 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14816 				(struct sli4_wcqe_xri_aborted *)&cqevt);
14817 		break;
14818 	case CQE_CODE_RECEIVE:
14819 	case CQE_CODE_RECEIVE_V1:
14820 		/* Process the RQ event */
14821 		phba->last_completion_time = jiffies;
14822 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
14823 				(struct lpfc_rcqe *)&cqevt);
14824 		break;
14825 	default:
14826 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14827 				"0388 Not a valid WCQE code: x%x\n",
14828 				bf_get(lpfc_cqe_code, &cqevt));
14829 		break;
14830 	}
14831 	return workposted;
14832 }
14833 
14834 /**
14835  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14836  * @phba: Pointer to HBA context object.
14837  * @eqe: Pointer to fast-path event queue entry.
14838  * @speq: Pointer to slow-path event queue.
14839  *
14840  * This routine process a event queue entry from the slow-path event queue.
14841  * It will check the MajorCode and MinorCode to determine this is for a
14842  * completion event on a completion queue, if not, an error shall be logged
14843  * and just return. Otherwise, it will get to the corresponding completion
14844  * queue and process all the entries on that completion queue, rearm the
14845  * completion queue, and then return.
14846  *
14847  **/
14848 static void
14849 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14850 	struct lpfc_queue *speq)
14851 {
14852 	struct lpfc_queue *cq = NULL, *childq;
14853 	uint16_t cqid;
14854 	int ret = 0;
14855 
14856 	/* Get the reference to the corresponding CQ */
14857 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14858 
14859 	list_for_each_entry(childq, &speq->child_list, list) {
14860 		if (childq->queue_id == cqid) {
14861 			cq = childq;
14862 			break;
14863 		}
14864 	}
14865 	if (unlikely(!cq)) {
14866 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14867 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14868 					"0365 Slow-path CQ identifier "
14869 					"(%d) does not exist\n", cqid);
14870 		return;
14871 	}
14872 
14873 	/* Save EQ associated with this CQ */
14874 	cq->assoc_qp = speq;
14875 
14876 	if (is_kdump_kernel())
14877 		ret = queue_work(phba->wq, &cq->spwork);
14878 	else
14879 		ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14880 
14881 	if (!ret)
14882 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14883 				"0390 Cannot schedule queue work "
14884 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14885 				cqid, cq->queue_id, raw_smp_processor_id());
14886 }
14887 
14888 /**
14889  * __lpfc_sli4_process_cq - Process elements of a CQ
14890  * @phba: Pointer to HBA context object.
14891  * @cq: Pointer to CQ to be processed
14892  * @handler: Routine to process each cqe
14893  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14894  *
14895  * This routine processes completion queue entries in a CQ. While a valid
14896  * queue element is found, the handler is called. During processing checks
14897  * are made for periodic doorbell writes to let the hardware know of
14898  * element consumption.
14899  *
14900  * If the max limit on cqes to process is hit, or there are no more valid
14901  * entries, the loop stops. If we processed a sufficient number of elements,
14902  * meaning there is sufficient load, rather than rearming and generating
14903  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14904  * indicates no rescheduling.
14905  *
14906  * Returns True if work scheduled, False otherwise.
14907  **/
14908 static bool
14909 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14910 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14911 			struct lpfc_cqe *), unsigned long *delay)
14912 {
14913 	struct lpfc_cqe *cqe;
14914 	bool workposted = false;
14915 	int count = 0, consumed = 0;
14916 	bool arm = true;
14917 
14918 	/* default - no reschedule */
14919 	*delay = 0;
14920 
14921 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14922 		goto rearm_and_exit;
14923 
14924 	/* Process all the entries to the CQ */
14925 	cq->q_flag = 0;
14926 	cqe = lpfc_sli4_cq_get(cq);
14927 	while (cqe) {
14928 		workposted |= handler(phba, cq, cqe);
14929 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
14930 
14931 		consumed++;
14932 		if (!(++count % cq->max_proc_limit))
14933 			break;
14934 
14935 		if (!(count % cq->notify_interval)) {
14936 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14937 						LPFC_QUEUE_NOARM);
14938 			consumed = 0;
14939 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14940 		}
14941 
14942 		if (count == LPFC_NVMET_CQ_NOTIFY)
14943 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14944 
14945 		cqe = lpfc_sli4_cq_get(cq);
14946 	}
14947 	if (count >= phba->cfg_cq_poll_threshold) {
14948 		*delay = 1;
14949 		arm = false;
14950 	}
14951 
14952 	/* Track the max number of CQEs processed in 1 EQ */
14953 	if (count > cq->CQ_max_cqe)
14954 		cq->CQ_max_cqe = count;
14955 
14956 	cq->assoc_qp->EQ_cqe_cnt += count;
14957 
14958 	/* Catch the no cq entry condition */
14959 	if (unlikely(count == 0))
14960 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14961 				"0369 No entry from completion queue "
14962 				"qid=%d\n", cq->queue_id);
14963 
14964 	xchg(&cq->queue_claimed, 0);
14965 
14966 rearm_and_exit:
14967 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14968 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14969 
14970 	return workposted;
14971 }
14972 
14973 /**
14974  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14975  * @cq: pointer to CQ to process
14976  *
14977  * This routine calls the cq processing routine with a handler specific
14978  * to the type of queue bound to it.
14979  *
14980  * The CQ routine returns two values: the first is the calling status,
14981  * which indicates whether work was queued to the  background discovery
14982  * thread. If true, the routine should wakeup the discovery thread;
14983  * the second is the delay parameter. If non-zero, rather than rearming
14984  * the CQ and yet another interrupt, the CQ handler should be queued so
14985  * that it is processed in a subsequent polling action. The value of
14986  * the delay indicates when to reschedule it.
14987  **/
14988 static void
14989 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14990 {
14991 	struct lpfc_hba *phba = cq->phba;
14992 	unsigned long delay;
14993 	bool workposted = false;
14994 	int ret = 0;
14995 
14996 	/* Process and rearm the CQ */
14997 	switch (cq->type) {
14998 	case LPFC_MCQ:
14999 		workposted |= __lpfc_sli4_process_cq(phba, cq,
15000 						lpfc_sli4_sp_handle_mcqe,
15001 						&delay);
15002 		break;
15003 	case LPFC_WCQ:
15004 		if (cq->subtype == LPFC_IO)
15005 			workposted |= __lpfc_sli4_process_cq(phba, cq,
15006 						lpfc_sli4_fp_handle_cqe,
15007 						&delay);
15008 		else
15009 			workposted |= __lpfc_sli4_process_cq(phba, cq,
15010 						lpfc_sli4_sp_handle_cqe,
15011 						&delay);
15012 		break;
15013 	default:
15014 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15015 				"0370 Invalid completion queue type (%d)\n",
15016 				cq->type);
15017 		return;
15018 	}
15019 
15020 	if (delay) {
15021 		if (is_kdump_kernel())
15022 			ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
15023 						delay);
15024 		else
15025 			ret = queue_delayed_work_on(cq->chann, phba->wq,
15026 						&cq->sched_spwork, delay);
15027 		if (!ret)
15028 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15029 				"0394 Cannot schedule queue work "
15030 				"for cqid=%d on CPU %d\n",
15031 				cq->queue_id, cq->chann);
15032 	}
15033 
15034 	/* wake up worker thread if there are works to be done */
15035 	if (workposted)
15036 		lpfc_worker_wake_up(phba);
15037 }
15038 
15039 /**
15040  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
15041  *   interrupt
15042  * @work: pointer to work element
15043  *
15044  * translates from the work handler and calls the slow-path handler.
15045  **/
15046 static void
15047 lpfc_sli4_sp_process_cq(struct work_struct *work)
15048 {
15049 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
15050 
15051 	__lpfc_sli4_sp_process_cq(cq);
15052 }
15053 
15054 /**
15055  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
15056  * @work: pointer to work element
15057  *
15058  * translates from the work handler and calls the slow-path handler.
15059  **/
15060 static void
15061 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
15062 {
15063 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15064 					struct lpfc_queue, sched_spwork);
15065 
15066 	__lpfc_sli4_sp_process_cq(cq);
15067 }
15068 
15069 /**
15070  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
15071  * @phba: Pointer to HBA context object.
15072  * @cq: Pointer to associated CQ
15073  * @wcqe: Pointer to work-queue completion queue entry.
15074  *
15075  * This routine process a fast-path work queue completion entry from fast-path
15076  * event queue for FCP command response completion.
15077  **/
15078 static void
15079 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15080 			     struct lpfc_wcqe_complete *wcqe)
15081 {
15082 	struct lpfc_sli_ring *pring = cq->pring;
15083 	struct lpfc_iocbq *cmdiocbq;
15084 	unsigned long iflags;
15085 
15086 	/* Check for response status */
15087 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
15088 		/* If resource errors reported from HBA, reduce queue
15089 		 * depth of the SCSI device.
15090 		 */
15091 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
15092 		     IOSTAT_LOCAL_REJECT)) &&
15093 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
15094 		     IOERR_NO_RESOURCES))
15095 			phba->lpfc_rampdown_queue_depth(phba);
15096 
15097 		/* Log the cmpl status */
15098 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15099 				"0373 FCP CQE cmpl: status=x%x: "
15100 				"CQE: %08x %08x %08x %08x\n",
15101 				bf_get(lpfc_wcqe_c_status, wcqe),
15102 				wcqe->word0, wcqe->total_data_placed,
15103 				wcqe->parameter, wcqe->word3);
15104 	}
15105 
15106 	/* Look up the FCP command IOCB and create pseudo response IOCB */
15107 	spin_lock_irqsave(&pring->ring_lock, iflags);
15108 	pring->stats.iocb_event++;
15109 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
15110 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15111 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
15112 	if (unlikely(!cmdiocbq)) {
15113 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15114 				"0374 FCP complete with no corresponding "
15115 				"cmdiocb: iotag (%d)\n",
15116 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15117 		return;
15118 	}
15119 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
15120 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
15121 #endif
15122 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
15123 		spin_lock_irqsave(&phba->hbalock, iflags);
15124 		cmdiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
15125 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15126 	}
15127 
15128 	if (cmdiocbq->cmd_cmpl) {
15129 		/* For FCP the flag is cleared in cmd_cmpl */
15130 		if (!(cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
15131 		    cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED) {
15132 			spin_lock_irqsave(&phba->hbalock, iflags);
15133 			cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
15134 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15135 		}
15136 
15137 		/* Pass the cmd_iocb and the wcqe to the upper layer */
15138 		memcpy(&cmdiocbq->wcqe_cmpl, wcqe,
15139 		       sizeof(struct lpfc_wcqe_complete));
15140 		cmdiocbq->cmd_cmpl(phba, cmdiocbq, cmdiocbq);
15141 	} else {
15142 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15143 				"0375 FCP cmdiocb not callback function "
15144 				"iotag: (%d)\n",
15145 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15146 	}
15147 }
15148 
15149 /**
15150  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
15151  * @phba: Pointer to HBA context object.
15152  * @cq: Pointer to completion queue.
15153  * @wcqe: Pointer to work-queue completion queue entry.
15154  *
15155  * This routine handles an fast-path WQ entry consumed event by invoking the
15156  * proper WQ release routine to the slow-path WQ.
15157  **/
15158 static void
15159 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15160 			     struct lpfc_wcqe_release *wcqe)
15161 {
15162 	struct lpfc_queue *childwq;
15163 	bool wqid_matched = false;
15164 	uint16_t hba_wqid;
15165 
15166 	/* Check for fast-path FCP work queue release */
15167 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
15168 	list_for_each_entry(childwq, &cq->child_list, list) {
15169 		if (childwq->queue_id == hba_wqid) {
15170 			lpfc_sli4_wq_release(childwq,
15171 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
15172 			if (childwq->q_flag & HBA_NVMET_WQFULL)
15173 				lpfc_nvmet_wqfull_process(phba, childwq);
15174 			wqid_matched = true;
15175 			break;
15176 		}
15177 	}
15178 	/* Report warning log message if no match found */
15179 	if (wqid_matched != true)
15180 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15181 				"2580 Fast-path wqe consume event carries "
15182 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
15183 }
15184 
15185 /**
15186  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
15187  * @phba: Pointer to HBA context object.
15188  * @cq: Pointer to completion queue.
15189  * @rcqe: Pointer to receive-queue completion queue entry.
15190  *
15191  * This routine process a receive-queue completion queue entry.
15192  *
15193  * Return: true if work posted to worker thread, otherwise false.
15194  **/
15195 static bool
15196 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15197 			    struct lpfc_rcqe *rcqe)
15198 {
15199 	bool workposted = false;
15200 	struct lpfc_queue *hrq;
15201 	struct lpfc_queue *drq;
15202 	struct rqb_dmabuf *dma_buf;
15203 	struct fc_frame_header *fc_hdr;
15204 	struct lpfc_nvmet_tgtport *tgtp;
15205 	uint32_t status, rq_id;
15206 	unsigned long iflags;
15207 	uint32_t fctl, idx;
15208 
15209 	if ((phba->nvmet_support == 0) ||
15210 	    (phba->sli4_hba.nvmet_cqset == NULL))
15211 		return workposted;
15212 
15213 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
15214 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
15215 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
15216 
15217 	/* sanity check on queue memory */
15218 	if (unlikely(!hrq) || unlikely(!drq))
15219 		return workposted;
15220 
15221 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
15222 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
15223 	else
15224 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
15225 
15226 	if ((phba->nvmet_support == 0) ||
15227 	    (rq_id != hrq->queue_id))
15228 		return workposted;
15229 
15230 	status = bf_get(lpfc_rcqe_status, rcqe);
15231 	switch (status) {
15232 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
15233 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15234 				"6126 Receive Frame Truncated!!\n");
15235 		fallthrough;
15236 	case FC_STATUS_RQ_SUCCESS:
15237 		spin_lock_irqsave(&phba->hbalock, iflags);
15238 		lpfc_sli4_rq_release(hrq, drq);
15239 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15240 		if (!dma_buf) {
15241 			hrq->RQ_no_buf_found++;
15242 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15243 			goto out;
15244 		}
15245 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15246 		hrq->RQ_rcv_buf++;
15247 		hrq->RQ_buf_posted--;
15248 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
15249 
15250 		/* Just some basic sanity checks on FCP Command frame */
15251 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
15252 			fc_hdr->fh_f_ctl[1] << 8 |
15253 			fc_hdr->fh_f_ctl[2]);
15254 		if (((fctl &
15255 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
15256 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
15257 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
15258 			goto drop;
15259 
15260 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
15261 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
15262 			lpfc_nvmet_unsol_fcp_event(
15263 				phba, idx, dma_buf, cq->isr_timestamp,
15264 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
15265 			return false;
15266 		}
15267 drop:
15268 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15269 		break;
15270 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
15271 		if (phba->nvmet_support) {
15272 			tgtp = phba->targetport->private;
15273 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15274 					"6401 RQE Error x%x, posted %d err_cnt "
15275 					"%d: %x %x %x\n",
15276 					status, hrq->RQ_buf_posted,
15277 					hrq->RQ_no_posted_buf,
15278 					atomic_read(&tgtp->rcv_fcp_cmd_in),
15279 					atomic_read(&tgtp->rcv_fcp_cmd_out),
15280 					atomic_read(&tgtp->xmt_fcp_release));
15281 		}
15282 		fallthrough;
15283 
15284 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
15285 		hrq->RQ_no_posted_buf++;
15286 		/* Post more buffers if possible */
15287 		break;
15288 	case FC_STATUS_RQ_DMA_FAILURE:
15289 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15290 				"2575 RQE DMA Error x%x, x%08x x%08x x%08x "
15291 				"x%08x\n",
15292 				status, rcqe->word0, rcqe->word1,
15293 				rcqe->word2, rcqe->word3);
15294 
15295 		/* If IV set, no further recovery */
15296 		if (bf_get(lpfc_rcqe_iv, rcqe))
15297 			break;
15298 
15299 		/* recycle consumed resource */
15300 		spin_lock_irqsave(&phba->hbalock, iflags);
15301 		lpfc_sli4_rq_release(hrq, drq);
15302 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15303 		if (!dma_buf) {
15304 			hrq->RQ_no_buf_found++;
15305 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15306 			break;
15307 		}
15308 		hrq->RQ_rcv_buf++;
15309 		hrq->RQ_buf_posted--;
15310 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15311 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15312 		break;
15313 	default:
15314 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15315 				"2576 Unexpected RQE Status x%x, w0-3 x%08x "
15316 				"x%08x x%08x x%08x\n",
15317 				status, rcqe->word0, rcqe->word1,
15318 				rcqe->word2, rcqe->word3);
15319 		break;
15320 	}
15321 out:
15322 	return workposted;
15323 }
15324 
15325 /**
15326  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
15327  * @phba: adapter with cq
15328  * @cq: Pointer to the completion queue.
15329  * @cqe: Pointer to fast-path completion queue entry.
15330  *
15331  * This routine process a fast-path work queue completion entry from fast-path
15332  * event queue for FCP command response completion.
15333  *
15334  * Return: true if work posted to worker thread, otherwise false.
15335  **/
15336 static bool
15337 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15338 			 struct lpfc_cqe *cqe)
15339 {
15340 	struct lpfc_wcqe_release wcqe;
15341 	bool workposted = false;
15342 
15343 	/* Copy the work queue CQE and convert endian order if needed */
15344 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
15345 
15346 	/* Check and process for different type of WCQE and dispatch */
15347 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
15348 	case CQE_CODE_COMPL_WQE:
15349 	case CQE_CODE_NVME_ERSP:
15350 		cq->CQ_wq++;
15351 		/* Process the WQ complete event */
15352 		phba->last_completion_time = jiffies;
15353 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
15354 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
15355 				(struct lpfc_wcqe_complete *)&wcqe);
15356 		break;
15357 	case CQE_CODE_RELEASE_WQE:
15358 		cq->CQ_release_wqe++;
15359 		/* Process the WQ release event */
15360 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
15361 				(struct lpfc_wcqe_release *)&wcqe);
15362 		break;
15363 	case CQE_CODE_XRI_ABORTED:
15364 		cq->CQ_xri_aborted++;
15365 		/* Process the WQ XRI abort event */
15366 		phba->last_completion_time = jiffies;
15367 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
15368 				(struct sli4_wcqe_xri_aborted *)&wcqe);
15369 		break;
15370 	case CQE_CODE_RECEIVE_V1:
15371 	case CQE_CODE_RECEIVE:
15372 		phba->last_completion_time = jiffies;
15373 		if (cq->subtype == LPFC_NVMET) {
15374 			workposted = lpfc_sli4_nvmet_handle_rcqe(
15375 				phba, cq, (struct lpfc_rcqe *)&wcqe);
15376 		}
15377 		break;
15378 	default:
15379 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15380 				"0144 Not a valid CQE code: x%x\n",
15381 				bf_get(lpfc_wcqe_c_code, &wcqe));
15382 		break;
15383 	}
15384 	return workposted;
15385 }
15386 
15387 /**
15388  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
15389  * @cq: Pointer to CQ to be processed
15390  *
15391  * This routine calls the cq processing routine with the handler for
15392  * fast path CQEs.
15393  *
15394  * The CQ routine returns two values: the first is the calling status,
15395  * which indicates whether work was queued to the  background discovery
15396  * thread. If true, the routine should wakeup the discovery thread;
15397  * the second is the delay parameter. If non-zero, rather than rearming
15398  * the CQ and yet another interrupt, the CQ handler should be queued so
15399  * that it is processed in a subsequent polling action. The value of
15400  * the delay indicates when to reschedule it.
15401  **/
15402 static void
15403 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq)
15404 {
15405 	struct lpfc_hba *phba = cq->phba;
15406 	unsigned long delay;
15407 	bool workposted = false;
15408 	int ret;
15409 
15410 	/* process and rearm the CQ */
15411 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
15412 					     &delay);
15413 
15414 	if (delay) {
15415 		if (is_kdump_kernel())
15416 			ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
15417 						delay);
15418 		else
15419 			ret = queue_delayed_work_on(cq->chann, phba->wq,
15420 						&cq->sched_irqwork, delay);
15421 		if (!ret)
15422 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15423 					"0367 Cannot schedule queue work "
15424 					"for cqid=%d on CPU %d\n",
15425 					cq->queue_id, cq->chann);
15426 	}
15427 
15428 	/* wake up worker thread if there are works to be done */
15429 	if (workposted)
15430 		lpfc_worker_wake_up(phba);
15431 }
15432 
15433 /**
15434  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
15435  *   interrupt
15436  * @work: pointer to work element
15437  *
15438  * translates from the work handler and calls the fast-path handler.
15439  **/
15440 static void
15441 lpfc_sli4_hba_process_cq(struct work_struct *work)
15442 {
15443 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
15444 
15445 	__lpfc_sli4_hba_process_cq(cq);
15446 }
15447 
15448 /**
15449  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
15450  * @phba: Pointer to HBA context object.
15451  * @eq: Pointer to the queue structure.
15452  * @eqe: Pointer to fast-path event queue entry.
15453  * @poll_mode: poll_mode to execute processing the cq.
15454  *
15455  * This routine process a event queue entry from the fast-path event queue.
15456  * It will check the MajorCode and MinorCode to determine this is for a
15457  * completion event on a completion queue, if not, an error shall be logged
15458  * and just return. Otherwise, it will get to the corresponding completion
15459  * queue and process all the entries on the completion queue, rearm the
15460  * completion queue, and then return.
15461  **/
15462 static void
15463 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
15464 			 struct lpfc_eqe *eqe, enum lpfc_poll_mode poll_mode)
15465 {
15466 	struct lpfc_queue *cq = NULL;
15467 	uint32_t qidx = eq->hdwq;
15468 	uint16_t cqid, id;
15469 	int ret;
15470 
15471 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
15472 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15473 				"0366 Not a valid completion "
15474 				"event: majorcode=x%x, minorcode=x%x\n",
15475 				bf_get_le32(lpfc_eqe_major_code, eqe),
15476 				bf_get_le32(lpfc_eqe_minor_code, eqe));
15477 		return;
15478 	}
15479 
15480 	/* Get the reference to the corresponding CQ */
15481 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
15482 
15483 	/* Use the fast lookup method first */
15484 	if (cqid <= phba->sli4_hba.cq_max) {
15485 		cq = phba->sli4_hba.cq_lookup[cqid];
15486 		if (cq)
15487 			goto  work_cq;
15488 	}
15489 
15490 	/* Next check for NVMET completion */
15491 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
15492 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
15493 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
15494 			/* Process NVMET unsol rcv */
15495 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
15496 			goto  process_cq;
15497 		}
15498 	}
15499 
15500 	if (phba->sli4_hba.nvmels_cq &&
15501 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
15502 		/* Process NVME unsol rcv */
15503 		cq = phba->sli4_hba.nvmels_cq;
15504 	}
15505 
15506 	/* Otherwise this is a Slow path event */
15507 	if (cq == NULL) {
15508 		lpfc_sli4_sp_handle_eqe(phba, eqe,
15509 					phba->sli4_hba.hdwq[qidx].hba_eq);
15510 		return;
15511 	}
15512 
15513 process_cq:
15514 	if (unlikely(cqid != cq->queue_id)) {
15515 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15516 				"0368 Miss-matched fast-path completion "
15517 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
15518 				cqid, cq->queue_id);
15519 		return;
15520 	}
15521 
15522 work_cq:
15523 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
15524 	if (phba->ktime_on)
15525 		cq->isr_timestamp = ktime_get_ns();
15526 	else
15527 		cq->isr_timestamp = 0;
15528 #endif
15529 
15530 	switch (poll_mode) {
15531 	case LPFC_THREADED_IRQ:
15532 		__lpfc_sli4_hba_process_cq(cq);
15533 		break;
15534 	case LPFC_QUEUE_WORK:
15535 	default:
15536 		if (is_kdump_kernel())
15537 			ret = queue_work(phba->wq, &cq->irqwork);
15538 		else
15539 			ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
15540 		if (!ret)
15541 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15542 					"0383 Cannot schedule queue work "
15543 					"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
15544 					cqid, cq->queue_id,
15545 					raw_smp_processor_id());
15546 		break;
15547 	}
15548 }
15549 
15550 /**
15551  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
15552  * @work: pointer to work element
15553  *
15554  * translates from the work handler and calls the fast-path handler.
15555  **/
15556 static void
15557 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
15558 {
15559 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15560 					struct lpfc_queue, sched_irqwork);
15561 
15562 	__lpfc_sli4_hba_process_cq(cq);
15563 }
15564 
15565 /**
15566  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
15567  * @irq: Interrupt number.
15568  * @dev_id: The device context pointer.
15569  *
15570  * This function is directly called from the PCI layer as an interrupt
15571  * service routine when device with SLI-4 interface spec is enabled with
15572  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
15573  * ring event in the HBA. However, when the device is enabled with either
15574  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
15575  * device-level interrupt handler. When the PCI slot is in error recovery
15576  * or the HBA is undergoing initialization, the interrupt handler will not
15577  * process the interrupt. The SCSI FCP fast-path ring event are handled in
15578  * the interrupt context. This function is called without any lock held.
15579  * It gets the hbalock to access and update SLI data structures. Note that,
15580  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
15581  * equal to that of FCP CQ index.
15582  *
15583  * The link attention and ELS ring attention events are handled
15584  * by the worker thread. The interrupt handler signals the worker thread
15585  * and returns for these events. This function is called without any lock
15586  * held. It gets the hbalock to access and update SLI data structures.
15587  *
15588  * This function returns IRQ_HANDLED when interrupt is handled, IRQ_WAKE_THREAD
15589  * when interrupt is scheduled to be handled from a threaded irq context, or
15590  * else returns IRQ_NONE.
15591  **/
15592 irqreturn_t
15593 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
15594 {
15595 	struct lpfc_hba *phba;
15596 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
15597 	struct lpfc_queue *fpeq;
15598 	unsigned long iflag;
15599 	int hba_eqidx;
15600 	int ecount = 0;
15601 	struct lpfc_eq_intr_info *eqi;
15602 
15603 	/* Get the driver's phba structure from the dev_id */
15604 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
15605 	phba = hba_eq_hdl->phba;
15606 	hba_eqidx = hba_eq_hdl->idx;
15607 
15608 	if (unlikely(!phba))
15609 		return IRQ_NONE;
15610 	if (unlikely(!phba->sli4_hba.hdwq))
15611 		return IRQ_NONE;
15612 
15613 	/* Get to the EQ struct associated with this vector */
15614 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
15615 	if (unlikely(!fpeq))
15616 		return IRQ_NONE;
15617 
15618 	/* Check device state for handling interrupt */
15619 	if (unlikely(lpfc_intr_state_check(phba))) {
15620 		/* Check again for link_state with lock held */
15621 		spin_lock_irqsave(&phba->hbalock, iflag);
15622 		if (phba->link_state < LPFC_LINK_DOWN)
15623 			/* Flush, clear interrupt, and rearm the EQ */
15624 			lpfc_sli4_eqcq_flush(phba, fpeq);
15625 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15626 		return IRQ_NONE;
15627 	}
15628 
15629 	switch (fpeq->poll_mode) {
15630 	case LPFC_THREADED_IRQ:
15631 		/* CGN mgmt is mutually exclusive from irq processing */
15632 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
15633 			return IRQ_WAKE_THREAD;
15634 		fallthrough;
15635 	case LPFC_QUEUE_WORK:
15636 	default:
15637 		eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
15638 		eqi->icnt++;
15639 
15640 		fpeq->last_cpu = raw_smp_processor_id();
15641 
15642 		if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
15643 		    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
15644 		    phba->cfg_auto_imax &&
15645 		    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
15646 		    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
15647 			lpfc_sli4_mod_hba_eq_delay(phba, fpeq,
15648 						   LPFC_MAX_AUTO_EQ_DELAY);
15649 
15650 		/* process and rearm the EQ */
15651 		ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
15652 					      LPFC_QUEUE_WORK);
15653 
15654 		if (unlikely(ecount == 0)) {
15655 			fpeq->EQ_no_entry++;
15656 			if (phba->intr_type == MSIX)
15657 				/* MSI-X treated interrupt served as no EQ share INT */
15658 				lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15659 						"0358 MSI-X interrupt with no EQE\n");
15660 			else
15661 				/* Non MSI-X treated on interrupt as EQ share INT */
15662 				return IRQ_NONE;
15663 		}
15664 	}
15665 
15666 	return IRQ_HANDLED;
15667 } /* lpfc_sli4_hba_intr_handler */
15668 
15669 /**
15670  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
15671  * @irq: Interrupt number.
15672  * @dev_id: The device context pointer.
15673  *
15674  * This function is the device-level interrupt handler to device with SLI-4
15675  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
15676  * interrupt mode is enabled and there is an event in the HBA which requires
15677  * driver attention. This function invokes the slow-path interrupt attention
15678  * handling function and fast-path interrupt attention handling function in
15679  * turn to process the relevant HBA attention events. This function is called
15680  * without any lock held. It gets the hbalock to access and update SLI data
15681  * structures.
15682  *
15683  * This function returns IRQ_HANDLED when interrupt is handled, else it
15684  * returns IRQ_NONE.
15685  **/
15686 irqreturn_t
15687 lpfc_sli4_intr_handler(int irq, void *dev_id)
15688 {
15689 	struct lpfc_hba  *phba;
15690 	irqreturn_t hba_irq_rc;
15691 	bool hba_handled = false;
15692 	int qidx;
15693 
15694 	/* Get the driver's phba structure from the dev_id */
15695 	phba = (struct lpfc_hba *)dev_id;
15696 
15697 	if (unlikely(!phba))
15698 		return IRQ_NONE;
15699 
15700 	/*
15701 	 * Invoke fast-path host attention interrupt handling as appropriate.
15702 	 */
15703 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
15704 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
15705 					&phba->sli4_hba.hba_eq_hdl[qidx]);
15706 		if (hba_irq_rc == IRQ_HANDLED)
15707 			hba_handled |= true;
15708 	}
15709 
15710 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
15711 } /* lpfc_sli4_intr_handler */
15712 
15713 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
15714 {
15715 	struct lpfc_hba *phba = timer_container_of(phba, t, cpuhp_poll_timer);
15716 	struct lpfc_queue *eq;
15717 
15718 	rcu_read_lock();
15719 
15720 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
15721 		lpfc_sli4_poll_eq(eq);
15722 	if (!list_empty(&phba->poll_list))
15723 		mod_timer(&phba->cpuhp_poll_timer,
15724 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15725 
15726 	rcu_read_unlock();
15727 }
15728 
15729 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
15730 {
15731 	struct lpfc_hba *phba = eq->phba;
15732 
15733 	/* kickstart slowpath processing if needed */
15734 	if (list_empty(&phba->poll_list))
15735 		mod_timer(&phba->cpuhp_poll_timer,
15736 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15737 
15738 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
15739 	synchronize_rcu();
15740 }
15741 
15742 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
15743 {
15744 	struct lpfc_hba *phba = eq->phba;
15745 
15746 	/* Disable slowpath processing for this eq.  Kick start the eq
15747 	 * by RE-ARMING the eq's ASAP
15748 	 */
15749 	list_del_rcu(&eq->_poll_list);
15750 	synchronize_rcu();
15751 
15752 	if (list_empty(&phba->poll_list))
15753 		timer_delete_sync(&phba->cpuhp_poll_timer);
15754 }
15755 
15756 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
15757 {
15758 	struct lpfc_queue *eq, *next;
15759 
15760 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
15761 		list_del(&eq->_poll_list);
15762 
15763 	INIT_LIST_HEAD(&phba->poll_list);
15764 	synchronize_rcu();
15765 }
15766 
15767 static inline void
15768 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
15769 {
15770 	if (mode == eq->mode)
15771 		return;
15772 	/*
15773 	 * currently this function is only called during a hotplug
15774 	 * event and the cpu on which this function is executing
15775 	 * is going offline.  By now the hotplug has instructed
15776 	 * the scheduler to remove this cpu from cpu active mask.
15777 	 * So we don't need to work about being put aside by the
15778 	 * scheduler for a high priority process.  Yes, the inte-
15779 	 * rrupts could come but they are known to retire ASAP.
15780 	 */
15781 
15782 	/* Disable polling in the fastpath */
15783 	WRITE_ONCE(eq->mode, mode);
15784 	/* flush out the store buffer */
15785 	smp_wmb();
15786 
15787 	/*
15788 	 * Add this eq to the polling list and start polling. For
15789 	 * a grace period both interrupt handler and poller will
15790 	 * try to process the eq _but_ that's fine.  We have a
15791 	 * synchronization mechanism in place (queue_claimed) to
15792 	 * deal with it.  This is just a draining phase for int-
15793 	 * errupt handler (not eq's) as we have guranteed through
15794 	 * barrier that all the CPUs have seen the new CQ_POLLED
15795 	 * state. which will effectively disable the REARMING of
15796 	 * the EQ.  The whole idea is eq's die off eventually as
15797 	 * we are not rearming EQ's anymore.
15798 	 */
15799 	mode ? lpfc_sli4_add_to_poll_list(eq) :
15800 	       lpfc_sli4_remove_from_poll_list(eq);
15801 }
15802 
15803 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15804 {
15805 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15806 }
15807 
15808 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15809 {
15810 	struct lpfc_hba *phba = eq->phba;
15811 
15812 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15813 
15814 	/* Kick start for the pending io's in h/w.
15815 	 * Once we switch back to interrupt processing on a eq
15816 	 * the io path completion will only arm eq's when it
15817 	 * receives a completion.  But since eq's are in disa-
15818 	 * rmed state it doesn't receive a completion.  This
15819 	 * creates a deadlock scenaro.
15820 	 */
15821 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15822 }
15823 
15824 /**
15825  * lpfc_sli4_queue_free - free a queue structure and associated memory
15826  * @queue: The queue structure to free.
15827  *
15828  * This function frees a queue structure and the DMAable memory used for
15829  * the host resident queue. This function must be called after destroying the
15830  * queue on the HBA.
15831  **/
15832 void
15833 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15834 {
15835 	struct lpfc_dmabuf *dmabuf;
15836 
15837 	if (!queue)
15838 		return;
15839 
15840 	if (!list_empty(&queue->wq_list))
15841 		list_del(&queue->wq_list);
15842 
15843 	while (!list_empty(&queue->page_list)) {
15844 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15845 				 list);
15846 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15847 				  dmabuf->virt, dmabuf->phys);
15848 		kfree(dmabuf);
15849 	}
15850 	if (queue->rqbp) {
15851 		lpfc_free_rq_buffer(queue->phba, queue);
15852 		kfree(queue->rqbp);
15853 	}
15854 
15855 	if (!list_empty(&queue->cpu_list))
15856 		list_del(&queue->cpu_list);
15857 
15858 	kfree(queue);
15859 	return;
15860 }
15861 
15862 /**
15863  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15864  * @phba: The HBA that this queue is being created on.
15865  * @page_size: The size of a queue page
15866  * @entry_size: The size of each queue entry for this queue.
15867  * @entry_count: The number of entries that this queue will handle.
15868  * @cpu: The cpu that will primarily utilize this queue.
15869  *
15870  * This function allocates a queue structure and the DMAable memory used for
15871  * the host resident queue. This function must be called before creating the
15872  * queue on the HBA.
15873  **/
15874 struct lpfc_queue *
15875 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15876 		      uint32_t entry_size, uint32_t entry_count, int cpu)
15877 {
15878 	struct lpfc_queue *queue;
15879 	struct lpfc_dmabuf *dmabuf;
15880 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15881 	uint16_t x, pgcnt;
15882 
15883 	if (!phba->sli4_hba.pc_sli4_params.supported)
15884 		hw_page_size = page_size;
15885 
15886 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15887 
15888 	/* If needed, Adjust page count to match the max the adapter supports */
15889 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15890 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15891 
15892 	queue = kzalloc_node(struct_size(queue, q_pgs, pgcnt),
15893 			     GFP_KERNEL, cpu_to_node(cpu));
15894 	if (!queue)
15895 		return NULL;
15896 
15897 	INIT_LIST_HEAD(&queue->list);
15898 	INIT_LIST_HEAD(&queue->_poll_list);
15899 	INIT_LIST_HEAD(&queue->wq_list);
15900 	INIT_LIST_HEAD(&queue->wqfull_list);
15901 	INIT_LIST_HEAD(&queue->page_list);
15902 	INIT_LIST_HEAD(&queue->child_list);
15903 	INIT_LIST_HEAD(&queue->cpu_list);
15904 
15905 	/* Set queue parameters now.  If the system cannot provide memory
15906 	 * resources, the free routine needs to know what was allocated.
15907 	 */
15908 	queue->page_count = pgcnt;
15909 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
15910 	queue->entry_size = entry_size;
15911 	queue->entry_count = entry_count;
15912 	queue->page_size = hw_page_size;
15913 	queue->phba = phba;
15914 
15915 	for (x = 0; x < queue->page_count; x++) {
15916 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15917 				      dev_to_node(&phba->pcidev->dev));
15918 		if (!dmabuf)
15919 			goto out_fail;
15920 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15921 						  hw_page_size, &dmabuf->phys,
15922 						  GFP_KERNEL);
15923 		if (!dmabuf->virt) {
15924 			kfree(dmabuf);
15925 			goto out_fail;
15926 		}
15927 		dmabuf->buffer_tag = x;
15928 		list_add_tail(&dmabuf->list, &queue->page_list);
15929 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
15930 		queue->q_pgs[x] = dmabuf->virt;
15931 	}
15932 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15933 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15934 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15935 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15936 
15937 	/* notify_interval will be set during q creation */
15938 
15939 	return queue;
15940 out_fail:
15941 	lpfc_sli4_queue_free(queue);
15942 	return NULL;
15943 }
15944 
15945 /**
15946  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15947  * @phba: HBA structure that indicates port to create a queue on.
15948  * @pci_barset: PCI BAR set flag.
15949  *
15950  * This function shall perform iomap of the specified PCI BAR address to host
15951  * memory address if not already done so and return it. The returned host
15952  * memory address can be NULL.
15953  */
15954 static void __iomem *
15955 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15956 {
15957 	if (!phba->pcidev)
15958 		return NULL;
15959 
15960 	switch (pci_barset) {
15961 	case WQ_PCI_BAR_0_AND_1:
15962 		return phba->pci_bar0_memmap_p;
15963 	case WQ_PCI_BAR_2_AND_3:
15964 		return phba->pci_bar2_memmap_p;
15965 	case WQ_PCI_BAR_4_AND_5:
15966 		return phba->pci_bar4_memmap_p;
15967 	default:
15968 		break;
15969 	}
15970 	return NULL;
15971 }
15972 
15973 static __maybe_unused void __iomem *
15974 lpfc_dpp_wc_map(struct lpfc_hba *phba, uint8_t dpp_barset)
15975 {
15976 
15977 	/* DPP region is supposed to cover 64-bit BAR2 */
15978 	if (dpp_barset != WQ_PCI_BAR_4_AND_5) {
15979 		lpfc_log_msg(phba, KERN_WARNING, LOG_INIT,
15980 			     "3273 dpp_barset x%x != WQ_PCI_BAR_4_AND_5\n",
15981 			     dpp_barset);
15982 		return NULL;
15983 	}
15984 
15985 	if (!phba->sli4_hba.dpp_regs_memmap_wc_p) {
15986 		void __iomem *dpp_map;
15987 
15988 		dpp_map = ioremap_wc(phba->pci_bar2_map,
15989 				     pci_resource_len(phba->pcidev,
15990 						      PCI_64BIT_BAR4));
15991 
15992 		if (dpp_map)
15993 			phba->sli4_hba.dpp_regs_memmap_wc_p = dpp_map;
15994 	}
15995 
15996 	return phba->sli4_hba.dpp_regs_memmap_wc_p;
15997 }
15998 
15999 /**
16000  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
16001  * @phba: HBA structure that EQs are on.
16002  * @startq: The starting EQ index to modify
16003  * @numq: The number of EQs (consecutive indexes) to modify
16004  * @usdelay: amount of delay
16005  *
16006  * This function revises the EQ delay on 1 or more EQs. The EQ delay
16007  * is set either by writing to a register (if supported by the SLI Port)
16008  * or by mailbox command. The mailbox command allows several EQs to be
16009  * updated at once.
16010  *
16011  * The @phba struct is used to send a mailbox command to HBA. The @startq
16012  * is used to get the starting EQ index to change. The @numq value is
16013  * used to specify how many consecutive EQ indexes, starting at EQ index,
16014  * are to be changed. This function is asynchronous and will wait for any
16015  * mailbox commands to finish before returning.
16016  *
16017  * On success this function will return a zero. If unable to allocate
16018  * enough memory this function will return -ENOMEM. If a mailbox command
16019  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
16020  * have had their delay multiplier changed.
16021  **/
16022 void
16023 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
16024 			 uint32_t numq, uint32_t usdelay)
16025 {
16026 	struct lpfc_mbx_modify_eq_delay *eq_delay;
16027 	LPFC_MBOXQ_t *mbox;
16028 	struct lpfc_queue *eq;
16029 	int cnt = 0, rc, length;
16030 	uint32_t shdr_status, shdr_add_status;
16031 	uint32_t dmult;
16032 	int qidx;
16033 	union lpfc_sli4_cfg_shdr *shdr;
16034 
16035 	if (startq >= phba->cfg_irq_chann)
16036 		return;
16037 
16038 	if (usdelay > 0xFFFF) {
16039 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
16040 				"6429 usdelay %d too large. Scaled down to "
16041 				"0xFFFF.\n", usdelay);
16042 		usdelay = 0xFFFF;
16043 	}
16044 
16045 	/* set values by EQ_DELAY register if supported */
16046 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
16047 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
16048 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
16049 			if (!eq)
16050 				continue;
16051 
16052 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
16053 
16054 			if (++cnt >= numq)
16055 				break;
16056 		}
16057 		return;
16058 	}
16059 
16060 	/* Otherwise, set values by mailbox cmd */
16061 
16062 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16063 	if (!mbox) {
16064 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16065 				"6428 Failed allocating mailbox cmd buffer."
16066 				" EQ delay was not set.\n");
16067 		return;
16068 	}
16069 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
16070 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16071 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16072 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
16073 			 length, LPFC_SLI4_MBX_EMBED);
16074 	eq_delay = &mbox->u.mqe.un.eq_delay;
16075 
16076 	/* Calculate delay multiper from maximum interrupt per second */
16077 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
16078 	if (dmult)
16079 		dmult--;
16080 	if (dmult > LPFC_DMULT_MAX)
16081 		dmult = LPFC_DMULT_MAX;
16082 
16083 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
16084 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
16085 		if (!eq)
16086 			continue;
16087 		eq->q_mode = usdelay;
16088 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
16089 		eq_delay->u.request.eq[cnt].phase = 0;
16090 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
16091 
16092 		if (++cnt >= numq)
16093 			break;
16094 	}
16095 	eq_delay->u.request.num_eq = cnt;
16096 
16097 	mbox->vport = phba->pport;
16098 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16099 	mbox->ctx_ndlp = NULL;
16100 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16101 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
16102 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16103 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16104 	if (shdr_status || shdr_add_status || rc) {
16105 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16106 				"2512 MODIFY_EQ_DELAY mailbox failed with "
16107 				"status x%x add_status x%x, mbx status x%x\n",
16108 				shdr_status, shdr_add_status, rc);
16109 	}
16110 	mempool_free(mbox, phba->mbox_mem_pool);
16111 	return;
16112 }
16113 
16114 /**
16115  * lpfc_eq_create - Create an Event Queue on the HBA
16116  * @phba: HBA structure that indicates port to create a queue on.
16117  * @eq: The queue structure to use to create the event queue.
16118  * @imax: The maximum interrupt per second limit.
16119  *
16120  * This function creates an event queue, as detailed in @eq, on a port,
16121  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
16122  *
16123  * The @phba struct is used to send mailbox command to HBA. The @eq struct
16124  * is used to get the entry count and entry size that are necessary to
16125  * determine the number of pages to allocate and use for this queue. This
16126  * function will send the EQ_CREATE mailbox command to the HBA to setup the
16127  * event queue. This function is asynchronous and will wait for the mailbox
16128  * command to finish before continuing.
16129  *
16130  * On success this function will return a zero. If unable to allocate enough
16131  * memory this function will return -ENOMEM. If the queue create mailbox command
16132  * fails this function will return -ENXIO.
16133  **/
16134 int
16135 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
16136 {
16137 	struct lpfc_mbx_eq_create *eq_create;
16138 	LPFC_MBOXQ_t *mbox;
16139 	int rc, length, status = 0;
16140 	struct lpfc_dmabuf *dmabuf;
16141 	uint32_t shdr_status, shdr_add_status;
16142 	union lpfc_sli4_cfg_shdr *shdr;
16143 	uint16_t dmult;
16144 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16145 
16146 	/* sanity check on queue memory */
16147 	if (!eq)
16148 		return -ENODEV;
16149 	if (!phba->sli4_hba.pc_sli4_params.supported)
16150 		hw_page_size = SLI4_PAGE_SIZE;
16151 
16152 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16153 	if (!mbox)
16154 		return -ENOMEM;
16155 	length = (sizeof(struct lpfc_mbx_eq_create) -
16156 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16157 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16158 			 LPFC_MBOX_OPCODE_EQ_CREATE,
16159 			 length, LPFC_SLI4_MBX_EMBED);
16160 	eq_create = &mbox->u.mqe.un.eq_create;
16161 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
16162 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
16163 	       eq->page_count);
16164 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
16165 	       LPFC_EQE_SIZE);
16166 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
16167 
16168 	/* Use version 2 of CREATE_EQ if eqav is set */
16169 	if (phba->sli4_hba.pc_sli4_params.eqav) {
16170 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16171 		       LPFC_Q_CREATE_VERSION_2);
16172 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
16173 		       phba->sli4_hba.pc_sli4_params.eqav);
16174 	}
16175 
16176 	/* don't setup delay multiplier using EQ_CREATE */
16177 	dmult = 0;
16178 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
16179 	       dmult);
16180 	switch (eq->entry_count) {
16181 	default:
16182 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16183 				"0360 Unsupported EQ count. (%d)\n",
16184 				eq->entry_count);
16185 		if (eq->entry_count < 256) {
16186 			status = -EINVAL;
16187 			goto out;
16188 		}
16189 		fallthrough;	/* otherwise default to smallest count */
16190 	case 256:
16191 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16192 		       LPFC_EQ_CNT_256);
16193 		break;
16194 	case 512:
16195 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16196 		       LPFC_EQ_CNT_512);
16197 		break;
16198 	case 1024:
16199 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16200 		       LPFC_EQ_CNT_1024);
16201 		break;
16202 	case 2048:
16203 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16204 		       LPFC_EQ_CNT_2048);
16205 		break;
16206 	case 4096:
16207 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16208 		       LPFC_EQ_CNT_4096);
16209 		break;
16210 	}
16211 	list_for_each_entry(dmabuf, &eq->page_list, list) {
16212 		memset(dmabuf->virt, 0, hw_page_size);
16213 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16214 					putPaddrLow(dmabuf->phys);
16215 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16216 					putPaddrHigh(dmabuf->phys);
16217 	}
16218 	mbox->vport = phba->pport;
16219 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16220 	mbox->ctx_buf = NULL;
16221 	mbox->ctx_ndlp = NULL;
16222 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16223 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16224 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16225 	if (shdr_status || shdr_add_status || rc) {
16226 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16227 				"2500 EQ_CREATE mailbox failed with "
16228 				"status x%x add_status x%x, mbx status x%x\n",
16229 				shdr_status, shdr_add_status, rc);
16230 		status = -ENXIO;
16231 	}
16232 	eq->type = LPFC_EQ;
16233 	eq->subtype = LPFC_NONE;
16234 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
16235 	if (eq->queue_id == 0xFFFF)
16236 		status = -ENXIO;
16237 	eq->host_index = 0;
16238 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
16239 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
16240 out:
16241 	mempool_free(mbox, phba->mbox_mem_pool);
16242 	return status;
16243 }
16244 
16245 /**
16246  * lpfc_sli4_hba_intr_handler_th - SLI4 HBA threaded interrupt handler
16247  * @irq: Interrupt number.
16248  * @dev_id: The device context pointer.
16249  *
16250  * This routine is a mirror of lpfc_sli4_hba_intr_handler, but executed within
16251  * threaded irq context.
16252  *
16253  * Returns
16254  * IRQ_HANDLED - interrupt is handled
16255  * IRQ_NONE - otherwise
16256  **/
16257 irqreturn_t lpfc_sli4_hba_intr_handler_th(int irq, void *dev_id)
16258 {
16259 	struct lpfc_hba *phba;
16260 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
16261 	struct lpfc_queue *fpeq;
16262 	int ecount = 0;
16263 	int hba_eqidx;
16264 	struct lpfc_eq_intr_info *eqi;
16265 
16266 	/* Get the driver's phba structure from the dev_id */
16267 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
16268 	phba = hba_eq_hdl->phba;
16269 	hba_eqidx = hba_eq_hdl->idx;
16270 
16271 	if (unlikely(!phba))
16272 		return IRQ_NONE;
16273 	if (unlikely(!phba->sli4_hba.hdwq))
16274 		return IRQ_NONE;
16275 
16276 	/* Get to the EQ struct associated with this vector */
16277 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
16278 	if (unlikely(!fpeq))
16279 		return IRQ_NONE;
16280 
16281 	eqi = per_cpu_ptr(phba->sli4_hba.eq_info, raw_smp_processor_id());
16282 	eqi->icnt++;
16283 
16284 	fpeq->last_cpu = raw_smp_processor_id();
16285 
16286 	if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
16287 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
16288 	    phba->cfg_auto_imax &&
16289 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
16290 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
16291 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
16292 
16293 	/* process and rearm the EQ */
16294 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
16295 				      LPFC_THREADED_IRQ);
16296 
16297 	if (unlikely(ecount == 0)) {
16298 		fpeq->EQ_no_entry++;
16299 		if (phba->intr_type == MSIX)
16300 			/* MSI-X treated interrupt served as no EQ share INT */
16301 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
16302 					"3358 MSI-X interrupt with no EQE\n");
16303 		else
16304 			/* Non MSI-X treated on interrupt as EQ share INT */
16305 			return IRQ_NONE;
16306 	}
16307 	return IRQ_HANDLED;
16308 }
16309 
16310 /**
16311  * lpfc_cq_create - Create a Completion Queue on the HBA
16312  * @phba: HBA structure that indicates port to create a queue on.
16313  * @cq: The queue structure to use to create the completion queue.
16314  * @eq: The event queue to bind this completion queue to.
16315  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16316  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16317  *
16318  * This function creates a completion queue, as detailed in @wq, on a port,
16319  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
16320  *
16321  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16322  * is used to get the entry count and entry size that are necessary to
16323  * determine the number of pages to allocate and use for this queue. The @eq
16324  * is used to indicate which event queue to bind this completion queue to. This
16325  * function will send the CQ_CREATE mailbox command to the HBA to setup the
16326  * completion queue. This function is asynchronous and will wait for the mailbox
16327  * command to finish before continuing.
16328  *
16329  * On success this function will return a zero. If unable to allocate enough
16330  * memory this function will return -ENOMEM. If the queue create mailbox command
16331  * fails this function will return -ENXIO.
16332  **/
16333 int
16334 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
16335 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
16336 {
16337 	struct lpfc_mbx_cq_create *cq_create;
16338 	struct lpfc_dmabuf *dmabuf;
16339 	LPFC_MBOXQ_t *mbox;
16340 	int rc, length, status = 0;
16341 	uint32_t shdr_status, shdr_add_status;
16342 	union lpfc_sli4_cfg_shdr *shdr;
16343 
16344 	/* sanity check on queue memory */
16345 	if (!cq || !eq)
16346 		return -ENODEV;
16347 
16348 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16349 	if (!mbox)
16350 		return -ENOMEM;
16351 	length = (sizeof(struct lpfc_mbx_cq_create) -
16352 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16353 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16354 			 LPFC_MBOX_OPCODE_CQ_CREATE,
16355 			 length, LPFC_SLI4_MBX_EMBED);
16356 	cq_create = &mbox->u.mqe.un.cq_create;
16357 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
16358 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
16359 		    cq->page_count);
16360 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
16361 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
16362 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16363 	       phba->sli4_hba.pc_sli4_params.cqv);
16364 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
16365 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
16366 		       (cq->page_size / SLI4_PAGE_SIZE));
16367 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
16368 		       eq->queue_id);
16369 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
16370 		       phba->sli4_hba.pc_sli4_params.cqav);
16371 	} else {
16372 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
16373 		       eq->queue_id);
16374 	}
16375 	switch (cq->entry_count) {
16376 	case 2048:
16377 	case 4096:
16378 		if (phba->sli4_hba.pc_sli4_params.cqv ==
16379 		    LPFC_Q_CREATE_VERSION_2) {
16380 			cq_create->u.request.context.lpfc_cq_context_count =
16381 				cq->entry_count;
16382 			bf_set(lpfc_cq_context_count,
16383 			       &cq_create->u.request.context,
16384 			       LPFC_CQ_CNT_WORD7);
16385 			break;
16386 		}
16387 		fallthrough;
16388 	default:
16389 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16390 				"0361 Unsupported CQ count: "
16391 				"entry cnt %d sz %d pg cnt %d\n",
16392 				cq->entry_count, cq->entry_size,
16393 				cq->page_count);
16394 		if (cq->entry_count < 256) {
16395 			status = -EINVAL;
16396 			goto out;
16397 		}
16398 		fallthrough;	/* otherwise default to smallest count */
16399 	case 256:
16400 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16401 		       LPFC_CQ_CNT_256);
16402 		break;
16403 	case 512:
16404 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16405 		       LPFC_CQ_CNT_512);
16406 		break;
16407 	case 1024:
16408 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16409 		       LPFC_CQ_CNT_1024);
16410 		break;
16411 	}
16412 	list_for_each_entry(dmabuf, &cq->page_list, list) {
16413 		memset(dmabuf->virt, 0, cq->page_size);
16414 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16415 					putPaddrLow(dmabuf->phys);
16416 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16417 					putPaddrHigh(dmabuf->phys);
16418 	}
16419 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16420 
16421 	/* The IOCTL status is embedded in the mailbox subheader. */
16422 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16423 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16424 	if (shdr_status || shdr_add_status || rc) {
16425 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16426 				"2501 CQ_CREATE mailbox failed with "
16427 				"status x%x add_status x%x, mbx status x%x\n",
16428 				shdr_status, shdr_add_status, rc);
16429 		status = -ENXIO;
16430 		goto out;
16431 	}
16432 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16433 	if (cq->queue_id == 0xFFFF) {
16434 		status = -ENXIO;
16435 		goto out;
16436 	}
16437 	/* link the cq onto the parent eq child list */
16438 	list_add_tail(&cq->list, &eq->child_list);
16439 	/* Set up completion queue's type and subtype */
16440 	cq->type = type;
16441 	cq->subtype = subtype;
16442 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16443 	cq->assoc_qid = eq->queue_id;
16444 	cq->assoc_qp = eq;
16445 	cq->host_index = 0;
16446 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16447 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
16448 
16449 	if (cq->queue_id > phba->sli4_hba.cq_max)
16450 		phba->sli4_hba.cq_max = cq->queue_id;
16451 out:
16452 	mempool_free(mbox, phba->mbox_mem_pool);
16453 	return status;
16454 }
16455 
16456 /**
16457  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
16458  * @phba: HBA structure that indicates port to create a queue on.
16459  * @cqp: The queue structure array to use to create the completion queues.
16460  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
16461  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16462  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16463  *
16464  * This function creates a set of  completion queue, s to support MRQ
16465  * as detailed in @cqp, on a port,
16466  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
16467  *
16468  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16469  * is used to get the entry count and entry size that are necessary to
16470  * determine the number of pages to allocate and use for this queue. The @eq
16471  * is used to indicate which event queue to bind this completion queue to. This
16472  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
16473  * completion queue. This function is asynchronous and will wait for the mailbox
16474  * command to finish before continuing.
16475  *
16476  * On success this function will return a zero. If unable to allocate enough
16477  * memory this function will return -ENOMEM. If the queue create mailbox command
16478  * fails this function will return -ENXIO.
16479  **/
16480 int
16481 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
16482 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
16483 		   uint32_t subtype)
16484 {
16485 	struct lpfc_queue *cq;
16486 	struct lpfc_queue *eq;
16487 	struct lpfc_mbx_cq_create_set *cq_set;
16488 	struct lpfc_dmabuf *dmabuf;
16489 	LPFC_MBOXQ_t *mbox;
16490 	int rc, length, alloclen, status = 0;
16491 	int cnt, idx, numcq, page_idx = 0;
16492 	uint32_t shdr_status, shdr_add_status;
16493 	union lpfc_sli4_cfg_shdr *shdr;
16494 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16495 
16496 	/* sanity check on queue memory */
16497 	numcq = phba->cfg_nvmet_mrq;
16498 	if (!cqp || !hdwq || !numcq)
16499 		return -ENODEV;
16500 
16501 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16502 	if (!mbox)
16503 		return -ENOMEM;
16504 
16505 	length = sizeof(struct lpfc_mbx_cq_create_set);
16506 	length += ((numcq * cqp[0]->page_count) *
16507 		   sizeof(struct dma_address));
16508 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16509 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
16510 			LPFC_SLI4_MBX_NEMBED);
16511 	if (alloclen < length) {
16512 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16513 				"3098 Allocated DMA memory size (%d) is "
16514 				"less than the requested DMA memory size "
16515 				"(%d)\n", alloclen, length);
16516 		status = -ENOMEM;
16517 		goto out;
16518 	}
16519 	cq_set = mbox->sge_array->addr[0];
16520 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
16521 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
16522 
16523 	for (idx = 0; idx < numcq; idx++) {
16524 		cq = cqp[idx];
16525 		eq = hdwq[idx].hba_eq;
16526 		if (!cq || !eq) {
16527 			status = -ENOMEM;
16528 			goto out;
16529 		}
16530 		if (!phba->sli4_hba.pc_sli4_params.supported)
16531 			hw_page_size = cq->page_size;
16532 
16533 		switch (idx) {
16534 		case 0:
16535 			bf_set(lpfc_mbx_cq_create_set_page_size,
16536 			       &cq_set->u.request,
16537 			       (hw_page_size / SLI4_PAGE_SIZE));
16538 			bf_set(lpfc_mbx_cq_create_set_num_pages,
16539 			       &cq_set->u.request, cq->page_count);
16540 			bf_set(lpfc_mbx_cq_create_set_evt,
16541 			       &cq_set->u.request, 1);
16542 			bf_set(lpfc_mbx_cq_create_set_valid,
16543 			       &cq_set->u.request, 1);
16544 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
16545 			       &cq_set->u.request, 0);
16546 			bf_set(lpfc_mbx_cq_create_set_num_cq,
16547 			       &cq_set->u.request, numcq);
16548 			bf_set(lpfc_mbx_cq_create_set_autovalid,
16549 			       &cq_set->u.request,
16550 			       phba->sli4_hba.pc_sli4_params.cqav);
16551 			switch (cq->entry_count) {
16552 			case 2048:
16553 			case 4096:
16554 				if (phba->sli4_hba.pc_sli4_params.cqv ==
16555 				    LPFC_Q_CREATE_VERSION_2) {
16556 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt_lo,
16557 					       &cq_set->u.request,
16558 					       cq->entry_count);
16559 					bf_set(lpfc_mbx_cq_create_set_cqecnt,
16560 					       &cq_set->u.request,
16561 					       LPFC_CQ_CNT_WORD7);
16562 					break;
16563 				}
16564 				fallthrough;
16565 			default:
16566 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16567 						"3118 Bad CQ count. (%d)\n",
16568 						cq->entry_count);
16569 				if (cq->entry_count < 256) {
16570 					status = -EINVAL;
16571 					goto out;
16572 				}
16573 				fallthrough;	/* otherwise default to smallest */
16574 			case 256:
16575 				bf_set(lpfc_mbx_cq_create_set_cqecnt,
16576 				       &cq_set->u.request, LPFC_CQ_CNT_256);
16577 				break;
16578 			case 512:
16579 				bf_set(lpfc_mbx_cq_create_set_cqecnt,
16580 				       &cq_set->u.request, LPFC_CQ_CNT_512);
16581 				break;
16582 			case 1024:
16583 				bf_set(lpfc_mbx_cq_create_set_cqecnt,
16584 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
16585 				break;
16586 			}
16587 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
16588 			       &cq_set->u.request, eq->queue_id);
16589 			break;
16590 		case 1:
16591 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
16592 			       &cq_set->u.request, eq->queue_id);
16593 			break;
16594 		case 2:
16595 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
16596 			       &cq_set->u.request, eq->queue_id);
16597 			break;
16598 		case 3:
16599 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
16600 			       &cq_set->u.request, eq->queue_id);
16601 			break;
16602 		case 4:
16603 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
16604 			       &cq_set->u.request, eq->queue_id);
16605 			break;
16606 		case 5:
16607 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
16608 			       &cq_set->u.request, eq->queue_id);
16609 			break;
16610 		case 6:
16611 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
16612 			       &cq_set->u.request, eq->queue_id);
16613 			break;
16614 		case 7:
16615 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
16616 			       &cq_set->u.request, eq->queue_id);
16617 			break;
16618 		case 8:
16619 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
16620 			       &cq_set->u.request, eq->queue_id);
16621 			break;
16622 		case 9:
16623 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
16624 			       &cq_set->u.request, eq->queue_id);
16625 			break;
16626 		case 10:
16627 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
16628 			       &cq_set->u.request, eq->queue_id);
16629 			break;
16630 		case 11:
16631 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
16632 			       &cq_set->u.request, eq->queue_id);
16633 			break;
16634 		case 12:
16635 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
16636 			       &cq_set->u.request, eq->queue_id);
16637 			break;
16638 		case 13:
16639 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
16640 			       &cq_set->u.request, eq->queue_id);
16641 			break;
16642 		case 14:
16643 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
16644 			       &cq_set->u.request, eq->queue_id);
16645 			break;
16646 		case 15:
16647 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
16648 			       &cq_set->u.request, eq->queue_id);
16649 			break;
16650 		}
16651 
16652 		/* link the cq onto the parent eq child list */
16653 		list_add_tail(&cq->list, &eq->child_list);
16654 		/* Set up completion queue's type and subtype */
16655 		cq->type = type;
16656 		cq->subtype = subtype;
16657 		cq->assoc_qid = eq->queue_id;
16658 		cq->assoc_qp = eq;
16659 		cq->host_index = 0;
16660 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16661 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
16662 					 cq->entry_count);
16663 		cq->chann = idx;
16664 
16665 		rc = 0;
16666 		list_for_each_entry(dmabuf, &cq->page_list, list) {
16667 			memset(dmabuf->virt, 0, hw_page_size);
16668 			cnt = page_idx + dmabuf->buffer_tag;
16669 			cq_set->u.request.page[cnt].addr_lo =
16670 					putPaddrLow(dmabuf->phys);
16671 			cq_set->u.request.page[cnt].addr_hi =
16672 					putPaddrHigh(dmabuf->phys);
16673 			rc++;
16674 		}
16675 		page_idx += rc;
16676 	}
16677 
16678 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16679 
16680 	/* The IOCTL status is embedded in the mailbox subheader. */
16681 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16682 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16683 	if (shdr_status || shdr_add_status || rc) {
16684 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16685 				"3119 CQ_CREATE_SET mailbox failed with "
16686 				"status x%x add_status x%x, mbx status x%x\n",
16687 				shdr_status, shdr_add_status, rc);
16688 		status = -ENXIO;
16689 		goto out;
16690 	}
16691 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
16692 	if (rc == 0xFFFF) {
16693 		status = -ENXIO;
16694 		goto out;
16695 	}
16696 
16697 	for (idx = 0; idx < numcq; idx++) {
16698 		cq = cqp[idx];
16699 		cq->queue_id = rc + idx;
16700 		if (cq->queue_id > phba->sli4_hba.cq_max)
16701 			phba->sli4_hba.cq_max = cq->queue_id;
16702 	}
16703 
16704 out:
16705 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16706 	return status;
16707 }
16708 
16709 /**
16710  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
16711  * @phba: HBA structure that indicates port to create a queue on.
16712  * @mq: The queue structure to use to create the mailbox queue.
16713  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
16714  * @cq: The completion queue to associate with this cq.
16715  *
16716  * This function provides failback (fb) functionality when the
16717  * mq_create_ext fails on older FW generations.  It's purpose is identical
16718  * to mq_create_ext otherwise.
16719  *
16720  * This routine cannot fail as all attributes were previously accessed and
16721  * initialized in mq_create_ext.
16722  **/
16723 static void
16724 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
16725 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
16726 {
16727 	struct lpfc_mbx_mq_create *mq_create;
16728 	struct lpfc_dmabuf *dmabuf;
16729 	int length;
16730 
16731 	length = (sizeof(struct lpfc_mbx_mq_create) -
16732 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16733 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16734 			 LPFC_MBOX_OPCODE_MQ_CREATE,
16735 			 length, LPFC_SLI4_MBX_EMBED);
16736 	mq_create = &mbox->u.mqe.un.mq_create;
16737 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
16738 	       mq->page_count);
16739 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
16740 	       cq->queue_id);
16741 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
16742 	switch (mq->entry_count) {
16743 	case 16:
16744 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16745 		       LPFC_MQ_RING_SIZE_16);
16746 		break;
16747 	case 32:
16748 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16749 		       LPFC_MQ_RING_SIZE_32);
16750 		break;
16751 	case 64:
16752 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16753 		       LPFC_MQ_RING_SIZE_64);
16754 		break;
16755 	case 128:
16756 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16757 		       LPFC_MQ_RING_SIZE_128);
16758 		break;
16759 	}
16760 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16761 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16762 			putPaddrLow(dmabuf->phys);
16763 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16764 			putPaddrHigh(dmabuf->phys);
16765 	}
16766 }
16767 
16768 /**
16769  * lpfc_mq_create - Create a mailbox Queue on the HBA
16770  * @phba: HBA structure that indicates port to create a queue on.
16771  * @mq: The queue structure to use to create the mailbox queue.
16772  * @cq: The completion queue to associate with this cq.
16773  * @subtype: The queue's subtype.
16774  *
16775  * This function creates a mailbox queue, as detailed in @mq, on a port,
16776  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
16777  *
16778  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16779  * is used to get the entry count and entry size that are necessary to
16780  * determine the number of pages to allocate and use for this queue. This
16781  * function will send the MQ_CREATE mailbox command to the HBA to setup the
16782  * mailbox queue. This function is asynchronous and will wait for the mailbox
16783  * command to finish before continuing.
16784  *
16785  * On success this function will return a zero. If unable to allocate enough
16786  * memory this function will return -ENOMEM. If the queue create mailbox command
16787  * fails this function will return -ENXIO.
16788  **/
16789 int32_t
16790 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
16791 	       struct lpfc_queue *cq, uint32_t subtype)
16792 {
16793 	struct lpfc_mbx_mq_create *mq_create;
16794 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
16795 	struct lpfc_dmabuf *dmabuf;
16796 	LPFC_MBOXQ_t *mbox;
16797 	int rc, length, status = 0;
16798 	uint32_t shdr_status, shdr_add_status;
16799 	union lpfc_sli4_cfg_shdr *shdr;
16800 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16801 
16802 	/* sanity check on queue memory */
16803 	if (!mq || !cq)
16804 		return -ENODEV;
16805 	if (!phba->sli4_hba.pc_sli4_params.supported)
16806 		hw_page_size = SLI4_PAGE_SIZE;
16807 
16808 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16809 	if (!mbox)
16810 		return -ENOMEM;
16811 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
16812 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16813 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16814 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
16815 			 length, LPFC_SLI4_MBX_EMBED);
16816 
16817 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
16818 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
16819 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
16820 	       &mq_create_ext->u.request, mq->page_count);
16821 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
16822 	       &mq_create_ext->u.request, 1);
16823 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
16824 	       &mq_create_ext->u.request, 1);
16825 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
16826 	       &mq_create_ext->u.request, 1);
16827 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
16828 	       &mq_create_ext->u.request, 1);
16829 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
16830 	       &mq_create_ext->u.request, 1);
16831 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
16832 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16833 	       phba->sli4_hba.pc_sli4_params.mqv);
16834 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
16835 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
16836 		       cq->queue_id);
16837 	else
16838 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
16839 		       cq->queue_id);
16840 	switch (mq->entry_count) {
16841 	default:
16842 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16843 				"0362 Unsupported MQ count. (%d)\n",
16844 				mq->entry_count);
16845 		if (mq->entry_count < 16) {
16846 			status = -EINVAL;
16847 			goto out;
16848 		}
16849 		fallthrough;	/* otherwise default to smallest count */
16850 	case 16:
16851 		bf_set(lpfc_mq_context_ring_size,
16852 		       &mq_create_ext->u.request.context,
16853 		       LPFC_MQ_RING_SIZE_16);
16854 		break;
16855 	case 32:
16856 		bf_set(lpfc_mq_context_ring_size,
16857 		       &mq_create_ext->u.request.context,
16858 		       LPFC_MQ_RING_SIZE_32);
16859 		break;
16860 	case 64:
16861 		bf_set(lpfc_mq_context_ring_size,
16862 		       &mq_create_ext->u.request.context,
16863 		       LPFC_MQ_RING_SIZE_64);
16864 		break;
16865 	case 128:
16866 		bf_set(lpfc_mq_context_ring_size,
16867 		       &mq_create_ext->u.request.context,
16868 		       LPFC_MQ_RING_SIZE_128);
16869 		break;
16870 	}
16871 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16872 		memset(dmabuf->virt, 0, hw_page_size);
16873 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16874 					putPaddrLow(dmabuf->phys);
16875 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16876 					putPaddrHigh(dmabuf->phys);
16877 	}
16878 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16879 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16880 			      &mq_create_ext->u.response);
16881 	if (rc != MBX_SUCCESS) {
16882 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16883 				"2795 MQ_CREATE_EXT failed with "
16884 				"status x%x. Failback to MQ_CREATE.\n",
16885 				rc);
16886 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16887 		mq_create = &mbox->u.mqe.un.mq_create;
16888 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16889 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16890 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16891 				      &mq_create->u.response);
16892 	}
16893 
16894 	/* The IOCTL status is embedded in the mailbox subheader. */
16895 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16896 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16897 	if (shdr_status || shdr_add_status || rc) {
16898 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16899 				"2502 MQ_CREATE mailbox failed with "
16900 				"status x%x add_status x%x, mbx status x%x\n",
16901 				shdr_status, shdr_add_status, rc);
16902 		status = -ENXIO;
16903 		goto out;
16904 	}
16905 	if (mq->queue_id == 0xFFFF) {
16906 		status = -ENXIO;
16907 		goto out;
16908 	}
16909 	mq->type = LPFC_MQ;
16910 	mq->assoc_qid = cq->queue_id;
16911 	mq->subtype = subtype;
16912 	mq->host_index = 0;
16913 	mq->hba_index = 0;
16914 
16915 	/* link the mq onto the parent cq child list */
16916 	list_add_tail(&mq->list, &cq->child_list);
16917 out:
16918 	mempool_free(mbox, phba->mbox_mem_pool);
16919 	return status;
16920 }
16921 
16922 /**
16923  * lpfc_wq_create - Create a Work Queue on the HBA
16924  * @phba: HBA structure that indicates port to create a queue on.
16925  * @wq: The queue structure to use to create the work queue.
16926  * @cq: The completion queue to bind this work queue to.
16927  * @subtype: The subtype of the work queue indicating its functionality.
16928  *
16929  * This function creates a work queue, as detailed in @wq, on a port, described
16930  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16931  *
16932  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16933  * is used to get the entry count and entry size that are necessary to
16934  * determine the number of pages to allocate and use for this queue. The @cq
16935  * is used to indicate which completion queue to bind this work queue to. This
16936  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16937  * work queue. This function is asynchronous and will wait for the mailbox
16938  * command to finish before continuing.
16939  *
16940  * On success this function will return a zero. If unable to allocate enough
16941  * memory this function will return -ENOMEM. If the queue create mailbox command
16942  * fails this function will return -ENXIO.
16943  **/
16944 int
16945 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16946 	       struct lpfc_queue *cq, uint32_t subtype)
16947 {
16948 	struct lpfc_mbx_wq_create *wq_create;
16949 	struct lpfc_dmabuf *dmabuf;
16950 	LPFC_MBOXQ_t *mbox;
16951 	int rc, length, status = 0;
16952 	uint32_t shdr_status, shdr_add_status;
16953 	union lpfc_sli4_cfg_shdr *shdr;
16954 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16955 	struct dma_address *page;
16956 	void __iomem *bar_memmap_p;
16957 	uint32_t db_offset;
16958 	uint16_t pci_barset;
16959 	uint8_t dpp_barset;
16960 	uint32_t dpp_offset;
16961 	uint8_t wq_create_version;
16962 
16963 	/* sanity check on queue memory */
16964 	if (!wq || !cq)
16965 		return -ENODEV;
16966 	if (!phba->sli4_hba.pc_sli4_params.supported)
16967 		hw_page_size = wq->page_size;
16968 
16969 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16970 	if (!mbox)
16971 		return -ENOMEM;
16972 	length = (sizeof(struct lpfc_mbx_wq_create) -
16973 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16974 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16975 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16976 			 length, LPFC_SLI4_MBX_EMBED);
16977 	wq_create = &mbox->u.mqe.un.wq_create;
16978 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16979 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16980 		    wq->page_count);
16981 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16982 		    cq->queue_id);
16983 
16984 	/* wqv is the earliest version supported, NOT the latest */
16985 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16986 	       phba->sli4_hba.pc_sli4_params.wqv);
16987 
16988 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16989 	    (wq->page_size > SLI4_PAGE_SIZE))
16990 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
16991 	else
16992 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
16993 
16994 	switch (wq_create_version) {
16995 	case LPFC_Q_CREATE_VERSION_1:
16996 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
16997 		       wq->entry_count);
16998 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16999 		       LPFC_Q_CREATE_VERSION_1);
17000 
17001 		switch (wq->entry_size) {
17002 		default:
17003 		case 64:
17004 			bf_set(lpfc_mbx_wq_create_wqe_size,
17005 			       &wq_create->u.request_1,
17006 			       LPFC_WQ_WQE_SIZE_64);
17007 			break;
17008 		case 128:
17009 			bf_set(lpfc_mbx_wq_create_wqe_size,
17010 			       &wq_create->u.request_1,
17011 			       LPFC_WQ_WQE_SIZE_128);
17012 			break;
17013 		}
17014 		/* Request DPP by default */
17015 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
17016 		bf_set(lpfc_mbx_wq_create_page_size,
17017 		       &wq_create->u.request_1,
17018 		       (wq->page_size / SLI4_PAGE_SIZE));
17019 		page = wq_create->u.request_1.page;
17020 		break;
17021 	default:
17022 		page = wq_create->u.request.page;
17023 		break;
17024 	}
17025 
17026 	list_for_each_entry(dmabuf, &wq->page_list, list) {
17027 		memset(dmabuf->virt, 0, hw_page_size);
17028 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
17029 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
17030 	}
17031 
17032 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17033 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
17034 
17035 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17036 	/* The IOCTL status is embedded in the mailbox subheader. */
17037 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17038 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17039 	if (shdr_status || shdr_add_status || rc) {
17040 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17041 				"2503 WQ_CREATE mailbox failed with "
17042 				"status x%x add_status x%x, mbx status x%x\n",
17043 				shdr_status, shdr_add_status, rc);
17044 		status = -ENXIO;
17045 		goto out;
17046 	}
17047 
17048 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
17049 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
17050 					&wq_create->u.response);
17051 	else
17052 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
17053 					&wq_create->u.response_1);
17054 
17055 	if (wq->queue_id == 0xFFFF) {
17056 		status = -ENXIO;
17057 		goto out;
17058 	}
17059 
17060 	wq->db_format = LPFC_DB_LIST_FORMAT;
17061 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
17062 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
17063 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
17064 					       &wq_create->u.response);
17065 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
17066 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
17067 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17068 						"3265 WQ[%d] doorbell format "
17069 						"not supported: x%x\n",
17070 						wq->queue_id, wq->db_format);
17071 				status = -EINVAL;
17072 				goto out;
17073 			}
17074 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
17075 					    &wq_create->u.response);
17076 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17077 								   pci_barset);
17078 			if (!bar_memmap_p) {
17079 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17080 						"3263 WQ[%d] failed to memmap "
17081 						"pci barset:x%x\n",
17082 						wq->queue_id, pci_barset);
17083 				status = -ENOMEM;
17084 				goto out;
17085 			}
17086 			db_offset = wq_create->u.response.doorbell_offset;
17087 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
17088 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
17089 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17090 						"3252 WQ[%d] doorbell offset "
17091 						"not supported: x%x\n",
17092 						wq->queue_id, db_offset);
17093 				status = -EINVAL;
17094 				goto out;
17095 			}
17096 			wq->db_regaddr = bar_memmap_p + db_offset;
17097 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17098 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
17099 					"format:x%x\n", wq->queue_id,
17100 					pci_barset, db_offset, wq->db_format);
17101 		} else
17102 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17103 	} else {
17104 		/* Check if DPP was honored by the firmware */
17105 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
17106 				    &wq_create->u.response_1);
17107 		if (wq->dpp_enable) {
17108 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
17109 					    &wq_create->u.response_1);
17110 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17111 								   pci_barset);
17112 			if (!bar_memmap_p) {
17113 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17114 						"3267 WQ[%d] failed to memmap "
17115 						"pci barset:x%x\n",
17116 						wq->queue_id, pci_barset);
17117 				status = -ENOMEM;
17118 				goto out;
17119 			}
17120 			db_offset = wq_create->u.response_1.doorbell_offset;
17121 			wq->db_regaddr = bar_memmap_p + db_offset;
17122 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
17123 					    &wq_create->u.response_1);
17124 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
17125 					    &wq_create->u.response_1);
17126 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17127 								   dpp_barset);
17128 			if (!bar_memmap_p) {
17129 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17130 						"3268 WQ[%d] failed to memmap "
17131 						"pci barset:x%x\n",
17132 						wq->queue_id, dpp_barset);
17133 				status = -ENOMEM;
17134 				goto out;
17135 			}
17136 			dpp_offset = wq_create->u.response_1.dpp_offset;
17137 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
17138 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17139 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
17140 					"dpp_id:x%x dpp_barset:x%x "
17141 					"dpp_offset:x%x\n",
17142 					wq->queue_id, pci_barset, db_offset,
17143 					wq->dpp_id, dpp_barset, dpp_offset);
17144 
17145 #ifdef CONFIG_X86
17146 			/* Enable combined writes for DPP aperture */
17147 			bar_memmap_p = lpfc_dpp_wc_map(phba, dpp_barset);
17148 			if (!bar_memmap_p) {
17149 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17150 					"3272 Cannot setup Combined "
17151 					"Write on WQ[%d] - disable DPP\n",
17152 					wq->queue_id);
17153 				phba->cfg_enable_dpp = 0;
17154 			} else {
17155 				wq->dpp_regaddr = bar_memmap_p + dpp_offset;
17156 			}
17157 #else
17158 			phba->cfg_enable_dpp = 0;
17159 #endif
17160 		} else
17161 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17162 	}
17163 	wq->pring = kzalloc_obj(struct lpfc_sli_ring);
17164 	if (wq->pring == NULL) {
17165 		status = -ENOMEM;
17166 		goto out;
17167 	}
17168 	wq->type = LPFC_WQ;
17169 	wq->assoc_qid = cq->queue_id;
17170 	wq->subtype = subtype;
17171 	wq->host_index = 0;
17172 	wq->hba_index = 0;
17173 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
17174 
17175 	/* link the wq onto the parent cq child list */
17176 	list_add_tail(&wq->list, &cq->child_list);
17177 out:
17178 	mempool_free(mbox, phba->mbox_mem_pool);
17179 	return status;
17180 }
17181 
17182 /**
17183  * lpfc_rq_create - Create a Receive Queue on the HBA
17184  * @phba: HBA structure that indicates port to create a queue on.
17185  * @hrq: The queue structure to use to create the header receive queue.
17186  * @drq: The queue structure to use to create the data receive queue.
17187  * @cq: The completion queue to bind this work queue to.
17188  * @subtype: The subtype of the work queue indicating its functionality.
17189  *
17190  * This function creates a receive buffer queue pair , as detailed in @hrq and
17191  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17192  * to the HBA.
17193  *
17194  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17195  * struct is used to get the entry count that is necessary to determine the
17196  * number of pages to use for this queue. The @cq is used to indicate which
17197  * completion queue to bind received buffers that are posted to these queues to.
17198  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17199  * receive queue pair. This function is asynchronous and will wait for the
17200  * mailbox command to finish before continuing.
17201  *
17202  * On success this function will return a zero. If unable to allocate enough
17203  * memory this function will return -ENOMEM. If the queue create mailbox command
17204  * fails this function will return -ENXIO.
17205  **/
17206 int
17207 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17208 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
17209 {
17210 	struct lpfc_mbx_rq_create *rq_create;
17211 	struct lpfc_dmabuf *dmabuf;
17212 	LPFC_MBOXQ_t *mbox;
17213 	int rc, length, status = 0;
17214 	uint32_t shdr_status, shdr_add_status;
17215 	union lpfc_sli4_cfg_shdr *shdr;
17216 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17217 	void __iomem *bar_memmap_p;
17218 	uint32_t db_offset;
17219 	uint16_t pci_barset;
17220 
17221 	/* sanity check on queue memory */
17222 	if (!hrq || !drq || !cq)
17223 		return -ENODEV;
17224 	if (!phba->sli4_hba.pc_sli4_params.supported)
17225 		hw_page_size = SLI4_PAGE_SIZE;
17226 
17227 	if (hrq->entry_count != drq->entry_count)
17228 		return -EINVAL;
17229 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17230 	if (!mbox)
17231 		return -ENOMEM;
17232 	length = (sizeof(struct lpfc_mbx_rq_create) -
17233 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17234 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17235 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17236 			 length, LPFC_SLI4_MBX_EMBED);
17237 	rq_create = &mbox->u.mqe.un.rq_create;
17238 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17239 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17240 	       phba->sli4_hba.pc_sli4_params.rqv);
17241 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17242 		bf_set(lpfc_rq_context_rqe_count_1,
17243 		       &rq_create->u.request.context,
17244 		       hrq->entry_count);
17245 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
17246 		bf_set(lpfc_rq_context_rqe_size,
17247 		       &rq_create->u.request.context,
17248 		       LPFC_RQE_SIZE_8);
17249 		bf_set(lpfc_rq_context_page_size,
17250 		       &rq_create->u.request.context,
17251 		       LPFC_RQ_PAGE_SIZE_4096);
17252 	} else {
17253 		switch (hrq->entry_count) {
17254 		default:
17255 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17256 					"2535 Unsupported RQ count. (%d)\n",
17257 					hrq->entry_count);
17258 			if (hrq->entry_count < 512) {
17259 				status = -EINVAL;
17260 				goto out;
17261 			}
17262 			fallthrough;	/* otherwise default to smallest count */
17263 		case 512:
17264 			bf_set(lpfc_rq_context_rqe_count,
17265 			       &rq_create->u.request.context,
17266 			       LPFC_RQ_RING_SIZE_512);
17267 			break;
17268 		case 1024:
17269 			bf_set(lpfc_rq_context_rqe_count,
17270 			       &rq_create->u.request.context,
17271 			       LPFC_RQ_RING_SIZE_1024);
17272 			break;
17273 		case 2048:
17274 			bf_set(lpfc_rq_context_rqe_count,
17275 			       &rq_create->u.request.context,
17276 			       LPFC_RQ_RING_SIZE_2048);
17277 			break;
17278 		case 4096:
17279 			bf_set(lpfc_rq_context_rqe_count,
17280 			       &rq_create->u.request.context,
17281 			       LPFC_RQ_RING_SIZE_4096);
17282 			break;
17283 		}
17284 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
17285 		       LPFC_HDR_BUF_SIZE);
17286 	}
17287 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17288 	       cq->queue_id);
17289 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17290 	       hrq->page_count);
17291 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
17292 		memset(dmabuf->virt, 0, hw_page_size);
17293 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17294 					putPaddrLow(dmabuf->phys);
17295 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17296 					putPaddrHigh(dmabuf->phys);
17297 	}
17298 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17299 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17300 
17301 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17302 	/* The IOCTL status is embedded in the mailbox subheader. */
17303 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17304 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17305 	if (shdr_status || shdr_add_status || rc) {
17306 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17307 				"2504 RQ_CREATE mailbox failed with "
17308 				"status x%x add_status x%x, mbx status x%x\n",
17309 				shdr_status, shdr_add_status, rc);
17310 		status = -ENXIO;
17311 		goto out;
17312 	}
17313 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17314 	if (hrq->queue_id == 0xFFFF) {
17315 		status = -ENXIO;
17316 		goto out;
17317 	}
17318 
17319 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
17320 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
17321 					&rq_create->u.response);
17322 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
17323 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
17324 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17325 					"3262 RQ [%d] doorbell format not "
17326 					"supported: x%x\n", hrq->queue_id,
17327 					hrq->db_format);
17328 			status = -EINVAL;
17329 			goto out;
17330 		}
17331 
17332 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
17333 				    &rq_create->u.response);
17334 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
17335 		if (!bar_memmap_p) {
17336 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17337 					"3269 RQ[%d] failed to memmap pci "
17338 					"barset:x%x\n", hrq->queue_id,
17339 					pci_barset);
17340 			status = -ENOMEM;
17341 			goto out;
17342 		}
17343 
17344 		db_offset = rq_create->u.response.doorbell_offset;
17345 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
17346 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
17347 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17348 					"3270 RQ[%d] doorbell offset not "
17349 					"supported: x%x\n", hrq->queue_id,
17350 					db_offset);
17351 			status = -EINVAL;
17352 			goto out;
17353 		}
17354 		hrq->db_regaddr = bar_memmap_p + db_offset;
17355 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17356 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
17357 				"format:x%x\n", hrq->queue_id, pci_barset,
17358 				db_offset, hrq->db_format);
17359 	} else {
17360 		hrq->db_format = LPFC_DB_RING_FORMAT;
17361 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17362 	}
17363 	hrq->type = LPFC_HRQ;
17364 	hrq->assoc_qid = cq->queue_id;
17365 	hrq->subtype = subtype;
17366 	hrq->host_index = 0;
17367 	hrq->hba_index = 0;
17368 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17369 
17370 	/* now create the data queue */
17371 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17372 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17373 			 length, LPFC_SLI4_MBX_EMBED);
17374 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17375 	       phba->sli4_hba.pc_sli4_params.rqv);
17376 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17377 		bf_set(lpfc_rq_context_rqe_count_1,
17378 		       &rq_create->u.request.context, hrq->entry_count);
17379 		if (subtype == LPFC_NVMET)
17380 			rq_create->u.request.context.buffer_size =
17381 				LPFC_NVMET_DATA_BUF_SIZE;
17382 		else
17383 			rq_create->u.request.context.buffer_size =
17384 				LPFC_DATA_BUF_SIZE;
17385 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
17386 		       LPFC_RQE_SIZE_8);
17387 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
17388 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
17389 	} else {
17390 		switch (drq->entry_count) {
17391 		default:
17392 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17393 					"2536 Unsupported RQ count. (%d)\n",
17394 					drq->entry_count);
17395 			if (drq->entry_count < 512) {
17396 				status = -EINVAL;
17397 				goto out;
17398 			}
17399 			fallthrough;	/* otherwise default to smallest count */
17400 		case 512:
17401 			bf_set(lpfc_rq_context_rqe_count,
17402 			       &rq_create->u.request.context,
17403 			       LPFC_RQ_RING_SIZE_512);
17404 			break;
17405 		case 1024:
17406 			bf_set(lpfc_rq_context_rqe_count,
17407 			       &rq_create->u.request.context,
17408 			       LPFC_RQ_RING_SIZE_1024);
17409 			break;
17410 		case 2048:
17411 			bf_set(lpfc_rq_context_rqe_count,
17412 			       &rq_create->u.request.context,
17413 			       LPFC_RQ_RING_SIZE_2048);
17414 			break;
17415 		case 4096:
17416 			bf_set(lpfc_rq_context_rqe_count,
17417 			       &rq_create->u.request.context,
17418 			       LPFC_RQ_RING_SIZE_4096);
17419 			break;
17420 		}
17421 		if (subtype == LPFC_NVMET)
17422 			bf_set(lpfc_rq_context_buf_size,
17423 			       &rq_create->u.request.context,
17424 			       LPFC_NVMET_DATA_BUF_SIZE);
17425 		else
17426 			bf_set(lpfc_rq_context_buf_size,
17427 			       &rq_create->u.request.context,
17428 			       LPFC_DATA_BUF_SIZE);
17429 	}
17430 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17431 	       cq->queue_id);
17432 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17433 	       drq->page_count);
17434 	list_for_each_entry(dmabuf, &drq->page_list, list) {
17435 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17436 					putPaddrLow(dmabuf->phys);
17437 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17438 					putPaddrHigh(dmabuf->phys);
17439 	}
17440 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17441 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17442 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17443 	/* The IOCTL status is embedded in the mailbox subheader. */
17444 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17445 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17446 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17447 	if (shdr_status || shdr_add_status || rc) {
17448 		status = -ENXIO;
17449 		goto out;
17450 	}
17451 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17452 	if (drq->queue_id == 0xFFFF) {
17453 		status = -ENXIO;
17454 		goto out;
17455 	}
17456 	drq->type = LPFC_DRQ;
17457 	drq->assoc_qid = cq->queue_id;
17458 	drq->subtype = subtype;
17459 	drq->host_index = 0;
17460 	drq->hba_index = 0;
17461 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17462 
17463 	/* link the header and data RQs onto the parent cq child list */
17464 	list_add_tail(&hrq->list, &cq->child_list);
17465 	list_add_tail(&drq->list, &cq->child_list);
17466 
17467 out:
17468 	mempool_free(mbox, phba->mbox_mem_pool);
17469 	return status;
17470 }
17471 
17472 /**
17473  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
17474  * @phba: HBA structure that indicates port to create a queue on.
17475  * @hrqp: The queue structure array to use to create the header receive queues.
17476  * @drqp: The queue structure array to use to create the data receive queues.
17477  * @cqp: The completion queue array to bind these receive queues to.
17478  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
17479  *
17480  * This function creates a receive buffer queue pair , as detailed in @hrq and
17481  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17482  * to the HBA.
17483  *
17484  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17485  * struct is used to get the entry count that is necessary to determine the
17486  * number of pages to use for this queue. The @cq is used to indicate which
17487  * completion queue to bind received buffers that are posted to these queues to.
17488  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17489  * receive queue pair. This function is asynchronous and will wait for the
17490  * mailbox command to finish before continuing.
17491  *
17492  * On success this function will return a zero. If unable to allocate enough
17493  * memory this function will return -ENOMEM. If the queue create mailbox command
17494  * fails this function will return -ENXIO.
17495  **/
17496 int
17497 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
17498 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
17499 		uint32_t subtype)
17500 {
17501 	struct lpfc_queue *hrq, *drq, *cq;
17502 	struct lpfc_mbx_rq_create_v2 *rq_create;
17503 	struct lpfc_dmabuf *dmabuf;
17504 	LPFC_MBOXQ_t *mbox;
17505 	int rc, length, alloclen, status = 0;
17506 	int cnt, idx, numrq, page_idx = 0;
17507 	uint32_t shdr_status, shdr_add_status;
17508 	union lpfc_sli4_cfg_shdr *shdr;
17509 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17510 
17511 	numrq = phba->cfg_nvmet_mrq;
17512 	/* sanity check on array memory */
17513 	if (!hrqp || !drqp || !cqp || !numrq)
17514 		return -ENODEV;
17515 	if (!phba->sli4_hba.pc_sli4_params.supported)
17516 		hw_page_size = SLI4_PAGE_SIZE;
17517 
17518 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17519 	if (!mbox)
17520 		return -ENOMEM;
17521 
17522 	length = sizeof(struct lpfc_mbx_rq_create_v2);
17523 	length += ((2 * numrq * hrqp[0]->page_count) *
17524 		   sizeof(struct dma_address));
17525 
17526 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17527 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
17528 				    LPFC_SLI4_MBX_NEMBED);
17529 	if (alloclen < length) {
17530 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17531 				"3099 Allocated DMA memory size (%d) is "
17532 				"less than the requested DMA memory size "
17533 				"(%d)\n", alloclen, length);
17534 		status = -ENOMEM;
17535 		goto out;
17536 	}
17537 
17538 
17539 
17540 	rq_create = mbox->sge_array->addr[0];
17541 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
17542 
17543 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
17544 	cnt = 0;
17545 
17546 	for (idx = 0; idx < numrq; idx++) {
17547 		hrq = hrqp[idx];
17548 		drq = drqp[idx];
17549 		cq  = cqp[idx];
17550 
17551 		/* sanity check on queue memory */
17552 		if (!hrq || !drq || !cq) {
17553 			status = -ENODEV;
17554 			goto out;
17555 		}
17556 
17557 		if (hrq->entry_count != drq->entry_count) {
17558 			status = -EINVAL;
17559 			goto out;
17560 		}
17561 
17562 		if (idx == 0) {
17563 			bf_set(lpfc_mbx_rq_create_num_pages,
17564 			       &rq_create->u.request,
17565 			       hrq->page_count);
17566 			bf_set(lpfc_mbx_rq_create_rq_cnt,
17567 			       &rq_create->u.request, (numrq * 2));
17568 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
17569 			       1);
17570 			bf_set(lpfc_rq_context_base_cq,
17571 			       &rq_create->u.request.context,
17572 			       cq->queue_id);
17573 			bf_set(lpfc_rq_context_data_size,
17574 			       &rq_create->u.request.context,
17575 			       LPFC_NVMET_DATA_BUF_SIZE);
17576 			bf_set(lpfc_rq_context_hdr_size,
17577 			       &rq_create->u.request.context,
17578 			       LPFC_HDR_BUF_SIZE);
17579 			bf_set(lpfc_rq_context_rqe_count_1,
17580 			       &rq_create->u.request.context,
17581 			       hrq->entry_count);
17582 			bf_set(lpfc_rq_context_rqe_size,
17583 			       &rq_create->u.request.context,
17584 			       LPFC_RQE_SIZE_8);
17585 			bf_set(lpfc_rq_context_page_size,
17586 			       &rq_create->u.request.context,
17587 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
17588 		}
17589 		rc = 0;
17590 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
17591 			memset(dmabuf->virt, 0, hw_page_size);
17592 			cnt = page_idx + dmabuf->buffer_tag;
17593 			rq_create->u.request.page[cnt].addr_lo =
17594 					putPaddrLow(dmabuf->phys);
17595 			rq_create->u.request.page[cnt].addr_hi =
17596 					putPaddrHigh(dmabuf->phys);
17597 			rc++;
17598 		}
17599 		page_idx += rc;
17600 
17601 		rc = 0;
17602 		list_for_each_entry(dmabuf, &drq->page_list, list) {
17603 			memset(dmabuf->virt, 0, hw_page_size);
17604 			cnt = page_idx + dmabuf->buffer_tag;
17605 			rq_create->u.request.page[cnt].addr_lo =
17606 					putPaddrLow(dmabuf->phys);
17607 			rq_create->u.request.page[cnt].addr_hi =
17608 					putPaddrHigh(dmabuf->phys);
17609 			rc++;
17610 		}
17611 		page_idx += rc;
17612 
17613 		hrq->db_format = LPFC_DB_RING_FORMAT;
17614 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17615 		hrq->type = LPFC_HRQ;
17616 		hrq->assoc_qid = cq->queue_id;
17617 		hrq->subtype = subtype;
17618 		hrq->host_index = 0;
17619 		hrq->hba_index = 0;
17620 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17621 
17622 		drq->db_format = LPFC_DB_RING_FORMAT;
17623 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17624 		drq->type = LPFC_DRQ;
17625 		drq->assoc_qid = cq->queue_id;
17626 		drq->subtype = subtype;
17627 		drq->host_index = 0;
17628 		drq->hba_index = 0;
17629 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17630 
17631 		list_add_tail(&hrq->list, &cq->child_list);
17632 		list_add_tail(&drq->list, &cq->child_list);
17633 	}
17634 
17635 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17636 	/* The IOCTL status is embedded in the mailbox subheader. */
17637 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17638 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17639 	if (shdr_status || shdr_add_status || rc) {
17640 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17641 				"3120 RQ_CREATE mailbox failed with "
17642 				"status x%x add_status x%x, mbx status x%x\n",
17643 				shdr_status, shdr_add_status, rc);
17644 		status = -ENXIO;
17645 		goto out;
17646 	}
17647 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17648 	if (rc == 0xFFFF) {
17649 		status = -ENXIO;
17650 		goto out;
17651 	}
17652 
17653 	/* Initialize all RQs with associated queue id */
17654 	for (idx = 0; idx < numrq; idx++) {
17655 		hrq = hrqp[idx];
17656 		hrq->queue_id = rc + (2 * idx);
17657 		drq = drqp[idx];
17658 		drq->queue_id = rc + (2 * idx) + 1;
17659 	}
17660 
17661 out:
17662 	lpfc_sli4_mbox_cmd_free(phba, mbox);
17663 	return status;
17664 }
17665 
17666 /**
17667  * lpfc_eq_destroy - Destroy an event Queue on the HBA
17668  * @phba: HBA structure that indicates port to destroy a queue on.
17669  * @eq: The queue structure associated with the queue to destroy.
17670  *
17671  * This function destroys a queue, as detailed in @eq by sending an mailbox
17672  * command, specific to the type of queue, to the HBA.
17673  *
17674  * The @eq struct is used to get the queue ID of the queue to destroy.
17675  *
17676  * On success this function will return a zero. If the queue destroy mailbox
17677  * command fails this function will return -ENXIO.
17678  **/
17679 int
17680 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
17681 {
17682 	LPFC_MBOXQ_t *mbox;
17683 	int rc, length, status = 0;
17684 	uint32_t shdr_status, shdr_add_status;
17685 	union lpfc_sli4_cfg_shdr *shdr;
17686 
17687 	/* sanity check on queue memory */
17688 	if (!eq)
17689 		return -ENODEV;
17690 
17691 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17692 		goto list_remove;
17693 
17694 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
17695 	if (!mbox)
17696 		return -ENOMEM;
17697 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
17698 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17699 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17700 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
17701 			 length, LPFC_SLI4_MBX_EMBED);
17702 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
17703 	       eq->queue_id);
17704 	mbox->vport = eq->phba->pport;
17705 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17706 
17707 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
17708 	/* The IOCTL status is embedded in the mailbox subheader. */
17709 	shdr = (union lpfc_sli4_cfg_shdr *)
17710 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
17711 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17712 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17713 	if (shdr_status || shdr_add_status || rc) {
17714 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17715 				"2505 EQ_DESTROY mailbox failed with "
17716 				"status x%x add_status x%x, mbx status x%x\n",
17717 				shdr_status, shdr_add_status, rc);
17718 		status = -ENXIO;
17719 	}
17720 	mempool_free(mbox, eq->phba->mbox_mem_pool);
17721 
17722 list_remove:
17723 	/* Remove eq from any list */
17724 	list_del_init(&eq->list);
17725 
17726 	return status;
17727 }
17728 
17729 /**
17730  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
17731  * @phba: HBA structure that indicates port to destroy a queue on.
17732  * @cq: The queue structure associated with the queue to destroy.
17733  *
17734  * This function destroys a queue, as detailed in @cq by sending an mailbox
17735  * command, specific to the type of queue, to the HBA.
17736  *
17737  * The @cq struct is used to get the queue ID of the queue to destroy.
17738  *
17739  * On success this function will return a zero. If the queue destroy mailbox
17740  * command fails this function will return -ENXIO.
17741  **/
17742 int
17743 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
17744 {
17745 	LPFC_MBOXQ_t *mbox;
17746 	int rc, length, status = 0;
17747 	uint32_t shdr_status, shdr_add_status;
17748 	union lpfc_sli4_cfg_shdr *shdr;
17749 
17750 	/* sanity check on queue memory */
17751 	if (!cq)
17752 		return -ENODEV;
17753 
17754 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17755 		goto list_remove;
17756 
17757 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
17758 	if (!mbox)
17759 		return -ENOMEM;
17760 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
17761 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17762 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17763 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
17764 			 length, LPFC_SLI4_MBX_EMBED);
17765 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
17766 	       cq->queue_id);
17767 	mbox->vport = cq->phba->pport;
17768 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17769 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
17770 	/* The IOCTL status is embedded in the mailbox subheader. */
17771 	shdr = (union lpfc_sli4_cfg_shdr *)
17772 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
17773 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17774 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17775 	if (shdr_status || shdr_add_status || rc) {
17776 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17777 				"2506 CQ_DESTROY mailbox failed with "
17778 				"status x%x add_status x%x, mbx status x%x\n",
17779 				shdr_status, shdr_add_status, rc);
17780 		status = -ENXIO;
17781 	}
17782 	mempool_free(mbox, cq->phba->mbox_mem_pool);
17783 
17784 list_remove:
17785 	/* Remove cq from any list */
17786 	list_del_init(&cq->list);
17787 	return status;
17788 }
17789 
17790 /**
17791  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
17792  * @phba: HBA structure that indicates port to destroy a queue on.
17793  * @mq: The queue structure associated with the queue to destroy.
17794  *
17795  * This function destroys a queue, as detailed in @mq by sending an mailbox
17796  * command, specific to the type of queue, to the HBA.
17797  *
17798  * The @mq struct is used to get the queue ID of the queue to destroy.
17799  *
17800  * On success this function will return a zero. If the queue destroy mailbox
17801  * command fails this function will return -ENXIO.
17802  **/
17803 int
17804 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
17805 {
17806 	LPFC_MBOXQ_t *mbox;
17807 	int rc, length, status = 0;
17808 	uint32_t shdr_status, shdr_add_status;
17809 	union lpfc_sli4_cfg_shdr *shdr;
17810 
17811 	/* sanity check on queue memory */
17812 	if (!mq)
17813 		return -ENODEV;
17814 
17815 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17816 		goto list_remove;
17817 
17818 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
17819 	if (!mbox)
17820 		return -ENOMEM;
17821 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
17822 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17823 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17824 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
17825 			 length, LPFC_SLI4_MBX_EMBED);
17826 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
17827 	       mq->queue_id);
17828 	mbox->vport = mq->phba->pport;
17829 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17830 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
17831 	/* The IOCTL status is embedded in the mailbox subheader. */
17832 	shdr = (union lpfc_sli4_cfg_shdr *)
17833 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
17834 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17835 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17836 	if (shdr_status || shdr_add_status || rc) {
17837 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17838 				"2507 MQ_DESTROY mailbox failed with "
17839 				"status x%x add_status x%x, mbx status x%x\n",
17840 				shdr_status, shdr_add_status, rc);
17841 		status = -ENXIO;
17842 	}
17843 	mempool_free(mbox, mq->phba->mbox_mem_pool);
17844 
17845 list_remove:
17846 	/* Remove mq from any list */
17847 	list_del_init(&mq->list);
17848 	return status;
17849 }
17850 
17851 /**
17852  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
17853  * @phba: HBA structure that indicates port to destroy a queue on.
17854  * @wq: The queue structure associated with the queue to destroy.
17855  *
17856  * This function destroys a queue, as detailed in @wq by sending an mailbox
17857  * command, specific to the type of queue, to the HBA.
17858  *
17859  * The @wq struct is used to get the queue ID of the queue to destroy.
17860  *
17861  * On success this function will return a zero. If the queue destroy mailbox
17862  * command fails this function will return -ENXIO.
17863  **/
17864 int
17865 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
17866 {
17867 	LPFC_MBOXQ_t *mbox;
17868 	int rc, length, status = 0;
17869 	uint32_t shdr_status, shdr_add_status;
17870 	union lpfc_sli4_cfg_shdr *shdr;
17871 
17872 	/* sanity check on queue memory */
17873 	if (!wq)
17874 		return -ENODEV;
17875 
17876 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17877 		goto list_remove;
17878 
17879 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17880 	if (!mbox)
17881 		return -ENOMEM;
17882 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
17883 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17884 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17885 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17886 			 length, LPFC_SLI4_MBX_EMBED);
17887 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17888 	       wq->queue_id);
17889 	mbox->vport = wq->phba->pport;
17890 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17891 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17892 	shdr = (union lpfc_sli4_cfg_shdr *)
17893 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17894 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17895 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17896 	if (shdr_status || shdr_add_status || rc) {
17897 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17898 				"2508 WQ_DESTROY mailbox failed with "
17899 				"status x%x add_status x%x, mbx status x%x\n",
17900 				shdr_status, shdr_add_status, rc);
17901 		status = -ENXIO;
17902 	}
17903 	mempool_free(mbox, wq->phba->mbox_mem_pool);
17904 
17905 list_remove:
17906 	/* Remove wq from any list */
17907 	list_del_init(&wq->list);
17908 	kfree(wq->pring);
17909 	wq->pring = NULL;
17910 	return status;
17911 }
17912 
17913 /**
17914  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17915  * @phba: HBA structure that indicates port to destroy a queue on.
17916  * @hrq: The queue structure associated with the queue to destroy.
17917  * @drq: The queue structure associated with the queue to destroy.
17918  *
17919  * This function destroys a queue, as detailed in @rq by sending an mailbox
17920  * command, specific to the type of queue, to the HBA.
17921  *
17922  * The @rq struct is used to get the queue ID of the queue to destroy.
17923  *
17924  * On success this function will return a zero. If the queue destroy mailbox
17925  * command fails this function will return -ENXIO.
17926  **/
17927 int
17928 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17929 		struct lpfc_queue *drq)
17930 {
17931 	LPFC_MBOXQ_t *mbox;
17932 	int rc, length, status = 0;
17933 	uint32_t shdr_status, shdr_add_status;
17934 	union lpfc_sli4_cfg_shdr *shdr;
17935 
17936 	/* sanity check on queue memory */
17937 	if (!hrq || !drq)
17938 		return -ENODEV;
17939 
17940 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17941 		goto list_remove;
17942 
17943 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17944 	if (!mbox)
17945 		return -ENOMEM;
17946 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
17947 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17948 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17949 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17950 			 length, LPFC_SLI4_MBX_EMBED);
17951 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17952 	       hrq->queue_id);
17953 	mbox->vport = hrq->phba->pport;
17954 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17955 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17956 	/* The IOCTL status is embedded in the mailbox subheader. */
17957 	shdr = (union lpfc_sli4_cfg_shdr *)
17958 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17959 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17960 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17961 	if (shdr_status || shdr_add_status || rc) {
17962 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17963 				"2509 RQ_DESTROY mailbox failed with "
17964 				"status x%x add_status x%x, mbx status x%x\n",
17965 				shdr_status, shdr_add_status, rc);
17966 		mempool_free(mbox, hrq->phba->mbox_mem_pool);
17967 		return -ENXIO;
17968 	}
17969 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17970 	       drq->queue_id);
17971 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17972 	shdr = (union lpfc_sli4_cfg_shdr *)
17973 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17974 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17975 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17976 	if (shdr_status || shdr_add_status || rc) {
17977 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17978 				"2510 RQ_DESTROY mailbox failed with "
17979 				"status x%x add_status x%x, mbx status x%x\n",
17980 				shdr_status, shdr_add_status, rc);
17981 		status = -ENXIO;
17982 	}
17983 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
17984 
17985 list_remove:
17986 	list_del_init(&hrq->list);
17987 	list_del_init(&drq->list);
17988 	return status;
17989 }
17990 
17991 /**
17992  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17993  * @phba: The virtual port for which this call being executed.
17994  * @pdma_phys_addr0: Physical address of the 1st SGL page.
17995  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
17996  * @xritag: the xritag that ties this io to the SGL pages.
17997  *
17998  * This routine will post the sgl pages for the IO that has the xritag
17999  * that is in the iocbq structure. The xritag is assigned during iocbq
18000  * creation and persists for as long as the driver is loaded.
18001  * if the caller has fewer than 256 scatter gather segments to map then
18002  * pdma_phys_addr1 should be 0.
18003  * If the caller needs to map more than 256 scatter gather segment then
18004  * pdma_phys_addr1 should be a valid physical address.
18005  * physical address for SGLs must be 64 byte aligned.
18006  * If you are going to map 2 SGL's then the first one must have 256 entries
18007  * the second sgl can have between 1 and 256 entries.
18008  *
18009  * Return codes:
18010  * 	0 - Success
18011  * 	-ENXIO, -ENOMEM - Failure
18012  **/
18013 int
18014 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
18015 		dma_addr_t pdma_phys_addr0,
18016 		dma_addr_t pdma_phys_addr1,
18017 		uint16_t xritag)
18018 {
18019 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
18020 	LPFC_MBOXQ_t *mbox;
18021 	int rc;
18022 	uint32_t shdr_status, shdr_add_status;
18023 	uint32_t mbox_tmo;
18024 	union lpfc_sli4_cfg_shdr *shdr;
18025 
18026 	if (xritag == NO_XRI) {
18027 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18028 				"0364 Invalid param:\n");
18029 		return -EINVAL;
18030 	}
18031 
18032 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18033 	if (!mbox)
18034 		return -ENOMEM;
18035 
18036 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18037 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
18038 			sizeof(struct lpfc_mbx_post_sgl_pages) -
18039 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
18040 
18041 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
18042 				&mbox->u.mqe.un.post_sgl_pages;
18043 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
18044 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
18045 
18046 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
18047 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
18048 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
18049 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
18050 
18051 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
18052 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
18053 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
18054 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
18055 	if (!phba->sli4_hba.intr_enable)
18056 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18057 	else {
18058 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18059 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18060 	}
18061 	/* The IOCTL status is embedded in the mailbox subheader. */
18062 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
18063 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18064 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18065 	if (!phba->sli4_hba.intr_enable)
18066 		mempool_free(mbox, phba->mbox_mem_pool);
18067 	else if (rc != MBX_TIMEOUT)
18068 		mempool_free(mbox, phba->mbox_mem_pool);
18069 	if (shdr_status || shdr_add_status || rc) {
18070 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18071 				"2511 POST_SGL mailbox failed with "
18072 				"status x%x add_status x%x, mbx status x%x\n",
18073 				shdr_status, shdr_add_status, rc);
18074 	}
18075 	return 0;
18076 }
18077 
18078 /**
18079  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
18080  * @phba: pointer to lpfc hba data structure.
18081  *
18082  * This routine is invoked to post rpi header templates to the
18083  * HBA consistent with the SLI-4 interface spec.  This routine
18084  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18085  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18086  *
18087  * Returns
18088  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
18089  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
18090  **/
18091 static uint16_t
18092 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
18093 {
18094 	unsigned long xri;
18095 
18096 	/*
18097 	 * Fetch the next logical xri.  Because this index is logical,
18098 	 * the driver starts at 0 each time.
18099 	 */
18100 	spin_lock_irq(&phba->hbalock);
18101 	xri = find_first_zero_bit(phba->sli4_hba.xri_bmask,
18102 				 phba->sli4_hba.max_cfg_param.max_xri);
18103 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
18104 		spin_unlock_irq(&phba->hbalock);
18105 		return NO_XRI;
18106 	} else {
18107 		set_bit(xri, phba->sli4_hba.xri_bmask);
18108 		phba->sli4_hba.max_cfg_param.xri_used++;
18109 	}
18110 	spin_unlock_irq(&phba->hbalock);
18111 	return xri;
18112 }
18113 
18114 /**
18115  * __lpfc_sli4_free_xri - Release an xri for reuse.
18116  * @phba: pointer to lpfc hba data structure.
18117  * @xri: xri to release.
18118  *
18119  * This routine is invoked to release an xri to the pool of
18120  * available rpis maintained by the driver.
18121  **/
18122 static void
18123 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18124 {
18125 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
18126 		phba->sli4_hba.max_cfg_param.xri_used--;
18127 	}
18128 }
18129 
18130 /**
18131  * lpfc_sli4_free_xri - Release an xri for reuse.
18132  * @phba: pointer to lpfc hba data structure.
18133  * @xri: xri to release.
18134  *
18135  * This routine is invoked to release an xri to the pool of
18136  * available rpis maintained by the driver.
18137  **/
18138 void
18139 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18140 {
18141 	spin_lock_irq(&phba->hbalock);
18142 	__lpfc_sli4_free_xri(phba, xri);
18143 	spin_unlock_irq(&phba->hbalock);
18144 }
18145 
18146 /**
18147  * lpfc_sli4_next_xritag - Get an xritag for the io
18148  * @phba: Pointer to HBA context object.
18149  *
18150  * This function gets an xritag for the iocb. If there is no unused xritag
18151  * it will return 0xffff.
18152  * The function returns the allocated xritag if successful, else returns zero.
18153  * Zero is not a valid xritag.
18154  * The caller is not required to hold any lock.
18155  **/
18156 uint16_t
18157 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
18158 {
18159 	uint16_t xri_index;
18160 
18161 	xri_index = lpfc_sli4_alloc_xri(phba);
18162 	if (xri_index == NO_XRI)
18163 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18164 				"2004 Failed to allocate XRI.last XRITAG is %d"
18165 				" Max XRI is %d, Used XRI is %d\n",
18166 				xri_index,
18167 				phba->sli4_hba.max_cfg_param.max_xri,
18168 				phba->sli4_hba.max_cfg_param.xri_used);
18169 	return xri_index;
18170 }
18171 
18172 /**
18173  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
18174  * @phba: pointer to lpfc hba data structure.
18175  * @post_sgl_list: pointer to els sgl entry list.
18176  * @post_cnt: number of els sgl entries on the list.
18177  *
18178  * This routine is invoked to post a block of driver's sgl pages to the
18179  * HBA using non-embedded mailbox command. No Lock is held. This routine
18180  * is only called when the driver is loading and after all IO has been
18181  * stopped.
18182  **/
18183 static int
18184 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
18185 			    struct list_head *post_sgl_list,
18186 			    int post_cnt)
18187 {
18188 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
18189 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18190 	struct sgl_page_pairs *sgl_pg_pairs;
18191 	void *viraddr;
18192 	LPFC_MBOXQ_t *mbox;
18193 	uint32_t reqlen, alloclen, pg_pairs;
18194 	uint32_t mbox_tmo;
18195 	uint16_t xritag_start = 0;
18196 	int rc = 0;
18197 	uint32_t shdr_status, shdr_add_status;
18198 	union lpfc_sli4_cfg_shdr *shdr;
18199 
18200 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
18201 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18202 	if (reqlen > SLI4_PAGE_SIZE) {
18203 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18204 				"2559 Block sgl registration required DMA "
18205 				"size (%d) great than a page\n", reqlen);
18206 		return -ENOMEM;
18207 	}
18208 
18209 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18210 	if (!mbox)
18211 		return -ENOMEM;
18212 
18213 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18214 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18215 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
18216 			 LPFC_SLI4_MBX_NEMBED);
18217 
18218 	if (alloclen < reqlen) {
18219 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18220 				"0285 Allocated DMA memory size (%d) is "
18221 				"less than the requested DMA memory "
18222 				"size (%d)\n", alloclen, reqlen);
18223 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18224 		return -ENOMEM;
18225 	}
18226 	/* Set up the SGL pages in the non-embedded DMA pages */
18227 	viraddr = mbox->sge_array->addr[0];
18228 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18229 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18230 
18231 	pg_pairs = 0;
18232 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
18233 		/* Set up the sge entry */
18234 		sgl_pg_pairs->sgl_pg0_addr_lo =
18235 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
18236 		sgl_pg_pairs->sgl_pg0_addr_hi =
18237 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
18238 		sgl_pg_pairs->sgl_pg1_addr_lo =
18239 				cpu_to_le32(putPaddrLow(0));
18240 		sgl_pg_pairs->sgl_pg1_addr_hi =
18241 				cpu_to_le32(putPaddrHigh(0));
18242 
18243 		/* Keep the first xritag on the list */
18244 		if (pg_pairs == 0)
18245 			xritag_start = sglq_entry->sli4_xritag;
18246 		sgl_pg_pairs++;
18247 		pg_pairs++;
18248 	}
18249 
18250 	/* Complete initialization and perform endian conversion. */
18251 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18252 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
18253 	sgl->word0 = cpu_to_le32(sgl->word0);
18254 
18255 	if (!phba->sli4_hba.intr_enable)
18256 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18257 	else {
18258 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18259 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18260 	}
18261 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
18262 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18263 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18264 	if (!phba->sli4_hba.intr_enable)
18265 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18266 	else if (rc != MBX_TIMEOUT)
18267 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18268 	if (shdr_status || shdr_add_status || rc) {
18269 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18270 				"2513 POST_SGL_BLOCK mailbox command failed "
18271 				"status x%x add_status x%x mbx status x%x\n",
18272 				shdr_status, shdr_add_status, rc);
18273 		rc = -ENXIO;
18274 	}
18275 	return rc;
18276 }
18277 
18278 /**
18279  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
18280  * @phba: pointer to lpfc hba data structure.
18281  * @nblist: pointer to nvme buffer list.
18282  * @count: number of scsi buffers on the list.
18283  *
18284  * This routine is invoked to post a block of @count scsi sgl pages from a
18285  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
18286  * No Lock is held.
18287  *
18288  **/
18289 static int
18290 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
18291 			    int count)
18292 {
18293 	struct lpfc_io_buf *lpfc_ncmd;
18294 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18295 	struct sgl_page_pairs *sgl_pg_pairs;
18296 	void *viraddr;
18297 	LPFC_MBOXQ_t *mbox;
18298 	uint32_t reqlen, alloclen, pg_pairs;
18299 	uint32_t mbox_tmo;
18300 	uint16_t xritag_start = 0;
18301 	int rc = 0;
18302 	uint32_t shdr_status, shdr_add_status;
18303 	dma_addr_t pdma_phys_bpl1;
18304 	union lpfc_sli4_cfg_shdr *shdr;
18305 
18306 	/* Calculate the requested length of the dma memory */
18307 	reqlen = count * sizeof(struct sgl_page_pairs) +
18308 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18309 	if (reqlen > SLI4_PAGE_SIZE) {
18310 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
18311 				"6118 Block sgl registration required DMA "
18312 				"size (%d) great than a page\n", reqlen);
18313 		return -ENOMEM;
18314 	}
18315 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18316 	if (!mbox) {
18317 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18318 				"6119 Failed to allocate mbox cmd memory\n");
18319 		return -ENOMEM;
18320 	}
18321 
18322 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18323 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18324 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
18325 				    reqlen, LPFC_SLI4_MBX_NEMBED);
18326 
18327 	if (alloclen < reqlen) {
18328 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18329 				"6120 Allocated DMA memory size (%d) is "
18330 				"less than the requested DMA memory "
18331 				"size (%d)\n", alloclen, reqlen);
18332 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18333 		return -ENOMEM;
18334 	}
18335 
18336 	/* Get the first SGE entry from the non-embedded DMA memory */
18337 	viraddr = mbox->sge_array->addr[0];
18338 
18339 	/* Set up the SGL pages in the non-embedded DMA pages */
18340 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18341 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18342 
18343 	pg_pairs = 0;
18344 	list_for_each_entry(lpfc_ncmd, nblist, list) {
18345 		/* Set up the sge entry */
18346 		sgl_pg_pairs->sgl_pg0_addr_lo =
18347 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
18348 		sgl_pg_pairs->sgl_pg0_addr_hi =
18349 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
18350 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
18351 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
18352 						SGL_PAGE_SIZE;
18353 		else
18354 			pdma_phys_bpl1 = 0;
18355 		sgl_pg_pairs->sgl_pg1_addr_lo =
18356 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
18357 		sgl_pg_pairs->sgl_pg1_addr_hi =
18358 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
18359 		/* Keep the first xritag on the list */
18360 		if (pg_pairs == 0)
18361 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
18362 		sgl_pg_pairs++;
18363 		pg_pairs++;
18364 	}
18365 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18366 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
18367 	/* Perform endian conversion if necessary */
18368 	sgl->word0 = cpu_to_le32(sgl->word0);
18369 
18370 	if (!phba->sli4_hba.intr_enable) {
18371 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18372 	} else {
18373 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18374 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18375 	}
18376 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
18377 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18378 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18379 	if (!phba->sli4_hba.intr_enable)
18380 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18381 	else if (rc != MBX_TIMEOUT)
18382 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18383 	if (shdr_status || shdr_add_status || rc) {
18384 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18385 				"6125 POST_SGL_BLOCK mailbox command failed "
18386 				"status x%x add_status x%x mbx status x%x\n",
18387 				shdr_status, shdr_add_status, rc);
18388 		rc = -ENXIO;
18389 	}
18390 	return rc;
18391 }
18392 
18393 /**
18394  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
18395  * @phba: pointer to lpfc hba data structure.
18396  * @post_nblist: pointer to the nvme buffer list.
18397  * @sb_count: number of nvme buffers.
18398  *
18399  * This routine walks a list of nvme buffers that was passed in. It attempts
18400  * to construct blocks of nvme buffer sgls which contains contiguous xris and
18401  * uses the non-embedded SGL block post mailbox commands to post to the port.
18402  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
18403  * embedded SGL post mailbox command for posting. The @post_nblist passed in
18404  * must be local list, thus no lock is needed when manipulate the list.
18405  *
18406  * Returns: 0 = failure, non-zero number of successfully posted buffers.
18407  **/
18408 int
18409 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
18410 			   struct list_head *post_nblist, int sb_count)
18411 {
18412 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
18413 	int status, sgl_size;
18414 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
18415 	dma_addr_t pdma_phys_sgl1;
18416 	int last_xritag = NO_XRI;
18417 	int cur_xritag;
18418 	LIST_HEAD(prep_nblist);
18419 	LIST_HEAD(blck_nblist);
18420 	LIST_HEAD(nvme_nblist);
18421 
18422 	/* sanity check */
18423 	if (sb_count <= 0)
18424 		return -EINVAL;
18425 
18426 	sgl_size = phba->cfg_sg_dma_buf_size;
18427 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
18428 		list_del_init(&lpfc_ncmd->list);
18429 		block_cnt++;
18430 		if ((last_xritag != NO_XRI) &&
18431 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
18432 			/* a hole in xri block, form a sgl posting block */
18433 			list_splice_init(&prep_nblist, &blck_nblist);
18434 			post_cnt = block_cnt - 1;
18435 			/* prepare list for next posting block */
18436 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18437 			block_cnt = 1;
18438 		} else {
18439 			/* prepare list for next posting block */
18440 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18441 			/* enough sgls for non-embed sgl mbox command */
18442 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
18443 				list_splice_init(&prep_nblist, &blck_nblist);
18444 				post_cnt = block_cnt;
18445 				block_cnt = 0;
18446 			}
18447 		}
18448 		num_posting++;
18449 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18450 
18451 		/* end of repost sgl list condition for NVME buffers */
18452 		if (num_posting == sb_count) {
18453 			if (post_cnt == 0) {
18454 				/* last sgl posting block */
18455 				list_splice_init(&prep_nblist, &blck_nblist);
18456 				post_cnt = block_cnt;
18457 			} else if (block_cnt == 1) {
18458 				/* last single sgl with non-contiguous xri */
18459 				if (sgl_size > SGL_PAGE_SIZE)
18460 					pdma_phys_sgl1 =
18461 						lpfc_ncmd->dma_phys_sgl +
18462 						SGL_PAGE_SIZE;
18463 				else
18464 					pdma_phys_sgl1 = 0;
18465 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18466 				status = lpfc_sli4_post_sgl(
18467 						phba, lpfc_ncmd->dma_phys_sgl,
18468 						pdma_phys_sgl1, cur_xritag);
18469 				if (status) {
18470 					/* Post error.  Buffer unavailable. */
18471 					lpfc_ncmd->flags |=
18472 						LPFC_SBUF_NOT_POSTED;
18473 				} else {
18474 					/* Post success. Bffer available. */
18475 					lpfc_ncmd->flags &=
18476 						~LPFC_SBUF_NOT_POSTED;
18477 					lpfc_ncmd->status = IOSTAT_SUCCESS;
18478 					num_posted++;
18479 				}
18480 				/* success, put on NVME buffer sgl list */
18481 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18482 			}
18483 		}
18484 
18485 		/* continue until a nembed page worth of sgls */
18486 		if (post_cnt == 0)
18487 			continue;
18488 
18489 		/* post block of NVME buffer list sgls */
18490 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
18491 						     post_cnt);
18492 
18493 		/* don't reset xirtag due to hole in xri block */
18494 		if (block_cnt == 0)
18495 			last_xritag = NO_XRI;
18496 
18497 		/* reset NVME buffer post count for next round of posting */
18498 		post_cnt = 0;
18499 
18500 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
18501 		while (!list_empty(&blck_nblist)) {
18502 			list_remove_head(&blck_nblist, lpfc_ncmd,
18503 					 struct lpfc_io_buf, list);
18504 			if (status) {
18505 				/* Post error.  Mark buffer unavailable. */
18506 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
18507 			} else {
18508 				/* Post success, Mark buffer available. */
18509 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
18510 				lpfc_ncmd->status = IOSTAT_SUCCESS;
18511 				num_posted++;
18512 			}
18513 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18514 		}
18515 	}
18516 	/* Push NVME buffers with sgl posted to the available list */
18517 	lpfc_io_buf_replenish(phba, &nvme_nblist);
18518 
18519 	return num_posted;
18520 }
18521 
18522 /**
18523  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
18524  * @phba: pointer to lpfc_hba struct that the frame was received on
18525  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18526  *
18527  * This function checks the fields in the @fc_hdr to see if the FC frame is a
18528  * valid type of frame that the LPFC driver will handle. This function will
18529  * return a zero if the frame is a valid frame or a non zero value when the
18530  * frame does not pass the check.
18531  **/
18532 static int
18533 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
18534 {
18535 	/*  make rctl_names static to save stack space */
18536 	struct fc_vft_header *fc_vft_hdr;
18537 	struct fc_app_header *fc_app_hdr;
18538 	uint32_t *header = (uint32_t *) fc_hdr;
18539 
18540 #define FC_RCTL_MDS_DIAGS	0xF4
18541 
18542 	switch (fc_hdr->fh_r_ctl) {
18543 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
18544 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
18545 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
18546 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
18547 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
18548 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
18549 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
18550 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
18551 	case FC_RCTL_ELS_REQ:	/* extended link services request */
18552 	case FC_RCTL_ELS_REP:	/* extended link services reply */
18553 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
18554 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
18555 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
18556 	case FC_RCTL_BA_RMC: 	/* remove connection */
18557 	case FC_RCTL_BA_ACC:	/* basic accept */
18558 	case FC_RCTL_BA_RJT:	/* basic reject */
18559 	case FC_RCTL_BA_PRMT:
18560 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
18561 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
18562 	case FC_RCTL_P_RJT:	/* port reject */
18563 	case FC_RCTL_F_RJT:	/* fabric reject */
18564 	case FC_RCTL_P_BSY:	/* port busy */
18565 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
18566 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
18567 	case FC_RCTL_LCR:	/* link credit reset */
18568 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
18569 	case FC_RCTL_END:	/* end */
18570 		break;
18571 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
18572 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18573 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
18574 		return lpfc_fc_frame_check(phba, fc_hdr);
18575 	case FC_RCTL_BA_NOP:	/* basic link service NOP */
18576 	default:
18577 		goto drop;
18578 	}
18579 
18580 	switch (fc_hdr->fh_type) {
18581 	case FC_TYPE_BLS:
18582 	case FC_TYPE_ELS:
18583 	case FC_TYPE_FCP:
18584 	case FC_TYPE_CT:
18585 	case FC_TYPE_NVME:
18586 		break;
18587 	case FC_TYPE_IP:
18588 	case FC_TYPE_ILS:
18589 	default:
18590 		goto drop;
18591 	}
18592 
18593 	if (unlikely(phba->link_flag == LS_LOOPBACK_MODE &&
18594 				phba->cfg_vmid_app_header)) {
18595 		/* Application header is 16B device header */
18596 		if (fc_hdr->fh_df_ctl & LPFC_FC_16B_DEVICE_HEADER) {
18597 			fc_app_hdr = (struct fc_app_header *) (fc_hdr + 1);
18598 			if (be32_to_cpu(fc_app_hdr->src_app_id) !=
18599 					LOOPBACK_SRC_APPID) {
18600 				lpfc_printf_log(phba, KERN_WARNING,
18601 						LOG_ELS | LOG_LIBDFC,
18602 						"1932 Loopback src app id "
18603 						"not matched, app_id:x%x\n",
18604 						be32_to_cpu(fc_app_hdr->src_app_id));
18605 
18606 				goto drop;
18607 			}
18608 		} else {
18609 			lpfc_printf_log(phba, KERN_WARNING,
18610 					LOG_ELS | LOG_LIBDFC,
18611 					"1933 Loopback df_ctl bit not set, "
18612 					"df_ctl:x%x\n",
18613 					fc_hdr->fh_df_ctl);
18614 
18615 			goto drop;
18616 		}
18617 	}
18618 
18619 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
18620 			"2538 Received frame rctl:x%x, type:x%x, "
18621 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
18622 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
18623 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
18624 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
18625 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
18626 			be32_to_cpu(header[6]));
18627 	return 0;
18628 drop:
18629 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
18630 			"2539 Dropped frame rctl:x%x type:x%x\n",
18631 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18632 	return 1;
18633 }
18634 
18635 /**
18636  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
18637  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18638  *
18639  * This function processes the FC header to retrieve the VFI from the VF
18640  * header, if one exists. This function will return the VFI if one exists
18641  * or 0 if no VSAN Header exists.
18642  **/
18643 static uint32_t
18644 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
18645 {
18646 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18647 
18648 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
18649 		return 0;
18650 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
18651 }
18652 
18653 /**
18654  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
18655  * @phba: Pointer to the HBA structure to search for the vport on
18656  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18657  * @fcfi: The FC Fabric ID that the frame came from
18658  * @did: Destination ID to match against
18659  *
18660  * This function searches the @phba for a vport that matches the content of the
18661  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
18662  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
18663  * returns the matching vport pointer or NULL if unable to match frame to a
18664  * vport.
18665  **/
18666 static struct lpfc_vport *
18667 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
18668 		       uint16_t fcfi, uint32_t did)
18669 {
18670 	struct lpfc_vport **vports;
18671 	struct lpfc_vport *vport = NULL;
18672 	int i;
18673 
18674 	if (did == Fabric_DID)
18675 		return phba->pport;
18676 	if (test_bit(FC_PT2PT, &phba->pport->fc_flag) &&
18677 	    phba->link_state != LPFC_HBA_READY)
18678 		return phba->pport;
18679 
18680 	vports = lpfc_create_vport_work_array(phba);
18681 	if (vports != NULL) {
18682 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
18683 			if (phba->fcf.fcfi == fcfi &&
18684 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
18685 			    vports[i]->fc_myDID == did) {
18686 				vport = vports[i];
18687 				break;
18688 			}
18689 		}
18690 	}
18691 	lpfc_destroy_vport_work_array(phba, vports);
18692 	return vport;
18693 }
18694 
18695 /**
18696  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
18697  * @vport: The vport to work on.
18698  *
18699  * This function updates the receive sequence time stamp for this vport. The
18700  * receive sequence time stamp indicates the time that the last frame of the
18701  * the sequence that has been idle for the longest amount of time was received.
18702  * the driver uses this time stamp to indicate if any received sequences have
18703  * timed out.
18704  **/
18705 static void
18706 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
18707 {
18708 	struct lpfc_dmabuf *h_buf;
18709 	struct hbq_dmabuf *dmabuf = NULL;
18710 
18711 	/* get the oldest sequence on the rcv list */
18712 	h_buf = list_get_first(&vport->rcv_buffer_list,
18713 			       struct lpfc_dmabuf, list);
18714 	if (!h_buf)
18715 		return;
18716 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18717 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
18718 }
18719 
18720 /**
18721  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
18722  * @vport: The vport that the received sequences were sent to.
18723  *
18724  * This function cleans up all outstanding received sequences. This is called
18725  * by the driver when a link event or user action invalidates all the received
18726  * sequences.
18727  **/
18728 void
18729 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
18730 {
18731 	struct lpfc_dmabuf *h_buf, *hnext;
18732 	struct lpfc_dmabuf *d_buf, *dnext;
18733 	struct hbq_dmabuf *dmabuf = NULL;
18734 
18735 	/* start with the oldest sequence on the rcv list */
18736 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18737 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18738 		list_del_init(&dmabuf->hbuf.list);
18739 		list_for_each_entry_safe(d_buf, dnext,
18740 					 &dmabuf->dbuf.list, list) {
18741 			list_del_init(&d_buf->list);
18742 			lpfc_in_buf_free(vport->phba, d_buf);
18743 		}
18744 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18745 	}
18746 }
18747 
18748 /**
18749  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
18750  * @vport: The vport that the received sequences were sent to.
18751  *
18752  * This function determines whether any received sequences have timed out by
18753  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
18754  * indicates that there is at least one timed out sequence this routine will
18755  * go through the received sequences one at a time from most inactive to most
18756  * active to determine which ones need to be cleaned up. Once it has determined
18757  * that a sequence needs to be cleaned up it will simply free up the resources
18758  * without sending an abort.
18759  **/
18760 void
18761 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
18762 {
18763 	struct lpfc_dmabuf *h_buf, *hnext;
18764 	struct lpfc_dmabuf *d_buf, *dnext;
18765 	struct hbq_dmabuf *dmabuf = NULL;
18766 	unsigned long timeout;
18767 	int abort_count = 0;
18768 
18769 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18770 		   vport->rcv_buffer_time_stamp);
18771 	if (list_empty(&vport->rcv_buffer_list) ||
18772 	    time_before(jiffies, timeout))
18773 		return;
18774 	/* start with the oldest sequence on the rcv list */
18775 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18776 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18777 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18778 			   dmabuf->time_stamp);
18779 		if (time_before(jiffies, timeout))
18780 			break;
18781 		abort_count++;
18782 		list_del_init(&dmabuf->hbuf.list);
18783 		list_for_each_entry_safe(d_buf, dnext,
18784 					 &dmabuf->dbuf.list, list) {
18785 			list_del_init(&d_buf->list);
18786 			lpfc_in_buf_free(vport->phba, d_buf);
18787 		}
18788 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18789 	}
18790 	if (abort_count)
18791 		lpfc_update_rcv_time_stamp(vport);
18792 }
18793 
18794 /**
18795  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
18796  * @vport: pointer to a vitural port
18797  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
18798  *
18799  * This function searches through the existing incomplete sequences that have
18800  * been sent to this @vport. If the frame matches one of the incomplete
18801  * sequences then the dbuf in the @dmabuf is added to the list of frames that
18802  * make up that sequence. If no sequence is found that matches this frame then
18803  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
18804  * This function returns a pointer to the first dmabuf in the sequence list that
18805  * the frame was linked to.
18806  **/
18807 static struct hbq_dmabuf *
18808 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18809 {
18810 	struct fc_frame_header *new_hdr;
18811 	struct fc_frame_header *temp_hdr;
18812 	struct lpfc_dmabuf *d_buf;
18813 	struct lpfc_dmabuf *h_buf;
18814 	struct hbq_dmabuf *seq_dmabuf = NULL;
18815 	struct hbq_dmabuf *temp_dmabuf = NULL;
18816 	uint8_t	found = 0;
18817 
18818 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18819 	dmabuf->time_stamp = jiffies;
18820 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18821 
18822 	/* Use the hdr_buf to find the sequence that this frame belongs to */
18823 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18824 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18825 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18826 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18827 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18828 			continue;
18829 		/* found a pending sequence that matches this frame */
18830 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18831 		break;
18832 	}
18833 	if (!seq_dmabuf) {
18834 		/*
18835 		 * This indicates first frame received for this sequence.
18836 		 * Queue the buffer on the vport's rcv_buffer_list.
18837 		 */
18838 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18839 		lpfc_update_rcv_time_stamp(vport);
18840 		return dmabuf;
18841 	}
18842 	temp_hdr = seq_dmabuf->hbuf.virt;
18843 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
18844 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18845 		list_del_init(&seq_dmabuf->hbuf.list);
18846 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18847 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18848 		lpfc_update_rcv_time_stamp(vport);
18849 		return dmabuf;
18850 	}
18851 	/* move this sequence to the tail to indicate a young sequence */
18852 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
18853 	seq_dmabuf->time_stamp = jiffies;
18854 	lpfc_update_rcv_time_stamp(vport);
18855 	if (list_empty(&seq_dmabuf->dbuf.list)) {
18856 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18857 		return seq_dmabuf;
18858 	}
18859 	/* find the correct place in the sequence to insert this frame */
18860 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
18861 	while (!found) {
18862 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18863 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
18864 		/*
18865 		 * If the frame's sequence count is greater than the frame on
18866 		 * the list then insert the frame right after this frame
18867 		 */
18868 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
18869 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18870 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
18871 			found = 1;
18872 			break;
18873 		}
18874 
18875 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
18876 			break;
18877 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
18878 	}
18879 
18880 	if (found)
18881 		return seq_dmabuf;
18882 	return NULL;
18883 }
18884 
18885 /**
18886  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
18887  * @vport: pointer to a vitural port
18888  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18889  *
18890  * This function tries to abort from the partially assembed sequence, described
18891  * by the information from basic abbort @dmabuf. It checks to see whether such
18892  * partially assembled sequence held by the driver. If so, it shall free up all
18893  * the frames from the partially assembled sequence.
18894  *
18895  * Return
18896  * true  -- if there is matching partially assembled sequence present and all
18897  *          the frames freed with the sequence;
18898  * false -- if there is no matching partially assembled sequence present so
18899  *          nothing got aborted in the lower layer driver
18900  **/
18901 static bool
18902 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
18903 			    struct hbq_dmabuf *dmabuf)
18904 {
18905 	struct fc_frame_header *new_hdr;
18906 	struct fc_frame_header *temp_hdr;
18907 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
18908 	struct hbq_dmabuf *seq_dmabuf = NULL;
18909 
18910 	/* Use the hdr_buf to find the sequence that matches this frame */
18911 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18912 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
18913 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18914 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18915 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18916 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18917 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18918 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18919 			continue;
18920 		/* found a pending sequence that matches this frame */
18921 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18922 		break;
18923 	}
18924 
18925 	/* Free up all the frames from the partially assembled sequence */
18926 	if (seq_dmabuf) {
18927 		list_for_each_entry_safe(d_buf, n_buf,
18928 					 &seq_dmabuf->dbuf.list, list) {
18929 			list_del_init(&d_buf->list);
18930 			lpfc_in_buf_free(vport->phba, d_buf);
18931 		}
18932 		return true;
18933 	}
18934 	return false;
18935 }
18936 
18937 /**
18938  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18939  * @vport: pointer to a vitural port
18940  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18941  *
18942  * This function tries to abort from the assembed sequence from upper level
18943  * protocol, described by the information from basic abbort @dmabuf. It
18944  * checks to see whether such pending context exists at upper level protocol.
18945  * If so, it shall clean up the pending context.
18946  *
18947  * Return
18948  * true  -- if there is matching pending context of the sequence cleaned
18949  *          at ulp;
18950  * false -- if there is no matching pending context of the sequence present
18951  *          at ulp.
18952  **/
18953 static bool
18954 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18955 {
18956 	struct lpfc_hba *phba = vport->phba;
18957 	int handled;
18958 
18959 	/* Accepting abort at ulp with SLI4 only */
18960 	if (phba->sli_rev < LPFC_SLI_REV4)
18961 		return false;
18962 
18963 	/* Register all caring upper level protocols to attend abort */
18964 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18965 	if (handled)
18966 		return true;
18967 
18968 	return false;
18969 }
18970 
18971 /**
18972  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18973  * @phba: Pointer to HBA context object.
18974  * @cmd_iocbq: pointer to the command iocbq structure.
18975  * @rsp_iocbq: pointer to the response iocbq structure.
18976  *
18977  * This function handles the sequence abort response iocb command complete
18978  * event. It properly releases the memory allocated to the sequence abort
18979  * accept iocb.
18980  **/
18981 static void
18982 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18983 			     struct lpfc_iocbq *cmd_iocbq,
18984 			     struct lpfc_iocbq *rsp_iocbq)
18985 {
18986 	if (cmd_iocbq) {
18987 		lpfc_nlp_put(cmd_iocbq->ndlp);
18988 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
18989 	}
18990 
18991 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
18992 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18993 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18994 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
18995 			get_job_ulpstatus(phba, rsp_iocbq),
18996 			get_job_word4(phba, rsp_iocbq));
18997 }
18998 
18999 /**
19000  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
19001  * @phba: Pointer to HBA context object.
19002  * @xri: xri id in transaction.
19003  *
19004  * This function validates the xri maps to the known range of XRIs allocated an
19005  * used by the driver.
19006  **/
19007 uint16_t
19008 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
19009 		      uint16_t xri)
19010 {
19011 	uint16_t i;
19012 
19013 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
19014 		if (xri == phba->sli4_hba.xri_ids[i])
19015 			return i;
19016 	}
19017 	return NO_XRI;
19018 }
19019 
19020 /**
19021  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
19022  * @vport: pointer to a virtual port.
19023  * @fc_hdr: pointer to a FC frame header.
19024  * @aborted: was the partially assembled receive sequence successfully aborted
19025  *
19026  * This function sends a basic response to a previous unsol sequence abort
19027  * event after aborting the sequence handling.
19028  **/
19029 void
19030 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
19031 			struct fc_frame_header *fc_hdr, bool aborted)
19032 {
19033 	struct lpfc_hba *phba = vport->phba;
19034 	struct lpfc_iocbq *ctiocb = NULL;
19035 	struct lpfc_nodelist *ndlp;
19036 	uint16_t oxid, rxid, xri, lxri;
19037 	uint32_t sid, fctl;
19038 	union lpfc_wqe128 *icmd;
19039 	int rc;
19040 
19041 	if (!lpfc_is_link_up(phba))
19042 		return;
19043 
19044 	sid = sli4_sid_from_fc_hdr(fc_hdr);
19045 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
19046 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
19047 
19048 	ndlp = lpfc_findnode_did(vport, sid);
19049 	if (!ndlp) {
19050 		ndlp = lpfc_nlp_init(vport, sid);
19051 		if (!ndlp) {
19052 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
19053 					 "1268 Failed to allocate ndlp for "
19054 					 "oxid:x%x SID:x%x\n", oxid, sid);
19055 			return;
19056 		}
19057 		/* Put ndlp onto vport node list */
19058 		lpfc_enqueue_node(vport, ndlp);
19059 	}
19060 
19061 	/* Allocate buffer for rsp iocb */
19062 	ctiocb = lpfc_sli_get_iocbq(phba);
19063 	if (!ctiocb)
19064 		return;
19065 
19066 	icmd = &ctiocb->wqe;
19067 
19068 	/* Extract the F_CTL field from FC_HDR */
19069 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
19070 
19071 	ctiocb->ndlp = lpfc_nlp_get(ndlp);
19072 	if (!ctiocb->ndlp) {
19073 		lpfc_sli_release_iocbq(phba, ctiocb);
19074 		return;
19075 	}
19076 
19077 	ctiocb->vport = vport;
19078 	ctiocb->cmd_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
19079 	ctiocb->sli4_lxritag = NO_XRI;
19080 	ctiocb->sli4_xritag = NO_XRI;
19081 	ctiocb->abort_rctl = FC_RCTL_BA_ACC;
19082 
19083 	if (fctl & FC_FC_EX_CTX)
19084 		/* Exchange responder sent the abort so we
19085 		 * own the oxid.
19086 		 */
19087 		xri = oxid;
19088 	else
19089 		xri = rxid;
19090 	lxri = lpfc_sli4_xri_inrange(phba, xri);
19091 	if (lxri != NO_XRI)
19092 		lpfc_set_rrq_active(phba, ndlp, lxri,
19093 			(xri == oxid) ? rxid : oxid, 0);
19094 	/* For BA_ABTS from exchange responder, if the logical xri with
19095 	 * the oxid maps to the FCP XRI range, the port no longer has
19096 	 * that exchange context, send a BLS_RJT. Override the IOCB for
19097 	 * a BA_RJT.
19098 	 */
19099 	if ((fctl & FC_FC_EX_CTX) &&
19100 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
19101 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
19102 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
19103 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
19104 		       FC_BA_RJT_INV_XID);
19105 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
19106 		       FC_BA_RJT_UNABLE);
19107 	}
19108 
19109 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
19110 	 * the driver no longer has that exchange, send a BLS_RJT. Override
19111 	 * the IOCB for a BA_RJT.
19112 	 */
19113 	if (aborted == false) {
19114 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
19115 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
19116 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
19117 		       FC_BA_RJT_INV_XID);
19118 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
19119 		       FC_BA_RJT_UNABLE);
19120 	}
19121 
19122 	if (fctl & FC_FC_EX_CTX) {
19123 		/* ABTS sent by responder to CT exchange, construction
19124 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
19125 		 * field and RX_ID from ABTS for RX_ID field.
19126 		 */
19127 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_RSP;
19128 		bf_set(xmit_bls_rsp64_rxid, &icmd->xmit_bls_rsp, rxid);
19129 	} else {
19130 		/* ABTS sent by initiator to CT exchange, construction
19131 		 * of BA_ACC will need to allocate a new XRI as for the
19132 		 * XRI_TAG field.
19133 		 */
19134 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_INT;
19135 	}
19136 
19137 	/* OX_ID is invariable to who sent ABTS to CT exchange */
19138 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, oxid);
19139 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, rxid);
19140 
19141 	/* Use CT=VPI */
19142 	bf_set(wqe_els_did, &icmd->xmit_bls_rsp.wqe_dest,
19143 	       ndlp->nlp_DID);
19144 	bf_set(xmit_bls_rsp64_temprpi, &icmd->xmit_bls_rsp,
19145 	       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
19146 	bf_set(wqe_cmnd, &icmd->generic.wqe_com, CMD_XMIT_BLS_RSP64_CX);
19147 
19148 	/* Xmit CT abts response on exchange <xid> */
19149 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
19150 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
19151 			 ctiocb->abort_rctl, oxid, phba->link_state);
19152 
19153 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
19154 	if (rc == IOCB_ERROR) {
19155 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19156 				 "2925 Failed to issue CT ABTS RSP x%x on "
19157 				 "xri x%x, Data x%x\n",
19158 				 ctiocb->abort_rctl, oxid,
19159 				 phba->link_state);
19160 		lpfc_nlp_put(ndlp);
19161 		ctiocb->ndlp = NULL;
19162 		lpfc_sli_release_iocbq(phba, ctiocb);
19163 	}
19164 
19165 	/* if only usage of this nodelist is BLS response, release initial ref
19166 	 * to free ndlp when transmit completes
19167 	 */
19168 	if (ndlp->nlp_state == NLP_STE_UNUSED_NODE &&
19169 	    !test_bit(NLP_DROPPED, &ndlp->nlp_flag) &&
19170 	    !(ndlp->fc4_xpt_flags & (NVME_XPT_REGD | SCSI_XPT_REGD))) {
19171 		set_bit(NLP_DROPPED, &ndlp->nlp_flag);
19172 		lpfc_nlp_put(ndlp);
19173 	}
19174 }
19175 
19176 /**
19177  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
19178  * @vport: Pointer to the vport on which this sequence was received
19179  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19180  *
19181  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
19182  * receive sequence is only partially assembed by the driver, it shall abort
19183  * the partially assembled frames for the sequence. Otherwise, if the
19184  * unsolicited receive sequence has been completely assembled and passed to
19185  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
19186  * unsolicited sequence has been aborted. After that, it will issue a basic
19187  * accept to accept the abort.
19188  **/
19189 static void
19190 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
19191 			     struct hbq_dmabuf *dmabuf)
19192 {
19193 	struct lpfc_hba *phba = vport->phba;
19194 	struct fc_frame_header fc_hdr;
19195 	uint32_t fctl;
19196 	bool aborted;
19197 
19198 	/* Make a copy of fc_hdr before the dmabuf being released */
19199 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
19200 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
19201 
19202 	if (fctl & FC_FC_EX_CTX) {
19203 		/* ABTS by responder to exchange, no cleanup needed */
19204 		aborted = true;
19205 	} else {
19206 		/* ABTS by initiator to exchange, need to do cleanup */
19207 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
19208 		if (aborted == false)
19209 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
19210 	}
19211 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19212 
19213 	if (phba->nvmet_support) {
19214 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
19215 		return;
19216 	}
19217 
19218 	/* Respond with BA_ACC or BA_RJT accordingly */
19219 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
19220 }
19221 
19222 /**
19223  * lpfc_seq_complete - Indicates if a sequence is complete
19224  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19225  *
19226  * This function checks the sequence, starting with the frame described by
19227  * @dmabuf, to see if all the frames associated with this sequence are present.
19228  * the frames associated with this sequence are linked to the @dmabuf using the
19229  * dbuf list. This function looks for two major things. 1) That the first frame
19230  * has a sequence count of zero. 2) There is a frame with last frame of sequence
19231  * set. 3) That there are no holes in the sequence count. The function will
19232  * return 1 when the sequence is complete, otherwise it will return 0.
19233  **/
19234 static int
19235 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
19236 {
19237 	struct fc_frame_header *hdr;
19238 	struct lpfc_dmabuf *d_buf;
19239 	struct hbq_dmabuf *seq_dmabuf;
19240 	uint32_t fctl;
19241 	int seq_count = 0;
19242 
19243 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19244 	/* make sure first fame of sequence has a sequence count of zero */
19245 	if (hdr->fh_seq_cnt != seq_count)
19246 		return 0;
19247 	fctl = (hdr->fh_f_ctl[0] << 16 |
19248 		hdr->fh_f_ctl[1] << 8 |
19249 		hdr->fh_f_ctl[2]);
19250 	/* If last frame of sequence we can return success. */
19251 	if (fctl & FC_FC_END_SEQ)
19252 		return 1;
19253 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
19254 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19255 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19256 		/* If there is a hole in the sequence count then fail. */
19257 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
19258 			return 0;
19259 		fctl = (hdr->fh_f_ctl[0] << 16 |
19260 			hdr->fh_f_ctl[1] << 8 |
19261 			hdr->fh_f_ctl[2]);
19262 		/* If last frame of sequence we can return success. */
19263 		if (fctl & FC_FC_END_SEQ)
19264 			return 1;
19265 	}
19266 	return 0;
19267 }
19268 
19269 /**
19270  * lpfc_prep_seq - Prep sequence for ULP processing
19271  * @vport: Pointer to the vport on which this sequence was received
19272  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
19273  *
19274  * This function takes a sequence, described by a list of frames, and creates
19275  * a list of iocbq structures to describe the sequence. This iocbq list will be
19276  * used to issue to the generic unsolicited sequence handler. This routine
19277  * returns a pointer to the first iocbq in the list. If the function is unable
19278  * to allocate an iocbq then it throw out the received frames that were not
19279  * able to be described and return a pointer to the first iocbq. If unable to
19280  * allocate any iocbqs (including the first) this function will return NULL.
19281  **/
19282 static struct lpfc_iocbq *
19283 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
19284 {
19285 	struct hbq_dmabuf *hbq_buf;
19286 	struct lpfc_dmabuf *d_buf, *n_buf;
19287 	struct lpfc_iocbq *first_iocbq, *iocbq;
19288 	struct fc_frame_header *fc_hdr;
19289 	uint32_t sid;
19290 	uint32_t len, tot_len;
19291 
19292 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19293 	/* remove from receive buffer list */
19294 	list_del_init(&seq_dmabuf->hbuf.list);
19295 	lpfc_update_rcv_time_stamp(vport);
19296 	/* get the Remote Port's SID */
19297 	sid = sli4_sid_from_fc_hdr(fc_hdr);
19298 	tot_len = 0;
19299 	/* Get an iocbq struct to fill in. */
19300 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
19301 	if (first_iocbq) {
19302 		/* Initialize the first IOCB. */
19303 		first_iocbq->wcqe_cmpl.total_data_placed = 0;
19304 		bf_set(lpfc_wcqe_c_status, &first_iocbq->wcqe_cmpl,
19305 		       IOSTAT_SUCCESS);
19306 		first_iocbq->vport = vport;
19307 
19308 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
19309 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
19310 			bf_set(els_rsp64_sid, &first_iocbq->wqe.xmit_els_rsp,
19311 			       sli4_did_from_fc_hdr(fc_hdr));
19312 		}
19313 
19314 		bf_set(wqe_ctxt_tag, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19315 		       NO_XRI);
19316 		bf_set(wqe_rcvoxid, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19317 		       be16_to_cpu(fc_hdr->fh_ox_id));
19318 
19319 		/* put the first buffer into the first iocb */
19320 		tot_len = bf_get(lpfc_rcqe_length,
19321 				 &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
19322 
19323 		first_iocbq->cmd_dmabuf = &seq_dmabuf->dbuf;
19324 		first_iocbq->bpl_dmabuf = NULL;
19325 		/* Keep track of the BDE count */
19326 		first_iocbq->wcqe_cmpl.word3 = 1;
19327 
19328 		if (tot_len > LPFC_DATA_BUF_SIZE)
19329 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize =
19330 				LPFC_DATA_BUF_SIZE;
19331 		else
19332 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize = tot_len;
19333 
19334 		first_iocbq->wcqe_cmpl.total_data_placed = tot_len;
19335 		bf_set(wqe_els_did, &first_iocbq->wqe.xmit_els_rsp.wqe_dest,
19336 		       sid);
19337 	}
19338 	iocbq = first_iocbq;
19339 	/*
19340 	 * Each IOCBq can have two Buffers assigned, so go through the list
19341 	 * of buffers for this sequence and save two buffers in each IOCBq
19342 	 */
19343 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
19344 		if (!iocbq) {
19345 			lpfc_in_buf_free(vport->phba, d_buf);
19346 			continue;
19347 		}
19348 		if (!iocbq->bpl_dmabuf) {
19349 			iocbq->bpl_dmabuf = d_buf;
19350 			iocbq->wcqe_cmpl.word3++;
19351 			/* We need to get the size out of the right CQE */
19352 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19353 			len = bf_get(lpfc_rcqe_length,
19354 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19355 			iocbq->unsol_rcv_len = len;
19356 			iocbq->wcqe_cmpl.total_data_placed += len;
19357 			tot_len += len;
19358 		} else {
19359 			iocbq = lpfc_sli_get_iocbq(vport->phba);
19360 			if (!iocbq) {
19361 				if (first_iocbq) {
19362 					bf_set(lpfc_wcqe_c_status,
19363 					       &first_iocbq->wcqe_cmpl,
19364 					       IOSTAT_SUCCESS);
19365 					first_iocbq->wcqe_cmpl.parameter =
19366 						IOERR_NO_RESOURCES;
19367 				}
19368 				lpfc_in_buf_free(vport->phba, d_buf);
19369 				continue;
19370 			}
19371 			/* We need to get the size out of the right CQE */
19372 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19373 			len = bf_get(lpfc_rcqe_length,
19374 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19375 			iocbq->cmd_dmabuf = d_buf;
19376 			iocbq->bpl_dmabuf = NULL;
19377 			iocbq->wcqe_cmpl.word3 = 1;
19378 
19379 			if (len > LPFC_DATA_BUF_SIZE)
19380 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19381 					LPFC_DATA_BUF_SIZE;
19382 			else
19383 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19384 					len;
19385 
19386 			tot_len += len;
19387 			iocbq->wcqe_cmpl.total_data_placed = tot_len;
19388 			bf_set(wqe_els_did, &iocbq->wqe.xmit_els_rsp.wqe_dest,
19389 			       sid);
19390 			list_add_tail(&iocbq->list, &first_iocbq->list);
19391 		}
19392 	}
19393 	/* Free the sequence's header buffer */
19394 	if (!first_iocbq)
19395 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
19396 
19397 	return first_iocbq;
19398 }
19399 
19400 static void
19401 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
19402 			  struct hbq_dmabuf *seq_dmabuf)
19403 {
19404 	struct fc_frame_header *fc_hdr;
19405 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
19406 	struct lpfc_hba *phba = vport->phba;
19407 
19408 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19409 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
19410 	if (!iocbq) {
19411 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19412 				"2707 Ring %d handler: Failed to allocate "
19413 				"iocb Rctl x%x Type x%x received\n",
19414 				LPFC_ELS_RING,
19415 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19416 		return;
19417 	}
19418 	if (!lpfc_complete_unsol_iocb(phba,
19419 				      phba->sli4_hba.els_wq->pring,
19420 				      iocbq, fc_hdr->fh_r_ctl,
19421 				      fc_hdr->fh_type)) {
19422 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19423 				"2540 Ring %d handler: unexpected Rctl "
19424 				"x%x Type x%x received\n",
19425 				LPFC_ELS_RING,
19426 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19427 		lpfc_in_buf_free(phba, &seq_dmabuf->dbuf);
19428 	}
19429 
19430 	/* Free iocb created in lpfc_prep_seq */
19431 	list_for_each_entry_safe(curr_iocb, next_iocb,
19432 				 &iocbq->list, list) {
19433 		list_del_init(&curr_iocb->list);
19434 		lpfc_sli_release_iocbq(phba, curr_iocb);
19435 	}
19436 	lpfc_sli_release_iocbq(phba, iocbq);
19437 }
19438 
19439 static void
19440 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
19441 			    struct lpfc_iocbq *rspiocb)
19442 {
19443 	struct lpfc_dmabuf *pcmd = cmdiocb->cmd_dmabuf;
19444 
19445 	if (pcmd && pcmd->virt)
19446 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19447 	kfree(pcmd);
19448 	lpfc_sli_release_iocbq(phba, cmdiocb);
19449 	lpfc_drain_txq(phba);
19450 }
19451 
19452 static void
19453 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
19454 			      struct hbq_dmabuf *dmabuf)
19455 {
19456 	struct fc_frame_header *fc_hdr;
19457 	struct lpfc_hba *phba = vport->phba;
19458 	struct lpfc_iocbq *iocbq = NULL;
19459 	union  lpfc_wqe128 *pwqe;
19460 	struct lpfc_dmabuf *pcmd = NULL;
19461 	uint32_t frame_len;
19462 	int rc;
19463 	unsigned long iflags;
19464 
19465 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19466 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
19467 
19468 	/* Send the received frame back */
19469 	iocbq = lpfc_sli_get_iocbq(phba);
19470 	if (!iocbq) {
19471 		/* Queue cq event and wakeup worker thread to process it */
19472 		spin_lock_irqsave(&phba->hbalock, iflags);
19473 		list_add_tail(&dmabuf->cq_event.list,
19474 			      &phba->sli4_hba.sp_queue_event);
19475 		spin_unlock_irqrestore(&phba->hbalock, iflags);
19476 		set_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
19477 		lpfc_worker_wake_up(phba);
19478 		return;
19479 	}
19480 
19481 	/* Allocate buffer for command payload */
19482 	pcmd = kmalloc_obj(struct lpfc_dmabuf);
19483 	if (pcmd)
19484 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
19485 					    &pcmd->phys);
19486 	if (!pcmd || !pcmd->virt)
19487 		goto exit;
19488 
19489 	INIT_LIST_HEAD(&pcmd->list);
19490 
19491 	/* copyin the payload */
19492 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
19493 
19494 	iocbq->cmd_dmabuf = pcmd;
19495 	iocbq->vport = vport;
19496 	iocbq->cmd_flag &= ~LPFC_FIP_ELS_ID_MASK;
19497 	iocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
19498 	iocbq->num_bdes = 0;
19499 
19500 	pwqe = &iocbq->wqe;
19501 	/* fill in BDE's for command */
19502 	pwqe->gen_req.bde.addrHigh = putPaddrHigh(pcmd->phys);
19503 	pwqe->gen_req.bde.addrLow = putPaddrLow(pcmd->phys);
19504 	pwqe->gen_req.bde.tus.f.bdeSize = frame_len;
19505 	pwqe->gen_req.bde.tus.f.bdeFlags = BUFF_TYPE_BDE_64;
19506 
19507 	pwqe->send_frame.frame_len = frame_len;
19508 	pwqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((__be32 *)fc_hdr));
19509 	pwqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((__be32 *)fc_hdr + 1));
19510 	pwqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((__be32 *)fc_hdr + 2));
19511 	pwqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((__be32 *)fc_hdr + 3));
19512 	pwqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((__be32 *)fc_hdr + 4));
19513 	pwqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((__be32 *)fc_hdr + 5));
19514 
19515 	pwqe->generic.wqe_com.word7 = 0;
19516 	pwqe->generic.wqe_com.word10 = 0;
19517 
19518 	bf_set(wqe_cmnd, &pwqe->generic.wqe_com, CMD_SEND_FRAME);
19519 	bf_set(wqe_sof, &pwqe->generic.wqe_com, 0x2E); /* SOF byte */
19520 	bf_set(wqe_eof, &pwqe->generic.wqe_com, 0x41); /* EOF byte */
19521 	bf_set(wqe_lenloc, &pwqe->generic.wqe_com, 1);
19522 	bf_set(wqe_xbl, &pwqe->generic.wqe_com, 1);
19523 	bf_set(wqe_dbde, &pwqe->generic.wqe_com, 1);
19524 	bf_set(wqe_xc, &pwqe->generic.wqe_com, 1);
19525 	bf_set(wqe_cmd_type, &pwqe->generic.wqe_com, 0xA);
19526 	bf_set(wqe_cqid, &pwqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
19527 	bf_set(wqe_xri_tag, &pwqe->generic.wqe_com, iocbq->sli4_xritag);
19528 	bf_set(wqe_reqtag, &pwqe->generic.wqe_com, iocbq->iotag);
19529 	bf_set(wqe_class, &pwqe->generic.wqe_com, CLASS3);
19530 	pwqe->generic.wqe_com.abort_tag = iocbq->iotag;
19531 
19532 	iocbq->cmd_cmpl = lpfc_sli4_mds_loopback_cmpl;
19533 
19534 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
19535 	if (rc == IOCB_ERROR)
19536 		goto exit;
19537 
19538 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19539 	return;
19540 
19541 exit:
19542 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
19543 			"2023 Unable to process MDS loopback frame\n");
19544 	if (pcmd && pcmd->virt)
19545 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19546 	kfree(pcmd);
19547 	if (iocbq)
19548 		lpfc_sli_release_iocbq(phba, iocbq);
19549 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19550 }
19551 
19552 /**
19553  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
19554  * @phba: Pointer to HBA context object.
19555  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
19556  *
19557  * This function is called with no lock held. This function processes all
19558  * the received buffers and gives it to upper layers when a received buffer
19559  * indicates that it is the final frame in the sequence. The interrupt
19560  * service routine processes received buffers at interrupt contexts.
19561  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
19562  * appropriate receive function when the final frame in a sequence is received.
19563  **/
19564 void
19565 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
19566 				 struct hbq_dmabuf *dmabuf)
19567 {
19568 	struct hbq_dmabuf *seq_dmabuf;
19569 	struct fc_frame_header *fc_hdr;
19570 	struct lpfc_vport *vport;
19571 	uint32_t fcfi;
19572 	uint32_t did;
19573 
19574 	/* Process each received buffer */
19575 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19576 
19577 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
19578 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
19579 		vport = phba->pport;
19580 		/* Handle MDS Loopback frames */
19581 		if  (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
19582 			lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19583 		else
19584 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19585 		return;
19586 	}
19587 
19588 	/* check to see if this a valid type of frame */
19589 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
19590 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19591 		return;
19592 	}
19593 
19594 	if ((bf_get(lpfc_cqe_code,
19595 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
19596 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
19597 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19598 	else
19599 		fcfi = bf_get(lpfc_rcqe_fcf_id,
19600 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19601 
19602 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
19603 		vport = phba->pport;
19604 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
19605 				"2023 MDS Loopback %d bytes\n",
19606 				bf_get(lpfc_rcqe_length,
19607 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
19608 		/* Handle MDS Loopback frames */
19609 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19610 		return;
19611 	}
19612 
19613 	/* d_id this frame is directed to */
19614 	did = sli4_did_from_fc_hdr(fc_hdr);
19615 
19616 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
19617 	if (!vport) {
19618 		/* throw out the frame */
19619 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19620 		return;
19621 	}
19622 
19623 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
19624 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
19625 		(did != Fabric_DID)) {
19626 		/*
19627 		 * Throw out the frame if we are not pt2pt.
19628 		 * The pt2pt protocol allows for discovery frames
19629 		 * to be received without a registered VPI.
19630 		 */
19631 		if (!test_bit(FC_PT2PT, &vport->fc_flag) ||
19632 		    phba->link_state == LPFC_HBA_READY) {
19633 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19634 			return;
19635 		}
19636 	}
19637 
19638 	/* Handle the basic abort sequence (BA_ABTS) event */
19639 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
19640 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
19641 		return;
19642 	}
19643 
19644 	/* Link this frame */
19645 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
19646 	if (!seq_dmabuf) {
19647 		/* unable to add frame to vport - throw it out */
19648 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19649 		return;
19650 	}
19651 	/* If not last frame in sequence continue processing frames. */
19652 	if (!lpfc_seq_complete(seq_dmabuf))
19653 		return;
19654 
19655 	/* Send the complete sequence to the upper layer protocol */
19656 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
19657 }
19658 
19659 /**
19660  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
19661  * @phba: pointer to lpfc hba data structure.
19662  *
19663  * This routine is invoked to post rpi header templates to the
19664  * HBA consistent with the SLI-4 interface spec.  This routine
19665  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19666  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19667  *
19668  * This routine does not require any locks.  It's usage is expected
19669  * to be driver load or reset recovery when the driver is
19670  * sequential.
19671  *
19672  * Return codes
19673  * 	0 - successful
19674  *      -EIO - The mailbox failed to complete successfully.
19675  * 	When this error occurs, the driver is not guaranteed
19676  *	to have any rpi regions posted to the device and
19677  *	must either attempt to repost the regions or take a
19678  *	fatal error.
19679  **/
19680 int
19681 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
19682 {
19683 	struct lpfc_rpi_hdr *rpi_page;
19684 	uint32_t rc = 0;
19685 	uint16_t lrpi = 0;
19686 
19687 	/* SLI4 ports that support extents do not require RPI headers. */
19688 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19689 		goto exit;
19690 	if (phba->sli4_hba.extents_in_use)
19691 		return -EIO;
19692 
19693 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
19694 		/*
19695 		 * Assign the rpi headers a physical rpi only if the driver
19696 		 * has not initialized those resources.  A port reset only
19697 		 * needs the headers posted.
19698 		 */
19699 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
19700 		    LPFC_RPI_RSRC_RDY)
19701 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19702 
19703 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
19704 		if (rc != MBX_SUCCESS) {
19705 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19706 					"2008 Error %d posting all rpi "
19707 					"headers\n", rc);
19708 			rc = -EIO;
19709 			break;
19710 		}
19711 	}
19712 
19713  exit:
19714 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
19715 	       LPFC_RPI_RSRC_RDY);
19716 	return rc;
19717 }
19718 
19719 /**
19720  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
19721  * @phba: pointer to lpfc hba data structure.
19722  * @rpi_page:  pointer to the rpi memory region.
19723  *
19724  * This routine is invoked to post a single rpi header to the
19725  * HBA consistent with the SLI-4 interface spec.  This memory region
19726  * maps up to 64 rpi context regions.
19727  *
19728  * Return codes
19729  * 	0 - successful
19730  * 	-ENOMEM - No available memory
19731  *      -EIO - The mailbox failed to complete successfully.
19732  **/
19733 int
19734 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
19735 {
19736 	LPFC_MBOXQ_t *mboxq;
19737 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
19738 	uint32_t rc = 0;
19739 	uint32_t shdr_status, shdr_add_status;
19740 	union lpfc_sli4_cfg_shdr *shdr;
19741 
19742 	/* SLI4 ports that support extents do not require RPI headers. */
19743 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19744 		return rc;
19745 	if (phba->sli4_hba.extents_in_use)
19746 		return -EIO;
19747 
19748 	/* The port is notified of the header region via a mailbox command. */
19749 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19750 	if (!mboxq) {
19751 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19752 				"2001 Unable to allocate memory for issuing "
19753 				"SLI_CONFIG_SPECIAL mailbox command\n");
19754 		return -ENOMEM;
19755 	}
19756 
19757 	/* Post all rpi memory regions to the port. */
19758 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
19759 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19760 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
19761 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
19762 			 sizeof(struct lpfc_sli4_cfg_mhdr),
19763 			 LPFC_SLI4_MBX_EMBED);
19764 
19765 
19766 	/* Post the physical rpi to the port for this rpi header. */
19767 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
19768 	       rpi_page->start_rpi);
19769 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
19770 	       hdr_tmpl, rpi_page->page_count);
19771 
19772 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
19773 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
19774 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19775 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
19776 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19777 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19778 	mempool_free(mboxq, phba->mbox_mem_pool);
19779 	if (shdr_status || shdr_add_status || rc) {
19780 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19781 				"2514 POST_RPI_HDR mailbox failed with "
19782 				"status x%x add_status x%x, mbx status x%x\n",
19783 				shdr_status, shdr_add_status, rc);
19784 		rc = -ENXIO;
19785 	} else {
19786 		/*
19787 		 * The next_rpi stores the next logical module-64 rpi value used
19788 		 * to post physical rpis in subsequent rpi postings.
19789 		 */
19790 		spin_lock_irq(&phba->hbalock);
19791 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
19792 		spin_unlock_irq(&phba->hbalock);
19793 	}
19794 	return rc;
19795 }
19796 
19797 /**
19798  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
19799  * @phba: pointer to lpfc hba data structure.
19800  *
19801  * This routine is invoked to post rpi header templates to the
19802  * HBA consistent with the SLI-4 interface spec.  This routine
19803  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19804  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19805  *
19806  * Returns
19807  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
19808  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
19809  **/
19810 int
19811 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
19812 {
19813 	unsigned long rpi;
19814 	uint16_t max_rpi, rpi_limit;
19815 	uint16_t rpi_remaining, lrpi = 0;
19816 	struct lpfc_rpi_hdr *rpi_hdr;
19817 	unsigned long iflag;
19818 
19819 	/*
19820 	 * Fetch the next logical rpi.  Because this index is logical,
19821 	 * the  driver starts at 0 each time.
19822 	 */
19823 	spin_lock_irqsave(&phba->hbalock, iflag);
19824 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
19825 	rpi_limit = phba->sli4_hba.next_rpi;
19826 
19827 	rpi = find_first_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit);
19828 	if (rpi >= rpi_limit)
19829 		rpi = LPFC_RPI_ALLOC_ERROR;
19830 	else {
19831 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
19832 		phba->sli4_hba.max_cfg_param.rpi_used++;
19833 		phba->sli4_hba.rpi_count++;
19834 	}
19835 	lpfc_printf_log(phba, KERN_INFO,
19836 			LOG_NODE | LOG_DISCOVERY,
19837 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
19838 			(int) rpi, max_rpi, rpi_limit);
19839 
19840 	/*
19841 	 * Don't try to allocate more rpi header regions if the device limit
19842 	 * has been exhausted.
19843 	 */
19844 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
19845 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
19846 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19847 		return rpi;
19848 	}
19849 
19850 	/*
19851 	 * RPI header postings are not required for SLI4 ports capable of
19852 	 * extents.
19853 	 */
19854 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
19855 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19856 		return rpi;
19857 	}
19858 
19859 	/*
19860 	 * If the driver is running low on rpi resources, allocate another
19861 	 * page now.  Note that the next_rpi value is used because
19862 	 * it represents how many are actually in use whereas max_rpi notes
19863 	 * how many are supported max by the device.
19864 	 */
19865 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
19866 	spin_unlock_irqrestore(&phba->hbalock, iflag);
19867 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
19868 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
19869 		if (!rpi_hdr) {
19870 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19871 					"2002 Error Could not grow rpi "
19872 					"count\n");
19873 		} else {
19874 			lrpi = rpi_hdr->start_rpi;
19875 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19876 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
19877 		}
19878 	}
19879 
19880 	return rpi;
19881 }
19882 
19883 /**
19884  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
19885  * @phba: pointer to lpfc hba data structure.
19886  * @rpi: rpi to free
19887  *
19888  * This routine is invoked to release an rpi to the pool of
19889  * available rpis maintained by the driver.
19890  **/
19891 static void
19892 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19893 {
19894 	/*
19895 	 * if the rpi value indicates a prior unreg has already
19896 	 * been done, skip the unreg.
19897 	 */
19898 	if (rpi == LPFC_RPI_ALLOC_ERROR)
19899 		return;
19900 
19901 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
19902 		phba->sli4_hba.rpi_count--;
19903 		phba->sli4_hba.max_cfg_param.rpi_used--;
19904 	} else {
19905 		lpfc_printf_log(phba, KERN_INFO,
19906 				LOG_NODE | LOG_DISCOVERY,
19907 				"2016 rpi %x not inuse\n",
19908 				rpi);
19909 	}
19910 }
19911 
19912 /**
19913  * lpfc_sli4_free_rpi - Release an rpi for reuse.
19914  * @phba: pointer to lpfc hba data structure.
19915  * @rpi: rpi to free
19916  *
19917  * This routine is invoked to release an rpi to the pool of
19918  * available rpis maintained by the driver.
19919  **/
19920 void
19921 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19922 {
19923 	spin_lock_irq(&phba->hbalock);
19924 	__lpfc_sli4_free_rpi(phba, rpi);
19925 	spin_unlock_irq(&phba->hbalock);
19926 }
19927 
19928 /**
19929  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19930  * @phba: pointer to lpfc hba data structure.
19931  *
19932  * This routine is invoked to remove the memory region that
19933  * provided rpi via a bitmask.
19934  **/
19935 void
19936 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19937 {
19938 	kfree(phba->sli4_hba.rpi_bmask);
19939 	kfree(phba->sli4_hba.rpi_ids);
19940 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19941 }
19942 
19943 /**
19944  * lpfc_sli4_resume_rpi - Resume traffic relative to an RPI
19945  * @ndlp: pointer to lpfc nodelist data structure.
19946  * @cmpl: completion call-back.
19947  * @iocbq: data to load as mbox ctx_u information
19948  *
19949  * Return codes
19950  *	0 - successful
19951  *	-ENOMEM - No available memory
19952  *	-EIO - The mailbox failed to complete successfully.
19953  **/
19954 int
19955 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19956 		     void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *),
19957 		     struct lpfc_iocbq *iocbq)
19958 {
19959 	LPFC_MBOXQ_t *mboxq;
19960 	struct lpfc_hba *phba = ndlp->phba;
19961 	int rc;
19962 
19963 	/* The port is notified of the header region via a mailbox command. */
19964 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19965 	if (!mboxq)
19966 		return -ENOMEM;
19967 
19968 	/* If cmpl assigned, then this nlp_get pairs with
19969 	 * lpfc_mbx_cmpl_resume_rpi.
19970 	 *
19971 	 * Else cmpl is NULL, then this nlp_get pairs with
19972 	 * lpfc_sli_def_mbox_cmpl.
19973 	 */
19974 	if (!lpfc_nlp_get(ndlp)) {
19975 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19976 				"2122 %s: Failed to get nlp ref\n",
19977 				__func__);
19978 		mempool_free(mboxq, phba->mbox_mem_pool);
19979 		return -EIO;
19980 	}
19981 
19982 	lpfc_resume_rpi(mboxq, ndlp);
19983 	if (cmpl) {
19984 		mboxq->mbox_cmpl = cmpl;
19985 		mboxq->ctx_u.save_iocb = iocbq;
19986 	} else
19987 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19988 	mboxq->ctx_ndlp = ndlp;
19989 	mboxq->vport = ndlp->vport;
19990 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19991 	if (rc == MBX_NOT_FINISHED) {
19992 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19993 				"2010 Resume RPI Mailbox failed "
19994 				"status %d, mbxStatus x%x\n", rc,
19995 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19996 		lpfc_nlp_put(ndlp);
19997 		mempool_free(mboxq, phba->mbox_mem_pool);
19998 		return -EIO;
19999 	}
20000 	return 0;
20001 }
20002 
20003 /**
20004  * lpfc_sli4_init_vpi - Initialize a vpi with the port
20005  * @vport: Pointer to the vport for which the vpi is being initialized
20006  *
20007  * This routine is invoked to activate a vpi with the port.
20008  *
20009  * Returns:
20010  *    0 success
20011  *    -Evalue otherwise
20012  **/
20013 int
20014 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
20015 {
20016 	LPFC_MBOXQ_t *mboxq;
20017 	int rc = 0;
20018 	int retval = MBX_SUCCESS;
20019 	uint32_t mbox_tmo;
20020 	struct lpfc_hba *phba = vport->phba;
20021 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20022 	if (!mboxq)
20023 		return -ENOMEM;
20024 	lpfc_init_vpi(phba, mboxq, vport->vpi);
20025 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
20026 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
20027 	if (rc != MBX_SUCCESS) {
20028 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
20029 				"2022 INIT VPI Mailbox failed "
20030 				"status %d, mbxStatus x%x\n", rc,
20031 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
20032 		retval = -EIO;
20033 	}
20034 	if (rc != MBX_TIMEOUT)
20035 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
20036 
20037 	return retval;
20038 }
20039 
20040 /**
20041  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
20042  * @phba: pointer to lpfc hba data structure.
20043  * @mboxq: Pointer to mailbox object.
20044  *
20045  * This routine is invoked to manually add a single FCF record. The caller
20046  * must pass a completely initialized FCF_Record.  This routine takes
20047  * care of the nonembedded mailbox operations.
20048  **/
20049 static void
20050 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
20051 {
20052 	void *virt_addr;
20053 	union lpfc_sli4_cfg_shdr *shdr;
20054 	uint32_t shdr_status, shdr_add_status;
20055 
20056 	virt_addr = mboxq->sge_array->addr[0];
20057 	/* The IOCTL status is embedded in the mailbox subheader. */
20058 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
20059 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
20060 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
20061 
20062 	if ((shdr_status || shdr_add_status) &&
20063 		(shdr_status != STATUS_FCF_IN_USE))
20064 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20065 			"2558 ADD_FCF_RECORD mailbox failed with "
20066 			"status x%x add_status x%x\n",
20067 			shdr_status, shdr_add_status);
20068 
20069 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
20070 }
20071 
20072 /**
20073  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
20074  * @phba: pointer to lpfc hba data structure.
20075  * @fcf_record:  pointer to the initialized fcf record to add.
20076  *
20077  * This routine is invoked to manually add a single FCF record. The caller
20078  * must pass a completely initialized FCF_Record.  This routine takes
20079  * care of the nonembedded mailbox operations.
20080  **/
20081 int
20082 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
20083 {
20084 	int rc = 0;
20085 	LPFC_MBOXQ_t *mboxq;
20086 	uint8_t *bytep;
20087 	void *virt_addr;
20088 	struct lpfc_mbx_sge sge;
20089 	uint32_t alloc_len, req_len;
20090 	uint32_t fcfindex;
20091 
20092 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20093 	if (!mboxq) {
20094 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20095 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
20096 		return -ENOMEM;
20097 	}
20098 
20099 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
20100 		  sizeof(uint32_t);
20101 
20102 	/* Allocate DMA memory and set up the non-embedded mailbox command */
20103 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
20104 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
20105 				     req_len, LPFC_SLI4_MBX_NEMBED);
20106 	if (alloc_len < req_len) {
20107 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20108 			"2523 Allocated DMA memory size (x%x) is "
20109 			"less than the requested DMA memory "
20110 			"size (x%x)\n", alloc_len, req_len);
20111 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20112 		return -ENOMEM;
20113 	}
20114 
20115 	/*
20116 	 * Get the first SGE entry from the non-embedded DMA memory.  This
20117 	 * routine only uses a single SGE.
20118 	 */
20119 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
20120 	virt_addr = mboxq->sge_array->addr[0];
20121 	/*
20122 	 * Configure the FCF record for FCFI 0.  This is the driver's
20123 	 * hardcoded default and gets used in nonFIP mode.
20124 	 */
20125 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
20126 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
20127 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
20128 
20129 	/*
20130 	 * Copy the fcf_index and the FCF Record Data. The data starts after
20131 	 * the FCoE header plus word10. The data copy needs to be endian
20132 	 * correct.
20133 	 */
20134 	bytep += sizeof(uint32_t);
20135 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
20136 	mboxq->vport = phba->pport;
20137 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
20138 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20139 	if (rc == MBX_NOT_FINISHED) {
20140 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20141 			"2515 ADD_FCF_RECORD mailbox failed with "
20142 			"status 0x%x\n", rc);
20143 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20144 		rc = -EIO;
20145 	} else
20146 		rc = 0;
20147 
20148 	return rc;
20149 }
20150 
20151 /**
20152  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
20153  * @phba: pointer to lpfc hba data structure.
20154  * @fcf_record:  pointer to the fcf record to write the default data.
20155  * @fcf_index: FCF table entry index.
20156  *
20157  * This routine is invoked to build the driver's default FCF record.  The
20158  * values used are hardcoded.  This routine handles memory initialization.
20159  *
20160  **/
20161 void
20162 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
20163 				struct fcf_record *fcf_record,
20164 				uint16_t fcf_index)
20165 {
20166 	memset(fcf_record, 0, sizeof(struct fcf_record));
20167 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
20168 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
20169 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
20170 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
20171 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
20172 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
20173 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
20174 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
20175 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
20176 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
20177 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
20178 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
20179 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
20180 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
20181 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
20182 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
20183 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
20184 	/* Set the VLAN bit map */
20185 	if (phba->valid_vlan) {
20186 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
20187 			= 1 << (phba->vlan_id % 8);
20188 	}
20189 }
20190 
20191 /**
20192  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
20193  * @phba: pointer to lpfc hba data structure.
20194  * @fcf_index: FCF table entry offset.
20195  *
20196  * This routine is invoked to scan the entire FCF table by reading FCF
20197  * record and processing it one at a time starting from the @fcf_index
20198  * for initial FCF discovery or fast FCF failover rediscovery.
20199  *
20200  * Return 0 if the mailbox command is submitted successfully, none 0
20201  * otherwise.
20202  **/
20203 int
20204 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20205 {
20206 	int rc = 0, error;
20207 	LPFC_MBOXQ_t *mboxq;
20208 
20209 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
20210 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
20211 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20212 	if (!mboxq) {
20213 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20214 				"2000 Failed to allocate mbox for "
20215 				"READ_FCF cmd\n");
20216 		error = -ENOMEM;
20217 		goto fail_fcf_scan;
20218 	}
20219 	/* Construct the read FCF record mailbox command */
20220 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20221 	if (rc) {
20222 		error = -EINVAL;
20223 		goto fail_fcf_scan;
20224 	}
20225 	/* Issue the mailbox command asynchronously */
20226 	mboxq->vport = phba->pport;
20227 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
20228 
20229 	set_bit(FCF_TS_INPROG, &phba->hba_flag);
20230 
20231 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20232 	if (rc == MBX_NOT_FINISHED)
20233 		error = -EIO;
20234 	else {
20235 		/* Reset eligible FCF count for new scan */
20236 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
20237 			phba->fcf.eligible_fcf_cnt = 0;
20238 		error = 0;
20239 	}
20240 fail_fcf_scan:
20241 	if (error) {
20242 		if (mboxq)
20243 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
20244 		/* FCF scan failed, clear FCF_TS_INPROG flag */
20245 		clear_bit(FCF_TS_INPROG, &phba->hba_flag);
20246 	}
20247 	return error;
20248 }
20249 
20250 /**
20251  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
20252  * @phba: pointer to lpfc hba data structure.
20253  * @fcf_index: FCF table entry offset.
20254  *
20255  * This routine is invoked to read an FCF record indicated by @fcf_index
20256  * and to use it for FLOGI roundrobin FCF failover.
20257  *
20258  * Return 0 if the mailbox command is submitted successfully, none 0
20259  * otherwise.
20260  **/
20261 int
20262 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20263 {
20264 	int rc = 0, error;
20265 	LPFC_MBOXQ_t *mboxq;
20266 
20267 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20268 	if (!mboxq) {
20269 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20270 				"2763 Failed to allocate mbox for "
20271 				"READ_FCF cmd\n");
20272 		error = -ENOMEM;
20273 		goto fail_fcf_read;
20274 	}
20275 	/* Construct the read FCF record mailbox command */
20276 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20277 	if (rc) {
20278 		error = -EINVAL;
20279 		goto fail_fcf_read;
20280 	}
20281 	/* Issue the mailbox command asynchronously */
20282 	mboxq->vport = phba->pport;
20283 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
20284 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20285 	if (rc == MBX_NOT_FINISHED)
20286 		error = -EIO;
20287 	else
20288 		error = 0;
20289 
20290 fail_fcf_read:
20291 	if (error && mboxq)
20292 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20293 	return error;
20294 }
20295 
20296 /**
20297  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
20298  * @phba: pointer to lpfc hba data structure.
20299  * @fcf_index: FCF table entry offset.
20300  *
20301  * This routine is invoked to read an FCF record indicated by @fcf_index to
20302  * determine whether it's eligible for FLOGI roundrobin failover list.
20303  *
20304  * Return 0 if the mailbox command is submitted successfully, none 0
20305  * otherwise.
20306  **/
20307 int
20308 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20309 {
20310 	int rc = 0, error;
20311 	LPFC_MBOXQ_t *mboxq;
20312 
20313 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20314 	if (!mboxq) {
20315 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20316 				"2758 Failed to allocate mbox for "
20317 				"READ_FCF cmd\n");
20318 				error = -ENOMEM;
20319 				goto fail_fcf_read;
20320 	}
20321 	/* Construct the read FCF record mailbox command */
20322 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20323 	if (rc) {
20324 		error = -EINVAL;
20325 		goto fail_fcf_read;
20326 	}
20327 	/* Issue the mailbox command asynchronously */
20328 	mboxq->vport = phba->pport;
20329 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
20330 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20331 	if (rc == MBX_NOT_FINISHED)
20332 		error = -EIO;
20333 	else
20334 		error = 0;
20335 
20336 fail_fcf_read:
20337 	if (error && mboxq)
20338 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20339 	return error;
20340 }
20341 
20342 /**
20343  * lpfc_check_next_fcf_pri_level
20344  * @phba: pointer to the lpfc_hba struct for this port.
20345  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
20346  * routine when the rr_bmask is empty. The FCF indecies are put into the
20347  * rr_bmask based on their priority level. Starting from the highest priority
20348  * to the lowest. The most likely FCF candidate will be in the highest
20349  * priority group. When this routine is called it searches the fcf_pri list for
20350  * next lowest priority group and repopulates the rr_bmask with only those
20351  * fcf_indexes.
20352  * returns:
20353  * 1=success 0=failure
20354  **/
20355 static int
20356 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
20357 {
20358 	uint16_t next_fcf_pri;
20359 	uint16_t last_index;
20360 	struct lpfc_fcf_pri *fcf_pri;
20361 	int rc;
20362 	int ret = 0;
20363 
20364 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20365 			LPFC_SLI4_FCF_TBL_INDX_MAX);
20366 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20367 			"3060 Last IDX %d\n", last_index);
20368 
20369 	/* Verify the priority list has 2 or more entries */
20370 	spin_lock_irq(&phba->hbalock);
20371 	if (list_empty(&phba->fcf.fcf_pri_list) ||
20372 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
20373 		spin_unlock_irq(&phba->hbalock);
20374 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20375 			"3061 Last IDX %d\n", last_index);
20376 		return 0; /* Empty rr list */
20377 	}
20378 	spin_unlock_irq(&phba->hbalock);
20379 
20380 	next_fcf_pri = 0;
20381 	/*
20382 	 * Clear the rr_bmask and set all of the bits that are at this
20383 	 * priority.
20384 	 */
20385 	memset(phba->fcf.fcf_rr_bmask, 0,
20386 			sizeof(*phba->fcf.fcf_rr_bmask));
20387 	spin_lock_irq(&phba->hbalock);
20388 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20389 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
20390 			continue;
20391 		/*
20392 		 * the 1st priority that has not FLOGI failed
20393 		 * will be the highest.
20394 		 */
20395 		if (!next_fcf_pri)
20396 			next_fcf_pri = fcf_pri->fcf_rec.priority;
20397 		spin_unlock_irq(&phba->hbalock);
20398 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20399 			rc = lpfc_sli4_fcf_rr_index_set(phba,
20400 						fcf_pri->fcf_rec.fcf_index);
20401 			if (rc)
20402 				return 0;
20403 		}
20404 		spin_lock_irq(&phba->hbalock);
20405 	}
20406 	/*
20407 	 * if next_fcf_pri was not set above and the list is not empty then
20408 	 * we have failed flogis on all of them. So reset flogi failed
20409 	 * and start at the beginning.
20410 	 */
20411 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
20412 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20413 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
20414 			/*
20415 			 * the 1st priority that has not FLOGI failed
20416 			 * will be the highest.
20417 			 */
20418 			if (!next_fcf_pri)
20419 				next_fcf_pri = fcf_pri->fcf_rec.priority;
20420 			spin_unlock_irq(&phba->hbalock);
20421 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20422 				rc = lpfc_sli4_fcf_rr_index_set(phba,
20423 						fcf_pri->fcf_rec.fcf_index);
20424 				if (rc)
20425 					return 0;
20426 			}
20427 			spin_lock_irq(&phba->hbalock);
20428 		}
20429 	} else
20430 		ret = 1;
20431 	spin_unlock_irq(&phba->hbalock);
20432 
20433 	return ret;
20434 }
20435 /**
20436  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
20437  * @phba: pointer to lpfc hba data structure.
20438  *
20439  * This routine is to get the next eligible FCF record index in a round
20440  * robin fashion. If the next eligible FCF record index equals to the
20441  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
20442  * shall be returned, otherwise, the next eligible FCF record's index
20443  * shall be returned.
20444  **/
20445 uint16_t
20446 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
20447 {
20448 	uint16_t next;
20449 
20450 	do {
20451 		for_each_set_bit_wrap(next, phba->fcf.fcf_rr_bmask,
20452 				LPFC_SLI4_FCF_TBL_INDX_MAX, phba->fcf.current_rec.fcf_indx) {
20453 			if (next == phba->fcf.current_rec.fcf_indx)
20454 				continue;
20455 
20456 			if (!(phba->fcf.fcf_pri[next].fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)) {
20457 				lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20458 					"2845 Get next roundrobin failover FCF (x%x)\n", next);
20459 				return next;
20460 			}
20461 
20462 			if (list_is_singular(&phba->fcf.fcf_pri_list))
20463 				return LPFC_FCOE_FCF_NEXT_NONE;
20464 		}
20465 
20466 		/*
20467 		 * If next fcf index is not found check if there are lower
20468 		 * Priority level fcf's in the fcf_priority list.
20469 		 * Set up the rr_bmask with all of the available fcf bits
20470 		 * at that level and continue the selection process.
20471 		 */
20472 	} while (lpfc_check_next_fcf_pri_level(phba));
20473 
20474 	lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
20475 			"2844 No roundrobin failover FCF available\n");
20476 
20477 	return LPFC_FCOE_FCF_NEXT_NONE;
20478 }
20479 
20480 /**
20481  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
20482  * @phba: pointer to lpfc hba data structure.
20483  * @fcf_index: index into the FCF table to 'set'
20484  *
20485  * This routine sets the FCF record index in to the eligible bmask for
20486  * roundrobin failover search. It checks to make sure that the index
20487  * does not go beyond the range of the driver allocated bmask dimension
20488  * before setting the bit.
20489  *
20490  * Returns 0 if the index bit successfully set, otherwise, it returns
20491  * -EINVAL.
20492  **/
20493 int
20494 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
20495 {
20496 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20497 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20498 				"2610 FCF (x%x) reached driver's book "
20499 				"keeping dimension:x%x\n",
20500 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20501 		return -EINVAL;
20502 	}
20503 	/* Set the eligible FCF record index bmask */
20504 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20505 
20506 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20507 			"2790 Set FCF (x%x) to roundrobin FCF failover "
20508 			"bmask\n", fcf_index);
20509 
20510 	return 0;
20511 }
20512 
20513 /**
20514  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
20515  * @phba: pointer to lpfc hba data structure.
20516  * @fcf_index: index into the FCF table to 'clear'
20517  *
20518  * This routine clears the FCF record index from the eligible bmask for
20519  * roundrobin failover search. It checks to make sure that the index
20520  * does not go beyond the range of the driver allocated bmask dimension
20521  * before clearing the bit.
20522  **/
20523 void
20524 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
20525 {
20526 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
20527 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20528 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20529 				"2762 FCF (x%x) reached driver's book "
20530 				"keeping dimension:x%x\n",
20531 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20532 		return;
20533 	}
20534 	/* Clear the eligible FCF record index bmask */
20535 	spin_lock_irq(&phba->hbalock);
20536 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
20537 				 list) {
20538 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
20539 			list_del_init(&fcf_pri->list);
20540 			break;
20541 		}
20542 	}
20543 	spin_unlock_irq(&phba->hbalock);
20544 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20545 
20546 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20547 			"2791 Clear FCF (x%x) from roundrobin failover "
20548 			"bmask\n", fcf_index);
20549 }
20550 
20551 /**
20552  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
20553  * @phba: pointer to lpfc hba data structure.
20554  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
20555  *
20556  * This routine is the completion routine for the rediscover FCF table mailbox
20557  * command. If the mailbox command returned failure, it will try to stop the
20558  * FCF rediscover wait timer.
20559  **/
20560 static void
20561 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
20562 {
20563 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20564 	uint32_t shdr_status, shdr_add_status;
20565 
20566 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20567 
20568 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20569 			     &redisc_fcf->header.cfg_shdr.response);
20570 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20571 			     &redisc_fcf->header.cfg_shdr.response);
20572 	if (shdr_status || shdr_add_status) {
20573 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20574 				"2746 Requesting for FCF rediscovery failed "
20575 				"status x%x add_status x%x\n",
20576 				shdr_status, shdr_add_status);
20577 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
20578 			spin_lock_irq(&phba->hbalock);
20579 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
20580 			spin_unlock_irq(&phba->hbalock);
20581 			/*
20582 			 * CVL event triggered FCF rediscover request failed,
20583 			 * last resort to re-try current registered FCF entry.
20584 			 */
20585 			lpfc_retry_pport_discovery(phba);
20586 		} else {
20587 			spin_lock_irq(&phba->hbalock);
20588 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
20589 			spin_unlock_irq(&phba->hbalock);
20590 			/*
20591 			 * DEAD FCF event triggered FCF rediscover request
20592 			 * failed, last resort to fail over as a link down
20593 			 * to FCF registration.
20594 			 */
20595 			lpfc_sli4_fcf_dead_failthrough(phba);
20596 		}
20597 	} else {
20598 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20599 				"2775 Start FCF rediscover quiescent timer\n");
20600 		/*
20601 		 * Start FCF rediscovery wait timer for pending FCF
20602 		 * before rescan FCF record table.
20603 		 */
20604 		lpfc_fcf_redisc_wait_start_timer(phba);
20605 	}
20606 
20607 	mempool_free(mbox, phba->mbox_mem_pool);
20608 }
20609 
20610 /**
20611  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
20612  * @phba: pointer to lpfc hba data structure.
20613  *
20614  * This routine is invoked to request for rediscovery of the entire FCF table
20615  * by the port.
20616  **/
20617 int
20618 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
20619 {
20620 	LPFC_MBOXQ_t *mbox;
20621 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20622 	int rc, length;
20623 
20624 	/* Cancel retry delay timers to all vports before FCF rediscover */
20625 	lpfc_cancel_all_vport_retry_delay_timer(phba);
20626 
20627 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20628 	if (!mbox) {
20629 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20630 				"2745 Failed to allocate mbox for "
20631 				"requesting FCF rediscover.\n");
20632 		return -ENOMEM;
20633 	}
20634 
20635 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
20636 		  sizeof(struct lpfc_sli4_cfg_mhdr));
20637 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
20638 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
20639 			 length, LPFC_SLI4_MBX_EMBED);
20640 
20641 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20642 	/* Set count to 0 for invalidating the entire FCF database */
20643 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
20644 
20645 	/* Issue the mailbox command asynchronously */
20646 	mbox->vport = phba->pport;
20647 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
20648 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
20649 
20650 	if (rc == MBX_NOT_FINISHED) {
20651 		mempool_free(mbox, phba->mbox_mem_pool);
20652 		return -EIO;
20653 	}
20654 	return 0;
20655 }
20656 
20657 /**
20658  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
20659  * @phba: pointer to lpfc hba data structure.
20660  *
20661  * This function is the failover routine as a last resort to the FCF DEAD
20662  * event when driver failed to perform fast FCF failover.
20663  **/
20664 void
20665 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
20666 {
20667 	uint32_t link_state;
20668 
20669 	/*
20670 	 * Last resort as FCF DEAD event failover will treat this as
20671 	 * a link down, but save the link state because we don't want
20672 	 * it to be changed to Link Down unless it is already down.
20673 	 */
20674 	link_state = phba->link_state;
20675 	lpfc_linkdown(phba);
20676 	phba->link_state = link_state;
20677 
20678 	/* Unregister FCF if no devices connected to it */
20679 	lpfc_unregister_unused_fcf(phba);
20680 }
20681 
20682 /**
20683  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
20684  * @phba: pointer to lpfc hba data structure.
20685  * @rgn23_data: pointer to configure region 23 data.
20686  *
20687  * This function gets SLI3 port configure region 23 data through memory dump
20688  * mailbox command. When it successfully retrieves data, the size of the data
20689  * will be returned, otherwise, 0 will be returned.
20690  **/
20691 static uint32_t
20692 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20693 {
20694 	LPFC_MBOXQ_t *pmb = NULL;
20695 	MAILBOX_t *mb;
20696 	uint32_t offset = 0;
20697 	int rc;
20698 
20699 	if (!rgn23_data)
20700 		return 0;
20701 
20702 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20703 	if (!pmb) {
20704 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20705 				"2600 failed to allocate mailbox memory\n");
20706 		return 0;
20707 	}
20708 	mb = &pmb->u.mb;
20709 
20710 	do {
20711 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
20712 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
20713 
20714 		if (rc != MBX_SUCCESS) {
20715 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20716 					"2601 failed to read config "
20717 					"region 23, rc 0x%x Status 0x%x\n",
20718 					rc, mb->mbxStatus);
20719 			mb->un.varDmp.word_cnt = 0;
20720 		}
20721 		/*
20722 		 * dump mem may return a zero when finished or we got a
20723 		 * mailbox error, either way we are done.
20724 		 */
20725 		if (mb->un.varDmp.word_cnt == 0)
20726 			break;
20727 
20728 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
20729 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
20730 
20731 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
20732 				       rgn23_data + offset,
20733 				       mb->un.varDmp.word_cnt);
20734 		offset += mb->un.varDmp.word_cnt;
20735 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
20736 
20737 	mempool_free(pmb, phba->mbox_mem_pool);
20738 	return offset;
20739 }
20740 
20741 /**
20742  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
20743  * @phba: pointer to lpfc hba data structure.
20744  * @rgn23_data: pointer to configure region 23 data.
20745  *
20746  * This function gets SLI4 port configure region 23 data through memory dump
20747  * mailbox command. When it successfully retrieves data, the size of the data
20748  * will be returned, otherwise, 0 will be returned.
20749  **/
20750 static uint32_t
20751 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20752 {
20753 	LPFC_MBOXQ_t *mboxq = NULL;
20754 	struct lpfc_dmabuf *mp = NULL;
20755 	struct lpfc_mqe *mqe;
20756 	uint32_t data_length = 0;
20757 	int rc;
20758 
20759 	if (!rgn23_data)
20760 		return 0;
20761 
20762 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20763 	if (!mboxq) {
20764 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20765 				"3105 failed to allocate mailbox memory\n");
20766 		return 0;
20767 	}
20768 
20769 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
20770 		goto out;
20771 	mqe = &mboxq->u.mqe;
20772 	mp = mboxq->ctx_buf;
20773 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
20774 	if (rc)
20775 		goto out;
20776 	data_length = mqe->un.mb_words[5];
20777 	if (data_length == 0)
20778 		goto out;
20779 	if (data_length > DMP_RGN23_SIZE) {
20780 		data_length = 0;
20781 		goto out;
20782 	}
20783 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
20784 out:
20785 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
20786 	return data_length;
20787 }
20788 
20789 /**
20790  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
20791  * @phba: pointer to lpfc hba data structure.
20792  *
20793  * This function read region 23 and parse TLV for port status to
20794  * decide if the user disaled the port. If the TLV indicates the
20795  * port is disabled, the hba_flag is set accordingly.
20796  **/
20797 void
20798 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
20799 {
20800 	uint8_t *rgn23_data = NULL;
20801 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
20802 	uint32_t offset = 0;
20803 
20804 	/* Get adapter Region 23 data */
20805 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
20806 	if (!rgn23_data)
20807 		goto out;
20808 
20809 	if (phba->sli_rev < LPFC_SLI_REV4)
20810 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
20811 	else {
20812 		if_type = bf_get(lpfc_sli_intf_if_type,
20813 				 &phba->sli4_hba.sli_intf);
20814 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
20815 			goto out;
20816 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
20817 	}
20818 
20819 	if (!data_size)
20820 		goto out;
20821 
20822 	/* Check the region signature first */
20823 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
20824 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20825 			"2619 Config region 23 has bad signature\n");
20826 			goto out;
20827 	}
20828 	offset += 4;
20829 
20830 	/* Check the data structure version */
20831 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
20832 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20833 			"2620 Config region 23 has bad version\n");
20834 		goto out;
20835 	}
20836 	offset += 4;
20837 
20838 	/* Parse TLV entries in the region */
20839 	while (offset < data_size) {
20840 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
20841 			break;
20842 		/*
20843 		 * If the TLV is not driver specific TLV or driver id is
20844 		 * not linux driver id, skip the record.
20845 		 */
20846 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
20847 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
20848 		    (rgn23_data[offset + 3] != 0)) {
20849 			offset += rgn23_data[offset + 1] * 4 + 4;
20850 			continue;
20851 		}
20852 
20853 		/* Driver found a driver specific TLV in the config region */
20854 		sub_tlv_len = rgn23_data[offset + 1] * 4;
20855 		offset += 4;
20856 		tlv_offset = 0;
20857 
20858 		/*
20859 		 * Search for configured port state sub-TLV.
20860 		 */
20861 		while ((offset < data_size) &&
20862 			(tlv_offset < sub_tlv_len)) {
20863 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
20864 				offset += 4;
20865 				tlv_offset += 4;
20866 				break;
20867 			}
20868 			if (rgn23_data[offset] != PORT_STE_TYPE) {
20869 				offset += rgn23_data[offset + 1] * 4 + 4;
20870 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
20871 				continue;
20872 			}
20873 
20874 			/* This HBA contains PORT_STE configured */
20875 			if (!rgn23_data[offset + 2])
20876 				set_bit(LINK_DISABLED, &phba->hba_flag);
20877 
20878 			goto out;
20879 		}
20880 	}
20881 
20882 out:
20883 	kfree(rgn23_data);
20884 	return;
20885 }
20886 
20887 /**
20888  * lpfc_log_fw_write_cmpl - logs firmware write completion status
20889  * @phba: pointer to lpfc hba data structure
20890  * @shdr_status: wr_object rsp's status field
20891  * @shdr_add_status: wr_object rsp's add_status field
20892  * @shdr_add_status_2: wr_object rsp's add_status_2 field
20893  * @shdr_change_status: wr_object rsp's change_status field
20894  * @shdr_csf: wr_object rsp's csf bit
20895  *
20896  * This routine is intended to be called after a firmware write completes.
20897  * It will log next action items to be performed by the user to instantiate
20898  * the newly downloaded firmware or reason for incompatibility.
20899  **/
20900 static void
20901 lpfc_log_fw_write_cmpl(struct lpfc_hba *phba, u32 shdr_status,
20902 		       u32 shdr_add_status, u32 shdr_add_status_2,
20903 		       u32 shdr_change_status, u32 shdr_csf)
20904 {
20905 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20906 			"4198 %s: flash_id x%02x, asic_rev x%02x, "
20907 			"status x%02x, add_status x%02x, add_status_2 x%02x, "
20908 			"change_status x%02x, csf %01x\n", __func__,
20909 			phba->sli4_hba.flash_id, phba->sli4_hba.asic_rev,
20910 			shdr_status, shdr_add_status, shdr_add_status_2,
20911 			shdr_change_status, shdr_csf);
20912 
20913 	if (shdr_add_status == LPFC_ADD_STATUS_INCOMPAT_OBJ) {
20914 		switch (shdr_add_status_2) {
20915 		case LPFC_ADD_STATUS_2_INCOMPAT_FLASH:
20916 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20917 				     "4199 Firmware write failed: "
20918 				     "image incompatible with flash x%02x\n",
20919 				     phba->sli4_hba.flash_id);
20920 			break;
20921 		case LPFC_ADD_STATUS_2_INCORRECT_ASIC:
20922 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20923 				     "4200 Firmware write failed: "
20924 				     "image incompatible with ASIC "
20925 				     "architecture x%02x\n",
20926 				     phba->sli4_hba.asic_rev);
20927 			break;
20928 		default:
20929 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20930 				     "4210 Firmware write failed: "
20931 				     "add_status_2 x%02x\n",
20932 				     shdr_add_status_2);
20933 			break;
20934 		}
20935 	} else if (!shdr_status && !shdr_add_status) {
20936 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20937 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20938 			if (shdr_csf)
20939 				shdr_change_status =
20940 						   LPFC_CHANGE_STATUS_PCI_RESET;
20941 		}
20942 
20943 		switch (shdr_change_status) {
20944 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20945 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20946 				     "3198 Firmware write complete: System "
20947 				     "reboot required to instantiate\n");
20948 			break;
20949 		case (LPFC_CHANGE_STATUS_FW_RESET):
20950 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20951 				     "3199 Firmware write complete: "
20952 				     "Firmware reset required to "
20953 				     "instantiate\n");
20954 			break;
20955 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20956 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20957 				     "3200 Firmware write complete: Port "
20958 				     "Migration or PCI Reset required to "
20959 				     "instantiate\n");
20960 			break;
20961 		case (LPFC_CHANGE_STATUS_PCI_RESET):
20962 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20963 				     "3201 Firmware write complete: PCI "
20964 				     "Reset required to instantiate\n");
20965 			break;
20966 		default:
20967 			break;
20968 		}
20969 	}
20970 }
20971 
20972 /**
20973  * lpfc_wr_object - write an object to the firmware
20974  * @phba: HBA structure that indicates port to create a queue on.
20975  * @dmabuf_list: list of dmabufs to write to the port.
20976  * @size: the total byte value of the objects to write to the port.
20977  * @offset: the current offset to be used to start the transfer.
20978  *
20979  * This routine will create a wr_object mailbox command to send to the port.
20980  * the mailbox command will be constructed using the dma buffers described in
20981  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
20982  * BDEs that the imbedded mailbox can support. The @offset variable will be
20983  * used to indicate the starting offset of the transfer and will also return
20984  * the offset after the write object mailbox has completed. @size is used to
20985  * determine the end of the object and whether the eof bit should be set.
20986  *
20987  * Return 0 is successful and offset will contain the new offset to use
20988  * for the next write.
20989  * Return negative value for error cases.
20990  **/
20991 int
20992 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
20993 	       uint32_t size, uint32_t *offset)
20994 {
20995 	struct lpfc_mbx_wr_object *wr_object;
20996 	LPFC_MBOXQ_t *mbox;
20997 	int rc = 0, i = 0;
20998 	int mbox_status = 0;
20999 	uint32_t shdr_status, shdr_add_status, shdr_add_status_2;
21000 	uint32_t shdr_change_status = 0, shdr_csf = 0;
21001 	uint32_t mbox_tmo;
21002 	struct lpfc_dmabuf *dmabuf;
21003 	uint32_t written = 0;
21004 	bool check_change_status = false;
21005 
21006 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
21007 	if (!mbox)
21008 		return -ENOMEM;
21009 
21010 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
21011 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
21012 			sizeof(struct lpfc_mbx_wr_object) -
21013 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
21014 
21015 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
21016 	wr_object->u.request.write_offset = *offset;
21017 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
21018 	wr_object->u.request.object_name[0] =
21019 		cpu_to_le32(wr_object->u.request.object_name[0]);
21020 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
21021 	list_for_each_entry(dmabuf, dmabuf_list, list) {
21022 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
21023 			break;
21024 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
21025 		wr_object->u.request.bde[i].addrHigh =
21026 			putPaddrHigh(dmabuf->phys);
21027 		if (written + SLI4_PAGE_SIZE >= size) {
21028 			wr_object->u.request.bde[i].tus.f.bdeSize =
21029 				(size - written);
21030 			written += (size - written);
21031 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
21032 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
21033 			check_change_status = true;
21034 		} else {
21035 			wr_object->u.request.bde[i].tus.f.bdeSize =
21036 				SLI4_PAGE_SIZE;
21037 			written += SLI4_PAGE_SIZE;
21038 		}
21039 		i++;
21040 	}
21041 	wr_object->u.request.bde_count = i;
21042 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
21043 	if (!phba->sli4_hba.intr_enable)
21044 		mbox_status = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
21045 	else {
21046 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
21047 		mbox_status = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
21048 	}
21049 
21050 	/* The mbox status needs to be maintained to detect MBOX_TIMEOUT. */
21051 	rc = mbox_status;
21052 
21053 	/* The IOCTL status is embedded in the mailbox subheader. */
21054 	shdr_status = bf_get(lpfc_mbox_hdr_status,
21055 			     &wr_object->header.cfg_shdr.response);
21056 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
21057 				 &wr_object->header.cfg_shdr.response);
21058 	shdr_add_status_2 = bf_get(lpfc_mbox_hdr_add_status_2,
21059 				   &wr_object->header.cfg_shdr.response);
21060 	if (check_change_status) {
21061 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
21062 					    &wr_object->u.response);
21063 		shdr_csf = bf_get(lpfc_wr_object_csf,
21064 				  &wr_object->u.response);
21065 	}
21066 
21067 	if (shdr_status || shdr_add_status || shdr_add_status_2 || rc) {
21068 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21069 				"3025 Write Object mailbox failed with "
21070 				"status x%x add_status x%x, add_status_2 x%x, "
21071 				"mbx status x%x\n",
21072 				shdr_status, shdr_add_status, shdr_add_status_2,
21073 				rc);
21074 		rc = -ENXIO;
21075 		*offset = shdr_add_status;
21076 	} else {
21077 		*offset += wr_object->u.response.actual_write_length;
21078 	}
21079 
21080 	if (rc || check_change_status)
21081 		lpfc_log_fw_write_cmpl(phba, shdr_status, shdr_add_status,
21082 				       shdr_add_status_2, shdr_change_status,
21083 				       shdr_csf);
21084 
21085 	if (!phba->sli4_hba.intr_enable)
21086 		mempool_free(mbox, phba->mbox_mem_pool);
21087 	else if (mbox_status != MBX_TIMEOUT)
21088 		mempool_free(mbox, phba->mbox_mem_pool);
21089 
21090 	return rc;
21091 }
21092 
21093 /**
21094  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
21095  * @vport: pointer to vport data structure.
21096  *
21097  * This function iterate through the mailboxq and clean up all REG_LOGIN
21098  * and REG_VPI mailbox commands associated with the vport. This function
21099  * is called when driver want to restart discovery of the vport due to
21100  * a Clear Virtual Link event.
21101  **/
21102 void
21103 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
21104 {
21105 	struct lpfc_hba *phba = vport->phba;
21106 	LPFC_MBOXQ_t *mb, *nextmb;
21107 	struct lpfc_nodelist *ndlp;
21108 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
21109 	LIST_HEAD(mbox_cmd_list);
21110 	uint8_t restart_loop;
21111 
21112 	/* Clean up internally queued mailbox commands with the vport */
21113 	spin_lock_irq(&phba->hbalock);
21114 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
21115 		if (mb->vport != vport)
21116 			continue;
21117 
21118 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21119 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
21120 			continue;
21121 
21122 		list_move_tail(&mb->list, &mbox_cmd_list);
21123 	}
21124 	/* Clean up active mailbox command with the vport */
21125 	mb = phba->sli.mbox_active;
21126 	if (mb && (mb->vport == vport)) {
21127 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
21128 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
21129 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21130 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21131 			act_mbx_ndlp = mb->ctx_ndlp;
21132 
21133 			/* This reference is local to this routine.  The
21134 			 * reference is removed at routine exit.
21135 			 */
21136 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
21137 
21138 			/* Unregister the RPI when mailbox complete */
21139 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21140 		}
21141 	}
21142 	/* Cleanup any mailbox completions which are not yet processed */
21143 	do {
21144 		restart_loop = 0;
21145 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
21146 			/*
21147 			 * If this mailox is already processed or it is
21148 			 * for another vport ignore it.
21149 			 */
21150 			if ((mb->vport != vport) ||
21151 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
21152 				continue;
21153 
21154 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21155 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
21156 				continue;
21157 
21158 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21159 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21160 				ndlp = mb->ctx_ndlp;
21161 				/* Unregister the RPI when mailbox complete */
21162 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21163 				restart_loop = 1;
21164 				clear_bit(NLP_IGNR_REG_CMPL, &ndlp->nlp_flag);
21165 				break;
21166 			}
21167 		}
21168 	} while (restart_loop);
21169 
21170 	spin_unlock_irq(&phba->hbalock);
21171 
21172 	/* Release the cleaned-up mailbox commands */
21173 	while (!list_empty(&mbox_cmd_list)) {
21174 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
21175 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21176 			ndlp = mb->ctx_ndlp;
21177 			mb->ctx_ndlp = NULL;
21178 			if (ndlp) {
21179 				clear_bit(NLP_IGNR_REG_CMPL, &ndlp->nlp_flag);
21180 				lpfc_nlp_put(ndlp);
21181 			}
21182 		}
21183 		lpfc_mbox_rsrc_cleanup(phba, mb, MBOX_THD_UNLOCKED);
21184 	}
21185 
21186 	/* Release the ndlp with the cleaned-up active mailbox command */
21187 	if (act_mbx_ndlp) {
21188 		clear_bit(NLP_IGNR_REG_CMPL, &act_mbx_ndlp->nlp_flag);
21189 		lpfc_nlp_put(act_mbx_ndlp);
21190 	}
21191 }
21192 
21193 /**
21194  * lpfc_drain_txq - Drain the txq
21195  * @phba: Pointer to HBA context object.
21196  *
21197  * This function attempt to submit IOCBs on the txq
21198  * to the adapter.  For SLI4 adapters, the txq contains
21199  * ELS IOCBs that have been deferred because the there
21200  * are no SGLs.  This congestion can occur with large
21201  * vport counts during node discovery.
21202  **/
21203 
21204 uint32_t
21205 lpfc_drain_txq(struct lpfc_hba *phba)
21206 {
21207 	LIST_HEAD(completions);
21208 	struct lpfc_sli_ring *pring;
21209 	struct lpfc_iocbq *piocbq = NULL;
21210 	unsigned long iflags = 0;
21211 	char *fail_msg = NULL;
21212 	uint32_t txq_cnt = 0;
21213 	struct lpfc_queue *wq;
21214 	int ret = 0;
21215 
21216 	if (phba->link_flag & LS_MDS_LOOPBACK) {
21217 		/* MDS WQE are posted only to first WQ*/
21218 		wq = phba->sli4_hba.hdwq[0].io_wq;
21219 		if (unlikely(!wq))
21220 			return 0;
21221 		pring = wq->pring;
21222 	} else {
21223 		wq = phba->sli4_hba.els_wq;
21224 		if (unlikely(!wq))
21225 			return 0;
21226 		pring = lpfc_phba_elsring(phba);
21227 	}
21228 
21229 	if (unlikely(!pring) || list_empty(&pring->txq))
21230 		return 0;
21231 
21232 	spin_lock_irqsave(&pring->ring_lock, iflags);
21233 	list_for_each_entry(piocbq, &pring->txq, list) {
21234 		txq_cnt++;
21235 	}
21236 
21237 	if (txq_cnt > pring->txq_max)
21238 		pring->txq_max = txq_cnt;
21239 
21240 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
21241 
21242 	while (!list_empty(&pring->txq)) {
21243 		spin_lock_irqsave(&pring->ring_lock, iflags);
21244 
21245 		piocbq = lpfc_sli_ringtx_get(phba, pring);
21246 		if (!piocbq) {
21247 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21248 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21249 				"2823 txq empty and txq_cnt is %d\n",
21250 				txq_cnt);
21251 			break;
21252 		}
21253 		txq_cnt--;
21254 
21255 		ret = __lpfc_sli_issue_iocb(phba, pring->ringno, piocbq, 0);
21256 
21257 		if (ret && ret != IOCB_BUSY) {
21258 			fail_msg = " - Cannot send IO ";
21259 			piocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21260 		}
21261 		if (fail_msg) {
21262 			piocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
21263 			/* Failed means we can't issue and need to cancel */
21264 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21265 					"2822 IOCB failed %s iotag 0x%x "
21266 					"xri 0x%x %d flg x%x\n",
21267 					fail_msg, piocbq->iotag,
21268 					piocbq->sli4_xritag, ret,
21269 					piocbq->cmd_flag);
21270 			list_add_tail(&piocbq->list, &completions);
21271 			fail_msg = NULL;
21272 		}
21273 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21274 		if (txq_cnt == 0 || ret == IOCB_BUSY)
21275 			break;
21276 	}
21277 	/* Cancel all the IOCBs that cannot be issued */
21278 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
21279 			      IOERR_SLI_ABORTED);
21280 
21281 	return txq_cnt;
21282 }
21283 
21284 /**
21285  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
21286  * @phba: Pointer to HBA context object.
21287  * @pwqeq: Pointer to command WQE.
21288  * @sglq: Pointer to the scatter gather queue object.
21289  *
21290  * This routine converts the bpl or bde that is in the WQE
21291  * to a sgl list for the sli4 hardware. The physical address
21292  * of the bpl/bde is converted back to a virtual address.
21293  * If the WQE contains a BPL then the list of BDE's is
21294  * converted to sli4_sge's. If the WQE contains a single
21295  * BDE then it is converted to a single sli_sge.
21296  * The WQE is still in cpu endianness so the contents of
21297  * the bpl can be used without byte swapping.
21298  *
21299  * Returns valid XRI = Success, NO_XRI = Failure.
21300  */
21301 static uint16_t
21302 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
21303 		 struct lpfc_sglq *sglq)
21304 {
21305 	uint16_t xritag = NO_XRI;
21306 	struct ulp_bde64 *bpl = NULL;
21307 	struct ulp_bde64 bde;
21308 	struct sli4_sge *sgl  = NULL;
21309 	struct lpfc_dmabuf *dmabuf;
21310 	union lpfc_wqe128 *wqe;
21311 	int numBdes = 0;
21312 	int i = 0;
21313 	uint32_t offset = 0; /* accumulated offset in the sg request list */
21314 	int inbound = 0; /* number of sg reply entries inbound from firmware */
21315 	uint32_t cmd;
21316 
21317 	if (!pwqeq || !sglq)
21318 		return xritag;
21319 
21320 	sgl  = (struct sli4_sge *)sglq->sgl;
21321 	wqe = &pwqeq->wqe;
21322 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
21323 
21324 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
21325 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
21326 		return sglq->sli4_xritag;
21327 	numBdes = pwqeq->num_bdes;
21328 	if (numBdes) {
21329 		/* The addrHigh and addrLow fields within the WQE
21330 		 * have not been byteswapped yet so there is no
21331 		 * need to swap them back.
21332 		 */
21333 		if (pwqeq->bpl_dmabuf)
21334 			dmabuf = pwqeq->bpl_dmabuf;
21335 		else
21336 			return xritag;
21337 
21338 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
21339 		if (!bpl)
21340 			return xritag;
21341 
21342 		for (i = 0; i < numBdes; i++) {
21343 			/* Should already be byte swapped. */
21344 			sgl->addr_hi = bpl->addrHigh;
21345 			sgl->addr_lo = bpl->addrLow;
21346 
21347 			sgl->word2 = le32_to_cpu(sgl->word2);
21348 			if ((i+1) == numBdes)
21349 				bf_set(lpfc_sli4_sge_last, sgl, 1);
21350 			else
21351 				bf_set(lpfc_sli4_sge_last, sgl, 0);
21352 			/* swap the size field back to the cpu so we
21353 			 * can assign it to the sgl.
21354 			 */
21355 			bde.tus.w = le32_to_cpu(bpl->tus.w);
21356 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
21357 			/* The offsets in the sgl need to be accumulated
21358 			 * separately for the request and reply lists.
21359 			 * The request is always first, the reply follows.
21360 			 */
21361 			switch (cmd) {
21362 			case CMD_GEN_REQUEST64_WQE:
21363 				/* add up the reply sg entries */
21364 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
21365 					inbound++;
21366 				/* first inbound? reset the offset */
21367 				if (inbound == 1)
21368 					offset = 0;
21369 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21370 				bf_set(lpfc_sli4_sge_type, sgl,
21371 					LPFC_SGE_TYPE_DATA);
21372 				offset += bde.tus.f.bdeSize;
21373 				break;
21374 			case CMD_FCP_TRSP64_WQE:
21375 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
21376 				bf_set(lpfc_sli4_sge_type, sgl,
21377 					LPFC_SGE_TYPE_DATA);
21378 				break;
21379 			case CMD_FCP_TSEND64_WQE:
21380 			case CMD_FCP_TRECEIVE64_WQE:
21381 				bf_set(lpfc_sli4_sge_type, sgl,
21382 					bpl->tus.f.bdeFlags);
21383 				if (i < 3)
21384 					offset = 0;
21385 				else
21386 					offset += bde.tus.f.bdeSize;
21387 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21388 				break;
21389 			}
21390 			sgl->word2 = cpu_to_le32(sgl->word2);
21391 			bpl++;
21392 			sgl++;
21393 		}
21394 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
21395 		/* The addrHigh and addrLow fields of the BDE have not
21396 		 * been byteswapped yet so they need to be swapped
21397 		 * before putting them in the sgl.
21398 		 */
21399 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
21400 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
21401 		sgl->word2 = le32_to_cpu(sgl->word2);
21402 		bf_set(lpfc_sli4_sge_last, sgl, 1);
21403 		sgl->word2 = cpu_to_le32(sgl->word2);
21404 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
21405 	}
21406 	return sglq->sli4_xritag;
21407 }
21408 
21409 /**
21410  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
21411  * @phba: Pointer to HBA context object.
21412  * @qp: Pointer to HDW queue.
21413  * @pwqe: Pointer to command WQE.
21414  **/
21415 int
21416 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21417 		    struct lpfc_iocbq *pwqe)
21418 {
21419 	union lpfc_wqe128 *wqe = &pwqe->wqe;
21420 	struct lpfc_async_xchg_ctx *ctxp;
21421 	struct lpfc_queue *wq;
21422 	struct lpfc_sglq *sglq;
21423 	struct lpfc_sli_ring *pring;
21424 	unsigned long iflags;
21425 	int ret = 0;
21426 
21427 	/* NVME_LS and NVME_LS ABTS requests. */
21428 	if (pwqe->cmd_flag & LPFC_IO_NVME_LS) {
21429 		pring =  phba->sli4_hba.nvmels_wq->pring;
21430 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21431 					  qp, wq_access);
21432 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
21433 		if (!sglq) {
21434 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21435 			return WQE_BUSY;
21436 		}
21437 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
21438 		pwqe->sli4_xritag = sglq->sli4_xritag;
21439 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
21440 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21441 			return WQE_ERROR;
21442 		}
21443 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21444 		       pwqe->sli4_xritag);
21445 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
21446 		if (ret) {
21447 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21448 			return ret;
21449 		}
21450 
21451 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21452 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21453 
21454 		lpfc_sli4_poll_eq(qp->hba_eq);
21455 		return 0;
21456 	}
21457 
21458 	/* NVME_FCREQ and NVME_ABTS requests */
21459 	if (pwqe->cmd_flag & (LPFC_IO_NVME | LPFC_IO_FCP | LPFC_IO_CMF)) {
21460 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21461 		wq = qp->io_wq;
21462 		pring = wq->pring;
21463 
21464 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21465 
21466 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21467 					  qp, wq_access);
21468 		ret = lpfc_sli4_wq_put(wq, wqe);
21469 		if (ret) {
21470 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21471 			return ret;
21472 		}
21473 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21474 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21475 
21476 		lpfc_sli4_poll_eq(qp->hba_eq);
21477 		return 0;
21478 	}
21479 
21480 	/* NVMET requests */
21481 	if (pwqe->cmd_flag & LPFC_IO_NVMET) {
21482 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21483 		wq = qp->io_wq;
21484 		pring = wq->pring;
21485 
21486 		ctxp = pwqe->context_un.axchg;
21487 		sglq = ctxp->ctxbuf->sglq;
21488 		if (pwqe->sli4_xritag ==  NO_XRI) {
21489 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
21490 			pwqe->sli4_xritag = sglq->sli4_xritag;
21491 		}
21492 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21493 		       pwqe->sli4_xritag);
21494 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21495 
21496 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21497 					  qp, wq_access);
21498 		ret = lpfc_sli4_wq_put(wq, wqe);
21499 		if (ret) {
21500 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21501 			return ret;
21502 		}
21503 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21504 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21505 
21506 		lpfc_sli4_poll_eq(qp->hba_eq);
21507 		return 0;
21508 	}
21509 	return WQE_ERROR;
21510 }
21511 
21512 /**
21513  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
21514  * @phba: Pointer to HBA context object.
21515  * @cmdiocb: Pointer to driver command iocb object.
21516  * @cmpl: completion function.
21517  *
21518  * Fill the appropriate fields for the abort WQE and call
21519  * internal routine lpfc_sli4_issue_wqe to send the WQE
21520  * This function is called with hbalock held and no ring_lock held.
21521  *
21522  * RETURNS 0 - SUCCESS
21523  **/
21524 
21525 int
21526 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
21527 			    void *cmpl)
21528 {
21529 	struct lpfc_vport *vport = cmdiocb->vport;
21530 	struct lpfc_iocbq *abtsiocb = NULL;
21531 	union lpfc_wqe128 *abtswqe;
21532 	struct lpfc_io_buf *lpfc_cmd;
21533 	int retval = IOCB_ERROR;
21534 	u16 xritag = cmdiocb->sli4_xritag;
21535 
21536 	/*
21537 	 * The scsi command can not be in txq and it is in flight because the
21538 	 * pCmd is still pointing at the SCSI command we have to abort. There
21539 	 * is no need to search the txcmplq. Just send an abort to the FW.
21540 	 */
21541 
21542 	abtsiocb = __lpfc_sli_get_iocbq(phba);
21543 	if (!abtsiocb)
21544 		return WQE_NORESOURCE;
21545 
21546 	/* Indicate the IO is being aborted by the driver. */
21547 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
21548 
21549 	abtswqe = &abtsiocb->wqe;
21550 	memset(abtswqe, 0, sizeof(*abtswqe));
21551 
21552 	if (!lpfc_is_link_up(phba) || (phba->link_flag & LS_EXTERNAL_LOOPBACK))
21553 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
21554 	bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
21555 	abtswqe->abort_cmd.rsrvd5 = 0;
21556 	abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
21557 	bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
21558 	bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
21559 	bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
21560 	bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
21561 	bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
21562 	bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
21563 
21564 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
21565 	abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
21566 	abtsiocb->cmd_flag |= LPFC_USE_FCPWQIDX;
21567 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
21568 		abtsiocb->cmd_flag |= LPFC_IO_FCP;
21569 	if (cmdiocb->cmd_flag & LPFC_IO_NVME)
21570 		abtsiocb->cmd_flag |= LPFC_IO_NVME;
21571 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
21572 		abtsiocb->cmd_flag |= LPFC_IO_FOF;
21573 	abtsiocb->vport = vport;
21574 	abtsiocb->cmd_cmpl = cmpl;
21575 
21576 	lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
21577 	retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
21578 
21579 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21580 			 "0359 Abort xri x%x, original iotag x%x, "
21581 			 "abort cmd iotag x%x retval x%x\n",
21582 			 xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
21583 
21584 	if (retval) {
21585 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21586 		__lpfc_sli_release_iocbq(phba, abtsiocb);
21587 	}
21588 
21589 	return retval;
21590 }
21591 
21592 #ifdef LPFC_MXP_STAT
21593 /**
21594  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
21595  * @phba: pointer to lpfc hba data structure.
21596  * @hwqid: belong to which HWQ.
21597  *
21598  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
21599  * 15 seconds after a test case is running.
21600  *
21601  * The user should call lpfc_debugfs_multixripools_write before running a test
21602  * case to clear stat_snapshot_taken. Then the user starts a test case. During
21603  * test case is running, stat_snapshot_taken is incremented by 1 every time when
21604  * this routine is called from heartbeat timer. When stat_snapshot_taken is
21605  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
21606  **/
21607 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
21608 {
21609 	struct lpfc_sli4_hdw_queue *qp;
21610 	struct lpfc_multixri_pool *multixri_pool;
21611 	struct lpfc_pvt_pool *pvt_pool;
21612 	struct lpfc_pbl_pool *pbl_pool;
21613 	u32 txcmplq_cnt;
21614 
21615 	qp = &phba->sli4_hba.hdwq[hwqid];
21616 	multixri_pool = qp->p_multixri_pool;
21617 	if (!multixri_pool)
21618 		return;
21619 
21620 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
21621 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21622 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21623 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21624 
21625 		multixri_pool->stat_pbl_count = pbl_pool->count;
21626 		multixri_pool->stat_pvt_count = pvt_pool->count;
21627 		multixri_pool->stat_busy_count = txcmplq_cnt;
21628 	}
21629 
21630 	multixri_pool->stat_snapshot_taken++;
21631 }
21632 #endif
21633 
21634 /**
21635  * lpfc_adjust_pvt_pool_count - Adjust private pool count
21636  * @phba: pointer to lpfc hba data structure.
21637  * @hwqid: belong to which HWQ.
21638  *
21639  * This routine moves some XRIs from private to public pool when private pool
21640  * is not busy.
21641  **/
21642 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
21643 {
21644 	struct lpfc_multixri_pool *multixri_pool;
21645 	u32 io_req_count;
21646 	u32 prev_io_req_count;
21647 
21648 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21649 	if (!multixri_pool)
21650 		return;
21651 	io_req_count = multixri_pool->io_req_count;
21652 	prev_io_req_count = multixri_pool->prev_io_req_count;
21653 
21654 	if (prev_io_req_count != io_req_count) {
21655 		/* Private pool is busy */
21656 		multixri_pool->prev_io_req_count = io_req_count;
21657 	} else {
21658 		/* Private pool is not busy.
21659 		 * Move XRIs from private to public pool.
21660 		 */
21661 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
21662 	}
21663 }
21664 
21665 /**
21666  * lpfc_adjust_high_watermark - Adjust high watermark
21667  * @phba: pointer to lpfc hba data structure.
21668  * @hwqid: belong to which HWQ.
21669  *
21670  * This routine sets high watermark as number of outstanding XRIs,
21671  * but make sure the new value is between xri_limit/2 and xri_limit.
21672  **/
21673 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
21674 {
21675 	u32 new_watermark;
21676 	u32 watermark_max;
21677 	u32 watermark_min;
21678 	u32 xri_limit;
21679 	u32 txcmplq_cnt;
21680 	u32 abts_io_bufs;
21681 	struct lpfc_multixri_pool *multixri_pool;
21682 	struct lpfc_sli4_hdw_queue *qp;
21683 
21684 	qp = &phba->sli4_hba.hdwq[hwqid];
21685 	multixri_pool = qp->p_multixri_pool;
21686 	if (!multixri_pool)
21687 		return;
21688 	xri_limit = multixri_pool->xri_limit;
21689 
21690 	watermark_max = xri_limit;
21691 	watermark_min = xri_limit / 2;
21692 
21693 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21694 	abts_io_bufs = qp->abts_scsi_io_bufs;
21695 	abts_io_bufs += qp->abts_nvme_io_bufs;
21696 
21697 	new_watermark = txcmplq_cnt + abts_io_bufs;
21698 	new_watermark = min(watermark_max, new_watermark);
21699 	new_watermark = max(watermark_min, new_watermark);
21700 	multixri_pool->pvt_pool.high_watermark = new_watermark;
21701 
21702 #ifdef LPFC_MXP_STAT
21703 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
21704 					  new_watermark);
21705 #endif
21706 }
21707 
21708 /**
21709  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
21710  * @phba: pointer to lpfc hba data structure.
21711  * @hwqid: belong to which HWQ.
21712  *
21713  * This routine is called from heartbeat timer when pvt_pool is idle.
21714  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
21715  * The first step moves (all - low_watermark) amount of XRIs.
21716  * The second step moves the rest of XRIs.
21717  **/
21718 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
21719 {
21720 	struct lpfc_pbl_pool *pbl_pool;
21721 	struct lpfc_pvt_pool *pvt_pool;
21722 	struct lpfc_sli4_hdw_queue *qp;
21723 	struct lpfc_io_buf *lpfc_ncmd;
21724 	struct lpfc_io_buf *lpfc_ncmd_next;
21725 	unsigned long iflag;
21726 	struct list_head tmp_list;
21727 	u32 tmp_count;
21728 
21729 	qp = &phba->sli4_hba.hdwq[hwqid];
21730 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
21731 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
21732 	tmp_count = 0;
21733 
21734 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
21735 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
21736 
21737 	if (pvt_pool->count > pvt_pool->low_watermark) {
21738 		/* Step 1: move (all - low_watermark) from pvt_pool
21739 		 * to pbl_pool
21740 		 */
21741 
21742 		/* Move low watermark of bufs from pvt_pool to tmp_list */
21743 		INIT_LIST_HEAD(&tmp_list);
21744 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21745 					 &pvt_pool->list, list) {
21746 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
21747 			tmp_count++;
21748 			if (tmp_count >= pvt_pool->low_watermark)
21749 				break;
21750 		}
21751 
21752 		/* Move all bufs from pvt_pool to pbl_pool */
21753 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21754 
21755 		/* Move all bufs from tmp_list to pvt_pool */
21756 		list_splice(&tmp_list, &pvt_pool->list);
21757 
21758 		pbl_pool->count += (pvt_pool->count - tmp_count);
21759 		pvt_pool->count = tmp_count;
21760 	} else {
21761 		/* Step 2: move the rest from pvt_pool to pbl_pool */
21762 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21763 		pbl_pool->count += pvt_pool->count;
21764 		pvt_pool->count = 0;
21765 	}
21766 
21767 	spin_unlock(&pvt_pool->lock);
21768 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21769 }
21770 
21771 /**
21772  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21773  * @phba: pointer to lpfc hba data structure
21774  * @qp: pointer to HDW queue
21775  * @pbl_pool: specified public free XRI pool
21776  * @pvt_pool: specified private free XRI pool
21777  * @count: number of XRIs to move
21778  *
21779  * This routine tries to move some free common bufs from the specified pbl_pool
21780  * to the specified pvt_pool. It might move less than count XRIs if there's not
21781  * enough in public pool.
21782  *
21783  * Return:
21784  *   true - if XRIs are successfully moved from the specified pbl_pool to the
21785  *          specified pvt_pool
21786  *   false - if the specified pbl_pool is empty or locked by someone else
21787  **/
21788 static bool
21789 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21790 			  struct lpfc_pbl_pool *pbl_pool,
21791 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
21792 {
21793 	struct lpfc_io_buf *lpfc_ncmd;
21794 	struct lpfc_io_buf *lpfc_ncmd_next;
21795 	unsigned long iflag;
21796 	int ret;
21797 
21798 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
21799 	if (ret) {
21800 		if (pbl_pool->count) {
21801 			/* Move a batch of XRIs from public to private pool */
21802 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
21803 			list_for_each_entry_safe(lpfc_ncmd,
21804 						 lpfc_ncmd_next,
21805 						 &pbl_pool->list,
21806 						 list) {
21807 				list_move_tail(&lpfc_ncmd->list,
21808 					       &pvt_pool->list);
21809 				pvt_pool->count++;
21810 				pbl_pool->count--;
21811 				count--;
21812 				if (count == 0)
21813 					break;
21814 			}
21815 
21816 			spin_unlock(&pvt_pool->lock);
21817 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21818 			return true;
21819 		}
21820 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21821 	}
21822 
21823 	return false;
21824 }
21825 
21826 /**
21827  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21828  * @phba: pointer to lpfc hba data structure.
21829  * @hwqid: belong to which HWQ.
21830  * @count: number of XRIs to move
21831  *
21832  * This routine tries to find some free common bufs in one of public pools with
21833  * Round Robin method. The search always starts from local hwqid, then the next
21834  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
21835  * a batch of free common bufs are moved to private pool on hwqid.
21836  * It might move less than count XRIs if there's not enough in public pool.
21837  **/
21838 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
21839 {
21840 	struct lpfc_multixri_pool *multixri_pool;
21841 	struct lpfc_multixri_pool *next_multixri_pool;
21842 	struct lpfc_pvt_pool *pvt_pool;
21843 	struct lpfc_pbl_pool *pbl_pool;
21844 	struct lpfc_sli4_hdw_queue *qp;
21845 	u32 next_hwqid;
21846 	u32 hwq_count;
21847 	int ret;
21848 
21849 	qp = &phba->sli4_hba.hdwq[hwqid];
21850 	multixri_pool = qp->p_multixri_pool;
21851 	pvt_pool = &multixri_pool->pvt_pool;
21852 	pbl_pool = &multixri_pool->pbl_pool;
21853 
21854 	/* Check if local pbl_pool is available */
21855 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
21856 	if (ret) {
21857 #ifdef LPFC_MXP_STAT
21858 		multixri_pool->local_pbl_hit_count++;
21859 #endif
21860 		return;
21861 	}
21862 
21863 	hwq_count = phba->cfg_hdw_queue;
21864 
21865 	/* Get the next hwqid which was found last time */
21866 	next_hwqid = multixri_pool->rrb_next_hwqid;
21867 
21868 	do {
21869 		/* Go to next hwq */
21870 		next_hwqid = (next_hwqid + 1) % hwq_count;
21871 
21872 		next_multixri_pool =
21873 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
21874 		pbl_pool = &next_multixri_pool->pbl_pool;
21875 
21876 		/* Check if the public free xri pool is available */
21877 		ret = _lpfc_move_xri_pbl_to_pvt(
21878 			phba, qp, pbl_pool, pvt_pool, count);
21879 
21880 		/* Exit while-loop if success or all hwqid are checked */
21881 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
21882 
21883 	/* Starting point for the next time */
21884 	multixri_pool->rrb_next_hwqid = next_hwqid;
21885 
21886 	if (!ret) {
21887 		/* stats: all public pools are empty*/
21888 		multixri_pool->pbl_empty_count++;
21889 	}
21890 
21891 #ifdef LPFC_MXP_STAT
21892 	if (ret) {
21893 		if (next_hwqid == hwqid)
21894 			multixri_pool->local_pbl_hit_count++;
21895 		else
21896 			multixri_pool->other_pbl_hit_count++;
21897 	}
21898 #endif
21899 }
21900 
21901 /**
21902  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
21903  * @phba: pointer to lpfc hba data structure.
21904  * @hwqid: belong to which HWQ.
21905  *
21906  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
21907  * low watermark.
21908  **/
21909 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
21910 {
21911 	struct lpfc_multixri_pool *multixri_pool;
21912 	struct lpfc_pvt_pool *pvt_pool;
21913 
21914 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21915 	pvt_pool = &multixri_pool->pvt_pool;
21916 
21917 	if (pvt_pool->count < pvt_pool->low_watermark)
21918 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21919 }
21920 
21921 /**
21922  * lpfc_release_io_buf - Return one IO buf back to free pool
21923  * @phba: pointer to lpfc hba data structure.
21924  * @lpfc_ncmd: IO buf to be returned.
21925  * @qp: belong to which HWQ.
21926  *
21927  * This routine returns one IO buf back to free pool. If this is an urgent IO,
21928  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
21929  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
21930  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
21931  * lpfc_io_buf_list_put.
21932  **/
21933 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
21934 			 struct lpfc_sli4_hdw_queue *qp)
21935 {
21936 	unsigned long iflag;
21937 	struct lpfc_pbl_pool *pbl_pool;
21938 	struct lpfc_pvt_pool *pvt_pool;
21939 	struct lpfc_epd_pool *epd_pool;
21940 	u32 txcmplq_cnt;
21941 	u32 xri_owned;
21942 	u32 xri_limit;
21943 	u32 abts_io_bufs;
21944 
21945 	/* MUST zero fields if buffer is reused by another protocol */
21946 	lpfc_ncmd->nvmeCmd = NULL;
21947 	lpfc_ncmd->cur_iocbq.cmd_cmpl = NULL;
21948 
21949 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
21950 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
21951 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
21952 
21953 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
21954 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
21955 
21956 	if (phba->cfg_xri_rebalancing) {
21957 		if (lpfc_ncmd->expedite) {
21958 			/* Return to expedite pool */
21959 			epd_pool = &phba->epd_pool;
21960 			spin_lock_irqsave(&epd_pool->lock, iflag);
21961 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21962 			epd_pool->count++;
21963 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
21964 			return;
21965 		}
21966 
21967 		/* Avoid invalid access if an IO sneaks in and is being rejected
21968 		 * just _after_ xri pools are destroyed in lpfc_offline.
21969 		 * Nothing much can be done at this point.
21970 		 */
21971 		if (!qp->p_multixri_pool)
21972 			return;
21973 
21974 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21975 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21976 
21977 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21978 		abts_io_bufs = qp->abts_scsi_io_bufs;
21979 		abts_io_bufs += qp->abts_nvme_io_bufs;
21980 
21981 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21982 		xri_limit = qp->p_multixri_pool->xri_limit;
21983 
21984 #ifdef LPFC_MXP_STAT
21985 		if (xri_owned <= xri_limit)
21986 			qp->p_multixri_pool->below_limit_count++;
21987 		else
21988 			qp->p_multixri_pool->above_limit_count++;
21989 #endif
21990 
21991 		/* XRI goes to either public or private free xri pool
21992 		 *     based on watermark and xri_limit
21993 		 */
21994 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
21995 		    (xri_owned < xri_limit &&
21996 		     pvt_pool->count < pvt_pool->high_watermark)) {
21997 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
21998 						  qp, free_pvt_pool);
21999 			list_add_tail(&lpfc_ncmd->list,
22000 				      &pvt_pool->list);
22001 			pvt_pool->count++;
22002 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
22003 		} else {
22004 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
22005 						  qp, free_pub_pool);
22006 			list_add_tail(&lpfc_ncmd->list,
22007 				      &pbl_pool->list);
22008 			pbl_pool->count++;
22009 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
22010 		}
22011 	} else {
22012 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
22013 					  qp, free_xri);
22014 		list_add_tail(&lpfc_ncmd->list,
22015 			      &qp->lpfc_io_buf_list_put);
22016 		qp->put_io_bufs++;
22017 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
22018 				       iflag);
22019 	}
22020 }
22021 
22022 /**
22023  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
22024  * @phba: pointer to lpfc hba data structure.
22025  * @qp: pointer to HDW queue
22026  * @pvt_pool: pointer to private pool data structure.
22027  * @ndlp: pointer to lpfc nodelist data structure.
22028  *
22029  * This routine tries to get one free IO buf from private pool.
22030  *
22031  * Return:
22032  *   pointer to one free IO buf - if private pool is not empty
22033  *   NULL - if private pool is empty
22034  **/
22035 static struct lpfc_io_buf *
22036 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
22037 				  struct lpfc_sli4_hdw_queue *qp,
22038 				  struct lpfc_pvt_pool *pvt_pool,
22039 				  struct lpfc_nodelist *ndlp)
22040 {
22041 	struct lpfc_io_buf *lpfc_ncmd;
22042 	struct lpfc_io_buf *lpfc_ncmd_next;
22043 	unsigned long iflag;
22044 
22045 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
22046 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
22047 				 &pvt_pool->list, list) {
22048 		if (lpfc_test_rrq_active(
22049 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
22050 			continue;
22051 		list_del(&lpfc_ncmd->list);
22052 		pvt_pool->count--;
22053 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
22054 		return lpfc_ncmd;
22055 	}
22056 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
22057 
22058 	return NULL;
22059 }
22060 
22061 /**
22062  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
22063  * @phba: pointer to lpfc hba data structure.
22064  *
22065  * This routine tries to get one free IO buf from expedite pool.
22066  *
22067  * Return:
22068  *   pointer to one free IO buf - if expedite pool is not empty
22069  *   NULL - if expedite pool is empty
22070  **/
22071 static struct lpfc_io_buf *
22072 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
22073 {
22074 	struct lpfc_io_buf *lpfc_ncmd = NULL, *iter;
22075 	struct lpfc_io_buf *lpfc_ncmd_next;
22076 	unsigned long iflag;
22077 	struct lpfc_epd_pool *epd_pool;
22078 
22079 	epd_pool = &phba->epd_pool;
22080 
22081 	spin_lock_irqsave(&epd_pool->lock, iflag);
22082 	if (epd_pool->count > 0) {
22083 		list_for_each_entry_safe(iter, lpfc_ncmd_next,
22084 					 &epd_pool->list, list) {
22085 			list_del(&iter->list);
22086 			epd_pool->count--;
22087 			lpfc_ncmd = iter;
22088 			break;
22089 		}
22090 	}
22091 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
22092 
22093 	return lpfc_ncmd;
22094 }
22095 
22096 /**
22097  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
22098  * @phba: pointer to lpfc hba data structure.
22099  * @ndlp: pointer to lpfc nodelist data structure.
22100  * @hwqid: belong to which HWQ
22101  * @expedite: 1 means this request is urgent.
22102  *
22103  * This routine will do the following actions and then return a pointer to
22104  * one free IO buf.
22105  *
22106  * 1. If private free xri count is empty, move some XRIs from public to
22107  *    private pool.
22108  * 2. Get one XRI from private free xri pool.
22109  * 3. If we fail to get one from pvt_pool and this is an expedite request,
22110  *    get one free xri from expedite pool.
22111  *
22112  * Note: ndlp is only used on SCSI side for RRQ testing.
22113  *       The caller should pass NULL for ndlp on NVME side.
22114  *
22115  * Return:
22116  *   pointer to one free IO buf - if private pool is not empty
22117  *   NULL - if private pool is empty
22118  **/
22119 static struct lpfc_io_buf *
22120 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
22121 				    struct lpfc_nodelist *ndlp,
22122 				    int hwqid, int expedite)
22123 {
22124 	struct lpfc_sli4_hdw_queue *qp;
22125 	struct lpfc_multixri_pool *multixri_pool;
22126 	struct lpfc_pvt_pool *pvt_pool;
22127 	struct lpfc_io_buf *lpfc_ncmd;
22128 
22129 	qp = &phba->sli4_hba.hdwq[hwqid];
22130 	lpfc_ncmd = NULL;
22131 	if (!qp) {
22132 		lpfc_printf_log(phba, KERN_INFO,
22133 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22134 				"5556 NULL qp for hwqid  x%x\n", hwqid);
22135 		return lpfc_ncmd;
22136 	}
22137 	multixri_pool = qp->p_multixri_pool;
22138 	if (!multixri_pool) {
22139 		lpfc_printf_log(phba, KERN_INFO,
22140 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22141 				"5557 NULL multixri for hwqid  x%x\n", hwqid);
22142 		return lpfc_ncmd;
22143 	}
22144 	pvt_pool = &multixri_pool->pvt_pool;
22145 	if (!pvt_pool) {
22146 		lpfc_printf_log(phba, KERN_INFO,
22147 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22148 				"5558 NULL pvt_pool for hwqid  x%x\n", hwqid);
22149 		return lpfc_ncmd;
22150 	}
22151 	multixri_pool->io_req_count++;
22152 
22153 	/* If pvt_pool is empty, move some XRIs from public to private pool */
22154 	if (pvt_pool->count == 0)
22155 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
22156 
22157 	/* Get one XRI from private free xri pool */
22158 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
22159 
22160 	if (lpfc_ncmd) {
22161 		lpfc_ncmd->hdwq = qp;
22162 		lpfc_ncmd->hdwq_no = hwqid;
22163 	} else if (expedite) {
22164 		/* If we fail to get one from pvt_pool and this is an expedite
22165 		 * request, get one free xri from expedite pool.
22166 		 */
22167 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
22168 	}
22169 
22170 	return lpfc_ncmd;
22171 }
22172 
22173 static inline struct lpfc_io_buf *
22174 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
22175 {
22176 	struct lpfc_sli4_hdw_queue *qp;
22177 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
22178 
22179 	qp = &phba->sli4_hba.hdwq[idx];
22180 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
22181 				 &qp->lpfc_io_buf_list_get, list) {
22182 		if (lpfc_test_rrq_active(phba, ndlp,
22183 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
22184 			continue;
22185 
22186 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
22187 			continue;
22188 
22189 		list_del_init(&lpfc_cmd->list);
22190 		qp->get_io_bufs--;
22191 		lpfc_cmd->hdwq = qp;
22192 		lpfc_cmd->hdwq_no = idx;
22193 		return lpfc_cmd;
22194 	}
22195 	return NULL;
22196 }
22197 
22198 /**
22199  * lpfc_get_io_buf - Get one IO buffer from free pool
22200  * @phba: The HBA for which this call is being executed.
22201  * @ndlp: pointer to lpfc nodelist data structure.
22202  * @hwqid: belong to which HWQ
22203  * @expedite: 1 means this request is urgent.
22204  *
22205  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
22206  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
22207  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
22208  *
22209  * Note: ndlp is only used on SCSI side for RRQ testing.
22210  *       The caller should pass NULL for ndlp on NVME side.
22211  *
22212  * Return codes:
22213  *   NULL - Error
22214  *   Pointer to lpfc_io_buf - Success
22215  **/
22216 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
22217 				    struct lpfc_nodelist *ndlp,
22218 				    u32 hwqid, int expedite)
22219 {
22220 	struct lpfc_sli4_hdw_queue *qp;
22221 	unsigned long iflag;
22222 	struct lpfc_io_buf *lpfc_cmd;
22223 
22224 	qp = &phba->sli4_hba.hdwq[hwqid];
22225 	lpfc_cmd = NULL;
22226 	if (!qp) {
22227 		lpfc_printf_log(phba, KERN_WARNING,
22228 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22229 				"5555 NULL qp for hwqid  x%x\n", hwqid);
22230 		return lpfc_cmd;
22231 	}
22232 
22233 	if (phba->cfg_xri_rebalancing)
22234 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
22235 			phba, ndlp, hwqid, expedite);
22236 	else {
22237 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
22238 					  qp, alloc_xri_get);
22239 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
22240 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22241 		if (!lpfc_cmd) {
22242 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
22243 					  qp, alloc_xri_put);
22244 			list_splice(&qp->lpfc_io_buf_list_put,
22245 				    &qp->lpfc_io_buf_list_get);
22246 			qp->get_io_bufs += qp->put_io_bufs;
22247 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
22248 			qp->put_io_bufs = 0;
22249 			spin_unlock(&qp->io_buf_list_put_lock);
22250 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
22251 			    expedite)
22252 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22253 		}
22254 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
22255 	}
22256 
22257 	return lpfc_cmd;
22258 }
22259 
22260 /**
22261  * lpfc_read_object - Retrieve object data from HBA
22262  * @phba: The HBA for which this call is being executed.
22263  * @rdobject: Pathname of object data we want to read.
22264  * @datap: Pointer to where data will be copied to.
22265  * @datasz: size of data area
22266  *
22267  * This routine is limited to object sizes of LPFC_BPL_SIZE (1024) or less.
22268  * The data will be truncated if datasz is not large enough.
22269  * Version 1 is not supported with Embedded mbox cmd, so we must use version 0.
22270  * Returns the actual bytes read from the object.
22271  *
22272  * This routine is hard coded to use a poll completion.  Unlike other
22273  * sli4_config mailboxes, it uses lpfc_mbuf memory which is not
22274  * cleaned up in lpfc_sli4_cmd_mbox_free.  If this routine is modified
22275  * to use interrupt-based completions, code is needed to fully cleanup
22276  * the memory.
22277  */
22278 int
22279 lpfc_read_object(struct lpfc_hba *phba, char *rdobject, uint32_t *datap,
22280 		 uint32_t datasz)
22281 {
22282 	struct lpfc_mbx_read_object *read_object;
22283 	LPFC_MBOXQ_t *mbox;
22284 	int rc, length, eof, j, byte_cnt = 0;
22285 	uint32_t shdr_status, shdr_add_status;
22286 	union lpfc_sli4_cfg_shdr *shdr;
22287 	struct lpfc_dmabuf *pcmd;
22288 	u32 rd_object_name[LPFC_MBX_OBJECT_NAME_LEN_DW] = {0};
22289 
22290 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
22291 	if (!mbox)
22292 		return -ENOMEM;
22293 	length = (sizeof(struct lpfc_mbx_read_object) -
22294 		  sizeof(struct lpfc_sli4_cfg_mhdr));
22295 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
22296 			 LPFC_MBOX_OPCODE_READ_OBJECT,
22297 			 length, LPFC_SLI4_MBX_EMBED);
22298 	read_object = &mbox->u.mqe.un.read_object;
22299 	shdr = (union lpfc_sli4_cfg_shdr *)&read_object->header.cfg_shdr;
22300 
22301 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_0);
22302 	bf_set(lpfc_mbx_rd_object_rlen, &read_object->u.request, datasz);
22303 	read_object->u.request.rd_object_offset = 0;
22304 	read_object->u.request.rd_object_cnt = 1;
22305 
22306 	memset((void *)read_object->u.request.rd_object_name, 0,
22307 	       LPFC_OBJ_NAME_SZ);
22308 	scnprintf((char *)rd_object_name, sizeof(rd_object_name), rdobject);
22309 	for (j = 0; j < strlen(rdobject); j++)
22310 		read_object->u.request.rd_object_name[j] =
22311 			cpu_to_le32(rd_object_name[j]);
22312 
22313 	pcmd = kmalloc_obj(*pcmd);
22314 	if (pcmd)
22315 		pcmd->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &pcmd->phys);
22316 	if (!pcmd || !pcmd->virt) {
22317 		kfree(pcmd);
22318 		mempool_free(mbox, phba->mbox_mem_pool);
22319 		return -ENOMEM;
22320 	}
22321 	memset((void *)pcmd->virt, 0, LPFC_BPL_SIZE);
22322 	read_object->u.request.rd_object_hbuf[0].pa_lo =
22323 		putPaddrLow(pcmd->phys);
22324 	read_object->u.request.rd_object_hbuf[0].pa_hi =
22325 		putPaddrHigh(pcmd->phys);
22326 	read_object->u.request.rd_object_hbuf[0].length = LPFC_BPL_SIZE;
22327 
22328 	mbox->vport = phba->pport;
22329 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
22330 	mbox->ctx_ndlp = NULL;
22331 
22332 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
22333 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
22334 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
22335 
22336 	if (shdr_status == STATUS_FAILED &&
22337 	    shdr_add_status == ADD_STATUS_INVALID_OBJECT_NAME) {
22338 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22339 				"4674 No port cfg file in FW.\n");
22340 		byte_cnt = -ENOENT;
22341 	} else if (shdr_status || shdr_add_status || rc) {
22342 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22343 				"2625 READ_OBJECT mailbox failed with "
22344 				"status x%x add_status x%x, mbx status x%x\n",
22345 				shdr_status, shdr_add_status, rc);
22346 		byte_cnt = -ENXIO;
22347 	} else {
22348 		/* Success */
22349 		length = read_object->u.response.rd_object_actual_rlen;
22350 		eof = bf_get(lpfc_mbx_rd_object_eof, &read_object->u.response);
22351 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_CGN_MGMT,
22352 				"2626 READ_OBJECT Success len %d:%d, EOF %d\n",
22353 				length, datasz, eof);
22354 
22355 		/* Detect the port config file exists but is empty */
22356 		if (!length && eof) {
22357 			byte_cnt = 0;
22358 			goto exit;
22359 		}
22360 
22361 		byte_cnt = length;
22362 		lpfc_sli_pcimem_bcopy(pcmd->virt, datap, byte_cnt);
22363 	}
22364 
22365  exit:
22366 	/* This is an embedded SLI4 mailbox with an external buffer allocated.
22367 	 * Free the pcmd and then cleanup with the correct routine.
22368 	 */
22369 	lpfc_mbuf_free(phba, pcmd->virt, pcmd->phys);
22370 	kfree(pcmd);
22371 	lpfc_sli4_mbox_cmd_free(phba, mbox);
22372 	return byte_cnt;
22373 }
22374 
22375 /**
22376  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
22377  * @phba: The HBA for which this call is being executed.
22378  * @lpfc_buf: IO buf structure to append the SGL chunk
22379  *
22380  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
22381  * and will allocate an SGL chunk if the pool is empty.
22382  *
22383  * Return codes:
22384  *   NULL - Error
22385  *   Pointer to sli4_hybrid_sgl - Success
22386  **/
22387 struct sli4_hybrid_sgl *
22388 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22389 {
22390 	struct sli4_hybrid_sgl *list_entry = NULL;
22391 	struct sli4_hybrid_sgl *tmp = NULL;
22392 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
22393 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22394 	struct list_head *buf_list = &hdwq->sgl_list;
22395 	unsigned long iflags;
22396 
22397 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22398 
22399 	if (likely(!list_empty(buf_list))) {
22400 		/* break off 1 chunk from the sgl_list */
22401 		list_for_each_entry_safe(list_entry, tmp,
22402 					 buf_list, list_node) {
22403 			list_move_tail(&list_entry->list_node,
22404 				       &lpfc_buf->dma_sgl_xtra_list);
22405 			break;
22406 		}
22407 	} else {
22408 		/* allocate more */
22409 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22410 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22411 				   cpu_to_node(hdwq->io_wq->chann));
22412 		if (!tmp) {
22413 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22414 					"8353 error kmalloc memory for HDWQ "
22415 					"%d %s\n",
22416 					lpfc_buf->hdwq_no, __func__);
22417 			return NULL;
22418 		}
22419 
22420 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
22421 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
22422 		if (!tmp->dma_sgl) {
22423 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22424 					"8354 error pool_alloc memory for HDWQ "
22425 					"%d %s\n",
22426 					lpfc_buf->hdwq_no, __func__);
22427 			kfree(tmp);
22428 			return NULL;
22429 		}
22430 
22431 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22432 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
22433 	}
22434 
22435 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
22436 					struct sli4_hybrid_sgl,
22437 					list_node);
22438 
22439 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22440 
22441 	return allocated_sgl;
22442 }
22443 
22444 /**
22445  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
22446  * @phba: The HBA for which this call is being executed.
22447  * @lpfc_buf: IO buf structure with the SGL chunk
22448  *
22449  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
22450  *
22451  * Return codes:
22452  *   0 - Success
22453  *   -EINVAL - Error
22454  **/
22455 int
22456 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22457 {
22458 	int rc = 0;
22459 	struct sli4_hybrid_sgl *list_entry = NULL;
22460 	struct sli4_hybrid_sgl *tmp = NULL;
22461 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22462 	struct list_head *buf_list = &hdwq->sgl_list;
22463 	unsigned long iflags;
22464 
22465 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22466 
22467 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
22468 		list_for_each_entry_safe(list_entry, tmp,
22469 					 &lpfc_buf->dma_sgl_xtra_list,
22470 					 list_node) {
22471 			list_move_tail(&list_entry->list_node,
22472 				       buf_list);
22473 		}
22474 	} else {
22475 		rc = -EINVAL;
22476 	}
22477 
22478 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22479 	return rc;
22480 }
22481 
22482 /**
22483  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
22484  * @phba: phba object
22485  * @hdwq: hdwq to cleanup sgl buff resources on
22486  *
22487  * This routine frees all SGL chunks of hdwq SGL chunk pool.
22488  *
22489  * Return codes:
22490  *   None
22491  **/
22492 void
22493 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
22494 		       struct lpfc_sli4_hdw_queue *hdwq)
22495 {
22496 	struct list_head *buf_list = &hdwq->sgl_list;
22497 	struct sli4_hybrid_sgl *list_entry = NULL;
22498 	struct sli4_hybrid_sgl *tmp = NULL;
22499 	unsigned long iflags;
22500 
22501 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22502 
22503 	/* Free sgl pool */
22504 	list_for_each_entry_safe(list_entry, tmp,
22505 				 buf_list, list_node) {
22506 		list_del(&list_entry->list_node);
22507 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
22508 			      list_entry->dma_sgl,
22509 			      list_entry->dma_phys_sgl);
22510 		kfree(list_entry);
22511 	}
22512 
22513 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22514 }
22515 
22516 /**
22517  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
22518  * @phba: The HBA for which this call is being executed.
22519  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
22520  *
22521  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
22522  * and will allocate an CMD/RSP buffer if the pool is empty.
22523  *
22524  * Return codes:
22525  *   NULL - Error
22526  *   Pointer to fcp_cmd_rsp_buf - Success
22527  **/
22528 struct fcp_cmd_rsp_buf *
22529 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22530 			      struct lpfc_io_buf *lpfc_buf)
22531 {
22532 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22533 	struct fcp_cmd_rsp_buf *tmp = NULL;
22534 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
22535 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22536 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22537 	unsigned long iflags;
22538 
22539 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22540 
22541 	if (likely(!list_empty(buf_list))) {
22542 		/* break off 1 chunk from the list */
22543 		list_for_each_entry_safe(list_entry, tmp,
22544 					 buf_list,
22545 					 list_node) {
22546 			list_move_tail(&list_entry->list_node,
22547 				       &lpfc_buf->dma_cmd_rsp_list);
22548 			break;
22549 		}
22550 	} else {
22551 		/* allocate more */
22552 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22553 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22554 				   cpu_to_node(hdwq->io_wq->chann));
22555 		if (!tmp) {
22556 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22557 					"8355 error kmalloc memory for HDWQ "
22558 					"%d %s\n",
22559 					lpfc_buf->hdwq_no, __func__);
22560 			return NULL;
22561 		}
22562 
22563 		tmp->fcp_cmnd = dma_pool_zalloc(phba->lpfc_cmd_rsp_buf_pool,
22564 						GFP_ATOMIC,
22565 						&tmp->fcp_cmd_rsp_dma_handle);
22566 
22567 		if (!tmp->fcp_cmnd) {
22568 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22569 					"8356 error pool_alloc memory for HDWQ "
22570 					"%d %s\n",
22571 					lpfc_buf->hdwq_no, __func__);
22572 			kfree(tmp);
22573 			return NULL;
22574 		}
22575 
22576 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
22577 				sizeof(struct fcp_cmnd32));
22578 
22579 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22580 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
22581 	}
22582 
22583 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
22584 					struct fcp_cmd_rsp_buf,
22585 					list_node);
22586 
22587 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22588 
22589 	return allocated_buf;
22590 }
22591 
22592 /**
22593  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
22594  * @phba: The HBA for which this call is being executed.
22595  * @lpfc_buf: IO buf structure with the CMD/RSP buf
22596  *
22597  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
22598  *
22599  * Return codes:
22600  *   0 - Success
22601  *   -EINVAL - Error
22602  **/
22603 int
22604 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22605 			      struct lpfc_io_buf *lpfc_buf)
22606 {
22607 	int rc = 0;
22608 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22609 	struct fcp_cmd_rsp_buf *tmp = NULL;
22610 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22611 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22612 	unsigned long iflags;
22613 
22614 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22615 
22616 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
22617 		list_for_each_entry_safe(list_entry, tmp,
22618 					 &lpfc_buf->dma_cmd_rsp_list,
22619 					 list_node) {
22620 			list_move_tail(&list_entry->list_node,
22621 				       buf_list);
22622 		}
22623 	} else {
22624 		rc = -EINVAL;
22625 	}
22626 
22627 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22628 	return rc;
22629 }
22630 
22631 /**
22632  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
22633  * @phba: phba object
22634  * @hdwq: hdwq to cleanup cmd rsp buff resources on
22635  *
22636  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
22637  *
22638  * Return codes:
22639  *   None
22640  **/
22641 void
22642 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22643 			       struct lpfc_sli4_hdw_queue *hdwq)
22644 {
22645 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22646 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22647 	struct fcp_cmd_rsp_buf *tmp = NULL;
22648 	unsigned long iflags;
22649 
22650 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22651 
22652 	/* Free cmd_rsp buf pool */
22653 	list_for_each_entry_safe(list_entry, tmp,
22654 				 buf_list,
22655 				 list_node) {
22656 		list_del(&list_entry->list_node);
22657 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
22658 			      list_entry->fcp_cmnd,
22659 			      list_entry->fcp_cmd_rsp_dma_handle);
22660 		kfree(list_entry);
22661 	}
22662 
22663 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22664 }
22665 
22666 /**
22667  * lpfc_sli_prep_wqe - Prepare WQE for the command to be posted
22668  * @phba: phba object
22669  * @job: job entry of the command to be posted.
22670  *
22671  * Fill the common fields of the wqe for each of the command.
22672  *
22673  * Return codes:
22674  *	None
22675  **/
22676 void
22677 lpfc_sli_prep_wqe(struct lpfc_hba *phba, struct lpfc_iocbq *job)
22678 {
22679 	u8 cmnd;
22680 	u32 *pcmd;
22681 	u32 if_type = 0;
22682 	u32 abort_tag;
22683 	bool fip;
22684 	struct lpfc_nodelist *ndlp = NULL;
22685 	union lpfc_wqe128 *wqe = &job->wqe;
22686 	u8 command_type = ELS_COMMAND_NON_FIP;
22687 
22688 	fip = test_bit(HBA_FIP_SUPPORT, &phba->hba_flag);
22689 	/* The fcp commands will set command type */
22690 	if (job->cmd_flag &  LPFC_IO_FCP)
22691 		command_type = FCP_COMMAND;
22692 	else if (fip && (job->cmd_flag & LPFC_FIP_ELS_ID_MASK))
22693 		command_type = ELS_COMMAND_FIP;
22694 	else
22695 		command_type = ELS_COMMAND_NON_FIP;
22696 
22697 	abort_tag = job->iotag;
22698 	cmnd = bf_get(wqe_cmnd, &wqe->els_req.wqe_com);
22699 
22700 	switch (cmnd) {
22701 	case CMD_ELS_REQUEST64_WQE:
22702 		ndlp = job->ndlp;
22703 
22704 		if_type = bf_get(lpfc_sli_intf_if_type,
22705 				 &phba->sli4_hba.sli_intf);
22706 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22707 			pcmd = (u32 *)job->cmd_dmabuf->virt;
22708 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
22709 				     *pcmd == ELS_CMD_SCR ||
22710 				     *pcmd == ELS_CMD_RDF ||
22711 				     *pcmd == ELS_CMD_EDC ||
22712 				     *pcmd == ELS_CMD_RSCN_XMT ||
22713 				     *pcmd == ELS_CMD_FDISC ||
22714 				     *pcmd == ELS_CMD_LOGO ||
22715 				     *pcmd == ELS_CMD_QFPA ||
22716 				     *pcmd == ELS_CMD_UVEM ||
22717 				     *pcmd == ELS_CMD_PLOGI)) {
22718 				bf_set(els_req64_sp, &wqe->els_req, 1);
22719 				bf_set(els_req64_sid, &wqe->els_req,
22720 				       job->vport->fc_myDID);
22721 
22722 				if ((*pcmd == ELS_CMD_FLOGI) &&
22723 				    !(phba->fc_topology ==
22724 				      LPFC_TOPOLOGY_LOOP))
22725 					bf_set(els_req64_sid, &wqe->els_req, 0);
22726 
22727 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
22728 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22729 				       phba->vpi_ids[job->vport->vpi]);
22730 			} else if (pcmd) {
22731 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
22732 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22733 				       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22734 			}
22735 		}
22736 
22737 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
22738 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22739 
22740 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
22741 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
22742 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
22743 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22744 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
22745 		break;
22746 	case CMD_XMIT_ELS_RSP64_WQE:
22747 		ndlp = job->ndlp;
22748 
22749 		/* word4 */
22750 		wqe->xmit_els_rsp.word4 = 0;
22751 
22752 		if_type = bf_get(lpfc_sli_intf_if_type,
22753 				 &phba->sli4_hba.sli_intf);
22754 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22755 			if (test_bit(FC_PT2PT, &job->vport->fc_flag)) {
22756 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22757 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22758 				       job->vport->fc_myDID);
22759 				if (job->vport->fc_myDID == Fabric_DID) {
22760 					bf_set(wqe_els_did,
22761 					       &wqe->xmit_els_rsp.wqe_dest, 0);
22762 				}
22763 			}
22764 		}
22765 
22766 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
22767 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
22768 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
22769 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
22770 		       LPFC_WQE_LENLOC_WORD3);
22771 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
22772 
22773 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
22774 			bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22775 			bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22776 			       job->vport->fc_myDID);
22777 			bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
22778 		}
22779 
22780 		if (phba->sli_rev == LPFC_SLI_REV4) {
22781 			bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
22782 			       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22783 
22784 			if (bf_get(wqe_ct, &wqe->xmit_els_rsp.wqe_com))
22785 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
22786 				       phba->vpi_ids[job->vport->vpi]);
22787 		}
22788 		command_type = OTHER_COMMAND;
22789 		break;
22790 	case CMD_GEN_REQUEST64_WQE:
22791 		/* Word 10 */
22792 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
22793 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
22794 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
22795 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22796 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
22797 		command_type = OTHER_COMMAND;
22798 		break;
22799 	case CMD_XMIT_SEQUENCE64_WQE:
22800 		if (phba->link_flag & LS_LOOPBACK_MODE)
22801 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
22802 
22803 		wqe->xmit_sequence.rsvd3 = 0;
22804 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
22805 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
22806 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
22807 		       LPFC_WQE_IOD_WRITE);
22808 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
22809 		       LPFC_WQE_LENLOC_WORD12);
22810 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
22811 		command_type = OTHER_COMMAND;
22812 		break;
22813 	case CMD_XMIT_BLS_RSP64_WQE:
22814 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
22815 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
22816 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
22817 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
22818 		       phba->vpi_ids[phba->pport->vpi]);
22819 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
22820 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
22821 		       LPFC_WQE_LENLOC_NONE);
22822 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
22823 		command_type = OTHER_COMMAND;
22824 		break;
22825 	case CMD_FCP_ICMND64_WQE:	/* task mgmt commands */
22826 	case CMD_ABORT_XRI_WQE:		/* abort iotag */
22827 	case CMD_SEND_FRAME:		/* mds loopback */
22828 		/* cases already formatted for sli4 wqe - no chgs necessary */
22829 		return;
22830 	default:
22831 		dump_stack();
22832 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
22833 				"6207 Invalid command 0x%x\n",
22834 				cmnd);
22835 		break;
22836 	}
22837 
22838 	wqe->generic.wqe_com.abort_tag = abort_tag;
22839 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, job->iotag);
22840 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
22841 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
22842 }
22843