xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision 21ab7031)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2022 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.     *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/pci.h>
26 #include <linux/interrupt.h>
27 #include <linux/delay.h>
28 #include <linux/slab.h>
29 #include <linux/lockdep.h>
30 
31 #include <scsi/scsi.h>
32 #include <scsi/scsi_cmnd.h>
33 #include <scsi/scsi_device.h>
34 #include <scsi/scsi_host.h>
35 #include <scsi/scsi_transport_fc.h>
36 #include <scsi/fc/fc_fs.h>
37 #include <linux/aer.h>
38 #include <linux/crash_dump.h>
39 #ifdef CONFIG_X86
40 #include <asm/set_memory.h>
41 #endif
42 
43 #include "lpfc_hw4.h"
44 #include "lpfc_hw.h"
45 #include "lpfc_sli.h"
46 #include "lpfc_sli4.h"
47 #include "lpfc_nl.h"
48 #include "lpfc_disc.h"
49 #include "lpfc.h"
50 #include "lpfc_scsi.h"
51 #include "lpfc_nvme.h"
52 #include "lpfc_crtn.h"
53 #include "lpfc_logmsg.h"
54 #include "lpfc_compat.h"
55 #include "lpfc_debugfs.h"
56 #include "lpfc_vport.h"
57 #include "lpfc_version.h"
58 
59 /* There are only four IOCB completion types. */
60 typedef enum _lpfc_iocb_type {
61 	LPFC_UNKNOWN_IOCB,
62 	LPFC_UNSOL_IOCB,
63 	LPFC_SOL_IOCB,
64 	LPFC_ABORT_IOCB
65 } lpfc_iocb_type;
66 
67 
68 /* Provide function prototypes local to this module. */
69 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
70 				  uint32_t);
71 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
72 			      uint8_t *, uint32_t *);
73 static struct lpfc_iocbq *
74 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
75 				  struct lpfc_iocbq *rspiocbq);
76 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
77 				      struct hbq_dmabuf *);
78 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
79 					  struct hbq_dmabuf *dmabuf);
80 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
81 				   struct lpfc_queue *cq, struct lpfc_cqe *cqe);
82 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
83 				       int);
84 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
85 				     struct lpfc_queue *eq,
86 				     struct lpfc_eqe *eqe);
87 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
88 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
89 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
90 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
91 				    struct lpfc_queue *cq,
92 				    struct lpfc_cqe *cqe);
93 static uint16_t lpfc_wqe_bpl2sgl(struct lpfc_hba *phba,
94 				 struct lpfc_iocbq *pwqeq,
95 				 struct lpfc_sglq *sglq);
96 
97 union lpfc_wqe128 lpfc_iread_cmd_template;
98 union lpfc_wqe128 lpfc_iwrite_cmd_template;
99 union lpfc_wqe128 lpfc_icmnd_cmd_template;
100 
101 /* Setup WQE templates for IOs */
102 void lpfc_wqe_cmd_template(void)
103 {
104 	union lpfc_wqe128 *wqe;
105 
106 	/* IREAD template */
107 	wqe = &lpfc_iread_cmd_template;
108 	memset(wqe, 0, sizeof(union lpfc_wqe128));
109 
110 	/* Word 0, 1, 2 - BDE is variable */
111 
112 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
113 
114 	/* Word 4 - total_xfer_len is variable */
115 
116 	/* Word 5 - is zero */
117 
118 	/* Word 6 - ctxt_tag, xri_tag is variable */
119 
120 	/* Word 7 */
121 	bf_set(wqe_cmnd, &wqe->fcp_iread.wqe_com, CMD_FCP_IREAD64_WQE);
122 	bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, PARM_READ_CHECK);
123 	bf_set(wqe_class, &wqe->fcp_iread.wqe_com, CLASS3);
124 	bf_set(wqe_ct, &wqe->fcp_iread.wqe_com, SLI4_CT_RPI);
125 
126 	/* Word 8 - abort_tag is variable */
127 
128 	/* Word 9  - reqtag is variable */
129 
130 	/* Word 10 - dbde, wqes is variable */
131 	bf_set(wqe_qosd, &wqe->fcp_iread.wqe_com, 0);
132 	bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
133 	bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com, LPFC_WQE_LENLOC_WORD4);
134 	bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
135 	bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
136 
137 	/* Word 11 - pbde is variable */
138 	bf_set(wqe_cmd_type, &wqe->fcp_iread.wqe_com, COMMAND_DATA_IN);
139 	bf_set(wqe_cqid, &wqe->fcp_iread.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
140 	bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
141 
142 	/* Word 12 - is zero */
143 
144 	/* Word 13, 14, 15 - PBDE is variable */
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 - pbde is variable */
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 	bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
181 
182 	/* Word 12 - is zero */
183 
184 	/* Word 13, 14, 15 - PBDE is variable */
185 
186 	/* ICMND template */
187 	wqe = &lpfc_icmnd_cmd_template;
188 	memset(wqe, 0, sizeof(union lpfc_wqe128));
189 
190 	/* Word 0, 1, 2 - BDE is variable */
191 
192 	/* Word 3 - payload_offset_len is variable */
193 
194 	/* Word 4, 5 - is zero */
195 
196 	/* Word 6 - ctxt_tag, xri_tag is variable */
197 
198 	/* Word 7 */
199 	bf_set(wqe_cmnd, &wqe->fcp_icmd.wqe_com, CMD_FCP_ICMND64_WQE);
200 	bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
201 	bf_set(wqe_class, &wqe->fcp_icmd.wqe_com, CLASS3);
202 	bf_set(wqe_ct, &wqe->fcp_icmd.wqe_com, SLI4_CT_RPI);
203 
204 	/* Word 8 - abort_tag is variable */
205 
206 	/* Word 9  - reqtag is variable */
207 
208 	/* Word 10 - dbde, wqes is variable */
209 	bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
210 	bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_NONE);
211 	bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com, LPFC_WQE_LENLOC_NONE);
212 	bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
213 	bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
214 
215 	/* Word 11 */
216 	bf_set(wqe_cmd_type, &wqe->fcp_icmd.wqe_com, COMMAND_DATA_IN);
217 	bf_set(wqe_cqid, &wqe->fcp_icmd.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
218 	bf_set(wqe_pbde, &wqe->fcp_icmd.wqe_com, 0);
219 
220 	/* Word 12, 13, 14, 15 - is zero */
221 }
222 
223 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
224 /**
225  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
226  * @srcp: Source memory pointer.
227  * @destp: Destination memory pointer.
228  * @cnt: Number of words required to be copied.
229  *       Must be a multiple of sizeof(uint64_t)
230  *
231  * This function is used for copying data between driver memory
232  * and the SLI WQ. This function also changes the endianness
233  * of each word if native endianness is different from SLI
234  * endianness. This function can be called with or without
235  * lock.
236  **/
237 static void
238 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
239 {
240 	uint64_t *src = srcp;
241 	uint64_t *dest = destp;
242 	int i;
243 
244 	for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
245 		*dest++ = *src++;
246 }
247 #else
248 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
249 #endif
250 
251 /**
252  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
253  * @q: The Work Queue to operate on.
254  * @wqe: The work Queue Entry to put on the Work queue.
255  *
256  * This routine will copy the contents of @wqe to the next available entry on
257  * the @q. This function will then ring the Work Queue Doorbell to signal the
258  * HBA to start processing the Work Queue Entry. This function returns 0 if
259  * successful. If no entries are available on @q then this function will return
260  * -ENOMEM.
261  * The caller is expected to hold the hbalock when calling this routine.
262  **/
263 static int
264 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
265 {
266 	union lpfc_wqe *temp_wqe;
267 	struct lpfc_register doorbell;
268 	uint32_t host_index;
269 	uint32_t idx;
270 	uint32_t i = 0;
271 	uint8_t *tmp;
272 	u32 if_type;
273 
274 	/* sanity check on queue memory */
275 	if (unlikely(!q))
276 		return -ENOMEM;
277 
278 	temp_wqe = lpfc_sli4_qe(q, q->host_index);
279 
280 	/* If the host has not yet processed the next entry then we are done */
281 	idx = ((q->host_index + 1) % q->entry_count);
282 	if (idx == q->hba_index) {
283 		q->WQ_overflow++;
284 		return -EBUSY;
285 	}
286 	q->WQ_posted++;
287 	/* set consumption flag every once in a while */
288 	if (!((q->host_index + 1) % q->notify_interval))
289 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
290 	else
291 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
292 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
293 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
294 	lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
295 	if (q->dpp_enable && q->phba->cfg_enable_dpp) {
296 		/* write to DPP aperture taking advatage of Combined Writes */
297 		tmp = (uint8_t *)temp_wqe;
298 #ifdef __raw_writeq
299 		for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
300 			__raw_writeq(*((uint64_t *)(tmp + i)),
301 					q->dpp_regaddr + i);
302 #else
303 		for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
304 			__raw_writel(*((uint32_t *)(tmp + i)),
305 					q->dpp_regaddr + i);
306 #endif
307 	}
308 	/* ensure WQE bcopy and DPP flushed before doorbell write */
309 	wmb();
310 
311 	/* Update the host index before invoking device */
312 	host_index = q->host_index;
313 
314 	q->host_index = idx;
315 
316 	/* Ring Doorbell */
317 	doorbell.word0 = 0;
318 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
319 		if (q->dpp_enable && q->phba->cfg_enable_dpp) {
320 			bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
321 			bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
322 			bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
323 			    q->dpp_id);
324 			bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
325 			    q->queue_id);
326 		} else {
327 			bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
328 			bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
329 
330 			/* Leave bits <23:16> clear for if_type 6 dpp */
331 			if_type = bf_get(lpfc_sli_intf_if_type,
332 					 &q->phba->sli4_hba.sli_intf);
333 			if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
334 				bf_set(lpfc_wq_db_list_fm_index, &doorbell,
335 				       host_index);
336 		}
337 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
338 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
339 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
340 	} else {
341 		return -EINVAL;
342 	}
343 	writel(doorbell.word0, q->db_regaddr);
344 
345 	return 0;
346 }
347 
348 /**
349  * lpfc_sli4_wq_release - Updates internal hba index for WQ
350  * @q: The Work Queue to operate on.
351  * @index: The index to advance the hba index to.
352  *
353  * This routine will update the HBA index of a queue to reflect consumption of
354  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
355  * an entry the host calls this function to update the queue's internal
356  * pointers.
357  **/
358 static void
359 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
360 {
361 	/* sanity check on queue memory */
362 	if (unlikely(!q))
363 		return;
364 
365 	q->hba_index = index;
366 }
367 
368 /**
369  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
370  * @q: The Mailbox Queue to operate on.
371  * @mqe: The Mailbox Queue Entry to put on the Work queue.
372  *
373  * This routine will copy the contents of @mqe to the next available entry on
374  * the @q. This function will then ring the Work Queue Doorbell to signal the
375  * HBA to start processing the Work Queue Entry. This function returns 0 if
376  * successful. If no entries are available on @q then this function will return
377  * -ENOMEM.
378  * The caller is expected to hold the hbalock when calling this routine.
379  **/
380 static uint32_t
381 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
382 {
383 	struct lpfc_mqe *temp_mqe;
384 	struct lpfc_register doorbell;
385 
386 	/* sanity check on queue memory */
387 	if (unlikely(!q))
388 		return -ENOMEM;
389 	temp_mqe = lpfc_sli4_qe(q, q->host_index);
390 
391 	/* If the host has not yet processed the next entry then we are done */
392 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
393 		return -ENOMEM;
394 	lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
395 	/* Save off the mailbox pointer for completion */
396 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
397 
398 	/* Update the host index before invoking device */
399 	q->host_index = ((q->host_index + 1) % q->entry_count);
400 
401 	/* Ring Doorbell */
402 	doorbell.word0 = 0;
403 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
404 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
405 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
406 	return 0;
407 }
408 
409 /**
410  * lpfc_sli4_mq_release - Updates internal hba index for MQ
411  * @q: The Mailbox Queue to operate on.
412  *
413  * This routine will update the HBA index of a queue to reflect consumption of
414  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
415  * an entry the host calls this function to update the queue's internal
416  * pointers. This routine returns the number of entries that were consumed by
417  * the HBA.
418  **/
419 static uint32_t
420 lpfc_sli4_mq_release(struct lpfc_queue *q)
421 {
422 	/* sanity check on queue memory */
423 	if (unlikely(!q))
424 		return 0;
425 
426 	/* Clear the mailbox pointer for completion */
427 	q->phba->mbox = NULL;
428 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
429 	return 1;
430 }
431 
432 /**
433  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
434  * @q: The Event Queue to get the first valid EQE from
435  *
436  * This routine will get the first valid Event Queue Entry from @q, update
437  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
438  * the Queue (no more work to do), or the Queue is full of EQEs that have been
439  * processed, but not popped back to the HBA then this routine will return NULL.
440  **/
441 static struct lpfc_eqe *
442 lpfc_sli4_eq_get(struct lpfc_queue *q)
443 {
444 	struct lpfc_eqe *eqe;
445 
446 	/* sanity check on queue memory */
447 	if (unlikely(!q))
448 		return NULL;
449 	eqe = lpfc_sli4_qe(q, q->host_index);
450 
451 	/* If the next EQE is not valid then we are done */
452 	if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
453 		return NULL;
454 
455 	/*
456 	 * insert barrier for instruction interlock : data from the hardware
457 	 * must have the valid bit checked before it can be copied and acted
458 	 * upon. Speculative instructions were allowing a bcopy at the start
459 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
460 	 * after our return, to copy data before the valid bit check above
461 	 * was done. As such, some of the copied data was stale. The barrier
462 	 * ensures the check is before any data is copied.
463 	 */
464 	mb();
465 	return eqe;
466 }
467 
468 /**
469  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
470  * @q: The Event Queue to disable interrupts
471  *
472  **/
473 void
474 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
475 {
476 	struct lpfc_register doorbell;
477 
478 	doorbell.word0 = 0;
479 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
480 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
481 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
482 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
483 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
484 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
485 }
486 
487 /**
488  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
489  * @q: The Event Queue to disable interrupts
490  *
491  **/
492 void
493 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
494 {
495 	struct lpfc_register doorbell;
496 
497 	doorbell.word0 = 0;
498 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
499 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
500 }
501 
502 /**
503  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
504  * @phba: adapter with EQ
505  * @q: The Event Queue that the host has completed processing for.
506  * @count: Number of elements that have been consumed
507  * @arm: Indicates whether the host wants to arms this CQ.
508  *
509  * This routine will notify the HBA, by ringing the doorbell, that count
510  * number of EQEs have been processed. The @arm parameter indicates whether
511  * the queue should be rearmed when ringing the doorbell.
512  **/
513 void
514 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
515 		     uint32_t count, bool arm)
516 {
517 	struct lpfc_register doorbell;
518 
519 	/* sanity check on queue memory */
520 	if (unlikely(!q || (count == 0 && !arm)))
521 		return;
522 
523 	/* ring doorbell for number popped */
524 	doorbell.word0 = 0;
525 	if (arm) {
526 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
527 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
528 	}
529 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
530 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
531 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
532 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
533 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
534 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
535 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
536 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
537 		readl(q->phba->sli4_hba.EQDBregaddr);
538 }
539 
540 /**
541  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
542  * @phba: adapter with EQ
543  * @q: The Event Queue that the host has completed processing for.
544  * @count: Number of elements that have been consumed
545  * @arm: Indicates whether the host wants to arms this CQ.
546  *
547  * This routine will notify the HBA, by ringing the doorbell, that count
548  * number of EQEs have been processed. The @arm parameter indicates whether
549  * the queue should be rearmed when ringing the doorbell.
550  **/
551 void
552 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
553 			  uint32_t count, bool arm)
554 {
555 	struct lpfc_register doorbell;
556 
557 	/* sanity check on queue memory */
558 	if (unlikely(!q || (count == 0 && !arm)))
559 		return;
560 
561 	/* ring doorbell for number popped */
562 	doorbell.word0 = 0;
563 	if (arm)
564 		bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
565 	bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
566 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
567 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
568 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
569 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
570 		readl(q->phba->sli4_hba.EQDBregaddr);
571 }
572 
573 static void
574 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
575 			struct lpfc_eqe *eqe)
576 {
577 	if (!phba->sli4_hba.pc_sli4_params.eqav)
578 		bf_set_le32(lpfc_eqe_valid, eqe, 0);
579 
580 	eq->host_index = ((eq->host_index + 1) % eq->entry_count);
581 
582 	/* if the index wrapped around, toggle the valid bit */
583 	if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
584 		eq->qe_valid = (eq->qe_valid) ? 0 : 1;
585 }
586 
587 static void
588 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
589 {
590 	struct lpfc_eqe *eqe = NULL;
591 	u32 eq_count = 0, cq_count = 0;
592 	struct lpfc_cqe *cqe = NULL;
593 	struct lpfc_queue *cq = NULL, *childq = NULL;
594 	int cqid = 0;
595 
596 	/* walk all the EQ entries and drop on the floor */
597 	eqe = lpfc_sli4_eq_get(eq);
598 	while (eqe) {
599 		/* Get the reference to the corresponding CQ */
600 		cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
601 		cq = NULL;
602 
603 		list_for_each_entry(childq, &eq->child_list, list) {
604 			if (childq->queue_id == cqid) {
605 				cq = childq;
606 				break;
607 			}
608 		}
609 		/* If CQ is valid, iterate through it and drop all the CQEs */
610 		if (cq) {
611 			cqe = lpfc_sli4_cq_get(cq);
612 			while (cqe) {
613 				__lpfc_sli4_consume_cqe(phba, cq, cqe);
614 				cq_count++;
615 				cqe = lpfc_sli4_cq_get(cq);
616 			}
617 			/* Clear and re-arm the CQ */
618 			phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
619 			    LPFC_QUEUE_REARM);
620 			cq_count = 0;
621 		}
622 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
623 		eq_count++;
624 		eqe = lpfc_sli4_eq_get(eq);
625 	}
626 
627 	/* Clear and re-arm the EQ */
628 	phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
629 }
630 
631 static int
632 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
633 		     uint8_t rearm)
634 {
635 	struct lpfc_eqe *eqe;
636 	int count = 0, consumed = 0;
637 
638 	if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
639 		goto rearm_and_exit;
640 
641 	eqe = lpfc_sli4_eq_get(eq);
642 	while (eqe) {
643 		lpfc_sli4_hba_handle_eqe(phba, eq, eqe);
644 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
645 
646 		consumed++;
647 		if (!(++count % eq->max_proc_limit))
648 			break;
649 
650 		if (!(count % eq->notify_interval)) {
651 			phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
652 							LPFC_QUEUE_NOARM);
653 			consumed = 0;
654 		}
655 
656 		eqe = lpfc_sli4_eq_get(eq);
657 	}
658 	eq->EQ_processed += count;
659 
660 	/* Track the max number of EQEs processed in 1 intr */
661 	if (count > eq->EQ_max_eqe)
662 		eq->EQ_max_eqe = count;
663 
664 	xchg(&eq->queue_claimed, 0);
665 
666 rearm_and_exit:
667 	/* Always clear the EQ. */
668 	phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
669 
670 	return count;
671 }
672 
673 /**
674  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
675  * @q: The Completion Queue to get the first valid CQE from
676  *
677  * This routine will get the first valid Completion Queue Entry from @q, update
678  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
679  * the Queue (no more work to do), or the Queue is full of CQEs that have been
680  * processed, but not popped back to the HBA then this routine will return NULL.
681  **/
682 static struct lpfc_cqe *
683 lpfc_sli4_cq_get(struct lpfc_queue *q)
684 {
685 	struct lpfc_cqe *cqe;
686 
687 	/* sanity check on queue memory */
688 	if (unlikely(!q))
689 		return NULL;
690 	cqe = lpfc_sli4_qe(q, q->host_index);
691 
692 	/* If the next CQE is not valid then we are done */
693 	if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
694 		return NULL;
695 
696 	/*
697 	 * insert barrier for instruction interlock : data from the hardware
698 	 * must have the valid bit checked before it can be copied and acted
699 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
700 	 * instructions allowing action on content before valid bit checked,
701 	 * add barrier here as well. May not be needed as "content" is a
702 	 * single 32-bit entity here (vs multi word structure for cq's).
703 	 */
704 	mb();
705 	return cqe;
706 }
707 
708 static void
709 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
710 			struct lpfc_cqe *cqe)
711 {
712 	if (!phba->sli4_hba.pc_sli4_params.cqav)
713 		bf_set_le32(lpfc_cqe_valid, cqe, 0);
714 
715 	cq->host_index = ((cq->host_index + 1) % cq->entry_count);
716 
717 	/* if the index wrapped around, toggle the valid bit */
718 	if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
719 		cq->qe_valid = (cq->qe_valid) ? 0 : 1;
720 }
721 
722 /**
723  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
724  * @phba: the adapter with the CQ
725  * @q: The Completion Queue that the host has completed processing for.
726  * @count: the number of elements that were consumed
727  * @arm: Indicates whether the host wants to arms this CQ.
728  *
729  * This routine will notify the HBA, by ringing the doorbell, that the
730  * CQEs have been processed. The @arm parameter specifies whether the
731  * queue should be rearmed when ringing the doorbell.
732  **/
733 void
734 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
735 		     uint32_t count, bool arm)
736 {
737 	struct lpfc_register doorbell;
738 
739 	/* sanity check on queue memory */
740 	if (unlikely(!q || (count == 0 && !arm)))
741 		return;
742 
743 	/* ring doorbell for number popped */
744 	doorbell.word0 = 0;
745 	if (arm)
746 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
747 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
748 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
749 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
750 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
751 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
752 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
753 }
754 
755 /**
756  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
757  * @phba: the adapter with the CQ
758  * @q: The Completion Queue that the host has completed processing for.
759  * @count: the number of elements that were consumed
760  * @arm: Indicates whether the host wants to arms this CQ.
761  *
762  * This routine will notify the HBA, by ringing the doorbell, that the
763  * CQEs have been processed. The @arm parameter specifies whether the
764  * queue should be rearmed when ringing the doorbell.
765  **/
766 void
767 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
768 			 uint32_t count, bool arm)
769 {
770 	struct lpfc_register doorbell;
771 
772 	/* sanity check on queue memory */
773 	if (unlikely(!q || (count == 0 && !arm)))
774 		return;
775 
776 	/* ring doorbell for number popped */
777 	doorbell.word0 = 0;
778 	if (arm)
779 		bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
780 	bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
781 	bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
782 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
783 }
784 
785 /*
786  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
787  *
788  * This routine will copy the contents of @wqe to the next available entry on
789  * the @q. This function will then ring the Receive Queue Doorbell to signal the
790  * HBA to start processing the Receive Queue Entry. This function returns the
791  * index that the rqe was copied to if successful. If no entries are available
792  * on @q then this function will return -ENOMEM.
793  * The caller is expected to hold the hbalock when calling this routine.
794  **/
795 int
796 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
797 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
798 {
799 	struct lpfc_rqe *temp_hrqe;
800 	struct lpfc_rqe *temp_drqe;
801 	struct lpfc_register doorbell;
802 	int hq_put_index;
803 	int dq_put_index;
804 
805 	/* sanity check on queue memory */
806 	if (unlikely(!hq) || unlikely(!dq))
807 		return -ENOMEM;
808 	hq_put_index = hq->host_index;
809 	dq_put_index = dq->host_index;
810 	temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
811 	temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
812 
813 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
814 		return -EINVAL;
815 	if (hq_put_index != dq_put_index)
816 		return -EINVAL;
817 	/* If the host has not yet processed the next entry then we are done */
818 	if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
819 		return -EBUSY;
820 	lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
821 	lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
822 
823 	/* Update the host index to point to the next slot */
824 	hq->host_index = ((hq_put_index + 1) % hq->entry_count);
825 	dq->host_index = ((dq_put_index + 1) % dq->entry_count);
826 	hq->RQ_buf_posted++;
827 
828 	/* Ring The Header Receive Queue Doorbell */
829 	if (!(hq->host_index % hq->notify_interval)) {
830 		doorbell.word0 = 0;
831 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
832 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
833 			       hq->notify_interval);
834 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
835 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
836 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
837 			       hq->notify_interval);
838 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
839 			       hq->host_index);
840 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
841 		} else {
842 			return -EINVAL;
843 		}
844 		writel(doorbell.word0, hq->db_regaddr);
845 	}
846 	return hq_put_index;
847 }
848 
849 /*
850  * lpfc_sli4_rq_release - Updates internal hba index for RQ
851  *
852  * This routine will update the HBA index of a queue to reflect consumption of
853  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
854  * consumed an entry the host calls this function to update the queue's
855  * internal pointers. This routine returns the number of entries that were
856  * consumed by the HBA.
857  **/
858 static uint32_t
859 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
860 {
861 	/* sanity check on queue memory */
862 	if (unlikely(!hq) || unlikely(!dq))
863 		return 0;
864 
865 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
866 		return 0;
867 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
868 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
869 	return 1;
870 }
871 
872 /**
873  * lpfc_cmd_iocb - Get next command iocb entry in the ring
874  * @phba: Pointer to HBA context object.
875  * @pring: Pointer to driver SLI ring object.
876  *
877  * This function returns pointer to next command iocb entry
878  * in the command ring. The caller must hold hbalock to prevent
879  * other threads consume the next command iocb.
880  * SLI-2/SLI-3 provide different sized iocbs.
881  **/
882 static inline IOCB_t *
883 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
884 {
885 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
886 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
887 }
888 
889 /**
890  * lpfc_resp_iocb - Get next response iocb entry in the ring
891  * @phba: Pointer to HBA context object.
892  * @pring: Pointer to driver SLI ring object.
893  *
894  * This function returns pointer to next response iocb entry
895  * in the response ring. The caller must hold hbalock to make sure
896  * that no other thread consume the next response iocb.
897  * SLI-2/SLI-3 provide different sized iocbs.
898  **/
899 static inline IOCB_t *
900 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
901 {
902 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
903 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
904 }
905 
906 /**
907  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
908  * @phba: Pointer to HBA context object.
909  *
910  * This function is called with hbalock held. This function
911  * allocates a new driver iocb object from the iocb pool. If the
912  * allocation is successful, it returns pointer to the newly
913  * allocated iocb object else it returns NULL.
914  **/
915 struct lpfc_iocbq *
916 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
917 {
918 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
919 	struct lpfc_iocbq * iocbq = NULL;
920 
921 	lockdep_assert_held(&phba->hbalock);
922 
923 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
924 	if (iocbq)
925 		phba->iocb_cnt++;
926 	if (phba->iocb_cnt > phba->iocb_max)
927 		phba->iocb_max = phba->iocb_cnt;
928 	return iocbq;
929 }
930 
931 /**
932  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
933  * @phba: Pointer to HBA context object.
934  * @xritag: XRI value.
935  *
936  * This function clears the sglq pointer from the array of active
937  * sglq's. The xritag that is passed in is used to index into the
938  * array. Before the xritag can be used it needs to be adjusted
939  * by subtracting the xribase.
940  *
941  * Returns sglq ponter = success, NULL = Failure.
942  **/
943 struct lpfc_sglq *
944 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
945 {
946 	struct lpfc_sglq *sglq;
947 
948 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
949 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
950 	return sglq;
951 }
952 
953 /**
954  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
955  * @phba: Pointer to HBA context object.
956  * @xritag: XRI value.
957  *
958  * This function returns the sglq pointer from the array of active
959  * sglq's. The xritag that is passed in is used to index into the
960  * array. Before the xritag can be used it needs to be adjusted
961  * by subtracting the xribase.
962  *
963  * Returns sglq ponter = success, NULL = Failure.
964  **/
965 struct lpfc_sglq *
966 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
967 {
968 	struct lpfc_sglq *sglq;
969 
970 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
971 	return sglq;
972 }
973 
974 /**
975  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
976  * @phba: Pointer to HBA context object.
977  * @xritag: xri used in this exchange.
978  * @rrq: The RRQ to be cleared.
979  *
980  **/
981 void
982 lpfc_clr_rrq_active(struct lpfc_hba *phba,
983 		    uint16_t xritag,
984 		    struct lpfc_node_rrq *rrq)
985 {
986 	struct lpfc_nodelist *ndlp = NULL;
987 
988 	/* Lookup did to verify if did is still active on this vport */
989 	if (rrq->vport)
990 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
991 
992 	if (!ndlp)
993 		goto out;
994 
995 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
996 		rrq->send_rrq = 0;
997 		rrq->xritag = 0;
998 		rrq->rrq_stop_time = 0;
999 	}
1000 out:
1001 	mempool_free(rrq, phba->rrq_pool);
1002 }
1003 
1004 /**
1005  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
1006  * @phba: Pointer to HBA context object.
1007  *
1008  * This function is called with hbalock held. This function
1009  * Checks if stop_time (ratov from setting rrq active) has
1010  * been reached, if it has and the send_rrq flag is set then
1011  * it will call lpfc_send_rrq. If the send_rrq flag is not set
1012  * then it will just call the routine to clear the rrq and
1013  * free the rrq resource.
1014  * The timer is set to the next rrq that is going to expire before
1015  * leaving the routine.
1016  *
1017  **/
1018 void
1019 lpfc_handle_rrq_active(struct lpfc_hba *phba)
1020 {
1021 	struct lpfc_node_rrq *rrq;
1022 	struct lpfc_node_rrq *nextrrq;
1023 	unsigned long next_time;
1024 	unsigned long iflags;
1025 	LIST_HEAD(send_rrq);
1026 
1027 	spin_lock_irqsave(&phba->hbalock, iflags);
1028 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1029 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1030 	list_for_each_entry_safe(rrq, nextrrq,
1031 				 &phba->active_rrq_list, list) {
1032 		if (time_after(jiffies, rrq->rrq_stop_time))
1033 			list_move(&rrq->list, &send_rrq);
1034 		else if (time_before(rrq->rrq_stop_time, next_time))
1035 			next_time = rrq->rrq_stop_time;
1036 	}
1037 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1038 	if ((!list_empty(&phba->active_rrq_list)) &&
1039 	    (!(phba->pport->load_flag & FC_UNLOADING)))
1040 		mod_timer(&phba->rrq_tmr, next_time);
1041 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
1042 		list_del(&rrq->list);
1043 		if (!rrq->send_rrq) {
1044 			/* this call will free the rrq */
1045 			lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1046 		} else if (lpfc_send_rrq(phba, rrq)) {
1047 			/* if we send the rrq then the completion handler
1048 			*  will clear the bit in the xribitmap.
1049 			*/
1050 			lpfc_clr_rrq_active(phba, rrq->xritag,
1051 					    rrq);
1052 		}
1053 	}
1054 }
1055 
1056 /**
1057  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
1058  * @vport: Pointer to vport context object.
1059  * @xri: The xri used in the exchange.
1060  * @did: The targets DID for this exchange.
1061  *
1062  * returns NULL = rrq not found in the phba->active_rrq_list.
1063  *         rrq = rrq for this xri and target.
1064  **/
1065 struct lpfc_node_rrq *
1066 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
1067 {
1068 	struct lpfc_hba *phba = vport->phba;
1069 	struct lpfc_node_rrq *rrq;
1070 	struct lpfc_node_rrq *nextrrq;
1071 	unsigned long iflags;
1072 
1073 	if (phba->sli_rev != LPFC_SLI_REV4)
1074 		return NULL;
1075 	spin_lock_irqsave(&phba->hbalock, iflags);
1076 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1077 		if (rrq->vport == vport && rrq->xritag == xri &&
1078 				rrq->nlp_DID == did){
1079 			list_del(&rrq->list);
1080 			spin_unlock_irqrestore(&phba->hbalock, iflags);
1081 			return rrq;
1082 		}
1083 	}
1084 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1085 	return NULL;
1086 }
1087 
1088 /**
1089  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
1090  * @vport: Pointer to vport context object.
1091  * @ndlp: Pointer to the lpfc_node_list structure.
1092  * If ndlp is NULL Remove all active RRQs for this vport from the
1093  * phba->active_rrq_list and clear the rrq.
1094  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
1095  **/
1096 void
1097 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
1098 
1099 {
1100 	struct lpfc_hba *phba = vport->phba;
1101 	struct lpfc_node_rrq *rrq;
1102 	struct lpfc_node_rrq *nextrrq;
1103 	unsigned long iflags;
1104 	LIST_HEAD(rrq_list);
1105 
1106 	if (phba->sli_rev != LPFC_SLI_REV4)
1107 		return;
1108 	if (!ndlp) {
1109 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
1110 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
1111 	}
1112 	spin_lock_irqsave(&phba->hbalock, iflags);
1113 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1114 		if (rrq->vport != vport)
1115 			continue;
1116 
1117 		if (!ndlp || ndlp == lpfc_findnode_did(vport, rrq->nlp_DID))
1118 			list_move(&rrq->list, &rrq_list);
1119 
1120 	}
1121 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1122 
1123 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1124 		list_del(&rrq->list);
1125 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1126 	}
1127 }
1128 
1129 /**
1130  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1131  * @phba: Pointer to HBA context object.
1132  * @ndlp: Targets nodelist pointer for this exchange.
1133  * @xritag: the xri in the bitmap to test.
1134  *
1135  * This function returns:
1136  * 0 = rrq not active for this xri
1137  * 1 = rrq is valid for this xri.
1138  **/
1139 int
1140 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1141 			uint16_t  xritag)
1142 {
1143 	if (!ndlp)
1144 		return 0;
1145 	if (!ndlp->active_rrqs_xri_bitmap)
1146 		return 0;
1147 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1148 		return 1;
1149 	else
1150 		return 0;
1151 }
1152 
1153 /**
1154  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1155  * @phba: Pointer to HBA context object.
1156  * @ndlp: nodelist pointer for this target.
1157  * @xritag: xri used in this exchange.
1158  * @rxid: Remote Exchange ID.
1159  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1160  *
1161  * This function takes the hbalock.
1162  * The active bit is always set in the active rrq xri_bitmap even
1163  * if there is no slot avaiable for the other rrq information.
1164  *
1165  * returns 0 rrq actived for this xri
1166  *         < 0 No memory or invalid ndlp.
1167  **/
1168 int
1169 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1170 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1171 {
1172 	unsigned long iflags;
1173 	struct lpfc_node_rrq *rrq;
1174 	int empty;
1175 
1176 	if (!ndlp)
1177 		return -EINVAL;
1178 
1179 	if (!phba->cfg_enable_rrq)
1180 		return -EINVAL;
1181 
1182 	spin_lock_irqsave(&phba->hbalock, iflags);
1183 	if (phba->pport->load_flag & FC_UNLOADING) {
1184 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1185 		goto out;
1186 	}
1187 
1188 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
1189 		goto out;
1190 
1191 	if (!ndlp->active_rrqs_xri_bitmap)
1192 		goto out;
1193 
1194 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1195 		goto out;
1196 
1197 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1198 	rrq = mempool_alloc(phba->rrq_pool, GFP_ATOMIC);
1199 	if (!rrq) {
1200 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1201 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1202 				" DID:0x%x Send:%d\n",
1203 				xritag, rxid, ndlp->nlp_DID, send_rrq);
1204 		return -EINVAL;
1205 	}
1206 	if (phba->cfg_enable_rrq == 1)
1207 		rrq->send_rrq = send_rrq;
1208 	else
1209 		rrq->send_rrq = 0;
1210 	rrq->xritag = xritag;
1211 	rrq->rrq_stop_time = jiffies +
1212 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1213 	rrq->nlp_DID = ndlp->nlp_DID;
1214 	rrq->vport = ndlp->vport;
1215 	rrq->rxid = rxid;
1216 	spin_lock_irqsave(&phba->hbalock, iflags);
1217 	empty = list_empty(&phba->active_rrq_list);
1218 	list_add_tail(&rrq->list, &phba->active_rrq_list);
1219 	phba->hba_flag |= HBA_RRQ_ACTIVE;
1220 	if (empty)
1221 		lpfc_worker_wake_up(phba);
1222 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1223 	return 0;
1224 out:
1225 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1226 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1227 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
1228 			" DID:0x%x Send:%d\n",
1229 			xritag, rxid, ndlp->nlp_DID, send_rrq);
1230 	return -EINVAL;
1231 }
1232 
1233 /**
1234  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1235  * @phba: Pointer to HBA context object.
1236  * @piocbq: Pointer to the iocbq.
1237  *
1238  * The driver calls this function with either the nvme ls ring lock
1239  * or the fc els ring lock held depending on the iocb usage.  This function
1240  * gets a new driver sglq object from the sglq list. If the list is not empty
1241  * then it is successful, it returns pointer to the newly allocated sglq
1242  * object else it returns NULL.
1243  **/
1244 static struct lpfc_sglq *
1245 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1246 {
1247 	struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1248 	struct lpfc_sglq *sglq = NULL;
1249 	struct lpfc_sglq *start_sglq = NULL;
1250 	struct lpfc_io_buf *lpfc_cmd;
1251 	struct lpfc_nodelist *ndlp;
1252 	int found = 0;
1253 	u8 cmnd;
1254 
1255 	cmnd = get_job_cmnd(phba, piocbq);
1256 
1257 	if (piocbq->cmd_flag & LPFC_IO_FCP) {
1258 		lpfc_cmd = piocbq->io_buf;
1259 		ndlp = lpfc_cmd->rdata->pnode;
1260 	} else  if ((cmnd == CMD_GEN_REQUEST64_CR) &&
1261 			!(piocbq->cmd_flag & LPFC_IO_LIBDFC)) {
1262 		ndlp = piocbq->ndlp;
1263 	} else  if (piocbq->cmd_flag & LPFC_IO_LIBDFC) {
1264 		if (piocbq->cmd_flag & LPFC_IO_LOOPBACK)
1265 			ndlp = NULL;
1266 		else
1267 			ndlp = piocbq->ndlp;
1268 	} else {
1269 		ndlp = piocbq->ndlp;
1270 	}
1271 
1272 	spin_lock(&phba->sli4_hba.sgl_list_lock);
1273 	list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1274 	start_sglq = sglq;
1275 	while (!found) {
1276 		if (!sglq)
1277 			break;
1278 		if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1279 		    test_bit(sglq->sli4_lxritag,
1280 		    ndlp->active_rrqs_xri_bitmap)) {
1281 			/* This xri has an rrq outstanding for this DID.
1282 			 * put it back in the list and get another xri.
1283 			 */
1284 			list_add_tail(&sglq->list, lpfc_els_sgl_list);
1285 			sglq = NULL;
1286 			list_remove_head(lpfc_els_sgl_list, sglq,
1287 						struct lpfc_sglq, list);
1288 			if (sglq == start_sglq) {
1289 				list_add_tail(&sglq->list, lpfc_els_sgl_list);
1290 				sglq = NULL;
1291 				break;
1292 			} else
1293 				continue;
1294 		}
1295 		sglq->ndlp = ndlp;
1296 		found = 1;
1297 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1298 		sglq->state = SGL_ALLOCATED;
1299 	}
1300 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
1301 	return sglq;
1302 }
1303 
1304 /**
1305  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1306  * @phba: Pointer to HBA context object.
1307  * @piocbq: Pointer to the iocbq.
1308  *
1309  * This function is called with the sgl_list lock held. This function
1310  * gets a new driver sglq object from the sglq list. If the
1311  * list is not empty then it is successful, it returns pointer to the newly
1312  * allocated sglq object else it returns NULL.
1313  **/
1314 struct lpfc_sglq *
1315 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1316 {
1317 	struct list_head *lpfc_nvmet_sgl_list;
1318 	struct lpfc_sglq *sglq = NULL;
1319 
1320 	lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1321 
1322 	lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1323 
1324 	list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1325 	if (!sglq)
1326 		return NULL;
1327 	phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1328 	sglq->state = SGL_ALLOCATED;
1329 	return sglq;
1330 }
1331 
1332 /**
1333  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1334  * @phba: Pointer to HBA context object.
1335  *
1336  * This function is called with no lock held. This function
1337  * allocates a new driver iocb object from the iocb pool. If the
1338  * allocation is successful, it returns pointer to the newly
1339  * allocated iocb object else it returns NULL.
1340  **/
1341 struct lpfc_iocbq *
1342 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1343 {
1344 	struct lpfc_iocbq * iocbq = NULL;
1345 	unsigned long iflags;
1346 
1347 	spin_lock_irqsave(&phba->hbalock, iflags);
1348 	iocbq = __lpfc_sli_get_iocbq(phba);
1349 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1350 	return iocbq;
1351 }
1352 
1353 /**
1354  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1355  * @phba: Pointer to HBA context object.
1356  * @iocbq: Pointer to driver iocb object.
1357  *
1358  * This function is called to release the driver iocb object
1359  * to the iocb pool. The iotag in the iocb object
1360  * does not change for each use of the iocb object. This function
1361  * clears all other fields of the iocb object when it is freed.
1362  * The sqlq structure that holds the xritag and phys and virtual
1363  * mappings for the scatter gather list is retrieved from the
1364  * active array of sglq. The get of the sglq pointer also clears
1365  * the entry in the array. If the status of the IO indiactes that
1366  * this IO was aborted then the sglq entry it put on the
1367  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1368  * IO has good status or fails for any other reason then the sglq
1369  * entry is added to the free list (lpfc_els_sgl_list). The hbalock is
1370  *  asserted held in the code path calling this routine.
1371  **/
1372 static void
1373 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1374 {
1375 	struct lpfc_sglq *sglq;
1376 	unsigned long iflag = 0;
1377 	struct lpfc_sli_ring *pring;
1378 
1379 	if (iocbq->sli4_xritag == NO_XRI)
1380 		sglq = NULL;
1381 	else
1382 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1383 
1384 
1385 	if (sglq)  {
1386 		if (iocbq->cmd_flag & LPFC_IO_NVMET) {
1387 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1388 					  iflag);
1389 			sglq->state = SGL_FREED;
1390 			sglq->ndlp = NULL;
1391 			list_add_tail(&sglq->list,
1392 				      &phba->sli4_hba.lpfc_nvmet_sgl_list);
1393 			spin_unlock_irqrestore(
1394 				&phba->sli4_hba.sgl_list_lock, iflag);
1395 			goto out;
1396 		}
1397 
1398 		if ((iocbq->cmd_flag & LPFC_EXCHANGE_BUSY) &&
1399 		    (!(unlikely(pci_channel_offline(phba->pcidev)))) &&
1400 		    sglq->state != SGL_XRI_ABORTED) {
1401 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1402 					  iflag);
1403 
1404 			/* Check if we can get a reference on ndlp */
1405 			if (sglq->ndlp && !lpfc_nlp_get(sglq->ndlp))
1406 				sglq->ndlp = NULL;
1407 
1408 			list_add(&sglq->list,
1409 				 &phba->sli4_hba.lpfc_abts_els_sgl_list);
1410 			spin_unlock_irqrestore(
1411 				&phba->sli4_hba.sgl_list_lock, iflag);
1412 		} else {
1413 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1414 					  iflag);
1415 			sglq->state = SGL_FREED;
1416 			sglq->ndlp = NULL;
1417 			list_add_tail(&sglq->list,
1418 				      &phba->sli4_hba.lpfc_els_sgl_list);
1419 			spin_unlock_irqrestore(
1420 				&phba->sli4_hba.sgl_list_lock, iflag);
1421 			pring = lpfc_phba_elsring(phba);
1422 			/* Check if TXQ queue needs to be serviced */
1423 			if (pring && (!list_empty(&pring->txq)))
1424 				lpfc_worker_wake_up(phba);
1425 		}
1426 	}
1427 
1428 out:
1429 	/*
1430 	 * Clean all volatile data fields, preserve iotag and node struct.
1431 	 */
1432 	memset_startat(iocbq, 0, wqe);
1433 	iocbq->sli4_lxritag = NO_XRI;
1434 	iocbq->sli4_xritag = NO_XRI;
1435 	iocbq->cmd_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET | LPFC_IO_CMF |
1436 			      LPFC_IO_NVME_LS);
1437 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1438 }
1439 
1440 
1441 /**
1442  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1443  * @phba: Pointer to HBA context object.
1444  * @iocbq: Pointer to driver iocb object.
1445  *
1446  * This function is called to release the driver iocb object to the
1447  * iocb pool. The iotag in the iocb object does not change for each
1448  * use of the iocb object. This function clears all other fields of
1449  * the iocb object when it is freed. The hbalock is asserted held in
1450  * the code path calling this routine.
1451  **/
1452 static void
1453 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1454 {
1455 
1456 	/*
1457 	 * Clean all volatile data fields, preserve iotag and node struct.
1458 	 */
1459 	memset_startat(iocbq, 0, iocb);
1460 	iocbq->sli4_xritag = NO_XRI;
1461 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1462 }
1463 
1464 /**
1465  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1466  * @phba: Pointer to HBA context object.
1467  * @iocbq: Pointer to driver iocb object.
1468  *
1469  * This function is called with hbalock held to release driver
1470  * iocb object to the iocb pool. The iotag in the iocb object
1471  * does not change for each use of the iocb object. This function
1472  * clears all other fields of the iocb object when it is freed.
1473  **/
1474 static void
1475 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1476 {
1477 	lockdep_assert_held(&phba->hbalock);
1478 
1479 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1480 	phba->iocb_cnt--;
1481 }
1482 
1483 /**
1484  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1485  * @phba: Pointer to HBA context object.
1486  * @iocbq: Pointer to driver iocb object.
1487  *
1488  * This function is called with no lock held to release the iocb to
1489  * iocb pool.
1490  **/
1491 void
1492 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1493 {
1494 	unsigned long iflags;
1495 
1496 	/*
1497 	 * Clean all volatile data fields, preserve iotag and node struct.
1498 	 */
1499 	spin_lock_irqsave(&phba->hbalock, iflags);
1500 	__lpfc_sli_release_iocbq(phba, iocbq);
1501 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1502 }
1503 
1504 /**
1505  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1506  * @phba: Pointer to HBA context object.
1507  * @iocblist: List of IOCBs.
1508  * @ulpstatus: ULP status in IOCB command field.
1509  * @ulpWord4: ULP word-4 in IOCB command field.
1510  *
1511  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1512  * on the list by invoking the complete callback function associated with the
1513  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1514  * fields.
1515  **/
1516 void
1517 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1518 		      uint32_t ulpstatus, uint32_t ulpWord4)
1519 {
1520 	struct lpfc_iocbq *piocb;
1521 
1522 	while (!list_empty(iocblist)) {
1523 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1524 		if (piocb->cmd_cmpl) {
1525 			if (piocb->cmd_flag & LPFC_IO_NVME) {
1526 				lpfc_nvme_cancel_iocb(phba, piocb,
1527 						      ulpstatus, ulpWord4);
1528 			} else {
1529 				if (phba->sli_rev == LPFC_SLI_REV4) {
1530 					bf_set(lpfc_wcqe_c_status,
1531 					       &piocb->wcqe_cmpl, ulpstatus);
1532 					piocb->wcqe_cmpl.parameter = ulpWord4;
1533 				} else {
1534 					piocb->iocb.ulpStatus = ulpstatus;
1535 					piocb->iocb.un.ulpWord[4] = ulpWord4;
1536 				}
1537 				(piocb->cmd_cmpl) (phba, piocb, piocb);
1538 			}
1539 		} else {
1540 			lpfc_sli_release_iocbq(phba, piocb);
1541 		}
1542 	}
1543 	return;
1544 }
1545 
1546 /**
1547  * lpfc_sli_iocb_cmd_type - Get the iocb type
1548  * @iocb_cmnd: iocb command code.
1549  *
1550  * This function is called by ring event handler function to get the iocb type.
1551  * This function translates the iocb command to an iocb command type used to
1552  * decide the final disposition of each completed IOCB.
1553  * The function returns
1554  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1555  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1556  * LPFC_ABORT_IOCB   if it is an abort iocb
1557  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1558  *
1559  * The caller is not required to hold any lock.
1560  **/
1561 static lpfc_iocb_type
1562 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1563 {
1564 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1565 
1566 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1567 		return 0;
1568 
1569 	switch (iocb_cmnd) {
1570 	case CMD_XMIT_SEQUENCE_CR:
1571 	case CMD_XMIT_SEQUENCE_CX:
1572 	case CMD_XMIT_BCAST_CN:
1573 	case CMD_XMIT_BCAST_CX:
1574 	case CMD_ELS_REQUEST_CR:
1575 	case CMD_ELS_REQUEST_CX:
1576 	case CMD_CREATE_XRI_CR:
1577 	case CMD_CREATE_XRI_CX:
1578 	case CMD_GET_RPI_CN:
1579 	case CMD_XMIT_ELS_RSP_CX:
1580 	case CMD_GET_RPI_CR:
1581 	case CMD_FCP_IWRITE_CR:
1582 	case CMD_FCP_IWRITE_CX:
1583 	case CMD_FCP_IREAD_CR:
1584 	case CMD_FCP_IREAD_CX:
1585 	case CMD_FCP_ICMND_CR:
1586 	case CMD_FCP_ICMND_CX:
1587 	case CMD_FCP_TSEND_CX:
1588 	case CMD_FCP_TRSP_CX:
1589 	case CMD_FCP_TRECEIVE_CX:
1590 	case CMD_FCP_AUTO_TRSP_CX:
1591 	case CMD_ADAPTER_MSG:
1592 	case CMD_ADAPTER_DUMP:
1593 	case CMD_XMIT_SEQUENCE64_CR:
1594 	case CMD_XMIT_SEQUENCE64_CX:
1595 	case CMD_XMIT_BCAST64_CN:
1596 	case CMD_XMIT_BCAST64_CX:
1597 	case CMD_ELS_REQUEST64_CR:
1598 	case CMD_ELS_REQUEST64_CX:
1599 	case CMD_FCP_IWRITE64_CR:
1600 	case CMD_FCP_IWRITE64_CX:
1601 	case CMD_FCP_IREAD64_CR:
1602 	case CMD_FCP_IREAD64_CX:
1603 	case CMD_FCP_ICMND64_CR:
1604 	case CMD_FCP_ICMND64_CX:
1605 	case CMD_FCP_TSEND64_CX:
1606 	case CMD_FCP_TRSP64_CX:
1607 	case CMD_FCP_TRECEIVE64_CX:
1608 	case CMD_GEN_REQUEST64_CR:
1609 	case CMD_GEN_REQUEST64_CX:
1610 	case CMD_XMIT_ELS_RSP64_CX:
1611 	case DSSCMD_IWRITE64_CR:
1612 	case DSSCMD_IWRITE64_CX:
1613 	case DSSCMD_IREAD64_CR:
1614 	case DSSCMD_IREAD64_CX:
1615 	case CMD_SEND_FRAME:
1616 		type = LPFC_SOL_IOCB;
1617 		break;
1618 	case CMD_ABORT_XRI_CN:
1619 	case CMD_ABORT_XRI_CX:
1620 	case CMD_CLOSE_XRI_CN:
1621 	case CMD_CLOSE_XRI_CX:
1622 	case CMD_XRI_ABORTED_CX:
1623 	case CMD_ABORT_MXRI64_CN:
1624 	case CMD_XMIT_BLS_RSP64_CX:
1625 		type = LPFC_ABORT_IOCB;
1626 		break;
1627 	case CMD_RCV_SEQUENCE_CX:
1628 	case CMD_RCV_ELS_REQ_CX:
1629 	case CMD_RCV_SEQUENCE64_CX:
1630 	case CMD_RCV_ELS_REQ64_CX:
1631 	case CMD_ASYNC_STATUS:
1632 	case CMD_IOCB_RCV_SEQ64_CX:
1633 	case CMD_IOCB_RCV_ELS64_CX:
1634 	case CMD_IOCB_RCV_CONT64_CX:
1635 	case CMD_IOCB_RET_XRI64_CX:
1636 		type = LPFC_UNSOL_IOCB;
1637 		break;
1638 	case CMD_IOCB_XMIT_MSEQ64_CR:
1639 	case CMD_IOCB_XMIT_MSEQ64_CX:
1640 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1641 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1642 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1643 	case CMD_IOCB_ABORT_EXTENDED_CN:
1644 	case CMD_IOCB_RET_HBQE64_CN:
1645 	case CMD_IOCB_FCP_IBIDIR64_CR:
1646 	case CMD_IOCB_FCP_IBIDIR64_CX:
1647 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1648 	case CMD_IOCB_LOGENTRY_CN:
1649 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1650 		printk("%s - Unhandled SLI-3 Command x%x\n",
1651 				__func__, iocb_cmnd);
1652 		type = LPFC_UNKNOWN_IOCB;
1653 		break;
1654 	default:
1655 		type = LPFC_UNKNOWN_IOCB;
1656 		break;
1657 	}
1658 
1659 	return type;
1660 }
1661 
1662 /**
1663  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1664  * @phba: Pointer to HBA context object.
1665  *
1666  * This function is called from SLI initialization code
1667  * to configure every ring of the HBA's SLI interface. The
1668  * caller is not required to hold any lock. This function issues
1669  * a config_ring mailbox command for each ring.
1670  * This function returns zero if successful else returns a negative
1671  * error code.
1672  **/
1673 static int
1674 lpfc_sli_ring_map(struct lpfc_hba *phba)
1675 {
1676 	struct lpfc_sli *psli = &phba->sli;
1677 	LPFC_MBOXQ_t *pmb;
1678 	MAILBOX_t *pmbox;
1679 	int i, rc, ret = 0;
1680 
1681 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1682 	if (!pmb)
1683 		return -ENOMEM;
1684 	pmbox = &pmb->u.mb;
1685 	phba->link_state = LPFC_INIT_MBX_CMDS;
1686 	for (i = 0; i < psli->num_rings; i++) {
1687 		lpfc_config_ring(phba, i, pmb);
1688 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1689 		if (rc != MBX_SUCCESS) {
1690 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1691 					"0446 Adapter failed to init (%d), "
1692 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1693 					"ring %d\n",
1694 					rc, pmbox->mbxCommand,
1695 					pmbox->mbxStatus, i);
1696 			phba->link_state = LPFC_HBA_ERROR;
1697 			ret = -ENXIO;
1698 			break;
1699 		}
1700 	}
1701 	mempool_free(pmb, phba->mbox_mem_pool);
1702 	return ret;
1703 }
1704 
1705 /**
1706  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1707  * @phba: Pointer to HBA context object.
1708  * @pring: Pointer to driver SLI ring object.
1709  * @piocb: Pointer to the driver iocb object.
1710  *
1711  * The driver calls this function with the hbalock held for SLI3 ports or
1712  * the ring lock held for SLI4 ports. The function adds the
1713  * new iocb to txcmplq of the given ring. This function always returns
1714  * 0. If this function is called for ELS ring, this function checks if
1715  * there is a vport associated with the ELS command. This function also
1716  * starts els_tmofunc timer if this is an ELS command.
1717  **/
1718 static int
1719 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1720 			struct lpfc_iocbq *piocb)
1721 {
1722 	u32 ulp_command = 0;
1723 
1724 	BUG_ON(!piocb);
1725 	ulp_command = get_job_cmnd(phba, piocb);
1726 
1727 	list_add_tail(&piocb->list, &pring->txcmplq);
1728 	piocb->cmd_flag |= LPFC_IO_ON_TXCMPLQ;
1729 	pring->txcmplq_cnt++;
1730 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1731 	   (ulp_command != CMD_ABORT_XRI_WQE) &&
1732 	   (ulp_command != CMD_ABORT_XRI_CN) &&
1733 	   (ulp_command != CMD_CLOSE_XRI_CN)) {
1734 		BUG_ON(!piocb->vport);
1735 		if (!(piocb->vport->load_flag & FC_UNLOADING))
1736 			mod_timer(&piocb->vport->els_tmofunc,
1737 				  jiffies +
1738 				  msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1739 	}
1740 
1741 	return 0;
1742 }
1743 
1744 /**
1745  * lpfc_sli_ringtx_get - Get first element of the txq
1746  * @phba: Pointer to HBA context object.
1747  * @pring: Pointer to driver SLI ring object.
1748  *
1749  * This function is called with hbalock held to get next
1750  * iocb in txq of the given ring. If there is any iocb in
1751  * the txq, the function returns first iocb in the list after
1752  * removing the iocb from the list, else it returns NULL.
1753  **/
1754 struct lpfc_iocbq *
1755 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1756 {
1757 	struct lpfc_iocbq *cmd_iocb;
1758 
1759 	lockdep_assert_held(&phba->hbalock);
1760 
1761 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1762 	return cmd_iocb;
1763 }
1764 
1765 /**
1766  * lpfc_cmf_sync_cmpl - Process a CMF_SYNC_WQE cmpl
1767  * @phba: Pointer to HBA context object.
1768  * @cmdiocb: Pointer to driver command iocb object.
1769  * @rspiocb: Pointer to driver response iocb object.
1770  *
1771  * This routine will inform the driver of any BW adjustments we need
1772  * to make. These changes will be picked up during the next CMF
1773  * timer interrupt. In addition, any BW changes will be logged
1774  * with LOG_CGN_MGMT.
1775  **/
1776 static void
1777 lpfc_cmf_sync_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
1778 		   struct lpfc_iocbq *rspiocb)
1779 {
1780 	union lpfc_wqe128 *wqe;
1781 	uint32_t status, info;
1782 	struct lpfc_wcqe_complete *wcqe = &rspiocb->wcqe_cmpl;
1783 	uint64_t bw, bwdif, slop;
1784 	uint64_t pcent, bwpcent;
1785 	int asig, afpin, sigcnt, fpincnt;
1786 	int wsigmax, wfpinmax, cg, tdp;
1787 	char *s;
1788 
1789 	/* First check for error */
1790 	status = bf_get(lpfc_wcqe_c_status, wcqe);
1791 	if (status) {
1792 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1793 				"6211 CMF_SYNC_WQE Error "
1794 				"req_tag x%x status x%x hwstatus x%x "
1795 				"tdatap x%x parm x%x\n",
1796 				bf_get(lpfc_wcqe_c_request_tag, wcqe),
1797 				bf_get(lpfc_wcqe_c_status, wcqe),
1798 				bf_get(lpfc_wcqe_c_hw_status, wcqe),
1799 				wcqe->total_data_placed,
1800 				wcqe->parameter);
1801 		goto out;
1802 	}
1803 
1804 	/* Gather congestion information on a successful cmpl */
1805 	info = wcqe->parameter;
1806 	phba->cmf_active_info = info;
1807 
1808 	/* See if firmware info count is valid or has changed */
1809 	if (info > LPFC_MAX_CMF_INFO || phba->cmf_info_per_interval == info)
1810 		info = 0;
1811 	else
1812 		phba->cmf_info_per_interval = info;
1813 
1814 	tdp = bf_get(lpfc_wcqe_c_cmf_bw, wcqe);
1815 	cg = bf_get(lpfc_wcqe_c_cmf_cg, wcqe);
1816 
1817 	/* Get BW requirement from firmware */
1818 	bw = (uint64_t)tdp * LPFC_CMF_BLK_SIZE;
1819 	if (!bw) {
1820 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1821 				"6212 CMF_SYNC_WQE x%x: NULL bw\n",
1822 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
1823 		goto out;
1824 	}
1825 
1826 	/* Gather information needed for logging if a BW change is required */
1827 	wqe = &cmdiocb->wqe;
1828 	asig = bf_get(cmf_sync_asig, &wqe->cmf_sync);
1829 	afpin = bf_get(cmf_sync_afpin, &wqe->cmf_sync);
1830 	fpincnt = bf_get(cmf_sync_wfpincnt, &wqe->cmf_sync);
1831 	sigcnt = bf_get(cmf_sync_wsigcnt, &wqe->cmf_sync);
1832 	if (phba->cmf_max_bytes_per_interval != bw ||
1833 	    (asig || afpin || sigcnt || fpincnt)) {
1834 		/* Are we increasing or decreasing BW */
1835 		if (phba->cmf_max_bytes_per_interval <  bw) {
1836 			bwdif = bw - phba->cmf_max_bytes_per_interval;
1837 			s = "Increase";
1838 		} else {
1839 			bwdif = phba->cmf_max_bytes_per_interval - bw;
1840 			s = "Decrease";
1841 		}
1842 
1843 		/* What is the change percentage */
1844 		slop = div_u64(phba->cmf_link_byte_count, 200); /*For rounding*/
1845 		pcent = div64_u64(bwdif * 100 + slop,
1846 				  phba->cmf_link_byte_count);
1847 		bwpcent = div64_u64(bw * 100 + slop,
1848 				    phba->cmf_link_byte_count);
1849 		/* Because of bytes adjustment due to shorter timer in
1850 		 * lpfc_cmf_timer() the cmf_link_byte_count can be shorter and
1851 		 * may seem like BW is above 100%.
1852 		 */
1853 		if (bwpcent > 100)
1854 			bwpcent = 100;
1855 
1856 		if (phba->cmf_max_bytes_per_interval < bw &&
1857 		    bwpcent > 95)
1858 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1859 					"6208 Congestion bandwidth "
1860 					"limits removed\n");
1861 		else if ((phba->cmf_max_bytes_per_interval > bw) &&
1862 			 ((bwpcent + pcent) <= 100) && ((bwpcent + pcent) > 95))
1863 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1864 					"6209 Congestion bandwidth "
1865 					"limits in effect\n");
1866 
1867 		if (asig) {
1868 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1869 					"6237 BW Threshold %lld%% (%lld): "
1870 					"%lld%% %s: Signal Alarm: cg:%d "
1871 					"Info:%u\n",
1872 					bwpcent, bw, pcent, s, cg,
1873 					phba->cmf_active_info);
1874 		} else if (afpin) {
1875 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1876 					"6238 BW Threshold %lld%% (%lld): "
1877 					"%lld%% %s: FPIN Alarm: cg:%d "
1878 					"Info:%u\n",
1879 					bwpcent, bw, pcent, s, cg,
1880 					phba->cmf_active_info);
1881 		} else if (sigcnt) {
1882 			wsigmax = bf_get(cmf_sync_wsigmax, &wqe->cmf_sync);
1883 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1884 					"6239 BW Threshold %lld%% (%lld): "
1885 					"%lld%% %s: Signal Warning: "
1886 					"Cnt %d Max %d: cg:%d Info:%u\n",
1887 					bwpcent, bw, pcent, s, sigcnt,
1888 					wsigmax, cg, phba->cmf_active_info);
1889 		} else if (fpincnt) {
1890 			wfpinmax = bf_get(cmf_sync_wfpinmax, &wqe->cmf_sync);
1891 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1892 					"6240 BW Threshold %lld%% (%lld): "
1893 					"%lld%% %s: FPIN Warning: "
1894 					"Cnt %d Max %d: cg:%d Info:%u\n",
1895 					bwpcent, bw, pcent, s, fpincnt,
1896 					wfpinmax, cg, phba->cmf_active_info);
1897 		} else {
1898 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1899 					"6241 BW Threshold %lld%% (%lld): "
1900 					"CMF %lld%% %s: cg:%d Info:%u\n",
1901 					bwpcent, bw, pcent, s, cg,
1902 					phba->cmf_active_info);
1903 		}
1904 	} else if (info) {
1905 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1906 				"6246 Info Threshold %u\n", info);
1907 	}
1908 
1909 	/* Save BW change to be picked up during next timer interrupt */
1910 	phba->cmf_last_sync_bw = bw;
1911 out:
1912 	lpfc_sli_release_iocbq(phba, cmdiocb);
1913 }
1914 
1915 /**
1916  * lpfc_issue_cmf_sync_wqe - Issue a CMF_SYNC_WQE
1917  * @phba: Pointer to HBA context object.
1918  * @ms:   ms to set in WQE interval, 0 means use init op
1919  * @total: Total rcv bytes for this interval
1920  *
1921  * This routine is called every CMF timer interrupt. Its purpose is
1922  * to issue a CMF_SYNC_WQE to the firmware to inform it of any events
1923  * that may indicate we have congestion (FPINs or Signals). Upon
1924  * completion, the firmware will indicate any BW restrictions the
1925  * driver may need to take.
1926  **/
1927 int
1928 lpfc_issue_cmf_sync_wqe(struct lpfc_hba *phba, u32 ms, u64 total)
1929 {
1930 	union lpfc_wqe128 *wqe;
1931 	struct lpfc_iocbq *sync_buf;
1932 	unsigned long iflags;
1933 	u32 ret_val;
1934 	u32 atot, wtot, max;
1935 	u16 warn_sync_period = 0;
1936 
1937 	/* First address any alarm / warning activity */
1938 	atot = atomic_xchg(&phba->cgn_sync_alarm_cnt, 0);
1939 	wtot = atomic_xchg(&phba->cgn_sync_warn_cnt, 0);
1940 
1941 	/* ONLY Managed mode will send the CMF_SYNC_WQE to the HBA */
1942 	if (phba->cmf_active_mode != LPFC_CFG_MANAGED ||
1943 	    phba->link_state == LPFC_LINK_DOWN)
1944 		return 0;
1945 
1946 	spin_lock_irqsave(&phba->hbalock, iflags);
1947 	sync_buf = __lpfc_sli_get_iocbq(phba);
1948 	if (!sync_buf) {
1949 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
1950 				"6244 No available WQEs for CMF_SYNC_WQE\n");
1951 		ret_val = ENOMEM;
1952 		goto out_unlock;
1953 	}
1954 
1955 	wqe = &sync_buf->wqe;
1956 
1957 	/* WQEs are reused.  Clear stale data and set key fields to zero */
1958 	memset(wqe, 0, sizeof(*wqe));
1959 
1960 	/* If this is the very first CMF_SYNC_WQE, issue an init operation */
1961 	if (!ms) {
1962 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1963 				"6441 CMF Init %d - CMF_SYNC_WQE\n",
1964 				phba->fc_eventTag);
1965 		bf_set(cmf_sync_op, &wqe->cmf_sync, 1); /* 1=init */
1966 		bf_set(cmf_sync_interval, &wqe->cmf_sync, LPFC_CMF_INTERVAL);
1967 		goto initpath;
1968 	}
1969 
1970 	bf_set(cmf_sync_op, &wqe->cmf_sync, 0); /* 0=recalc */
1971 	bf_set(cmf_sync_interval, &wqe->cmf_sync, ms);
1972 
1973 	/* Check for alarms / warnings */
1974 	if (atot) {
1975 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1976 			/* We hit an Signal alarm condition */
1977 			bf_set(cmf_sync_asig, &wqe->cmf_sync, 1);
1978 		} else {
1979 			/* We hit a FPIN alarm condition */
1980 			bf_set(cmf_sync_afpin, &wqe->cmf_sync, 1);
1981 		}
1982 	} else if (wtot) {
1983 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
1984 		    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1985 			/* We hit an Signal warning condition */
1986 			max = LPFC_SEC_TO_MSEC / lpfc_fabric_cgn_frequency *
1987 				lpfc_acqe_cgn_frequency;
1988 			bf_set(cmf_sync_wsigmax, &wqe->cmf_sync, max);
1989 			bf_set(cmf_sync_wsigcnt, &wqe->cmf_sync, wtot);
1990 			warn_sync_period = lpfc_acqe_cgn_frequency;
1991 		} else {
1992 			/* We hit a FPIN warning condition */
1993 			bf_set(cmf_sync_wfpinmax, &wqe->cmf_sync, 1);
1994 			bf_set(cmf_sync_wfpincnt, &wqe->cmf_sync, 1);
1995 			if (phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ)
1996 				warn_sync_period =
1997 				LPFC_MSECS_TO_SECS(phba->cgn_fpin_frequency);
1998 		}
1999 	}
2000 
2001 	/* Update total read blocks during previous timer interval */
2002 	wqe->cmf_sync.read_bytes = (u32)(total / LPFC_CMF_BLK_SIZE);
2003 
2004 initpath:
2005 	bf_set(cmf_sync_ver, &wqe->cmf_sync, LPFC_CMF_SYNC_VER);
2006 	wqe->cmf_sync.event_tag = phba->fc_eventTag;
2007 	bf_set(cmf_sync_cmnd, &wqe->cmf_sync, CMD_CMF_SYNC_WQE);
2008 
2009 	/* Setup reqtag to match the wqe completion. */
2010 	bf_set(cmf_sync_reqtag, &wqe->cmf_sync, sync_buf->iotag);
2011 
2012 	bf_set(cmf_sync_qosd, &wqe->cmf_sync, 1);
2013 	bf_set(cmf_sync_period, &wqe->cmf_sync, warn_sync_period);
2014 
2015 	bf_set(cmf_sync_cmd_type, &wqe->cmf_sync, CMF_SYNC_COMMAND);
2016 	bf_set(cmf_sync_wqec, &wqe->cmf_sync, 1);
2017 	bf_set(cmf_sync_cqid, &wqe->cmf_sync, LPFC_WQE_CQ_ID_DEFAULT);
2018 
2019 	sync_buf->vport = phba->pport;
2020 	sync_buf->cmd_cmpl = lpfc_cmf_sync_cmpl;
2021 	sync_buf->cmd_dmabuf = NULL;
2022 	sync_buf->rsp_dmabuf = NULL;
2023 	sync_buf->bpl_dmabuf = NULL;
2024 	sync_buf->sli4_xritag = NO_XRI;
2025 
2026 	sync_buf->cmd_flag |= LPFC_IO_CMF;
2027 	ret_val = lpfc_sli4_issue_wqe(phba, &phba->sli4_hba.hdwq[0], sync_buf);
2028 	if (ret_val) {
2029 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
2030 				"6214 Cannot issue CMF_SYNC_WQE: x%x\n",
2031 				ret_val);
2032 		__lpfc_sli_release_iocbq(phba, sync_buf);
2033 	}
2034 out_unlock:
2035 	spin_unlock_irqrestore(&phba->hbalock, iflags);
2036 	return ret_val;
2037 }
2038 
2039 /**
2040  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
2041  * @phba: Pointer to HBA context object.
2042  * @pring: Pointer to driver SLI ring object.
2043  *
2044  * This function is called with hbalock held and the caller must post the
2045  * iocb without releasing the lock. If the caller releases the lock,
2046  * iocb slot returned by the function is not guaranteed to be available.
2047  * The function returns pointer to the next available iocb slot if there
2048  * is available slot in the ring, else it returns NULL.
2049  * If the get index of the ring is ahead of the put index, the function
2050  * will post an error attention event to the worker thread to take the
2051  * HBA to offline state.
2052  **/
2053 static IOCB_t *
2054 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2055 {
2056 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2057 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
2058 
2059 	lockdep_assert_held(&phba->hbalock);
2060 
2061 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
2062 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
2063 		pring->sli.sli3.next_cmdidx = 0;
2064 
2065 	if (unlikely(pring->sli.sli3.local_getidx ==
2066 		pring->sli.sli3.next_cmdidx)) {
2067 
2068 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
2069 
2070 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
2071 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2072 					"0315 Ring %d issue: portCmdGet %d "
2073 					"is bigger than cmd ring %d\n",
2074 					pring->ringno,
2075 					pring->sli.sli3.local_getidx,
2076 					max_cmd_idx);
2077 
2078 			phba->link_state = LPFC_HBA_ERROR;
2079 			/*
2080 			 * All error attention handlers are posted to
2081 			 * worker thread
2082 			 */
2083 			phba->work_ha |= HA_ERATT;
2084 			phba->work_hs = HS_FFER3;
2085 
2086 			lpfc_worker_wake_up(phba);
2087 
2088 			return NULL;
2089 		}
2090 
2091 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
2092 			return NULL;
2093 	}
2094 
2095 	return lpfc_cmd_iocb(phba, pring);
2096 }
2097 
2098 /**
2099  * lpfc_sli_next_iotag - Get an iotag for the iocb
2100  * @phba: Pointer to HBA context object.
2101  * @iocbq: Pointer to driver iocb object.
2102  *
2103  * This function gets an iotag for the iocb. If there is no unused iotag and
2104  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
2105  * array and assigns a new iotag.
2106  * The function returns the allocated iotag if successful, else returns zero.
2107  * Zero is not a valid iotag.
2108  * The caller is not required to hold any lock.
2109  **/
2110 uint16_t
2111 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
2112 {
2113 	struct lpfc_iocbq **new_arr;
2114 	struct lpfc_iocbq **old_arr;
2115 	size_t new_len;
2116 	struct lpfc_sli *psli = &phba->sli;
2117 	uint16_t iotag;
2118 
2119 	spin_lock_irq(&phba->hbalock);
2120 	iotag = psli->last_iotag;
2121 	if(++iotag < psli->iocbq_lookup_len) {
2122 		psli->last_iotag = iotag;
2123 		psli->iocbq_lookup[iotag] = iocbq;
2124 		spin_unlock_irq(&phba->hbalock);
2125 		iocbq->iotag = iotag;
2126 		return iotag;
2127 	} else if (psli->iocbq_lookup_len < (0xffff
2128 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
2129 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
2130 		spin_unlock_irq(&phba->hbalock);
2131 		new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
2132 				  GFP_KERNEL);
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 = (struct completion *)pmboxq->context3;
2834 	if (pmbox_done)
2835 		complete(pmbox_done);
2836 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2837 	return;
2838 }
2839 
2840 static void
2841 __lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2842 {
2843 	unsigned long iflags;
2844 
2845 	if (ndlp->nlp_flag & NLP_RELEASE_RPI) {
2846 		lpfc_sli4_free_rpi(vport->phba, ndlp->nlp_rpi);
2847 		spin_lock_irqsave(&ndlp->lock, iflags);
2848 		ndlp->nlp_flag &= ~NLP_RELEASE_RPI;
2849 		ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
2850 		spin_unlock_irqrestore(&ndlp->lock, iflags);
2851 	}
2852 	ndlp->nlp_flag &= ~NLP_UNREG_INP;
2853 }
2854 
2855 void
2856 lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2857 {
2858 	__lpfc_sli_rpi_release(vport, ndlp);
2859 }
2860 
2861 /**
2862  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2863  * @phba: Pointer to HBA context object.
2864  * @pmb: Pointer to mailbox object.
2865  *
2866  * This function is the default mailbox completion handler. It
2867  * frees the memory resources associated with the completed mailbox
2868  * command. If the completed command is a REG_LOGIN mailbox command,
2869  * this function will issue a UREG_LOGIN to re-claim the RPI.
2870  **/
2871 void
2872 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2873 {
2874 	struct lpfc_vport  *vport = pmb->vport;
2875 	struct lpfc_dmabuf *mp;
2876 	struct lpfc_nodelist *ndlp;
2877 	struct Scsi_Host *shost;
2878 	uint16_t rpi, vpi;
2879 	int rc;
2880 
2881 	/*
2882 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2883 	 * is in re-discovery driver need to cleanup the RPI.
2884 	 */
2885 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2886 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2887 	    !pmb->u.mb.mbxStatus) {
2888 		mp = (struct lpfc_dmabuf *)pmb->ctx_buf;
2889 		if (mp) {
2890 			pmb->ctx_buf = NULL;
2891 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
2892 			kfree(mp);
2893 		}
2894 		rpi = pmb->u.mb.un.varWords[0];
2895 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2896 		if (phba->sli_rev == LPFC_SLI_REV4)
2897 			vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2898 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2899 		pmb->vport = vport;
2900 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2901 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2902 		if (rc != MBX_NOT_FINISHED)
2903 			return;
2904 	}
2905 
2906 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2907 		!(phba->pport->load_flag & FC_UNLOADING) &&
2908 		!pmb->u.mb.mbxStatus) {
2909 		shost = lpfc_shost_from_vport(vport);
2910 		spin_lock_irq(shost->host_lock);
2911 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2912 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2913 		spin_unlock_irq(shost->host_lock);
2914 	}
2915 
2916 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2917 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2918 		lpfc_nlp_put(ndlp);
2919 	}
2920 
2921 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2922 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2923 
2924 		/* Check to see if there are any deferred events to process */
2925 		if (ndlp) {
2926 			lpfc_printf_vlog(
2927 				vport,
2928 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2929 				"1438 UNREG cmpl deferred mbox x%x "
2930 				"on NPort x%x Data: x%x x%x x%px x%x x%x\n",
2931 				ndlp->nlp_rpi, ndlp->nlp_DID,
2932 				ndlp->nlp_flag, ndlp->nlp_defer_did,
2933 				ndlp, vport->load_flag, kref_read(&ndlp->kref));
2934 
2935 			if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2936 			    (ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING)) {
2937 				ndlp->nlp_flag &= ~NLP_UNREG_INP;
2938 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2939 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2940 			} else {
2941 				__lpfc_sli_rpi_release(vport, ndlp);
2942 			}
2943 
2944 			/* The unreg_login mailbox is complete and had a
2945 			 * reference that has to be released.  The PLOGI
2946 			 * got its own ref.
2947 			 */
2948 			lpfc_nlp_put(ndlp);
2949 			pmb->ctx_ndlp = NULL;
2950 		}
2951 	}
2952 
2953 	/* This nlp_put pairs with lpfc_sli4_resume_rpi */
2954 	if (pmb->u.mb.mbxCommand == MBX_RESUME_RPI) {
2955 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2956 		lpfc_nlp_put(ndlp);
2957 	}
2958 
2959 	/* Check security permission status on INIT_LINK mailbox command */
2960 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2961 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2962 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2963 				"2860 SLI authentication is required "
2964 				"for INIT_LINK but has not done yet\n");
2965 
2966 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2967 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2968 	else
2969 		lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2970 }
2971  /**
2972  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2973  * @phba: Pointer to HBA context object.
2974  * @pmb: Pointer to mailbox object.
2975  *
2976  * This function is the unreg rpi mailbox completion handler. It
2977  * frees the memory resources associated with the completed mailbox
2978  * command. An additional reference is put on the ndlp to prevent
2979  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2980  * the unreg mailbox command completes, this routine puts the
2981  * reference back.
2982  *
2983  **/
2984 void
2985 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2986 {
2987 	struct lpfc_vport  *vport = pmb->vport;
2988 	struct lpfc_nodelist *ndlp;
2989 
2990 	ndlp = pmb->ctx_ndlp;
2991 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2992 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2993 		    (bf_get(lpfc_sli_intf_if_type,
2994 		     &phba->sli4_hba.sli_intf) >=
2995 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2996 			if (ndlp) {
2997 				lpfc_printf_vlog(
2998 					 vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2999 					 "0010 UNREG_LOGIN vpi:%x "
3000 					 "rpi:%x DID:%x defer x%x flg x%x "
3001 					 "x%px\n",
3002 					 vport->vpi, ndlp->nlp_rpi,
3003 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
3004 					 ndlp->nlp_flag,
3005 					 ndlp);
3006 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
3007 
3008 				/* Check to see if there are any deferred
3009 				 * events to process
3010 				 */
3011 				if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
3012 				    (ndlp->nlp_defer_did !=
3013 				    NLP_EVT_NOTHING_PENDING)) {
3014 					lpfc_printf_vlog(
3015 						vport, KERN_INFO, LOG_DISCOVERY,
3016 						"4111 UNREG cmpl deferred "
3017 						"clr x%x on "
3018 						"NPort x%x Data: x%x x%px\n",
3019 						ndlp->nlp_rpi, ndlp->nlp_DID,
3020 						ndlp->nlp_defer_did, ndlp);
3021 					ndlp->nlp_flag &= ~NLP_UNREG_INP;
3022 					ndlp->nlp_defer_did =
3023 						NLP_EVT_NOTHING_PENDING;
3024 					lpfc_issue_els_plogi(
3025 						vport, ndlp->nlp_DID, 0);
3026 				} else {
3027 					__lpfc_sli_rpi_release(vport, ndlp);
3028 				}
3029 				lpfc_nlp_put(ndlp);
3030 			}
3031 		}
3032 	}
3033 
3034 	mempool_free(pmb, phba->mbox_mem_pool);
3035 }
3036 
3037 /**
3038  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
3039  * @phba: Pointer to HBA context object.
3040  *
3041  * This function is called with no lock held. This function processes all
3042  * the completed mailbox commands and gives it to upper layers. The interrupt
3043  * service routine processes mailbox completion interrupt and adds completed
3044  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
3045  * Worker thread call lpfc_sli_handle_mb_event, which will return the
3046  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
3047  * function returns the mailbox commands to the upper layer by calling the
3048  * completion handler function of each mailbox.
3049  **/
3050 int
3051 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
3052 {
3053 	MAILBOX_t *pmbox;
3054 	LPFC_MBOXQ_t *pmb;
3055 	int rc;
3056 	LIST_HEAD(cmplq);
3057 
3058 	phba->sli.slistat.mbox_event++;
3059 
3060 	/* Get all completed mailboxe buffers into the cmplq */
3061 	spin_lock_irq(&phba->hbalock);
3062 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
3063 	spin_unlock_irq(&phba->hbalock);
3064 
3065 	/* Get a Mailbox buffer to setup mailbox commands for callback */
3066 	do {
3067 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
3068 		if (pmb == NULL)
3069 			break;
3070 
3071 		pmbox = &pmb->u.mb;
3072 
3073 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
3074 			if (pmb->vport) {
3075 				lpfc_debugfs_disc_trc(pmb->vport,
3076 					LPFC_DISC_TRC_MBOX_VPORT,
3077 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
3078 					(uint32_t)pmbox->mbxCommand,
3079 					pmbox->un.varWords[0],
3080 					pmbox->un.varWords[1]);
3081 			}
3082 			else {
3083 				lpfc_debugfs_disc_trc(phba->pport,
3084 					LPFC_DISC_TRC_MBOX,
3085 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
3086 					(uint32_t)pmbox->mbxCommand,
3087 					pmbox->un.varWords[0],
3088 					pmbox->un.varWords[1]);
3089 			}
3090 		}
3091 
3092 		/*
3093 		 * It is a fatal error if unknown mbox command completion.
3094 		 */
3095 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
3096 		    MBX_SHUTDOWN) {
3097 			/* Unknown mailbox command compl */
3098 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3099 					"(%d):0323 Unknown Mailbox command "
3100 					"x%x (x%x/x%x) Cmpl\n",
3101 					pmb->vport ? pmb->vport->vpi :
3102 					LPFC_VPORT_UNKNOWN,
3103 					pmbox->mbxCommand,
3104 					lpfc_sli_config_mbox_subsys_get(phba,
3105 									pmb),
3106 					lpfc_sli_config_mbox_opcode_get(phba,
3107 									pmb));
3108 			phba->link_state = LPFC_HBA_ERROR;
3109 			phba->work_hs = HS_FFER3;
3110 			lpfc_handle_eratt(phba);
3111 			continue;
3112 		}
3113 
3114 		if (pmbox->mbxStatus) {
3115 			phba->sli.slistat.mbox_stat_err++;
3116 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
3117 				/* Mbox cmd cmpl error - RETRYing */
3118 				lpfc_printf_log(phba, KERN_INFO,
3119 					LOG_MBOX | LOG_SLI,
3120 					"(%d):0305 Mbox cmd cmpl "
3121 					"error - RETRYing Data: x%x "
3122 					"(x%x/x%x) x%x x%x x%x\n",
3123 					pmb->vport ? pmb->vport->vpi :
3124 					LPFC_VPORT_UNKNOWN,
3125 					pmbox->mbxCommand,
3126 					lpfc_sli_config_mbox_subsys_get(phba,
3127 									pmb),
3128 					lpfc_sli_config_mbox_opcode_get(phba,
3129 									pmb),
3130 					pmbox->mbxStatus,
3131 					pmbox->un.varWords[0],
3132 					pmb->vport ? pmb->vport->port_state :
3133 					LPFC_VPORT_UNKNOWN);
3134 				pmbox->mbxStatus = 0;
3135 				pmbox->mbxOwner = OWN_HOST;
3136 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3137 				if (rc != MBX_NOT_FINISHED)
3138 					continue;
3139 			}
3140 		}
3141 
3142 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
3143 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
3144 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
3145 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
3146 				"x%x x%x x%x\n",
3147 				pmb->vport ? pmb->vport->vpi : 0,
3148 				pmbox->mbxCommand,
3149 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
3150 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
3151 				pmb->mbox_cmpl,
3152 				*((uint32_t *) pmbox),
3153 				pmbox->un.varWords[0],
3154 				pmbox->un.varWords[1],
3155 				pmbox->un.varWords[2],
3156 				pmbox->un.varWords[3],
3157 				pmbox->un.varWords[4],
3158 				pmbox->un.varWords[5],
3159 				pmbox->un.varWords[6],
3160 				pmbox->un.varWords[7],
3161 				pmbox->un.varWords[8],
3162 				pmbox->un.varWords[9],
3163 				pmbox->un.varWords[10]);
3164 
3165 		if (pmb->mbox_cmpl)
3166 			pmb->mbox_cmpl(phba,pmb);
3167 	} while (1);
3168 	return 0;
3169 }
3170 
3171 /**
3172  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
3173  * @phba: Pointer to HBA context object.
3174  * @pring: Pointer to driver SLI ring object.
3175  * @tag: buffer tag.
3176  *
3177  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
3178  * is set in the tag the buffer is posted for a particular exchange,
3179  * the function will return the buffer without replacing the buffer.
3180  * If the buffer is for unsolicited ELS or CT traffic, this function
3181  * returns the buffer and also posts another buffer to the firmware.
3182  **/
3183 static struct lpfc_dmabuf *
3184 lpfc_sli_get_buff(struct lpfc_hba *phba,
3185 		  struct lpfc_sli_ring *pring,
3186 		  uint32_t tag)
3187 {
3188 	struct hbq_dmabuf *hbq_entry;
3189 
3190 	if (tag & QUE_BUFTAG_BIT)
3191 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
3192 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
3193 	if (!hbq_entry)
3194 		return NULL;
3195 	return &hbq_entry->dbuf;
3196 }
3197 
3198 /**
3199  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
3200  *                              containing a NVME LS request.
3201  * @phba: pointer to lpfc hba data structure.
3202  * @piocb: pointer to the iocbq struct representing the sequence starting
3203  *        frame.
3204  *
3205  * This routine initially validates the NVME LS, validates there is a login
3206  * with the port that sent the LS, and then calls the appropriate nvme host
3207  * or target LS request handler.
3208  **/
3209 static void
3210 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
3211 {
3212 	struct lpfc_nodelist *ndlp;
3213 	struct lpfc_dmabuf *d_buf;
3214 	struct hbq_dmabuf *nvmebuf;
3215 	struct fc_frame_header *fc_hdr;
3216 	struct lpfc_async_xchg_ctx *axchg = NULL;
3217 	char *failwhy = NULL;
3218 	uint32_t oxid, sid, did, fctl, size;
3219 	int ret = 1;
3220 
3221 	d_buf = piocb->cmd_dmabuf;
3222 
3223 	nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
3224 	fc_hdr = nvmebuf->hbuf.virt;
3225 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
3226 	sid = sli4_sid_from_fc_hdr(fc_hdr);
3227 	did = sli4_did_from_fc_hdr(fc_hdr);
3228 	fctl = (fc_hdr->fh_f_ctl[0] << 16 |
3229 		fc_hdr->fh_f_ctl[1] << 8 |
3230 		fc_hdr->fh_f_ctl[2]);
3231 	size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
3232 
3233 	lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
3234 			 oxid, size, sid);
3235 
3236 	if (phba->pport->load_flag & FC_UNLOADING) {
3237 		failwhy = "Driver Unloading";
3238 	} else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
3239 		failwhy = "NVME FC4 Disabled";
3240 	} else if (!phba->nvmet_support && !phba->pport->localport) {
3241 		failwhy = "No Localport";
3242 	} else if (phba->nvmet_support && !phba->targetport) {
3243 		failwhy = "No Targetport";
3244 	} else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
3245 		failwhy = "Bad NVME LS R_CTL";
3246 	} else if (unlikely((fctl & 0x00FF0000) !=
3247 			(FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
3248 		failwhy = "Bad NVME LS F_CTL";
3249 	} else {
3250 		axchg = kzalloc(sizeof(*axchg), GFP_ATOMIC);
3251 		if (!axchg)
3252 			failwhy = "No CTX memory";
3253 	}
3254 
3255 	if (unlikely(failwhy)) {
3256 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3257 				"6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
3258 				sid, oxid, failwhy);
3259 		goto out_fail;
3260 	}
3261 
3262 	/* validate the source of the LS is logged in */
3263 	ndlp = lpfc_findnode_did(phba->pport, sid);
3264 	if (!ndlp ||
3265 	    ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
3266 	     (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
3267 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
3268 				"6216 NVME Unsol rcv: No ndlp: "
3269 				"NPort_ID x%x oxid x%x\n",
3270 				sid, oxid);
3271 		goto out_fail;
3272 	}
3273 
3274 	axchg->phba = phba;
3275 	axchg->ndlp = ndlp;
3276 	axchg->size = size;
3277 	axchg->oxid = oxid;
3278 	axchg->sid = sid;
3279 	axchg->wqeq = NULL;
3280 	axchg->state = LPFC_NVME_STE_LS_RCV;
3281 	axchg->entry_cnt = 1;
3282 	axchg->rqb_buffer = (void *)nvmebuf;
3283 	axchg->hdwq = &phba->sli4_hba.hdwq[0];
3284 	axchg->payload = nvmebuf->dbuf.virt;
3285 	INIT_LIST_HEAD(&axchg->list);
3286 
3287 	if (phba->nvmet_support) {
3288 		ret = lpfc_nvmet_handle_lsreq(phba, axchg);
3289 		spin_lock_irq(&ndlp->lock);
3290 		if (!ret && !(ndlp->fc4_xpt_flags & NLP_XPT_HAS_HH)) {
3291 			ndlp->fc4_xpt_flags |= NLP_XPT_HAS_HH;
3292 			spin_unlock_irq(&ndlp->lock);
3293 
3294 			/* This reference is a single occurrence to hold the
3295 			 * node valid until the nvmet transport calls
3296 			 * host_release.
3297 			 */
3298 			if (!lpfc_nlp_get(ndlp))
3299 				goto out_fail;
3300 
3301 			lpfc_printf_log(phba, KERN_ERR, LOG_NODE,
3302 					"6206 NVMET unsol ls_req ndlp x%px "
3303 					"DID x%x xflags x%x refcnt %d\n",
3304 					ndlp, ndlp->nlp_DID,
3305 					ndlp->fc4_xpt_flags,
3306 					kref_read(&ndlp->kref));
3307 		} else {
3308 			spin_unlock_irq(&ndlp->lock);
3309 		}
3310 	} else {
3311 		ret = lpfc_nvme_handle_lsreq(phba, axchg);
3312 	}
3313 
3314 	/* if zero, LS was successfully handled. If non-zero, LS not handled */
3315 	if (!ret)
3316 		return;
3317 
3318 out_fail:
3319 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3320 			"6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
3321 			"NVMe%s handler failed %d\n",
3322 			did, sid, oxid,
3323 			(phba->nvmet_support) ? "T" : "I", ret);
3324 
3325 	/* recycle receive buffer */
3326 	lpfc_in_buf_free(phba, &nvmebuf->dbuf);
3327 
3328 	/* If start of new exchange, abort it */
3329 	if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
3330 		ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
3331 
3332 	if (ret)
3333 		kfree(axchg);
3334 }
3335 
3336 /**
3337  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
3338  * @phba: Pointer to HBA context object.
3339  * @pring: Pointer to driver SLI ring object.
3340  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
3341  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
3342  * @fch_type: the type for the first frame of the sequence.
3343  *
3344  * This function is called with no lock held. This function uses the r_ctl and
3345  * type of the received sequence to find the correct callback function to call
3346  * to process the sequence.
3347  **/
3348 static int
3349 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3350 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
3351 			 uint32_t fch_type)
3352 {
3353 	int i;
3354 
3355 	switch (fch_type) {
3356 	case FC_TYPE_NVME:
3357 		lpfc_nvme_unsol_ls_handler(phba, saveq);
3358 		return 1;
3359 	default:
3360 		break;
3361 	}
3362 
3363 	/* unSolicited Responses */
3364 	if (pring->prt[0].profile) {
3365 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
3366 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
3367 									saveq);
3368 		return 1;
3369 	}
3370 	/* We must search, based on rctl / type
3371 	   for the right routine */
3372 	for (i = 0; i < pring->num_mask; i++) {
3373 		if ((pring->prt[i].rctl == fch_r_ctl) &&
3374 		    (pring->prt[i].type == fch_type)) {
3375 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
3376 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
3377 						(phba, pring, saveq);
3378 			return 1;
3379 		}
3380 	}
3381 	return 0;
3382 }
3383 
3384 static void
3385 lpfc_sli_prep_unsol_wqe(struct lpfc_hba *phba,
3386 			struct lpfc_iocbq *saveq)
3387 {
3388 	IOCB_t *irsp;
3389 	union lpfc_wqe128 *wqe;
3390 	u16 i = 0;
3391 
3392 	irsp = &saveq->iocb;
3393 	wqe = &saveq->wqe;
3394 
3395 	/* Fill wcqe with the IOCB status fields */
3396 	bf_set(lpfc_wcqe_c_status, &saveq->wcqe_cmpl, irsp->ulpStatus);
3397 	saveq->wcqe_cmpl.word3 = irsp->ulpBdeCount;
3398 	saveq->wcqe_cmpl.parameter = irsp->un.ulpWord[4];
3399 	saveq->wcqe_cmpl.total_data_placed = irsp->unsli3.rcvsli3.acc_len;
3400 
3401 	/* Source ID */
3402 	bf_set(els_rsp64_sid, &wqe->xmit_els_rsp, irsp->un.rcvels.parmRo);
3403 
3404 	/* rx-id of the response frame */
3405 	bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com, irsp->ulpContext);
3406 
3407 	/* ox-id of the frame */
3408 	bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
3409 	       irsp->unsli3.rcvsli3.ox_id);
3410 
3411 	/* DID */
3412 	bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
3413 	       irsp->un.rcvels.remoteID);
3414 
3415 	/* unsol data len */
3416 	for (i = 0; i < irsp->ulpBdeCount; i++) {
3417 		struct lpfc_hbq_entry *hbqe = NULL;
3418 
3419 		if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3420 			if (i == 0) {
3421 				hbqe = (struct lpfc_hbq_entry *)
3422 					&irsp->un.ulpWord[0];
3423 				saveq->wqe.gen_req.bde.tus.f.bdeSize =
3424 					hbqe->bde.tus.f.bdeSize;
3425 			} else if (i == 1) {
3426 				hbqe = (struct lpfc_hbq_entry *)
3427 					&irsp->unsli3.sli3Words[4];
3428 				saveq->unsol_rcv_len = hbqe->bde.tus.f.bdeSize;
3429 			}
3430 		}
3431 	}
3432 }
3433 
3434 /**
3435  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
3436  * @phba: Pointer to HBA context object.
3437  * @pring: Pointer to driver SLI ring object.
3438  * @saveq: Pointer to the unsolicited iocb.
3439  *
3440  * This function is called with no lock held by the ring event handler
3441  * when there is an unsolicited iocb posted to the response ring by the
3442  * firmware. This function gets the buffer associated with the iocbs
3443  * and calls the event handler for the ring. This function handles both
3444  * qring buffers and hbq buffers.
3445  * When the function returns 1 the caller can free the iocb object otherwise
3446  * upper layer functions will free the iocb objects.
3447  **/
3448 static int
3449 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3450 			    struct lpfc_iocbq *saveq)
3451 {
3452 	IOCB_t           * irsp;
3453 	WORD5            * w5p;
3454 	dma_addr_t	 paddr;
3455 	uint32_t           Rctl, Type;
3456 	struct lpfc_iocbq *iocbq;
3457 	struct lpfc_dmabuf *dmzbuf;
3458 
3459 	irsp = &saveq->iocb;
3460 	saveq->vport = phba->pport;
3461 
3462 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
3463 		if (pring->lpfc_sli_rcv_async_status)
3464 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
3465 		else
3466 			lpfc_printf_log(phba,
3467 					KERN_WARNING,
3468 					LOG_SLI,
3469 					"0316 Ring %d handler: unexpected "
3470 					"ASYNC_STATUS iocb received evt_code "
3471 					"0x%x\n",
3472 					pring->ringno,
3473 					irsp->un.asyncstat.evt_code);
3474 		return 1;
3475 	}
3476 
3477 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3478 	    (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3479 		if (irsp->ulpBdeCount > 0) {
3480 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3481 						   irsp->un.ulpWord[3]);
3482 			lpfc_in_buf_free(phba, dmzbuf);
3483 		}
3484 
3485 		if (irsp->ulpBdeCount > 1) {
3486 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3487 						   irsp->unsli3.sli3Words[3]);
3488 			lpfc_in_buf_free(phba, dmzbuf);
3489 		}
3490 
3491 		if (irsp->ulpBdeCount > 2) {
3492 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3493 						   irsp->unsli3.sli3Words[7]);
3494 			lpfc_in_buf_free(phba, dmzbuf);
3495 		}
3496 
3497 		return 1;
3498 	}
3499 
3500 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3501 		if (irsp->ulpBdeCount != 0) {
3502 			saveq->cmd_dmabuf = lpfc_sli_get_buff(phba, pring,
3503 						irsp->un.ulpWord[3]);
3504 			if (!saveq->cmd_dmabuf)
3505 				lpfc_printf_log(phba,
3506 					KERN_ERR,
3507 					LOG_SLI,
3508 					"0341 Ring %d Cannot find buffer for "
3509 					"an unsolicited iocb. tag 0x%x\n",
3510 					pring->ringno,
3511 					irsp->un.ulpWord[3]);
3512 		}
3513 		if (irsp->ulpBdeCount == 2) {
3514 			saveq->bpl_dmabuf = lpfc_sli_get_buff(phba, pring,
3515 						irsp->unsli3.sli3Words[7]);
3516 			if (!saveq->bpl_dmabuf)
3517 				lpfc_printf_log(phba,
3518 					KERN_ERR,
3519 					LOG_SLI,
3520 					"0342 Ring %d Cannot find buffer for an"
3521 					" unsolicited iocb. tag 0x%x\n",
3522 					pring->ringno,
3523 					irsp->unsli3.sli3Words[7]);
3524 		}
3525 		list_for_each_entry(iocbq, &saveq->list, list) {
3526 			irsp = &iocbq->iocb;
3527 			if (irsp->ulpBdeCount != 0) {
3528 				iocbq->cmd_dmabuf = lpfc_sli_get_buff(phba,
3529 							pring,
3530 							irsp->un.ulpWord[3]);
3531 				if (!iocbq->cmd_dmabuf)
3532 					lpfc_printf_log(phba,
3533 						KERN_ERR,
3534 						LOG_SLI,
3535 						"0343 Ring %d Cannot find "
3536 						"buffer for an unsolicited iocb"
3537 						". tag 0x%x\n", pring->ringno,
3538 						irsp->un.ulpWord[3]);
3539 			}
3540 			if (irsp->ulpBdeCount == 2) {
3541 				iocbq->bpl_dmabuf = lpfc_sli_get_buff(phba,
3542 						pring,
3543 						irsp->unsli3.sli3Words[7]);
3544 				if (!iocbq->bpl_dmabuf)
3545 					lpfc_printf_log(phba,
3546 						KERN_ERR,
3547 						LOG_SLI,
3548 						"0344 Ring %d Cannot find "
3549 						"buffer for an unsolicited "
3550 						"iocb. tag 0x%x\n",
3551 						pring->ringno,
3552 						irsp->unsli3.sli3Words[7]);
3553 			}
3554 		}
3555 	} else {
3556 		paddr = getPaddr(irsp->un.cont64[0].addrHigh,
3557 				 irsp->un.cont64[0].addrLow);
3558 		saveq->cmd_dmabuf = lpfc_sli_ringpostbuf_get(phba, pring,
3559 							     paddr);
3560 		if (irsp->ulpBdeCount == 2) {
3561 			paddr = getPaddr(irsp->un.cont64[1].addrHigh,
3562 					 irsp->un.cont64[1].addrLow);
3563 			saveq->bpl_dmabuf = lpfc_sli_ringpostbuf_get(phba,
3564 								   pring,
3565 								   paddr);
3566 		}
3567 	}
3568 
3569 	if (irsp->ulpBdeCount != 0 &&
3570 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3571 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3572 		int found = 0;
3573 
3574 		/* search continue save q for same XRI */
3575 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3576 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3577 				saveq->iocb.unsli3.rcvsli3.ox_id) {
3578 				list_add_tail(&saveq->list, &iocbq->list);
3579 				found = 1;
3580 				break;
3581 			}
3582 		}
3583 		if (!found)
3584 			list_add_tail(&saveq->clist,
3585 				      &pring->iocb_continue_saveq);
3586 
3587 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3588 			list_del_init(&iocbq->clist);
3589 			saveq = iocbq;
3590 			irsp = &saveq->iocb;
3591 		} else {
3592 			return 0;
3593 		}
3594 	}
3595 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3596 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3597 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3598 		Rctl = FC_RCTL_ELS_REQ;
3599 		Type = FC_TYPE_ELS;
3600 	} else {
3601 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3602 		Rctl = w5p->hcsw.Rctl;
3603 		Type = w5p->hcsw.Type;
3604 
3605 		/* Firmware Workaround */
3606 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3607 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3608 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3609 			Rctl = FC_RCTL_ELS_REQ;
3610 			Type = FC_TYPE_ELS;
3611 			w5p->hcsw.Rctl = Rctl;
3612 			w5p->hcsw.Type = Type;
3613 		}
3614 	}
3615 
3616 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) &&
3617 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX ||
3618 	    irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3619 		if (irsp->unsli3.rcvsli3.vpi == 0xffff)
3620 			saveq->vport = phba->pport;
3621 		else
3622 			saveq->vport = lpfc_find_vport_by_vpid(phba,
3623 					       irsp->unsli3.rcvsli3.vpi);
3624 	}
3625 
3626 	/* Prepare WQE with Unsol frame */
3627 	lpfc_sli_prep_unsol_wqe(phba, saveq);
3628 
3629 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3630 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3631 				"0313 Ring %d handler: unexpected Rctl x%x "
3632 				"Type x%x received\n",
3633 				pring->ringno, Rctl, Type);
3634 
3635 	return 1;
3636 }
3637 
3638 /**
3639  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3640  * @phba: Pointer to HBA context object.
3641  * @pring: Pointer to driver SLI ring object.
3642  * @prspiocb: Pointer to response iocb object.
3643  *
3644  * This function looks up the iocb_lookup table to get the command iocb
3645  * corresponding to the given response iocb using the iotag of the
3646  * response iocb. The driver calls this function with the hbalock held
3647  * for SLI3 ports or the ring lock held for SLI4 ports.
3648  * This function returns the command iocb object if it finds the command
3649  * iocb else returns NULL.
3650  **/
3651 static struct lpfc_iocbq *
3652 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3653 		      struct lpfc_sli_ring *pring,
3654 		      struct lpfc_iocbq *prspiocb)
3655 {
3656 	struct lpfc_iocbq *cmd_iocb = NULL;
3657 	u16 iotag;
3658 
3659 	if (phba->sli_rev == LPFC_SLI_REV4)
3660 		iotag = get_wqe_reqtag(prspiocb);
3661 	else
3662 		iotag = prspiocb->iocb.ulpIoTag;
3663 
3664 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3665 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3666 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3667 			/* remove from txcmpl queue list */
3668 			list_del_init(&cmd_iocb->list);
3669 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3670 			pring->txcmplq_cnt--;
3671 			return cmd_iocb;
3672 		}
3673 	}
3674 
3675 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3676 			"0317 iotag x%x is out of "
3677 			"range: max iotag x%x\n",
3678 			iotag, phba->sli.last_iotag);
3679 	return NULL;
3680 }
3681 
3682 /**
3683  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3684  * @phba: Pointer to HBA context object.
3685  * @pring: Pointer to driver SLI ring object.
3686  * @iotag: IOCB tag.
3687  *
3688  * This function looks up the iocb_lookup table to get the command iocb
3689  * corresponding to the given iotag. The driver calls this function with
3690  * the ring lock held because this function is an SLI4 port only helper.
3691  * This function returns the command iocb object if it finds the command
3692  * iocb else returns NULL.
3693  **/
3694 static struct lpfc_iocbq *
3695 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3696 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3697 {
3698 	struct lpfc_iocbq *cmd_iocb = NULL;
3699 
3700 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3701 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3702 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3703 			/* remove from txcmpl queue list */
3704 			list_del_init(&cmd_iocb->list);
3705 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3706 			pring->txcmplq_cnt--;
3707 			return cmd_iocb;
3708 		}
3709 	}
3710 
3711 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3712 			"0372 iotag x%x lookup error: max iotag (x%x) "
3713 			"cmd_flag x%x\n",
3714 			iotag, phba->sli.last_iotag,
3715 			cmd_iocb ? cmd_iocb->cmd_flag : 0xffff);
3716 	return NULL;
3717 }
3718 
3719 /**
3720  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3721  * @phba: Pointer to HBA context object.
3722  * @pring: Pointer to driver SLI ring object.
3723  * @saveq: Pointer to the response iocb to be processed.
3724  *
3725  * This function is called by the ring event handler for non-fcp
3726  * rings when there is a new response iocb in the response ring.
3727  * The caller is not required to hold any locks. This function
3728  * gets the command iocb associated with the response iocb and
3729  * calls the completion handler for the command iocb. If there
3730  * is no completion handler, the function will free the resources
3731  * associated with command iocb. If the response iocb is for
3732  * an already aborted command iocb, the status of the completion
3733  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3734  * This function always returns 1.
3735  **/
3736 static int
3737 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3738 			  struct lpfc_iocbq *saveq)
3739 {
3740 	struct lpfc_iocbq *cmdiocbp;
3741 	unsigned long iflag;
3742 	u32 ulp_command, ulp_status, ulp_word4, ulp_context, iotag;
3743 
3744 	if (phba->sli_rev == LPFC_SLI_REV4)
3745 		spin_lock_irqsave(&pring->ring_lock, iflag);
3746 	else
3747 		spin_lock_irqsave(&phba->hbalock, iflag);
3748 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3749 	if (phba->sli_rev == LPFC_SLI_REV4)
3750 		spin_unlock_irqrestore(&pring->ring_lock, iflag);
3751 	else
3752 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3753 
3754 	ulp_command = get_job_cmnd(phba, saveq);
3755 	ulp_status = get_job_ulpstatus(phba, saveq);
3756 	ulp_word4 = get_job_word4(phba, saveq);
3757 	ulp_context = get_job_ulpcontext(phba, saveq);
3758 	if (phba->sli_rev == LPFC_SLI_REV4)
3759 		iotag = get_wqe_reqtag(saveq);
3760 	else
3761 		iotag = saveq->iocb.ulpIoTag;
3762 
3763 	if (cmdiocbp) {
3764 		ulp_command = get_job_cmnd(phba, cmdiocbp);
3765 		if (cmdiocbp->cmd_cmpl) {
3766 			/*
3767 			 * If an ELS command failed send an event to mgmt
3768 			 * application.
3769 			 */
3770 			if (ulp_status &&
3771 			     (pring->ringno == LPFC_ELS_RING) &&
3772 			     (ulp_command == CMD_ELS_REQUEST64_CR))
3773 				lpfc_send_els_failure_event(phba,
3774 					cmdiocbp, saveq);
3775 
3776 			/*
3777 			 * Post all ELS completions to the worker thread.
3778 			 * All other are passed to the completion callback.
3779 			 */
3780 			if (pring->ringno == LPFC_ELS_RING) {
3781 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3782 				    (cmdiocbp->cmd_flag &
3783 							LPFC_DRIVER_ABORTED)) {
3784 					spin_lock_irqsave(&phba->hbalock,
3785 							  iflag);
3786 					cmdiocbp->cmd_flag &=
3787 						~LPFC_DRIVER_ABORTED;
3788 					spin_unlock_irqrestore(&phba->hbalock,
3789 							       iflag);
3790 					saveq->iocb.ulpStatus =
3791 						IOSTAT_LOCAL_REJECT;
3792 					saveq->iocb.un.ulpWord[4] =
3793 						IOERR_SLI_ABORTED;
3794 
3795 					/* Firmware could still be in progress
3796 					 * of DMAing payload, so don't free data
3797 					 * buffer till after a hbeat.
3798 					 */
3799 					spin_lock_irqsave(&phba->hbalock,
3800 							  iflag);
3801 					saveq->cmd_flag |= LPFC_DELAY_MEM_FREE;
3802 					spin_unlock_irqrestore(&phba->hbalock,
3803 							       iflag);
3804 				}
3805 				if (phba->sli_rev == LPFC_SLI_REV4) {
3806 					if (saveq->cmd_flag &
3807 					    LPFC_EXCHANGE_BUSY) {
3808 						/* Set cmdiocb flag for the
3809 						 * exchange busy so sgl (xri)
3810 						 * will not be released until
3811 						 * the abort xri is received
3812 						 * from hba.
3813 						 */
3814 						spin_lock_irqsave(
3815 							&phba->hbalock, iflag);
3816 						cmdiocbp->cmd_flag |=
3817 							LPFC_EXCHANGE_BUSY;
3818 						spin_unlock_irqrestore(
3819 							&phba->hbalock, iflag);
3820 					}
3821 					if (cmdiocbp->cmd_flag &
3822 					    LPFC_DRIVER_ABORTED) {
3823 						/*
3824 						 * Clear LPFC_DRIVER_ABORTED
3825 						 * bit in case it was driver
3826 						 * initiated abort.
3827 						 */
3828 						spin_lock_irqsave(
3829 							&phba->hbalock, iflag);
3830 						cmdiocbp->cmd_flag &=
3831 							~LPFC_DRIVER_ABORTED;
3832 						spin_unlock_irqrestore(
3833 							&phba->hbalock, iflag);
3834 						set_job_ulpstatus(cmdiocbp,
3835 								  IOSTAT_LOCAL_REJECT);
3836 						set_job_ulpword4(cmdiocbp,
3837 								 IOERR_ABORT_REQUESTED);
3838 						/*
3839 						 * For SLI4, irspiocb contains
3840 						 * NO_XRI in sli_xritag, it
3841 						 * shall not affect releasing
3842 						 * sgl (xri) process.
3843 						 */
3844 						set_job_ulpstatus(saveq,
3845 								  IOSTAT_LOCAL_REJECT);
3846 						set_job_ulpword4(saveq,
3847 								 IOERR_SLI_ABORTED);
3848 						spin_lock_irqsave(
3849 							&phba->hbalock, iflag);
3850 						saveq->cmd_flag |=
3851 							LPFC_DELAY_MEM_FREE;
3852 						spin_unlock_irqrestore(
3853 							&phba->hbalock, iflag);
3854 					}
3855 				}
3856 			}
3857 			cmdiocbp->cmd_cmpl(phba, cmdiocbp, saveq);
3858 		} else
3859 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3860 	} else {
3861 		/*
3862 		 * Unknown initiating command based on the response iotag.
3863 		 * This could be the case on the ELS ring because of
3864 		 * lpfc_els_abort().
3865 		 */
3866 		if (pring->ringno != LPFC_ELS_RING) {
3867 			/*
3868 			 * Ring <ringno> handler: unexpected completion IoTag
3869 			 * <IoTag>
3870 			 */
3871 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3872 					 "0322 Ring %d handler: "
3873 					 "unexpected completion IoTag x%x "
3874 					 "Data: x%x x%x x%x x%x\n",
3875 					 pring->ringno, iotag, ulp_status,
3876 					 ulp_word4, ulp_command, ulp_context);
3877 		}
3878 	}
3879 
3880 	return 1;
3881 }
3882 
3883 /**
3884  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3885  * @phba: Pointer to HBA context object.
3886  * @pring: Pointer to driver SLI ring object.
3887  *
3888  * This function is called from the iocb ring event handlers when
3889  * put pointer is ahead of the get pointer for a ring. This function signal
3890  * an error attention condition to the worker thread and the worker
3891  * thread will transition the HBA to offline state.
3892  **/
3893 static void
3894 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3895 {
3896 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3897 	/*
3898 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3899 	 * rsp ring <portRspMax>
3900 	 */
3901 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3902 			"0312 Ring %d handler: portRspPut %d "
3903 			"is bigger than rsp ring %d\n",
3904 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3905 			pring->sli.sli3.numRiocb);
3906 
3907 	phba->link_state = LPFC_HBA_ERROR;
3908 
3909 	/*
3910 	 * All error attention handlers are posted to
3911 	 * worker thread
3912 	 */
3913 	phba->work_ha |= HA_ERATT;
3914 	phba->work_hs = HS_FFER3;
3915 
3916 	lpfc_worker_wake_up(phba);
3917 
3918 	return;
3919 }
3920 
3921 /**
3922  * lpfc_poll_eratt - Error attention polling timer timeout handler
3923  * @t: Context to fetch pointer to address of HBA context object from.
3924  *
3925  * This function is invoked by the Error Attention polling timer when the
3926  * timer times out. It will check the SLI Error Attention register for
3927  * possible attention events. If so, it will post an Error Attention event
3928  * and wake up worker thread to process it. Otherwise, it will set up the
3929  * Error Attention polling timer for the next poll.
3930  **/
3931 void lpfc_poll_eratt(struct timer_list *t)
3932 {
3933 	struct lpfc_hba *phba;
3934 	uint32_t eratt = 0;
3935 	uint64_t sli_intr, cnt;
3936 
3937 	phba = from_timer(phba, t, eratt_poll);
3938 
3939 	/* Here we will also keep track of interrupts per sec of the hba */
3940 	sli_intr = phba->sli.slistat.sli_intr;
3941 
3942 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3943 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3944 			sli_intr);
3945 	else
3946 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3947 
3948 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3949 	do_div(cnt, phba->eratt_poll_interval);
3950 	phba->sli.slistat.sli_ips = cnt;
3951 
3952 	phba->sli.slistat.sli_prev_intr = sli_intr;
3953 
3954 	/* Check chip HA register for error event */
3955 	eratt = lpfc_sli_check_eratt(phba);
3956 
3957 	if (eratt)
3958 		/* Tell the worker thread there is work to do */
3959 		lpfc_worker_wake_up(phba);
3960 	else
3961 		/* Restart the timer for next eratt poll */
3962 		mod_timer(&phba->eratt_poll,
3963 			  jiffies +
3964 			  msecs_to_jiffies(1000 * 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 	spin_lock_irqsave(&phba->hbalock, iflag);
4519 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
4520 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4521 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4522 		/* Get the response iocb from the head of work queue */
4523 		spin_lock_irqsave(&phba->hbalock, iflag);
4524 		list_remove_head(&phba->sli4_hba.sp_queue_event,
4525 				 cq_event, struct lpfc_cq_event, list);
4526 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4527 
4528 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4529 		case CQE_CODE_COMPL_WQE:
4530 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4531 						 cq_event);
4532 			/* Translate ELS WCQE to response IOCBQ */
4533 			irspiocbq = lpfc_sli4_els_preprocess_rspiocbq(phba,
4534 								      irspiocbq);
4535 			if (irspiocbq)
4536 				lpfc_sli_sp_handle_rspiocb(phba, pring,
4537 							   irspiocbq);
4538 			count++;
4539 			break;
4540 		case CQE_CODE_RECEIVE:
4541 		case CQE_CODE_RECEIVE_V1:
4542 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
4543 					      cq_event);
4544 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
4545 			count++;
4546 			break;
4547 		default:
4548 			break;
4549 		}
4550 
4551 		/* Limit the number of events to 64 to avoid soft lockups */
4552 		if (count == 64)
4553 			break;
4554 	}
4555 }
4556 
4557 /**
4558  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4559  * @phba: Pointer to HBA context object.
4560  * @pring: Pointer to driver SLI ring object.
4561  *
4562  * This function aborts all iocbs in the given ring and frees all the iocb
4563  * objects in txq. This function issues an abort iocb for all the iocb commands
4564  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4565  * the return of this function. The caller is not required to hold any locks.
4566  **/
4567 void
4568 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4569 {
4570 	LIST_HEAD(tx_completions);
4571 	LIST_HEAD(txcmplq_completions);
4572 	struct lpfc_iocbq *iocb, *next_iocb;
4573 	int offline;
4574 
4575 	if (pring->ringno == LPFC_ELS_RING) {
4576 		lpfc_fabric_abort_hba(phba);
4577 	}
4578 	offline = pci_channel_offline(phba->pcidev);
4579 
4580 	/* Error everything on txq and txcmplq
4581 	 * First do the txq.
4582 	 */
4583 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4584 		spin_lock_irq(&pring->ring_lock);
4585 		list_splice_init(&pring->txq, &tx_completions);
4586 		pring->txq_cnt = 0;
4587 
4588 		if (offline) {
4589 			list_splice_init(&pring->txcmplq,
4590 					 &txcmplq_completions);
4591 		} else {
4592 			/* Next issue ABTS for everything on the txcmplq */
4593 			list_for_each_entry_safe(iocb, next_iocb,
4594 						 &pring->txcmplq, list)
4595 				lpfc_sli_issue_abort_iotag(phba, pring,
4596 							   iocb, NULL);
4597 		}
4598 		spin_unlock_irq(&pring->ring_lock);
4599 	} else {
4600 		spin_lock_irq(&phba->hbalock);
4601 		list_splice_init(&pring->txq, &tx_completions);
4602 		pring->txq_cnt = 0;
4603 
4604 		if (offline) {
4605 			list_splice_init(&pring->txcmplq, &txcmplq_completions);
4606 		} else {
4607 			/* Next issue ABTS for everything on the txcmplq */
4608 			list_for_each_entry_safe(iocb, next_iocb,
4609 						 &pring->txcmplq, list)
4610 				lpfc_sli_issue_abort_iotag(phba, pring,
4611 							   iocb, NULL);
4612 		}
4613 		spin_unlock_irq(&phba->hbalock);
4614 	}
4615 
4616 	if (offline) {
4617 		/* Cancel all the IOCBs from the completions list */
4618 		lpfc_sli_cancel_iocbs(phba, &txcmplq_completions,
4619 				      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
4620 	} else {
4621 		/* Make sure HBA is alive */
4622 		lpfc_issue_hb_tmo(phba);
4623 	}
4624 	/* Cancel all the IOCBs from the completions list */
4625 	lpfc_sli_cancel_iocbs(phba, &tx_completions, IOSTAT_LOCAL_REJECT,
4626 			      IOERR_SLI_ABORTED);
4627 }
4628 
4629 /**
4630  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4631  * @phba: Pointer to HBA context object.
4632  *
4633  * This function aborts all iocbs in FCP rings and frees all the iocb
4634  * objects in txq. This function issues an abort iocb for all the iocb commands
4635  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4636  * the return of this function. The caller is not required to hold any locks.
4637  **/
4638 void
4639 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4640 {
4641 	struct lpfc_sli *psli = &phba->sli;
4642 	struct lpfc_sli_ring  *pring;
4643 	uint32_t i;
4644 
4645 	/* Look on all the FCP Rings for the iotag */
4646 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4647 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4648 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4649 			lpfc_sli_abort_iocb_ring(phba, pring);
4650 		}
4651 	} else {
4652 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4653 		lpfc_sli_abort_iocb_ring(phba, pring);
4654 	}
4655 }
4656 
4657 /**
4658  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4659  * @phba: Pointer to HBA context object.
4660  *
4661  * This function flushes all iocbs in the IO ring and frees all the iocb
4662  * objects in txq and txcmplq. This function will not issue abort iocbs
4663  * for all the iocb commands in txcmplq, they will just be returned with
4664  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4665  * slot has been permanently disabled.
4666  **/
4667 void
4668 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4669 {
4670 	LIST_HEAD(txq);
4671 	LIST_HEAD(txcmplq);
4672 	struct lpfc_sli *psli = &phba->sli;
4673 	struct lpfc_sli_ring  *pring;
4674 	uint32_t i;
4675 	struct lpfc_iocbq *piocb, *next_iocb;
4676 
4677 	spin_lock_irq(&phba->hbalock);
4678 	/* Indicate the I/O queues are flushed */
4679 	phba->hba_flag |= HBA_IOQ_FLUSH;
4680 	spin_unlock_irq(&phba->hbalock);
4681 
4682 	/* Look on all the FCP Rings for the iotag */
4683 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4684 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4685 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4686 
4687 			spin_lock_irq(&pring->ring_lock);
4688 			/* Retrieve everything on txq */
4689 			list_splice_init(&pring->txq, &txq);
4690 			list_for_each_entry_safe(piocb, next_iocb,
4691 						 &pring->txcmplq, list)
4692 				piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4693 			/* Retrieve everything on the txcmplq */
4694 			list_splice_init(&pring->txcmplq, &txcmplq);
4695 			pring->txq_cnt = 0;
4696 			pring->txcmplq_cnt = 0;
4697 			spin_unlock_irq(&pring->ring_lock);
4698 
4699 			/* Flush the txq */
4700 			lpfc_sli_cancel_iocbs(phba, &txq,
4701 					      IOSTAT_LOCAL_REJECT,
4702 					      IOERR_SLI_DOWN);
4703 			/* Flush the txcmplq */
4704 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4705 					      IOSTAT_LOCAL_REJECT,
4706 					      IOERR_SLI_DOWN);
4707 			if (unlikely(pci_channel_offline(phba->pcidev)))
4708 				lpfc_sli4_io_xri_aborted(phba, NULL, 0);
4709 		}
4710 	} else {
4711 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4712 
4713 		spin_lock_irq(&phba->hbalock);
4714 		/* Retrieve everything on txq */
4715 		list_splice_init(&pring->txq, &txq);
4716 		list_for_each_entry_safe(piocb, next_iocb,
4717 					 &pring->txcmplq, list)
4718 			piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4719 		/* Retrieve everything on the txcmplq */
4720 		list_splice_init(&pring->txcmplq, &txcmplq);
4721 		pring->txq_cnt = 0;
4722 		pring->txcmplq_cnt = 0;
4723 		spin_unlock_irq(&phba->hbalock);
4724 
4725 		/* Flush the txq */
4726 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4727 				      IOERR_SLI_DOWN);
4728 		/* Flush the txcmpq */
4729 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4730 				      IOERR_SLI_DOWN);
4731 	}
4732 }
4733 
4734 /**
4735  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4736  * @phba: Pointer to HBA context object.
4737  * @mask: Bit mask to be checked.
4738  *
4739  * This function reads the host status register and compares
4740  * with the provided bit mask to check if HBA completed
4741  * the restart. This function will wait in a loop for the
4742  * HBA to complete restart. If the HBA does not restart within
4743  * 15 iterations, the function will reset the HBA again. The
4744  * function returns 1 when HBA fail to restart otherwise returns
4745  * zero.
4746  **/
4747 static int
4748 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4749 {
4750 	uint32_t status;
4751 	int i = 0;
4752 	int retval = 0;
4753 
4754 	/* Read the HBA Host Status Register */
4755 	if (lpfc_readl(phba->HSregaddr, &status))
4756 		return 1;
4757 
4758 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4759 
4760 	/*
4761 	 * Check status register every 100ms for 5 retries, then every
4762 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4763 	 * every 2.5 sec for 4.
4764 	 * Break our of the loop if errors occurred during init.
4765 	 */
4766 	while (((status & mask) != mask) &&
4767 	       !(status & HS_FFERM) &&
4768 	       i++ < 20) {
4769 
4770 		if (i <= 5)
4771 			msleep(10);
4772 		else if (i <= 10)
4773 			msleep(500);
4774 		else
4775 			msleep(2500);
4776 
4777 		if (i == 15) {
4778 				/* Do post */
4779 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4780 			lpfc_sli_brdrestart(phba);
4781 		}
4782 		/* Read the HBA Host Status Register */
4783 		if (lpfc_readl(phba->HSregaddr, &status)) {
4784 			retval = 1;
4785 			break;
4786 		}
4787 	}
4788 
4789 	/* Check to see if any errors occurred during init */
4790 	if ((status & HS_FFERM) || (i >= 20)) {
4791 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4792 				"2751 Adapter failed to restart, "
4793 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4794 				status,
4795 				readl(phba->MBslimaddr + 0xa8),
4796 				readl(phba->MBslimaddr + 0xac));
4797 		phba->link_state = LPFC_HBA_ERROR;
4798 		retval = 1;
4799 	}
4800 
4801 	return retval;
4802 }
4803 
4804 /**
4805  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4806  * @phba: Pointer to HBA context object.
4807  * @mask: Bit mask to be checked.
4808  *
4809  * This function checks the host status register to check if HBA is
4810  * ready. This function will wait in a loop for the HBA to be ready
4811  * If the HBA is not ready , the function will will reset the HBA PCI
4812  * function again. The function returns 1 when HBA fail to be ready
4813  * otherwise returns zero.
4814  **/
4815 static int
4816 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4817 {
4818 	uint32_t status;
4819 	int retval = 0;
4820 
4821 	/* Read the HBA Host Status Register */
4822 	status = lpfc_sli4_post_status_check(phba);
4823 
4824 	if (status) {
4825 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4826 		lpfc_sli_brdrestart(phba);
4827 		status = lpfc_sli4_post_status_check(phba);
4828 	}
4829 
4830 	/* Check to see if any errors occurred during init */
4831 	if (status) {
4832 		phba->link_state = LPFC_HBA_ERROR;
4833 		retval = 1;
4834 	} else
4835 		phba->sli4_hba.intr_enable = 0;
4836 
4837 	phba->hba_flag &= ~HBA_SETUP;
4838 	return retval;
4839 }
4840 
4841 /**
4842  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4843  * @phba: Pointer to HBA context object.
4844  * @mask: Bit mask to be checked.
4845  *
4846  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4847  * from the API jump table function pointer from the lpfc_hba struct.
4848  **/
4849 int
4850 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4851 {
4852 	return phba->lpfc_sli_brdready(phba, mask);
4853 }
4854 
4855 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4856 
4857 /**
4858  * lpfc_reset_barrier - Make HBA ready for HBA reset
4859  * @phba: Pointer to HBA context object.
4860  *
4861  * This function is called before resetting an HBA. This function is called
4862  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4863  **/
4864 void lpfc_reset_barrier(struct lpfc_hba *phba)
4865 {
4866 	uint32_t __iomem *resp_buf;
4867 	uint32_t __iomem *mbox_buf;
4868 	volatile struct MAILBOX_word0 mbox;
4869 	uint32_t hc_copy, ha_copy, resp_data;
4870 	int  i;
4871 	uint8_t hdrtype;
4872 
4873 	lockdep_assert_held(&phba->hbalock);
4874 
4875 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4876 	if (hdrtype != 0x80 ||
4877 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4878 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4879 		return;
4880 
4881 	/*
4882 	 * Tell the other part of the chip to suspend temporarily all
4883 	 * its DMA activity.
4884 	 */
4885 	resp_buf = phba->MBslimaddr;
4886 
4887 	/* Disable the error attention */
4888 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4889 		return;
4890 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4891 	readl(phba->HCregaddr); /* flush */
4892 	phba->link_flag |= LS_IGNORE_ERATT;
4893 
4894 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4895 		return;
4896 	if (ha_copy & HA_ERATT) {
4897 		/* Clear Chip error bit */
4898 		writel(HA_ERATT, phba->HAregaddr);
4899 		phba->pport->stopped = 1;
4900 	}
4901 
4902 	mbox.word0 = 0;
4903 	mbox.mbxCommand = MBX_KILL_BOARD;
4904 	mbox.mbxOwner = OWN_CHIP;
4905 
4906 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4907 	mbox_buf = phba->MBslimaddr;
4908 	writel(mbox.word0, mbox_buf);
4909 
4910 	for (i = 0; i < 50; i++) {
4911 		if (lpfc_readl((resp_buf + 1), &resp_data))
4912 			return;
4913 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4914 			mdelay(1);
4915 		else
4916 			break;
4917 	}
4918 	resp_data = 0;
4919 	if (lpfc_readl((resp_buf + 1), &resp_data))
4920 		return;
4921 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4922 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4923 		    phba->pport->stopped)
4924 			goto restore_hc;
4925 		else
4926 			goto clear_errat;
4927 	}
4928 
4929 	mbox.mbxOwner = OWN_HOST;
4930 	resp_data = 0;
4931 	for (i = 0; i < 500; i++) {
4932 		if (lpfc_readl(resp_buf, &resp_data))
4933 			return;
4934 		if (resp_data != mbox.word0)
4935 			mdelay(1);
4936 		else
4937 			break;
4938 	}
4939 
4940 clear_errat:
4941 
4942 	while (++i < 500) {
4943 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4944 			return;
4945 		if (!(ha_copy & HA_ERATT))
4946 			mdelay(1);
4947 		else
4948 			break;
4949 	}
4950 
4951 	if (readl(phba->HAregaddr) & HA_ERATT) {
4952 		writel(HA_ERATT, phba->HAregaddr);
4953 		phba->pport->stopped = 1;
4954 	}
4955 
4956 restore_hc:
4957 	phba->link_flag &= ~LS_IGNORE_ERATT;
4958 	writel(hc_copy, phba->HCregaddr);
4959 	readl(phba->HCregaddr); /* flush */
4960 }
4961 
4962 /**
4963  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4964  * @phba: Pointer to HBA context object.
4965  *
4966  * This function issues a kill_board mailbox command and waits for
4967  * the error attention interrupt. This function is called for stopping
4968  * the firmware processing. The caller is not required to hold any
4969  * locks. This function calls lpfc_hba_down_post function to free
4970  * any pending commands after the kill. The function will return 1 when it
4971  * fails to kill the board else will return 0.
4972  **/
4973 int
4974 lpfc_sli_brdkill(struct lpfc_hba *phba)
4975 {
4976 	struct lpfc_sli *psli;
4977 	LPFC_MBOXQ_t *pmb;
4978 	uint32_t status;
4979 	uint32_t ha_copy;
4980 	int retval;
4981 	int i = 0;
4982 
4983 	psli = &phba->sli;
4984 
4985 	/* Kill HBA */
4986 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4987 			"0329 Kill HBA Data: x%x x%x\n",
4988 			phba->pport->port_state, psli->sli_flag);
4989 
4990 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4991 	if (!pmb)
4992 		return 1;
4993 
4994 	/* Disable the error attention */
4995 	spin_lock_irq(&phba->hbalock);
4996 	if (lpfc_readl(phba->HCregaddr, &status)) {
4997 		spin_unlock_irq(&phba->hbalock);
4998 		mempool_free(pmb, phba->mbox_mem_pool);
4999 		return 1;
5000 	}
5001 	status &= ~HC_ERINT_ENA;
5002 	writel(status, phba->HCregaddr);
5003 	readl(phba->HCregaddr); /* flush */
5004 	phba->link_flag |= LS_IGNORE_ERATT;
5005 	spin_unlock_irq(&phba->hbalock);
5006 
5007 	lpfc_kill_board(phba, pmb);
5008 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
5009 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5010 
5011 	if (retval != MBX_SUCCESS) {
5012 		if (retval != MBX_BUSY)
5013 			mempool_free(pmb, phba->mbox_mem_pool);
5014 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5015 				"2752 KILL_BOARD command failed retval %d\n",
5016 				retval);
5017 		spin_lock_irq(&phba->hbalock);
5018 		phba->link_flag &= ~LS_IGNORE_ERATT;
5019 		spin_unlock_irq(&phba->hbalock);
5020 		return 1;
5021 	}
5022 
5023 	spin_lock_irq(&phba->hbalock);
5024 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
5025 	spin_unlock_irq(&phba->hbalock);
5026 
5027 	mempool_free(pmb, phba->mbox_mem_pool);
5028 
5029 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
5030 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
5031 	 * 3 seconds we still set HBA_ERROR state because the status of the
5032 	 * board is now undefined.
5033 	 */
5034 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
5035 		return 1;
5036 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
5037 		mdelay(100);
5038 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
5039 			return 1;
5040 	}
5041 
5042 	del_timer_sync(&psli->mbox_tmo);
5043 	if (ha_copy & HA_ERATT) {
5044 		writel(HA_ERATT, phba->HAregaddr);
5045 		phba->pport->stopped = 1;
5046 	}
5047 	spin_lock_irq(&phba->hbalock);
5048 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5049 	psli->mbox_active = NULL;
5050 	phba->link_flag &= ~LS_IGNORE_ERATT;
5051 	spin_unlock_irq(&phba->hbalock);
5052 
5053 	lpfc_hba_down_post(phba);
5054 	phba->link_state = LPFC_HBA_ERROR;
5055 
5056 	return ha_copy & HA_ERATT ? 0 : 1;
5057 }
5058 
5059 /**
5060  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
5061  * @phba: Pointer to HBA context object.
5062  *
5063  * This function resets the HBA by writing HC_INITFF to the control
5064  * register. After the HBA resets, this function resets all the iocb ring
5065  * indices. This function disables PCI layer parity checking during
5066  * the reset.
5067  * This function returns 0 always.
5068  * The caller is not required to hold any locks.
5069  **/
5070 int
5071 lpfc_sli_brdreset(struct lpfc_hba *phba)
5072 {
5073 	struct lpfc_sli *psli;
5074 	struct lpfc_sli_ring *pring;
5075 	uint16_t cfg_value;
5076 	int i;
5077 
5078 	psli = &phba->sli;
5079 
5080 	/* Reset HBA */
5081 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5082 			"0325 Reset HBA Data: x%x x%x\n",
5083 			(phba->pport) ? phba->pport->port_state : 0,
5084 			psli->sli_flag);
5085 
5086 	/* perform board reset */
5087 	phba->fc_eventTag = 0;
5088 	phba->link_events = 0;
5089 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5090 	if (phba->pport) {
5091 		phba->pport->fc_myDID = 0;
5092 		phba->pport->fc_prevDID = 0;
5093 	}
5094 
5095 	/* Turn off parity checking and serr during the physical reset */
5096 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
5097 		return -EIO;
5098 
5099 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
5100 			      (cfg_value &
5101 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5102 
5103 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
5104 
5105 	/* Now toggle INITFF bit in the Host Control Register */
5106 	writel(HC_INITFF, phba->HCregaddr);
5107 	mdelay(1);
5108 	readl(phba->HCregaddr); /* flush */
5109 	writel(0, phba->HCregaddr);
5110 	readl(phba->HCregaddr); /* flush */
5111 
5112 	/* Restore PCI cmd register */
5113 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5114 
5115 	/* Initialize relevant SLI info */
5116 	for (i = 0; i < psli->num_rings; i++) {
5117 		pring = &psli->sli3_ring[i];
5118 		pring->flag = 0;
5119 		pring->sli.sli3.rspidx = 0;
5120 		pring->sli.sli3.next_cmdidx  = 0;
5121 		pring->sli.sli3.local_getidx = 0;
5122 		pring->sli.sli3.cmdidx = 0;
5123 		pring->missbufcnt = 0;
5124 	}
5125 
5126 	phba->link_state = LPFC_WARM_START;
5127 	return 0;
5128 }
5129 
5130 /**
5131  * lpfc_sli4_brdreset - Reset a sli-4 HBA
5132  * @phba: Pointer to HBA context object.
5133  *
5134  * This function resets a SLI4 HBA. This function disables PCI layer parity
5135  * checking during resets the device. The caller is not required to hold
5136  * any locks.
5137  *
5138  * This function returns 0 on success else returns negative error code.
5139  **/
5140 int
5141 lpfc_sli4_brdreset(struct lpfc_hba *phba)
5142 {
5143 	struct lpfc_sli *psli = &phba->sli;
5144 	uint16_t cfg_value;
5145 	int rc = 0;
5146 
5147 	/* Reset HBA */
5148 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5149 			"0295 Reset HBA Data: x%x x%x x%x\n",
5150 			phba->pport->port_state, psli->sli_flag,
5151 			phba->hba_flag);
5152 
5153 	/* perform board reset */
5154 	phba->fc_eventTag = 0;
5155 	phba->link_events = 0;
5156 	phba->pport->fc_myDID = 0;
5157 	phba->pport->fc_prevDID = 0;
5158 	phba->hba_flag &= ~HBA_SETUP;
5159 
5160 	spin_lock_irq(&phba->hbalock);
5161 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
5162 	phba->fcf.fcf_flag = 0;
5163 	spin_unlock_irq(&phba->hbalock);
5164 
5165 	/* Now physically reset the device */
5166 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5167 			"0389 Performing PCI function reset!\n");
5168 
5169 	/* Turn off parity checking and serr during the physical reset */
5170 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
5171 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5172 				"3205 PCI read Config failed\n");
5173 		return -EIO;
5174 	}
5175 
5176 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
5177 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5178 
5179 	/* Perform FCoE PCI function reset before freeing queue memory */
5180 	rc = lpfc_pci_function_reset(phba);
5181 
5182 	/* Restore PCI cmd register */
5183 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5184 
5185 	return rc;
5186 }
5187 
5188 /**
5189  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
5190  * @phba: Pointer to HBA context object.
5191  *
5192  * This function is called in the SLI initialization code path to
5193  * restart the HBA. The caller is not required to hold any lock.
5194  * This function writes MBX_RESTART mailbox command to the SLIM and
5195  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
5196  * function to free any pending commands. The function enables
5197  * POST only during the first initialization. The function returns zero.
5198  * The function does not guarantee completion of MBX_RESTART mailbox
5199  * command before the return of this function.
5200  **/
5201 static int
5202 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
5203 {
5204 	volatile struct MAILBOX_word0 mb;
5205 	struct lpfc_sli *psli;
5206 	void __iomem *to_slim;
5207 	uint32_t hba_aer_enabled;
5208 
5209 	spin_lock_irq(&phba->hbalock);
5210 
5211 	/* Take PCIe device Advanced Error Reporting (AER) state */
5212 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
5213 
5214 	psli = &phba->sli;
5215 
5216 	/* Restart HBA */
5217 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5218 			"0337 Restart HBA Data: x%x x%x\n",
5219 			(phba->pport) ? phba->pport->port_state : 0,
5220 			psli->sli_flag);
5221 
5222 	mb.word0 = 0;
5223 	mb.mbxCommand = MBX_RESTART;
5224 	mb.mbxHc = 1;
5225 
5226 	lpfc_reset_barrier(phba);
5227 
5228 	to_slim = phba->MBslimaddr;
5229 	writel(mb.word0, to_slim);
5230 	readl(to_slim); /* flush */
5231 
5232 	/* Only skip post after fc_ffinit is completed */
5233 	if (phba->pport && phba->pport->port_state)
5234 		mb.word0 = 1;	/* This is really setting up word1 */
5235 	else
5236 		mb.word0 = 0;	/* This is really setting up word1 */
5237 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
5238 	writel(mb.word0, to_slim);
5239 	readl(to_slim); /* flush */
5240 
5241 	lpfc_sli_brdreset(phba);
5242 	if (phba->pport)
5243 		phba->pport->stopped = 0;
5244 	phba->link_state = LPFC_INIT_START;
5245 	phba->hba_flag = 0;
5246 	spin_unlock_irq(&phba->hbalock);
5247 
5248 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5249 	psli->stats_start = ktime_get_seconds();
5250 
5251 	/* Give the INITFF and Post time to settle. */
5252 	mdelay(100);
5253 
5254 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
5255 	if (hba_aer_enabled)
5256 		pci_disable_pcie_error_reporting(phba->pcidev);
5257 
5258 	lpfc_hba_down_post(phba);
5259 
5260 	return 0;
5261 }
5262 
5263 /**
5264  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
5265  * @phba: Pointer to HBA context object.
5266  *
5267  * This function is called in the SLI initialization code path to restart
5268  * a SLI4 HBA. The caller is not required to hold any lock.
5269  * At the end of the function, it calls lpfc_hba_down_post function to
5270  * free any pending commands.
5271  **/
5272 static int
5273 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
5274 {
5275 	struct lpfc_sli *psli = &phba->sli;
5276 	uint32_t hba_aer_enabled;
5277 	int rc;
5278 
5279 	/* Restart HBA */
5280 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5281 			"0296 Restart HBA Data: x%x x%x\n",
5282 			phba->pport->port_state, psli->sli_flag);
5283 
5284 	/* Take PCIe device Advanced Error Reporting (AER) state */
5285 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
5286 
5287 	rc = lpfc_sli4_brdreset(phba);
5288 	if (rc) {
5289 		phba->link_state = LPFC_HBA_ERROR;
5290 		goto hba_down_queue;
5291 	}
5292 
5293 	spin_lock_irq(&phba->hbalock);
5294 	phba->pport->stopped = 0;
5295 	phba->link_state = LPFC_INIT_START;
5296 	phba->hba_flag = 0;
5297 	/* Preserve FA-PWWN expectation */
5298 	phba->sli4_hba.fawwpn_flag &= LPFC_FAWWPN_FABRIC;
5299 	spin_unlock_irq(&phba->hbalock);
5300 
5301 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5302 	psli->stats_start = ktime_get_seconds();
5303 
5304 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
5305 	if (hba_aer_enabled)
5306 		pci_disable_pcie_error_reporting(phba->pcidev);
5307 
5308 hba_down_queue:
5309 	lpfc_hba_down_post(phba);
5310 	lpfc_sli4_queue_destroy(phba);
5311 
5312 	return rc;
5313 }
5314 
5315 /**
5316  * lpfc_sli_brdrestart - Wrapper func for restarting hba
5317  * @phba: Pointer to HBA context object.
5318  *
5319  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
5320  * API jump table function pointer from the lpfc_hba struct.
5321 **/
5322 int
5323 lpfc_sli_brdrestart(struct lpfc_hba *phba)
5324 {
5325 	return phba->lpfc_sli_brdrestart(phba);
5326 }
5327 
5328 /**
5329  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
5330  * @phba: Pointer to HBA context object.
5331  *
5332  * This function is called after a HBA restart to wait for successful
5333  * restart of the HBA. Successful restart of the HBA is indicated by
5334  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
5335  * iteration, the function will restart the HBA again. The function returns
5336  * zero if HBA successfully restarted else returns negative error code.
5337  **/
5338 int
5339 lpfc_sli_chipset_init(struct lpfc_hba *phba)
5340 {
5341 	uint32_t status, i = 0;
5342 
5343 	/* Read the HBA Host Status Register */
5344 	if (lpfc_readl(phba->HSregaddr, &status))
5345 		return -EIO;
5346 
5347 	/* Check status register to see what current state is */
5348 	i = 0;
5349 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
5350 
5351 		/* Check every 10ms for 10 retries, then every 100ms for 90
5352 		 * retries, then every 1 sec for 50 retires for a total of
5353 		 * ~60 seconds before reset the board again and check every
5354 		 * 1 sec for 50 retries. The up to 60 seconds before the
5355 		 * board ready is required by the Falcon FIPS zeroization
5356 		 * complete, and any reset the board in between shall cause
5357 		 * restart of zeroization, further delay the board ready.
5358 		 */
5359 		if (i++ >= 200) {
5360 			/* Adapter failed to init, timeout, status reg
5361 			   <status> */
5362 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5363 					"0436 Adapter failed to init, "
5364 					"timeout, status reg x%x, "
5365 					"FW Data: A8 x%x AC x%x\n", status,
5366 					readl(phba->MBslimaddr + 0xa8),
5367 					readl(phba->MBslimaddr + 0xac));
5368 			phba->link_state = LPFC_HBA_ERROR;
5369 			return -ETIMEDOUT;
5370 		}
5371 
5372 		/* Check to see if any errors occurred during init */
5373 		if (status & HS_FFERM) {
5374 			/* ERROR: During chipset initialization */
5375 			/* Adapter failed to init, chipset, status reg
5376 			   <status> */
5377 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5378 					"0437 Adapter failed to init, "
5379 					"chipset, status reg x%x, "
5380 					"FW Data: A8 x%x AC x%x\n", status,
5381 					readl(phba->MBslimaddr + 0xa8),
5382 					readl(phba->MBslimaddr + 0xac));
5383 			phba->link_state = LPFC_HBA_ERROR;
5384 			return -EIO;
5385 		}
5386 
5387 		if (i <= 10)
5388 			msleep(10);
5389 		else if (i <= 100)
5390 			msleep(100);
5391 		else
5392 			msleep(1000);
5393 
5394 		if (i == 150) {
5395 			/* Do post */
5396 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5397 			lpfc_sli_brdrestart(phba);
5398 		}
5399 		/* Read the HBA Host Status Register */
5400 		if (lpfc_readl(phba->HSregaddr, &status))
5401 			return -EIO;
5402 	}
5403 
5404 	/* Check to see if any errors occurred during init */
5405 	if (status & HS_FFERM) {
5406 		/* ERROR: During chipset initialization */
5407 		/* Adapter failed to init, chipset, status reg <status> */
5408 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5409 				"0438 Adapter failed to init, chipset, "
5410 				"status reg x%x, "
5411 				"FW Data: A8 x%x AC x%x\n", status,
5412 				readl(phba->MBslimaddr + 0xa8),
5413 				readl(phba->MBslimaddr + 0xac));
5414 		phba->link_state = LPFC_HBA_ERROR;
5415 		return -EIO;
5416 	}
5417 
5418 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5419 
5420 	/* Clear all interrupt enable conditions */
5421 	writel(0, phba->HCregaddr);
5422 	readl(phba->HCregaddr); /* flush */
5423 
5424 	/* setup host attn register */
5425 	writel(0xffffffff, phba->HAregaddr);
5426 	readl(phba->HAregaddr); /* flush */
5427 	return 0;
5428 }
5429 
5430 /**
5431  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5432  *
5433  * This function calculates and returns the number of HBQs required to be
5434  * configured.
5435  **/
5436 int
5437 lpfc_sli_hbq_count(void)
5438 {
5439 	return ARRAY_SIZE(lpfc_hbq_defs);
5440 }
5441 
5442 /**
5443  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5444  *
5445  * This function adds the number of hbq entries in every HBQ to get
5446  * the total number of hbq entries required for the HBA and returns
5447  * the total count.
5448  **/
5449 static int
5450 lpfc_sli_hbq_entry_count(void)
5451 {
5452 	int  hbq_count = lpfc_sli_hbq_count();
5453 	int  count = 0;
5454 	int  i;
5455 
5456 	for (i = 0; i < hbq_count; ++i)
5457 		count += lpfc_hbq_defs[i]->entry_count;
5458 	return count;
5459 }
5460 
5461 /**
5462  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5463  *
5464  * This function calculates amount of memory required for all hbq entries
5465  * to be configured and returns the total memory required.
5466  **/
5467 int
5468 lpfc_sli_hbq_size(void)
5469 {
5470 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5471 }
5472 
5473 /**
5474  * lpfc_sli_hbq_setup - configure and initialize HBQs
5475  * @phba: Pointer to HBA context object.
5476  *
5477  * This function is called during the SLI initialization to configure
5478  * all the HBQs and post buffers to the HBQ. The caller is not
5479  * required to hold any locks. This function will return zero if successful
5480  * else it will return negative error code.
5481  **/
5482 static int
5483 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5484 {
5485 	int  hbq_count = lpfc_sli_hbq_count();
5486 	LPFC_MBOXQ_t *pmb;
5487 	MAILBOX_t *pmbox;
5488 	uint32_t hbqno;
5489 	uint32_t hbq_entry_index;
5490 
5491 				/* Get a Mailbox buffer to setup mailbox
5492 				 * commands for HBA initialization
5493 				 */
5494 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5495 
5496 	if (!pmb)
5497 		return -ENOMEM;
5498 
5499 	pmbox = &pmb->u.mb;
5500 
5501 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
5502 	phba->link_state = LPFC_INIT_MBX_CMDS;
5503 	phba->hbq_in_use = 1;
5504 
5505 	hbq_entry_index = 0;
5506 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5507 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
5508 		phba->hbqs[hbqno].hbqPutIdx      = 0;
5509 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5510 		phba->hbqs[hbqno].entry_count =
5511 			lpfc_hbq_defs[hbqno]->entry_count;
5512 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5513 			hbq_entry_index, pmb);
5514 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
5515 
5516 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5517 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5518 			   mbxStatus <status>, ring <num> */
5519 
5520 			lpfc_printf_log(phba, KERN_ERR,
5521 					LOG_SLI | LOG_VPORT,
5522 					"1805 Adapter failed to init. "
5523 					"Data: x%x x%x x%x\n",
5524 					pmbox->mbxCommand,
5525 					pmbox->mbxStatus, hbqno);
5526 
5527 			phba->link_state = LPFC_HBA_ERROR;
5528 			mempool_free(pmb, phba->mbox_mem_pool);
5529 			return -ENXIO;
5530 		}
5531 	}
5532 	phba->hbq_count = hbq_count;
5533 
5534 	mempool_free(pmb, phba->mbox_mem_pool);
5535 
5536 	/* Initially populate or replenish the HBQs */
5537 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5538 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5539 	return 0;
5540 }
5541 
5542 /**
5543  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5544  * @phba: Pointer to HBA context object.
5545  *
5546  * This function is called during the SLI initialization to configure
5547  * all the HBQs and post buffers to the HBQ. The caller is not
5548  * required to hold any locks. This function will return zero if successful
5549  * else it will return negative error code.
5550  **/
5551 static int
5552 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5553 {
5554 	phba->hbq_in_use = 1;
5555 	/**
5556 	 * Specific case when the MDS diagnostics is enabled and supported.
5557 	 * The receive buffer count is truncated to manage the incoming
5558 	 * traffic.
5559 	 **/
5560 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5561 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5562 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5563 	else
5564 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5565 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5566 	phba->hbq_count = 1;
5567 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5568 	/* Initially populate or replenish the HBQs */
5569 	return 0;
5570 }
5571 
5572 /**
5573  * lpfc_sli_config_port - Issue config port mailbox command
5574  * @phba: Pointer to HBA context object.
5575  * @sli_mode: sli mode - 2/3
5576  *
5577  * This function is called by the sli initialization code path
5578  * to issue config_port mailbox command. This function restarts the
5579  * HBA firmware and issues a config_port mailbox command to configure
5580  * the SLI interface in the sli mode specified by sli_mode
5581  * variable. The caller is not required to hold any locks.
5582  * The function returns 0 if successful, else returns negative error
5583  * code.
5584  **/
5585 int
5586 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5587 {
5588 	LPFC_MBOXQ_t *pmb;
5589 	uint32_t resetcount = 0, rc = 0, done = 0;
5590 
5591 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5592 	if (!pmb) {
5593 		phba->link_state = LPFC_HBA_ERROR;
5594 		return -ENOMEM;
5595 	}
5596 
5597 	phba->sli_rev = sli_mode;
5598 	while (resetcount < 2 && !done) {
5599 		spin_lock_irq(&phba->hbalock);
5600 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5601 		spin_unlock_irq(&phba->hbalock);
5602 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5603 		lpfc_sli_brdrestart(phba);
5604 		rc = lpfc_sli_chipset_init(phba);
5605 		if (rc)
5606 			break;
5607 
5608 		spin_lock_irq(&phba->hbalock);
5609 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5610 		spin_unlock_irq(&phba->hbalock);
5611 		resetcount++;
5612 
5613 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5614 		 * value of 0 means the call was successful.  Any other
5615 		 * nonzero value is a failure, but if ERESTART is returned,
5616 		 * the driver may reset the HBA and try again.
5617 		 */
5618 		rc = lpfc_config_port_prep(phba);
5619 		if (rc == -ERESTART) {
5620 			phba->link_state = LPFC_LINK_UNKNOWN;
5621 			continue;
5622 		} else if (rc)
5623 			break;
5624 
5625 		phba->link_state = LPFC_INIT_MBX_CMDS;
5626 		lpfc_config_port(phba, pmb);
5627 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5628 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5629 					LPFC_SLI3_HBQ_ENABLED |
5630 					LPFC_SLI3_CRP_ENABLED |
5631 					LPFC_SLI3_DSS_ENABLED);
5632 		if (rc != MBX_SUCCESS) {
5633 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5634 				"0442 Adapter failed to init, mbxCmd x%x "
5635 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5636 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5637 			spin_lock_irq(&phba->hbalock);
5638 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5639 			spin_unlock_irq(&phba->hbalock);
5640 			rc = -ENXIO;
5641 		} else {
5642 			/* Allow asynchronous mailbox command to go through */
5643 			spin_lock_irq(&phba->hbalock);
5644 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5645 			spin_unlock_irq(&phba->hbalock);
5646 			done = 1;
5647 
5648 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5649 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5650 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5651 					"3110 Port did not grant ASABT\n");
5652 		}
5653 	}
5654 	if (!done) {
5655 		rc = -EINVAL;
5656 		goto do_prep_failed;
5657 	}
5658 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5659 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5660 			rc = -ENXIO;
5661 			goto do_prep_failed;
5662 		}
5663 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5664 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5665 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5666 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5667 				phba->max_vpi : phba->max_vports;
5668 
5669 		} else
5670 			phba->max_vpi = 0;
5671 		if (pmb->u.mb.un.varCfgPort.gerbm)
5672 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5673 		if (pmb->u.mb.un.varCfgPort.gcrp)
5674 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5675 
5676 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5677 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5678 
5679 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5680 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5681 				phba->cfg_enable_bg = 0;
5682 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5683 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5684 						"0443 Adapter did not grant "
5685 						"BlockGuard\n");
5686 			}
5687 		}
5688 	} else {
5689 		phba->hbq_get = NULL;
5690 		phba->port_gp = phba->mbox->us.s2.port;
5691 		phba->max_vpi = 0;
5692 	}
5693 do_prep_failed:
5694 	mempool_free(pmb, phba->mbox_mem_pool);
5695 	return rc;
5696 }
5697 
5698 
5699 /**
5700  * lpfc_sli_hba_setup - SLI initialization function
5701  * @phba: Pointer to HBA context object.
5702  *
5703  * This function is the main SLI initialization function. This function
5704  * is called by the HBA initialization code, HBA reset code and HBA
5705  * error attention handler code. Caller is not required to hold any
5706  * locks. This function issues config_port mailbox command to configure
5707  * the SLI, setup iocb rings and HBQ rings. In the end the function
5708  * calls the config_port_post function to issue init_link mailbox
5709  * command and to start the discovery. The function will return zero
5710  * if successful, else it will return negative error code.
5711  **/
5712 int
5713 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5714 {
5715 	uint32_t rc;
5716 	int  i;
5717 	int longs;
5718 
5719 	/* Enable ISR already does config_port because of config_msi mbx */
5720 	if (phba->hba_flag & HBA_NEEDS_CFG_PORT) {
5721 		rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5722 		if (rc)
5723 			return -EIO;
5724 		phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
5725 	}
5726 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5727 
5728 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
5729 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
5730 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
5731 		if (!rc) {
5732 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5733 					"2709 This device supports "
5734 					"Advanced Error Reporting (AER)\n");
5735 			spin_lock_irq(&phba->hbalock);
5736 			phba->hba_flag |= HBA_AER_ENABLED;
5737 			spin_unlock_irq(&phba->hbalock);
5738 		} else {
5739 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5740 					"2708 This device does not support "
5741 					"Advanced Error Reporting (AER): %d\n",
5742 					rc);
5743 			phba->cfg_aer_support = 0;
5744 		}
5745 	}
5746 
5747 	if (phba->sli_rev == 3) {
5748 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5749 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5750 	} else {
5751 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5752 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5753 		phba->sli3_options = 0;
5754 	}
5755 
5756 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5757 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5758 			phba->sli_rev, phba->max_vpi);
5759 	rc = lpfc_sli_ring_map(phba);
5760 
5761 	if (rc)
5762 		goto lpfc_sli_hba_setup_error;
5763 
5764 	/* Initialize VPIs. */
5765 	if (phba->sli_rev == LPFC_SLI_REV3) {
5766 		/*
5767 		 * The VPI bitmask and physical ID array are allocated
5768 		 * and initialized once only - at driver load.  A port
5769 		 * reset doesn't need to reinitialize this memory.
5770 		 */
5771 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5772 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5773 			phba->vpi_bmask = kcalloc(longs,
5774 						  sizeof(unsigned long),
5775 						  GFP_KERNEL);
5776 			if (!phba->vpi_bmask) {
5777 				rc = -ENOMEM;
5778 				goto lpfc_sli_hba_setup_error;
5779 			}
5780 
5781 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5782 						sizeof(uint16_t),
5783 						GFP_KERNEL);
5784 			if (!phba->vpi_ids) {
5785 				kfree(phba->vpi_bmask);
5786 				rc = -ENOMEM;
5787 				goto lpfc_sli_hba_setup_error;
5788 			}
5789 			for (i = 0; i < phba->max_vpi; i++)
5790 				phba->vpi_ids[i] = i;
5791 		}
5792 	}
5793 
5794 	/* Init HBQs */
5795 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5796 		rc = lpfc_sli_hbq_setup(phba);
5797 		if (rc)
5798 			goto lpfc_sli_hba_setup_error;
5799 	}
5800 	spin_lock_irq(&phba->hbalock);
5801 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5802 	spin_unlock_irq(&phba->hbalock);
5803 
5804 	rc = lpfc_config_port_post(phba);
5805 	if (rc)
5806 		goto lpfc_sli_hba_setup_error;
5807 
5808 	return rc;
5809 
5810 lpfc_sli_hba_setup_error:
5811 	phba->link_state = LPFC_HBA_ERROR;
5812 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5813 			"0445 Firmware initialization failed\n");
5814 	return rc;
5815 }
5816 
5817 /**
5818  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5819  * @phba: Pointer to HBA context object.
5820  *
5821  * This function issue a dump mailbox command to read config region
5822  * 23 and parse the records in the region and populate driver
5823  * data structure.
5824  **/
5825 static int
5826 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5827 {
5828 	LPFC_MBOXQ_t *mboxq;
5829 	struct lpfc_dmabuf *mp;
5830 	struct lpfc_mqe *mqe;
5831 	uint32_t data_length;
5832 	int rc;
5833 
5834 	/* Program the default value of vlan_id and fc_map */
5835 	phba->valid_vlan = 0;
5836 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5837 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5838 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5839 
5840 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5841 	if (!mboxq)
5842 		return -ENOMEM;
5843 
5844 	mqe = &mboxq->u.mqe;
5845 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5846 		rc = -ENOMEM;
5847 		goto out_free_mboxq;
5848 	}
5849 
5850 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5851 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5852 
5853 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5854 			"(%d):2571 Mailbox cmd x%x Status x%x "
5855 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5856 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5857 			"CQ: x%x x%x x%x x%x\n",
5858 			mboxq->vport ? mboxq->vport->vpi : 0,
5859 			bf_get(lpfc_mqe_command, mqe),
5860 			bf_get(lpfc_mqe_status, mqe),
5861 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5862 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5863 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5864 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5865 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5866 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5867 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5868 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5869 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5870 			mboxq->mcqe.word0,
5871 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5872 			mboxq->mcqe.trailer);
5873 
5874 	if (rc) {
5875 		rc = -EIO;
5876 		goto out_free_mboxq;
5877 	}
5878 	data_length = mqe->un.mb_words[5];
5879 	if (data_length > DMP_RGN23_SIZE) {
5880 		rc = -EIO;
5881 		goto out_free_mboxq;
5882 	}
5883 
5884 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5885 	rc = 0;
5886 
5887 out_free_mboxq:
5888 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
5889 	return rc;
5890 }
5891 
5892 /**
5893  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5894  * @phba: pointer to lpfc hba data structure.
5895  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5896  * @vpd: pointer to the memory to hold resulting port vpd data.
5897  * @vpd_size: On input, the number of bytes allocated to @vpd.
5898  *	      On output, the number of data bytes in @vpd.
5899  *
5900  * This routine executes a READ_REV SLI4 mailbox command.  In
5901  * addition, this routine gets the port vpd data.
5902  *
5903  * Return codes
5904  * 	0 - successful
5905  * 	-ENOMEM - could not allocated memory.
5906  **/
5907 static int
5908 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5909 		    uint8_t *vpd, uint32_t *vpd_size)
5910 {
5911 	int rc = 0;
5912 	uint32_t dma_size;
5913 	struct lpfc_dmabuf *dmabuf;
5914 	struct lpfc_mqe *mqe;
5915 
5916 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5917 	if (!dmabuf)
5918 		return -ENOMEM;
5919 
5920 	/*
5921 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5922 	 * mailbox command.
5923 	 */
5924 	dma_size = *vpd_size;
5925 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5926 					  &dmabuf->phys, GFP_KERNEL);
5927 	if (!dmabuf->virt) {
5928 		kfree(dmabuf);
5929 		return -ENOMEM;
5930 	}
5931 
5932 	/*
5933 	 * The SLI4 implementation of READ_REV conflicts at word1,
5934 	 * bits 31:16 and SLI4 adds vpd functionality not present
5935 	 * in SLI3.  This code corrects the conflicts.
5936 	 */
5937 	lpfc_read_rev(phba, mboxq);
5938 	mqe = &mboxq->u.mqe;
5939 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5940 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5941 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5942 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5943 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5944 
5945 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5946 	if (rc) {
5947 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5948 				  dmabuf->virt, dmabuf->phys);
5949 		kfree(dmabuf);
5950 		return -EIO;
5951 	}
5952 
5953 	/*
5954 	 * The available vpd length cannot be bigger than the
5955 	 * DMA buffer passed to the port.  Catch the less than
5956 	 * case and update the caller's size.
5957 	 */
5958 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5959 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5960 
5961 	memcpy(vpd, dmabuf->virt, *vpd_size);
5962 
5963 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5964 			  dmabuf->virt, dmabuf->phys);
5965 	kfree(dmabuf);
5966 	return 0;
5967 }
5968 
5969 /**
5970  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5971  * @phba: pointer to lpfc hba data structure.
5972  *
5973  * This routine retrieves SLI4 device physical port name this PCI function
5974  * is attached to.
5975  *
5976  * Return codes
5977  *      0 - successful
5978  *      otherwise - failed to retrieve controller attributes
5979  **/
5980 static int
5981 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5982 {
5983 	LPFC_MBOXQ_t *mboxq;
5984 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5985 	struct lpfc_controller_attribute *cntl_attr;
5986 	void *virtaddr = NULL;
5987 	uint32_t alloclen, reqlen;
5988 	uint32_t shdr_status, shdr_add_status;
5989 	union lpfc_sli4_cfg_shdr *shdr;
5990 	int rc;
5991 
5992 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5993 	if (!mboxq)
5994 		return -ENOMEM;
5995 
5996 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5997 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5998 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5999 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
6000 			LPFC_SLI4_MBX_NEMBED);
6001 
6002 	if (alloclen < reqlen) {
6003 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6004 				"3084 Allocated DMA memory size (%d) is "
6005 				"less than the requested DMA memory size "
6006 				"(%d)\n", alloclen, reqlen);
6007 		rc = -ENOMEM;
6008 		goto out_free_mboxq;
6009 	}
6010 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6011 	virtaddr = mboxq->sge_array->addr[0];
6012 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
6013 	shdr = &mbx_cntl_attr->cfg_shdr;
6014 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6015 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6016 	if (shdr_status || shdr_add_status || rc) {
6017 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6018 				"3085 Mailbox x%x (x%x/x%x) failed, "
6019 				"rc:x%x, status:x%x, add_status:x%x\n",
6020 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6021 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6022 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6023 				rc, shdr_status, shdr_add_status);
6024 		rc = -ENXIO;
6025 		goto out_free_mboxq;
6026 	}
6027 
6028 	cntl_attr = &mbx_cntl_attr->cntl_attr;
6029 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
6030 	phba->sli4_hba.lnk_info.lnk_tp =
6031 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
6032 	phba->sli4_hba.lnk_info.lnk_no =
6033 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
6034 	phba->sli4_hba.flash_id = bf_get(lpfc_cntl_attr_flash_id, cntl_attr);
6035 	phba->sli4_hba.asic_rev = bf_get(lpfc_cntl_attr_asic_rev, cntl_attr);
6036 
6037 	memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
6038 	strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
6039 		sizeof(phba->BIOSVersion));
6040 
6041 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6042 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s, "
6043 			"flash_id: x%02x, asic_rev: x%02x\n",
6044 			phba->sli4_hba.lnk_info.lnk_tp,
6045 			phba->sli4_hba.lnk_info.lnk_no,
6046 			phba->BIOSVersion, phba->sli4_hba.flash_id,
6047 			phba->sli4_hba.asic_rev);
6048 out_free_mboxq:
6049 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6050 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6051 	else
6052 		mempool_free(mboxq, phba->mbox_mem_pool);
6053 	return rc;
6054 }
6055 
6056 /**
6057  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
6058  * @phba: pointer to lpfc hba data structure.
6059  *
6060  * This routine retrieves SLI4 device physical port name this PCI function
6061  * is attached to.
6062  *
6063  * Return codes
6064  *      0 - successful
6065  *      otherwise - failed to retrieve physical port name
6066  **/
6067 static int
6068 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
6069 {
6070 	LPFC_MBOXQ_t *mboxq;
6071 	struct lpfc_mbx_get_port_name *get_port_name;
6072 	uint32_t shdr_status, shdr_add_status;
6073 	union lpfc_sli4_cfg_shdr *shdr;
6074 	char cport_name = 0;
6075 	int rc;
6076 
6077 	/* We assume nothing at this point */
6078 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6079 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
6080 
6081 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6082 	if (!mboxq)
6083 		return -ENOMEM;
6084 	/* obtain link type and link number via READ_CONFIG */
6085 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6086 	lpfc_sli4_read_config(phba);
6087 
6088 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG)
6089 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
6090 
6091 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
6092 		goto retrieve_ppname;
6093 
6094 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
6095 	rc = lpfc_sli4_get_ctl_attr(phba);
6096 	if (rc)
6097 		goto out_free_mboxq;
6098 
6099 retrieve_ppname:
6100 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
6101 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
6102 		sizeof(struct lpfc_mbx_get_port_name) -
6103 		sizeof(struct lpfc_sli4_cfg_mhdr),
6104 		LPFC_SLI4_MBX_EMBED);
6105 	get_port_name = &mboxq->u.mqe.un.get_port_name;
6106 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
6107 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
6108 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
6109 		phba->sli4_hba.lnk_info.lnk_tp);
6110 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6111 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6112 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6113 	if (shdr_status || shdr_add_status || rc) {
6114 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6115 				"3087 Mailbox x%x (x%x/x%x) failed: "
6116 				"rc:x%x, status:x%x, add_status:x%x\n",
6117 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6118 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6119 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6120 				rc, shdr_status, shdr_add_status);
6121 		rc = -ENXIO;
6122 		goto out_free_mboxq;
6123 	}
6124 	switch (phba->sli4_hba.lnk_info.lnk_no) {
6125 	case LPFC_LINK_NUMBER_0:
6126 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
6127 				&get_port_name->u.response);
6128 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6129 		break;
6130 	case LPFC_LINK_NUMBER_1:
6131 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
6132 				&get_port_name->u.response);
6133 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6134 		break;
6135 	case LPFC_LINK_NUMBER_2:
6136 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
6137 				&get_port_name->u.response);
6138 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6139 		break;
6140 	case LPFC_LINK_NUMBER_3:
6141 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
6142 				&get_port_name->u.response);
6143 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6144 		break;
6145 	default:
6146 		break;
6147 	}
6148 
6149 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
6150 		phba->Port[0] = cport_name;
6151 		phba->Port[1] = '\0';
6152 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6153 				"3091 SLI get port name: %s\n", phba->Port);
6154 	}
6155 
6156 out_free_mboxq:
6157 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6158 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6159 	else
6160 		mempool_free(mboxq, phba->mbox_mem_pool);
6161 	return rc;
6162 }
6163 
6164 /**
6165  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
6166  * @phba: pointer to lpfc hba data structure.
6167  *
6168  * This routine is called to explicitly arm the SLI4 device's completion and
6169  * event queues
6170  **/
6171 static void
6172 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
6173 {
6174 	int qidx;
6175 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
6176 	struct lpfc_sli4_hdw_queue *qp;
6177 	struct lpfc_queue *eq;
6178 
6179 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
6180 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
6181 	if (sli4_hba->nvmels_cq)
6182 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
6183 					   LPFC_QUEUE_REARM);
6184 
6185 	if (sli4_hba->hdwq) {
6186 		/* Loop thru all Hardware Queues */
6187 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
6188 			qp = &sli4_hba->hdwq[qidx];
6189 			/* ARM the corresponding CQ */
6190 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
6191 						LPFC_QUEUE_REARM);
6192 		}
6193 
6194 		/* Loop thru all IRQ vectors */
6195 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
6196 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
6197 			/* ARM the corresponding EQ */
6198 			sli4_hba->sli4_write_eq_db(phba, eq,
6199 						   0, LPFC_QUEUE_REARM);
6200 		}
6201 	}
6202 
6203 	if (phba->nvmet_support) {
6204 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
6205 			sli4_hba->sli4_write_cq_db(phba,
6206 				sli4_hba->nvmet_cqset[qidx], 0,
6207 				LPFC_QUEUE_REARM);
6208 		}
6209 	}
6210 }
6211 
6212 /**
6213  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
6214  * @phba: Pointer to HBA context object.
6215  * @type: The resource extent type.
6216  * @extnt_count: buffer to hold port available extent count.
6217  * @extnt_size: buffer to hold element count per extent.
6218  *
6219  * This function calls the port and retrievs the number of available
6220  * extents and their size for a particular extent type.
6221  *
6222  * Returns: 0 if successful.  Nonzero otherwise.
6223  **/
6224 int
6225 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
6226 			       uint16_t *extnt_count, uint16_t *extnt_size)
6227 {
6228 	int rc = 0;
6229 	uint32_t length;
6230 	uint32_t mbox_tmo;
6231 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
6232 	LPFC_MBOXQ_t *mbox;
6233 
6234 	*extnt_count = 0;
6235 	*extnt_size = 0;
6236 
6237 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6238 	if (!mbox)
6239 		return -ENOMEM;
6240 
6241 	/* Find out how many extents are available for this resource type */
6242 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
6243 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6244 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6245 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
6246 			 length, LPFC_SLI4_MBX_EMBED);
6247 
6248 	/* Send an extents count of 0 - the GET doesn't use it. */
6249 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6250 					LPFC_SLI4_MBX_EMBED);
6251 	if (unlikely(rc)) {
6252 		rc = -EIO;
6253 		goto err_exit;
6254 	}
6255 
6256 	if (!phba->sli4_hba.intr_enable)
6257 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6258 	else {
6259 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6260 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6261 	}
6262 	if (unlikely(rc)) {
6263 		rc = -EIO;
6264 		goto err_exit;
6265 	}
6266 
6267 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
6268 	if (bf_get(lpfc_mbox_hdr_status,
6269 		   &rsrc_info->header.cfg_shdr.response)) {
6270 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6271 				"2930 Failed to get resource extents "
6272 				"Status 0x%x Add'l Status 0x%x\n",
6273 				bf_get(lpfc_mbox_hdr_status,
6274 				       &rsrc_info->header.cfg_shdr.response),
6275 				bf_get(lpfc_mbox_hdr_add_status,
6276 				       &rsrc_info->header.cfg_shdr.response));
6277 		rc = -EIO;
6278 		goto err_exit;
6279 	}
6280 
6281 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
6282 			      &rsrc_info->u.rsp);
6283 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
6284 			     &rsrc_info->u.rsp);
6285 
6286 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6287 			"3162 Retrieved extents type-%d from port: count:%d, "
6288 			"size:%d\n", type, *extnt_count, *extnt_size);
6289 
6290 err_exit:
6291 	mempool_free(mbox, phba->mbox_mem_pool);
6292 	return rc;
6293 }
6294 
6295 /**
6296  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
6297  * @phba: Pointer to HBA context object.
6298  * @type: The extent type to check.
6299  *
6300  * This function reads the current available extents from the port and checks
6301  * if the extent count or extent size has changed since the last access.
6302  * Callers use this routine post port reset to understand if there is a
6303  * extent reprovisioning requirement.
6304  *
6305  * Returns:
6306  *   -Error: error indicates problem.
6307  *   1: Extent count or size has changed.
6308  *   0: No changes.
6309  **/
6310 static int
6311 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
6312 {
6313 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
6314 	uint16_t size_diff, rsrc_ext_size;
6315 	int rc = 0;
6316 	struct lpfc_rsrc_blks *rsrc_entry;
6317 	struct list_head *rsrc_blk_list = NULL;
6318 
6319 	size_diff = 0;
6320 	curr_ext_cnt = 0;
6321 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6322 					    &rsrc_ext_cnt,
6323 					    &rsrc_ext_size);
6324 	if (unlikely(rc))
6325 		return -EIO;
6326 
6327 	switch (type) {
6328 	case LPFC_RSC_TYPE_FCOE_RPI:
6329 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6330 		break;
6331 	case LPFC_RSC_TYPE_FCOE_VPI:
6332 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
6333 		break;
6334 	case LPFC_RSC_TYPE_FCOE_XRI:
6335 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6336 		break;
6337 	case LPFC_RSC_TYPE_FCOE_VFI:
6338 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6339 		break;
6340 	default:
6341 		break;
6342 	}
6343 
6344 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
6345 		curr_ext_cnt++;
6346 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
6347 			size_diff++;
6348 	}
6349 
6350 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
6351 		rc = 1;
6352 
6353 	return rc;
6354 }
6355 
6356 /**
6357  * lpfc_sli4_cfg_post_extnts -
6358  * @phba: Pointer to HBA context object.
6359  * @extnt_cnt: number of available extents.
6360  * @type: the extent type (rpi, xri, vfi, vpi).
6361  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
6362  * @mbox: pointer to the caller's allocated mailbox structure.
6363  *
6364  * This function executes the extents allocation request.  It also
6365  * takes care of the amount of memory needed to allocate or get the
6366  * allocated extents. It is the caller's responsibility to evaluate
6367  * the response.
6368  *
6369  * Returns:
6370  *   -Error:  Error value describes the condition found.
6371  *   0: if successful
6372  **/
6373 static int
6374 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6375 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6376 {
6377 	int rc = 0;
6378 	uint32_t req_len;
6379 	uint32_t emb_len;
6380 	uint32_t alloc_len, mbox_tmo;
6381 
6382 	/* Calculate the total requested length of the dma memory */
6383 	req_len = extnt_cnt * sizeof(uint16_t);
6384 
6385 	/*
6386 	 * Calculate the size of an embedded mailbox.  The uint32_t
6387 	 * accounts for extents-specific word.
6388 	 */
6389 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6390 		sizeof(uint32_t);
6391 
6392 	/*
6393 	 * Presume the allocation and response will fit into an embedded
6394 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6395 	 */
6396 	*emb = LPFC_SLI4_MBX_EMBED;
6397 	if (req_len > emb_len) {
6398 		req_len = extnt_cnt * sizeof(uint16_t) +
6399 			sizeof(union lpfc_sli4_cfg_shdr) +
6400 			sizeof(uint32_t);
6401 		*emb = LPFC_SLI4_MBX_NEMBED;
6402 	}
6403 
6404 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6405 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6406 				     req_len, *emb);
6407 	if (alloc_len < req_len) {
6408 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6409 			"2982 Allocated DMA memory size (x%x) is "
6410 			"less than the requested DMA memory "
6411 			"size (x%x)\n", alloc_len, req_len);
6412 		return -ENOMEM;
6413 	}
6414 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6415 	if (unlikely(rc))
6416 		return -EIO;
6417 
6418 	if (!phba->sli4_hba.intr_enable)
6419 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6420 	else {
6421 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6422 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6423 	}
6424 
6425 	if (unlikely(rc))
6426 		rc = -EIO;
6427 	return rc;
6428 }
6429 
6430 /**
6431  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6432  * @phba: Pointer to HBA context object.
6433  * @type:  The resource extent type to allocate.
6434  *
6435  * This function allocates the number of elements for the specified
6436  * resource type.
6437  **/
6438 static int
6439 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6440 {
6441 	bool emb = false;
6442 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6443 	uint16_t rsrc_id, rsrc_start, j, k;
6444 	uint16_t *ids;
6445 	int i, rc;
6446 	unsigned long longs;
6447 	unsigned long *bmask;
6448 	struct lpfc_rsrc_blks *rsrc_blks;
6449 	LPFC_MBOXQ_t *mbox;
6450 	uint32_t length;
6451 	struct lpfc_id_range *id_array = NULL;
6452 	void *virtaddr = NULL;
6453 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6454 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6455 	struct list_head *ext_blk_list;
6456 
6457 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6458 					    &rsrc_cnt,
6459 					    &rsrc_size);
6460 	if (unlikely(rc))
6461 		return -EIO;
6462 
6463 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6464 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6465 			"3009 No available Resource Extents "
6466 			"for resource type 0x%x: Count: 0x%x, "
6467 			"Size 0x%x\n", type, rsrc_cnt,
6468 			rsrc_size);
6469 		return -ENOMEM;
6470 	}
6471 
6472 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6473 			"2903 Post resource extents type-0x%x: "
6474 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6475 
6476 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6477 	if (!mbox)
6478 		return -ENOMEM;
6479 
6480 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6481 	if (unlikely(rc)) {
6482 		rc = -EIO;
6483 		goto err_exit;
6484 	}
6485 
6486 	/*
6487 	 * Figure out where the response is located.  Then get local pointers
6488 	 * to the response data.  The port does not guarantee to respond to
6489 	 * all extents counts request so update the local variable with the
6490 	 * allocated count from the port.
6491 	 */
6492 	if (emb == LPFC_SLI4_MBX_EMBED) {
6493 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6494 		id_array = &rsrc_ext->u.rsp.id[0];
6495 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6496 	} else {
6497 		virtaddr = mbox->sge_array->addr[0];
6498 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6499 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6500 		id_array = &n_rsrc->id;
6501 	}
6502 
6503 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6504 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6505 
6506 	/*
6507 	 * Based on the resource size and count, correct the base and max
6508 	 * resource values.
6509 	 */
6510 	length = sizeof(struct lpfc_rsrc_blks);
6511 	switch (type) {
6512 	case LPFC_RSC_TYPE_FCOE_RPI:
6513 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6514 						   sizeof(unsigned long),
6515 						   GFP_KERNEL);
6516 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6517 			rc = -ENOMEM;
6518 			goto err_exit;
6519 		}
6520 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6521 						 sizeof(uint16_t),
6522 						 GFP_KERNEL);
6523 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6524 			kfree(phba->sli4_hba.rpi_bmask);
6525 			rc = -ENOMEM;
6526 			goto err_exit;
6527 		}
6528 
6529 		/*
6530 		 * The next_rpi was initialized with the maximum available
6531 		 * count but the port may allocate a smaller number.  Catch
6532 		 * that case and update the next_rpi.
6533 		 */
6534 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6535 
6536 		/* Initialize local ptrs for common extent processing later. */
6537 		bmask = phba->sli4_hba.rpi_bmask;
6538 		ids = phba->sli4_hba.rpi_ids;
6539 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6540 		break;
6541 	case LPFC_RSC_TYPE_FCOE_VPI:
6542 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6543 					  GFP_KERNEL);
6544 		if (unlikely(!phba->vpi_bmask)) {
6545 			rc = -ENOMEM;
6546 			goto err_exit;
6547 		}
6548 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6549 					 GFP_KERNEL);
6550 		if (unlikely(!phba->vpi_ids)) {
6551 			kfree(phba->vpi_bmask);
6552 			rc = -ENOMEM;
6553 			goto err_exit;
6554 		}
6555 
6556 		/* Initialize local ptrs for common extent processing later. */
6557 		bmask = phba->vpi_bmask;
6558 		ids = phba->vpi_ids;
6559 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6560 		break;
6561 	case LPFC_RSC_TYPE_FCOE_XRI:
6562 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6563 						   sizeof(unsigned long),
6564 						   GFP_KERNEL);
6565 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6566 			rc = -ENOMEM;
6567 			goto err_exit;
6568 		}
6569 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6570 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6571 						 sizeof(uint16_t),
6572 						 GFP_KERNEL);
6573 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6574 			kfree(phba->sli4_hba.xri_bmask);
6575 			rc = -ENOMEM;
6576 			goto err_exit;
6577 		}
6578 
6579 		/* Initialize local ptrs for common extent processing later. */
6580 		bmask = phba->sli4_hba.xri_bmask;
6581 		ids = phba->sli4_hba.xri_ids;
6582 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6583 		break;
6584 	case LPFC_RSC_TYPE_FCOE_VFI:
6585 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6586 						   sizeof(unsigned long),
6587 						   GFP_KERNEL);
6588 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6589 			rc = -ENOMEM;
6590 			goto err_exit;
6591 		}
6592 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6593 						 sizeof(uint16_t),
6594 						 GFP_KERNEL);
6595 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6596 			kfree(phba->sli4_hba.vfi_bmask);
6597 			rc = -ENOMEM;
6598 			goto err_exit;
6599 		}
6600 
6601 		/* Initialize local ptrs for common extent processing later. */
6602 		bmask = phba->sli4_hba.vfi_bmask;
6603 		ids = phba->sli4_hba.vfi_ids;
6604 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6605 		break;
6606 	default:
6607 		/* Unsupported Opcode.  Fail call. */
6608 		id_array = NULL;
6609 		bmask = NULL;
6610 		ids = NULL;
6611 		ext_blk_list = NULL;
6612 		goto err_exit;
6613 	}
6614 
6615 	/*
6616 	 * Complete initializing the extent configuration with the
6617 	 * allocated ids assigned to this function.  The bitmask serves
6618 	 * as an index into the array and manages the available ids.  The
6619 	 * array just stores the ids communicated to the port via the wqes.
6620 	 */
6621 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6622 		if ((i % 2) == 0)
6623 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6624 					 &id_array[k]);
6625 		else
6626 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6627 					 &id_array[k]);
6628 
6629 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6630 		if (unlikely(!rsrc_blks)) {
6631 			rc = -ENOMEM;
6632 			kfree(bmask);
6633 			kfree(ids);
6634 			goto err_exit;
6635 		}
6636 		rsrc_blks->rsrc_start = rsrc_id;
6637 		rsrc_blks->rsrc_size = rsrc_size;
6638 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6639 		rsrc_start = rsrc_id;
6640 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6641 			phba->sli4_hba.io_xri_start = rsrc_start +
6642 				lpfc_sli4_get_iocb_cnt(phba);
6643 		}
6644 
6645 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6646 			ids[j] = rsrc_id;
6647 			rsrc_id++;
6648 			j++;
6649 		}
6650 		/* Entire word processed.  Get next word.*/
6651 		if ((i % 2) == 1)
6652 			k++;
6653 	}
6654  err_exit:
6655 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6656 	return rc;
6657 }
6658 
6659 
6660 
6661 /**
6662  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6663  * @phba: Pointer to HBA context object.
6664  * @type: the extent's type.
6665  *
6666  * This function deallocates all extents of a particular resource type.
6667  * SLI4 does not allow for deallocating a particular extent range.  It
6668  * is the caller's responsibility to release all kernel memory resources.
6669  **/
6670 static int
6671 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6672 {
6673 	int rc;
6674 	uint32_t length, mbox_tmo = 0;
6675 	LPFC_MBOXQ_t *mbox;
6676 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6677 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6678 
6679 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6680 	if (!mbox)
6681 		return -ENOMEM;
6682 
6683 	/*
6684 	 * This function sends an embedded mailbox because it only sends the
6685 	 * the resource type.  All extents of this type are released by the
6686 	 * port.
6687 	 */
6688 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6689 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6690 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6691 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6692 			 length, LPFC_SLI4_MBX_EMBED);
6693 
6694 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6695 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6696 					LPFC_SLI4_MBX_EMBED);
6697 	if (unlikely(rc)) {
6698 		rc = -EIO;
6699 		goto out_free_mbox;
6700 	}
6701 	if (!phba->sli4_hba.intr_enable)
6702 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6703 	else {
6704 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6705 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6706 	}
6707 	if (unlikely(rc)) {
6708 		rc = -EIO;
6709 		goto out_free_mbox;
6710 	}
6711 
6712 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6713 	if (bf_get(lpfc_mbox_hdr_status,
6714 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6715 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6716 				"2919 Failed to release resource extents "
6717 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6718 				"Resource memory not released.\n",
6719 				type,
6720 				bf_get(lpfc_mbox_hdr_status,
6721 				    &dealloc_rsrc->header.cfg_shdr.response),
6722 				bf_get(lpfc_mbox_hdr_add_status,
6723 				    &dealloc_rsrc->header.cfg_shdr.response));
6724 		rc = -EIO;
6725 		goto out_free_mbox;
6726 	}
6727 
6728 	/* Release kernel memory resources for the specific type. */
6729 	switch (type) {
6730 	case LPFC_RSC_TYPE_FCOE_VPI:
6731 		kfree(phba->vpi_bmask);
6732 		kfree(phba->vpi_ids);
6733 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6734 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6735 				    &phba->lpfc_vpi_blk_list, list) {
6736 			list_del_init(&rsrc_blk->list);
6737 			kfree(rsrc_blk);
6738 		}
6739 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6740 		break;
6741 	case LPFC_RSC_TYPE_FCOE_XRI:
6742 		kfree(phba->sli4_hba.xri_bmask);
6743 		kfree(phba->sli4_hba.xri_ids);
6744 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6745 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6746 			list_del_init(&rsrc_blk->list);
6747 			kfree(rsrc_blk);
6748 		}
6749 		break;
6750 	case LPFC_RSC_TYPE_FCOE_VFI:
6751 		kfree(phba->sli4_hba.vfi_bmask);
6752 		kfree(phba->sli4_hba.vfi_ids);
6753 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6754 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6755 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6756 			list_del_init(&rsrc_blk->list);
6757 			kfree(rsrc_blk);
6758 		}
6759 		break;
6760 	case LPFC_RSC_TYPE_FCOE_RPI:
6761 		/* RPI bitmask and physical id array are cleaned up earlier. */
6762 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6763 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6764 			list_del_init(&rsrc_blk->list);
6765 			kfree(rsrc_blk);
6766 		}
6767 		break;
6768 	default:
6769 		break;
6770 	}
6771 
6772 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6773 
6774  out_free_mbox:
6775 	mempool_free(mbox, phba->mbox_mem_pool);
6776 	return rc;
6777 }
6778 
6779 static void
6780 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6781 		  uint32_t feature)
6782 {
6783 	uint32_t len;
6784 	u32 sig_freq = 0;
6785 
6786 	len = sizeof(struct lpfc_mbx_set_feature) -
6787 		sizeof(struct lpfc_sli4_cfg_mhdr);
6788 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6789 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6790 			 LPFC_SLI4_MBX_EMBED);
6791 
6792 	switch (feature) {
6793 	case LPFC_SET_UE_RECOVERY:
6794 		bf_set(lpfc_mbx_set_feature_UER,
6795 		       &mbox->u.mqe.un.set_feature, 1);
6796 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6797 		mbox->u.mqe.un.set_feature.param_len = 8;
6798 		break;
6799 	case LPFC_SET_MDS_DIAGS:
6800 		bf_set(lpfc_mbx_set_feature_mds,
6801 		       &mbox->u.mqe.un.set_feature, 1);
6802 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6803 		       &mbox->u.mqe.un.set_feature, 1);
6804 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6805 		mbox->u.mqe.un.set_feature.param_len = 8;
6806 		break;
6807 	case LPFC_SET_CGN_SIGNAL:
6808 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6809 			sig_freq = 0;
6810 		else
6811 			sig_freq = phba->cgn_sig_freq;
6812 
6813 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6814 			bf_set(lpfc_mbx_set_feature_CGN_alarm_freq,
6815 			       &mbox->u.mqe.un.set_feature, sig_freq);
6816 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6817 			       &mbox->u.mqe.un.set_feature, sig_freq);
6818 		}
6819 
6820 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY)
6821 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6822 			       &mbox->u.mqe.un.set_feature, sig_freq);
6823 
6824 		if (phba->cmf_active_mode == LPFC_CFG_OFF ||
6825 		    phba->cgn_reg_signal == EDC_CG_SIG_NOTSUPPORTED)
6826 			sig_freq = 0;
6827 		else
6828 			sig_freq = lpfc_acqe_cgn_frequency;
6829 
6830 		bf_set(lpfc_mbx_set_feature_CGN_acqe_freq,
6831 		       &mbox->u.mqe.un.set_feature, sig_freq);
6832 
6833 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_CGN_SIGNAL;
6834 		mbox->u.mqe.un.set_feature.param_len = 12;
6835 		break;
6836 	case LPFC_SET_DUAL_DUMP:
6837 		bf_set(lpfc_mbx_set_feature_dd,
6838 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6839 		bf_set(lpfc_mbx_set_feature_ddquery,
6840 		       &mbox->u.mqe.un.set_feature, 0);
6841 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6842 		mbox->u.mqe.un.set_feature.param_len = 4;
6843 		break;
6844 	case LPFC_SET_ENABLE_MI:
6845 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_MI;
6846 		mbox->u.mqe.un.set_feature.param_len = 4;
6847 		bf_set(lpfc_mbx_set_feature_milunq, &mbox->u.mqe.un.set_feature,
6848 		       phba->pport->cfg_lun_queue_depth);
6849 		bf_set(lpfc_mbx_set_feature_mi, &mbox->u.mqe.un.set_feature,
6850 		       phba->sli4_hba.pc_sli4_params.mi_ver);
6851 		break;
6852 	case LPFC_SET_LD_SIGNAL:
6853 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_LD_SIGNAL;
6854 		mbox->u.mqe.un.set_feature.param_len = 16;
6855 		bf_set(lpfc_mbx_set_feature_lds_qry,
6856 		       &mbox->u.mqe.un.set_feature, LPFC_QUERY_LDS_OP);
6857 		break;
6858 	case LPFC_SET_ENABLE_CMF:
6859 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_CMF;
6860 		mbox->u.mqe.un.set_feature.param_len = 4;
6861 		bf_set(lpfc_mbx_set_feature_cmf,
6862 		       &mbox->u.mqe.un.set_feature, 1);
6863 		break;
6864 	}
6865 	return;
6866 }
6867 
6868 /**
6869  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6870  * @phba: Pointer to HBA context object.
6871  *
6872  * Disable FW logging into host memory on the adapter. To
6873  * be done before reading logs from the host memory.
6874  **/
6875 void
6876 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6877 {
6878 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6879 
6880 	spin_lock_irq(&phba->hbalock);
6881 	ras_fwlog->state = INACTIVE;
6882 	spin_unlock_irq(&phba->hbalock);
6883 
6884 	/* Disable FW logging to host memory */
6885 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6886 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6887 
6888 	/* Wait 10ms for firmware to stop using DMA buffer */
6889 	usleep_range(10 * 1000, 20 * 1000);
6890 }
6891 
6892 /**
6893  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6894  * @phba: Pointer to HBA context object.
6895  *
6896  * This function is called to free memory allocated for RAS FW logging
6897  * support in the driver.
6898  **/
6899 void
6900 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6901 {
6902 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6903 	struct lpfc_dmabuf *dmabuf, *next;
6904 
6905 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6906 		list_for_each_entry_safe(dmabuf, next,
6907 				    &ras_fwlog->fwlog_buff_list,
6908 				    list) {
6909 			list_del(&dmabuf->list);
6910 			dma_free_coherent(&phba->pcidev->dev,
6911 					  LPFC_RAS_MAX_ENTRY_SIZE,
6912 					  dmabuf->virt, dmabuf->phys);
6913 			kfree(dmabuf);
6914 		}
6915 	}
6916 
6917 	if (ras_fwlog->lwpd.virt) {
6918 		dma_free_coherent(&phba->pcidev->dev,
6919 				  sizeof(uint32_t) * 2,
6920 				  ras_fwlog->lwpd.virt,
6921 				  ras_fwlog->lwpd.phys);
6922 		ras_fwlog->lwpd.virt = NULL;
6923 	}
6924 
6925 	spin_lock_irq(&phba->hbalock);
6926 	ras_fwlog->state = INACTIVE;
6927 	spin_unlock_irq(&phba->hbalock);
6928 }
6929 
6930 /**
6931  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6932  * @phba: Pointer to HBA context object.
6933  * @fwlog_buff_count: Count of buffers to be created.
6934  *
6935  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6936  * to update FW log is posted to the adapter.
6937  * Buffer count is calculated based on module param ras_fwlog_buffsize
6938  * Size of each buffer posted to FW is 64K.
6939  **/
6940 
6941 static int
6942 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6943 			uint32_t fwlog_buff_count)
6944 {
6945 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6946 	struct lpfc_dmabuf *dmabuf;
6947 	int rc = 0, i = 0;
6948 
6949 	/* Initialize List */
6950 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6951 
6952 	/* Allocate memory for the LWPD */
6953 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6954 					    sizeof(uint32_t) * 2,
6955 					    &ras_fwlog->lwpd.phys,
6956 					    GFP_KERNEL);
6957 	if (!ras_fwlog->lwpd.virt) {
6958 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6959 				"6185 LWPD Memory Alloc Failed\n");
6960 
6961 		return -ENOMEM;
6962 	}
6963 
6964 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6965 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6966 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6967 				 GFP_KERNEL);
6968 		if (!dmabuf) {
6969 			rc = -ENOMEM;
6970 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6971 					"6186 Memory Alloc failed FW logging");
6972 			goto free_mem;
6973 		}
6974 
6975 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6976 						  LPFC_RAS_MAX_ENTRY_SIZE,
6977 						  &dmabuf->phys, GFP_KERNEL);
6978 		if (!dmabuf->virt) {
6979 			kfree(dmabuf);
6980 			rc = -ENOMEM;
6981 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6982 					"6187 DMA Alloc Failed FW logging");
6983 			goto free_mem;
6984 		}
6985 		dmabuf->buffer_tag = i;
6986 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6987 	}
6988 
6989 free_mem:
6990 	if (rc)
6991 		lpfc_sli4_ras_dma_free(phba);
6992 
6993 	return rc;
6994 }
6995 
6996 /**
6997  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6998  * @phba: pointer to lpfc hba data structure.
6999  * @pmb: pointer to the driver internal queue element for mailbox command.
7000  *
7001  * Completion handler for driver's RAS MBX command to the device.
7002  **/
7003 static void
7004 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7005 {
7006 	MAILBOX_t *mb;
7007 	union lpfc_sli4_cfg_shdr *shdr;
7008 	uint32_t shdr_status, shdr_add_status;
7009 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
7010 
7011 	mb = &pmb->u.mb;
7012 
7013 	shdr = (union lpfc_sli4_cfg_shdr *)
7014 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
7015 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7016 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7017 
7018 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
7019 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7020 				"6188 FW LOG mailbox "
7021 				"completed with status x%x add_status x%x,"
7022 				" mbx status x%x\n",
7023 				shdr_status, shdr_add_status, mb->mbxStatus);
7024 
7025 		ras_fwlog->ras_hwsupport = false;
7026 		goto disable_ras;
7027 	}
7028 
7029 	spin_lock_irq(&phba->hbalock);
7030 	ras_fwlog->state = ACTIVE;
7031 	spin_unlock_irq(&phba->hbalock);
7032 	mempool_free(pmb, phba->mbox_mem_pool);
7033 
7034 	return;
7035 
7036 disable_ras:
7037 	/* Free RAS DMA memory */
7038 	lpfc_sli4_ras_dma_free(phba);
7039 	mempool_free(pmb, phba->mbox_mem_pool);
7040 }
7041 
7042 /**
7043  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
7044  * @phba: pointer to lpfc hba data structure.
7045  * @fwlog_level: Logging verbosity level.
7046  * @fwlog_enable: Enable/Disable logging.
7047  *
7048  * Initialize memory and post mailbox command to enable FW logging in host
7049  * memory.
7050  **/
7051 int
7052 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
7053 			 uint32_t fwlog_level,
7054 			 uint32_t fwlog_enable)
7055 {
7056 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
7057 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
7058 	struct lpfc_dmabuf *dmabuf;
7059 	LPFC_MBOXQ_t *mbox;
7060 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
7061 	int rc = 0;
7062 
7063 	spin_lock_irq(&phba->hbalock);
7064 	ras_fwlog->state = INACTIVE;
7065 	spin_unlock_irq(&phba->hbalock);
7066 
7067 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
7068 			  phba->cfg_ras_fwlog_buffsize);
7069 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
7070 
7071 	/*
7072 	 * If re-enabling FW logging support use earlier allocated
7073 	 * DMA buffers while posting MBX command.
7074 	 **/
7075 	if (!ras_fwlog->lwpd.virt) {
7076 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
7077 		if (rc) {
7078 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7079 					"6189 FW Log Memory Allocation Failed");
7080 			return rc;
7081 		}
7082 	}
7083 
7084 	/* Setup Mailbox command */
7085 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7086 	if (!mbox) {
7087 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7088 				"6190 RAS MBX Alloc Failed");
7089 		rc = -ENOMEM;
7090 		goto mem_free;
7091 	}
7092 
7093 	ras_fwlog->fw_loglevel = fwlog_level;
7094 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
7095 		sizeof(struct lpfc_sli4_cfg_mhdr));
7096 
7097 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
7098 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
7099 			 len, LPFC_SLI4_MBX_EMBED);
7100 
7101 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
7102 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
7103 	       fwlog_enable);
7104 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
7105 	       ras_fwlog->fw_loglevel);
7106 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
7107 	       ras_fwlog->fw_buffcount);
7108 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
7109 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
7110 
7111 	/* Update DMA buffer address */
7112 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
7113 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
7114 
7115 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
7116 			putPaddrLow(dmabuf->phys);
7117 
7118 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
7119 			putPaddrHigh(dmabuf->phys);
7120 	}
7121 
7122 	/* Update LPWD address */
7123 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
7124 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
7125 
7126 	spin_lock_irq(&phba->hbalock);
7127 	ras_fwlog->state = REG_INPROGRESS;
7128 	spin_unlock_irq(&phba->hbalock);
7129 	mbox->vport = phba->pport;
7130 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
7131 
7132 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
7133 
7134 	if (rc == MBX_NOT_FINISHED) {
7135 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7136 				"6191 FW-Log Mailbox failed. "
7137 				"status %d mbxStatus : x%x", rc,
7138 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
7139 		mempool_free(mbox, phba->mbox_mem_pool);
7140 		rc = -EIO;
7141 		goto mem_free;
7142 	} else
7143 		rc = 0;
7144 mem_free:
7145 	if (rc)
7146 		lpfc_sli4_ras_dma_free(phba);
7147 
7148 	return rc;
7149 }
7150 
7151 /**
7152  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
7153  * @phba: Pointer to HBA context object.
7154  *
7155  * Check if RAS is supported on the adapter and initialize it.
7156  **/
7157 void
7158 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
7159 {
7160 	/* Check RAS FW Log needs to be enabled or not */
7161 	if (lpfc_check_fwlog_support(phba))
7162 		return;
7163 
7164 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
7165 				 LPFC_RAS_ENABLE_LOGGING);
7166 }
7167 
7168 /**
7169  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
7170  * @phba: Pointer to HBA context object.
7171  *
7172  * This function allocates all SLI4 resource identifiers.
7173  **/
7174 int
7175 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
7176 {
7177 	int i, rc, error = 0;
7178 	uint16_t count, base;
7179 	unsigned long longs;
7180 
7181 	if (!phba->sli4_hba.rpi_hdrs_in_use)
7182 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
7183 	if (phba->sli4_hba.extents_in_use) {
7184 		/*
7185 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
7186 		 * resource extent count must be read and allocated before
7187 		 * provisioning the resource id arrays.
7188 		 */
7189 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7190 		    LPFC_IDX_RSRC_RDY) {
7191 			/*
7192 			 * Extent-based resources are set - the driver could
7193 			 * be in a port reset. Figure out if any corrective
7194 			 * actions need to be taken.
7195 			 */
7196 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7197 						 LPFC_RSC_TYPE_FCOE_VFI);
7198 			if (rc != 0)
7199 				error++;
7200 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7201 						 LPFC_RSC_TYPE_FCOE_VPI);
7202 			if (rc != 0)
7203 				error++;
7204 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7205 						 LPFC_RSC_TYPE_FCOE_XRI);
7206 			if (rc != 0)
7207 				error++;
7208 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7209 						 LPFC_RSC_TYPE_FCOE_RPI);
7210 			if (rc != 0)
7211 				error++;
7212 
7213 			/*
7214 			 * It's possible that the number of resources
7215 			 * provided to this port instance changed between
7216 			 * resets.  Detect this condition and reallocate
7217 			 * resources.  Otherwise, there is no action.
7218 			 */
7219 			if (error) {
7220 				lpfc_printf_log(phba, KERN_INFO,
7221 						LOG_MBOX | LOG_INIT,
7222 						"2931 Detected extent resource "
7223 						"change.  Reallocating all "
7224 						"extents.\n");
7225 				rc = lpfc_sli4_dealloc_extent(phba,
7226 						 LPFC_RSC_TYPE_FCOE_VFI);
7227 				rc = lpfc_sli4_dealloc_extent(phba,
7228 						 LPFC_RSC_TYPE_FCOE_VPI);
7229 				rc = lpfc_sli4_dealloc_extent(phba,
7230 						 LPFC_RSC_TYPE_FCOE_XRI);
7231 				rc = lpfc_sli4_dealloc_extent(phba,
7232 						 LPFC_RSC_TYPE_FCOE_RPI);
7233 			} else
7234 				return 0;
7235 		}
7236 
7237 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7238 		if (unlikely(rc))
7239 			goto err_exit;
7240 
7241 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7242 		if (unlikely(rc))
7243 			goto err_exit;
7244 
7245 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7246 		if (unlikely(rc))
7247 			goto err_exit;
7248 
7249 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7250 		if (unlikely(rc))
7251 			goto err_exit;
7252 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7253 		       LPFC_IDX_RSRC_RDY);
7254 		return rc;
7255 	} else {
7256 		/*
7257 		 * The port does not support resource extents.  The XRI, VPI,
7258 		 * VFI, RPI resource ids were determined from READ_CONFIG.
7259 		 * Just allocate the bitmasks and provision the resource id
7260 		 * arrays.  If a port reset is active, the resources don't
7261 		 * need any action - just exit.
7262 		 */
7263 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7264 		    LPFC_IDX_RSRC_RDY) {
7265 			lpfc_sli4_dealloc_resource_identifiers(phba);
7266 			lpfc_sli4_remove_rpis(phba);
7267 		}
7268 		/* RPIs. */
7269 		count = phba->sli4_hba.max_cfg_param.max_rpi;
7270 		if (count <= 0) {
7271 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7272 					"3279 Invalid provisioning of "
7273 					"rpi:%d\n", count);
7274 			rc = -EINVAL;
7275 			goto err_exit;
7276 		}
7277 		base = phba->sli4_hba.max_cfg_param.rpi_base;
7278 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7279 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
7280 						   sizeof(unsigned long),
7281 						   GFP_KERNEL);
7282 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
7283 			rc = -ENOMEM;
7284 			goto err_exit;
7285 		}
7286 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
7287 						 GFP_KERNEL);
7288 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
7289 			rc = -ENOMEM;
7290 			goto free_rpi_bmask;
7291 		}
7292 
7293 		for (i = 0; i < count; i++)
7294 			phba->sli4_hba.rpi_ids[i] = base + i;
7295 
7296 		/* VPIs. */
7297 		count = phba->sli4_hba.max_cfg_param.max_vpi;
7298 		if (count <= 0) {
7299 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7300 					"3280 Invalid provisioning of "
7301 					"vpi:%d\n", count);
7302 			rc = -EINVAL;
7303 			goto free_rpi_ids;
7304 		}
7305 		base = phba->sli4_hba.max_cfg_param.vpi_base;
7306 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7307 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
7308 					  GFP_KERNEL);
7309 		if (unlikely(!phba->vpi_bmask)) {
7310 			rc = -ENOMEM;
7311 			goto free_rpi_ids;
7312 		}
7313 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
7314 					GFP_KERNEL);
7315 		if (unlikely(!phba->vpi_ids)) {
7316 			rc = -ENOMEM;
7317 			goto free_vpi_bmask;
7318 		}
7319 
7320 		for (i = 0; i < count; i++)
7321 			phba->vpi_ids[i] = base + i;
7322 
7323 		/* XRIs. */
7324 		count = phba->sli4_hba.max_cfg_param.max_xri;
7325 		if (count <= 0) {
7326 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7327 					"3281 Invalid provisioning of "
7328 					"xri:%d\n", count);
7329 			rc = -EINVAL;
7330 			goto free_vpi_ids;
7331 		}
7332 		base = phba->sli4_hba.max_cfg_param.xri_base;
7333 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7334 		phba->sli4_hba.xri_bmask = kcalloc(longs,
7335 						   sizeof(unsigned long),
7336 						   GFP_KERNEL);
7337 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
7338 			rc = -ENOMEM;
7339 			goto free_vpi_ids;
7340 		}
7341 		phba->sli4_hba.max_cfg_param.xri_used = 0;
7342 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
7343 						 GFP_KERNEL);
7344 		if (unlikely(!phba->sli4_hba.xri_ids)) {
7345 			rc = -ENOMEM;
7346 			goto free_xri_bmask;
7347 		}
7348 
7349 		for (i = 0; i < count; i++)
7350 			phba->sli4_hba.xri_ids[i] = base + i;
7351 
7352 		/* VFIs. */
7353 		count = phba->sli4_hba.max_cfg_param.max_vfi;
7354 		if (count <= 0) {
7355 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7356 					"3282 Invalid provisioning of "
7357 					"vfi:%d\n", count);
7358 			rc = -EINVAL;
7359 			goto free_xri_ids;
7360 		}
7361 		base = phba->sli4_hba.max_cfg_param.vfi_base;
7362 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7363 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
7364 						   sizeof(unsigned long),
7365 						   GFP_KERNEL);
7366 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
7367 			rc = -ENOMEM;
7368 			goto free_xri_ids;
7369 		}
7370 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
7371 						 GFP_KERNEL);
7372 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
7373 			rc = -ENOMEM;
7374 			goto free_vfi_bmask;
7375 		}
7376 
7377 		for (i = 0; i < count; i++)
7378 			phba->sli4_hba.vfi_ids[i] = base + i;
7379 
7380 		/*
7381 		 * Mark all resources ready.  An HBA reset doesn't need
7382 		 * to reset the initialization.
7383 		 */
7384 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7385 		       LPFC_IDX_RSRC_RDY);
7386 		return 0;
7387 	}
7388 
7389  free_vfi_bmask:
7390 	kfree(phba->sli4_hba.vfi_bmask);
7391 	phba->sli4_hba.vfi_bmask = NULL;
7392  free_xri_ids:
7393 	kfree(phba->sli4_hba.xri_ids);
7394 	phba->sli4_hba.xri_ids = NULL;
7395  free_xri_bmask:
7396 	kfree(phba->sli4_hba.xri_bmask);
7397 	phba->sli4_hba.xri_bmask = NULL;
7398  free_vpi_ids:
7399 	kfree(phba->vpi_ids);
7400 	phba->vpi_ids = NULL;
7401  free_vpi_bmask:
7402 	kfree(phba->vpi_bmask);
7403 	phba->vpi_bmask = NULL;
7404  free_rpi_ids:
7405 	kfree(phba->sli4_hba.rpi_ids);
7406 	phba->sli4_hba.rpi_ids = NULL;
7407  free_rpi_bmask:
7408 	kfree(phba->sli4_hba.rpi_bmask);
7409 	phba->sli4_hba.rpi_bmask = NULL;
7410  err_exit:
7411 	return rc;
7412 }
7413 
7414 /**
7415  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
7416  * @phba: Pointer to HBA context object.
7417  *
7418  * This function allocates the number of elements for the specified
7419  * resource type.
7420  **/
7421 int
7422 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7423 {
7424 	if (phba->sli4_hba.extents_in_use) {
7425 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7426 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7427 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7428 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7429 	} else {
7430 		kfree(phba->vpi_bmask);
7431 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
7432 		kfree(phba->vpi_ids);
7433 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7434 		kfree(phba->sli4_hba.xri_bmask);
7435 		kfree(phba->sli4_hba.xri_ids);
7436 		kfree(phba->sli4_hba.vfi_bmask);
7437 		kfree(phba->sli4_hba.vfi_ids);
7438 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7439 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7440 	}
7441 
7442 	return 0;
7443 }
7444 
7445 /**
7446  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7447  * @phba: Pointer to HBA context object.
7448  * @type: The resource extent type.
7449  * @extnt_cnt: buffer to hold port extent count response
7450  * @extnt_size: buffer to hold port extent size response.
7451  *
7452  * This function calls the port to read the host allocated extents
7453  * for a particular type.
7454  **/
7455 int
7456 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7457 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
7458 {
7459 	bool emb;
7460 	int rc = 0;
7461 	uint16_t curr_blks = 0;
7462 	uint32_t req_len, emb_len;
7463 	uint32_t alloc_len, mbox_tmo;
7464 	struct list_head *blk_list_head;
7465 	struct lpfc_rsrc_blks *rsrc_blk;
7466 	LPFC_MBOXQ_t *mbox;
7467 	void *virtaddr = NULL;
7468 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7469 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7470 	union  lpfc_sli4_cfg_shdr *shdr;
7471 
7472 	switch (type) {
7473 	case LPFC_RSC_TYPE_FCOE_VPI:
7474 		blk_list_head = &phba->lpfc_vpi_blk_list;
7475 		break;
7476 	case LPFC_RSC_TYPE_FCOE_XRI:
7477 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7478 		break;
7479 	case LPFC_RSC_TYPE_FCOE_VFI:
7480 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7481 		break;
7482 	case LPFC_RSC_TYPE_FCOE_RPI:
7483 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7484 		break;
7485 	default:
7486 		return -EIO;
7487 	}
7488 
7489 	/* Count the number of extents currently allocatd for this type. */
7490 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
7491 		if (curr_blks == 0) {
7492 			/*
7493 			 * The GET_ALLOCATED mailbox does not return the size,
7494 			 * just the count.  The size should be just the size
7495 			 * stored in the current allocated block and all sizes
7496 			 * for an extent type are the same so set the return
7497 			 * value now.
7498 			 */
7499 			*extnt_size = rsrc_blk->rsrc_size;
7500 		}
7501 		curr_blks++;
7502 	}
7503 
7504 	/*
7505 	 * Calculate the size of an embedded mailbox.  The uint32_t
7506 	 * accounts for extents-specific word.
7507 	 */
7508 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7509 		sizeof(uint32_t);
7510 
7511 	/*
7512 	 * Presume the allocation and response will fit into an embedded
7513 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7514 	 */
7515 	emb = LPFC_SLI4_MBX_EMBED;
7516 	req_len = emb_len;
7517 	if (req_len > emb_len) {
7518 		req_len = curr_blks * sizeof(uint16_t) +
7519 			sizeof(union lpfc_sli4_cfg_shdr) +
7520 			sizeof(uint32_t);
7521 		emb = LPFC_SLI4_MBX_NEMBED;
7522 	}
7523 
7524 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7525 	if (!mbox)
7526 		return -ENOMEM;
7527 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7528 
7529 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7530 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7531 				     req_len, emb);
7532 	if (alloc_len < req_len) {
7533 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7534 			"2983 Allocated DMA memory size (x%x) is "
7535 			"less than the requested DMA memory "
7536 			"size (x%x)\n", alloc_len, req_len);
7537 		rc = -ENOMEM;
7538 		goto err_exit;
7539 	}
7540 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7541 	if (unlikely(rc)) {
7542 		rc = -EIO;
7543 		goto err_exit;
7544 	}
7545 
7546 	if (!phba->sli4_hba.intr_enable)
7547 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7548 	else {
7549 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7550 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7551 	}
7552 
7553 	if (unlikely(rc)) {
7554 		rc = -EIO;
7555 		goto err_exit;
7556 	}
7557 
7558 	/*
7559 	 * Figure out where the response is located.  Then get local pointers
7560 	 * to the response data.  The port does not guarantee to respond to
7561 	 * all extents counts request so update the local variable with the
7562 	 * allocated count from the port.
7563 	 */
7564 	if (emb == LPFC_SLI4_MBX_EMBED) {
7565 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7566 		shdr = &rsrc_ext->header.cfg_shdr;
7567 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7568 	} else {
7569 		virtaddr = mbox->sge_array->addr[0];
7570 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7571 		shdr = &n_rsrc->cfg_shdr;
7572 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7573 	}
7574 
7575 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7576 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7577 			"2984 Failed to read allocated resources "
7578 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7579 			type,
7580 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7581 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7582 		rc = -EIO;
7583 		goto err_exit;
7584 	}
7585  err_exit:
7586 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7587 	return rc;
7588 }
7589 
7590 /**
7591  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7592  * @phba: pointer to lpfc hba data structure.
7593  * @sgl_list: linked link of sgl buffers to post
7594  * @cnt: number of linked list buffers
7595  *
7596  * This routine walks the list of buffers that have been allocated and
7597  * repost them to the port by using SGL block post. This is needed after a
7598  * pci_function_reset/warm_start or start. It attempts to construct blocks
7599  * of buffer sgls which contains contiguous xris and uses the non-embedded
7600  * SGL block post mailbox commands to post them to the port. For single
7601  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7602  * mailbox command for posting.
7603  *
7604  * Returns: 0 = success, non-zero failure.
7605  **/
7606 static int
7607 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7608 			  struct list_head *sgl_list, int cnt)
7609 {
7610 	struct lpfc_sglq *sglq_entry = NULL;
7611 	struct lpfc_sglq *sglq_entry_next = NULL;
7612 	struct lpfc_sglq *sglq_entry_first = NULL;
7613 	int status, total_cnt;
7614 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7615 	int last_xritag = NO_XRI;
7616 	LIST_HEAD(prep_sgl_list);
7617 	LIST_HEAD(blck_sgl_list);
7618 	LIST_HEAD(allc_sgl_list);
7619 	LIST_HEAD(post_sgl_list);
7620 	LIST_HEAD(free_sgl_list);
7621 
7622 	spin_lock_irq(&phba->hbalock);
7623 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7624 	list_splice_init(sgl_list, &allc_sgl_list);
7625 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7626 	spin_unlock_irq(&phba->hbalock);
7627 
7628 	total_cnt = cnt;
7629 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7630 				 &allc_sgl_list, list) {
7631 		list_del_init(&sglq_entry->list);
7632 		block_cnt++;
7633 		if ((last_xritag != NO_XRI) &&
7634 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7635 			/* a hole in xri block, form a sgl posting block */
7636 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7637 			post_cnt = block_cnt - 1;
7638 			/* prepare list for next posting block */
7639 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7640 			block_cnt = 1;
7641 		} else {
7642 			/* prepare list for next posting block */
7643 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7644 			/* enough sgls for non-embed sgl mbox command */
7645 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7646 				list_splice_init(&prep_sgl_list,
7647 						 &blck_sgl_list);
7648 				post_cnt = block_cnt;
7649 				block_cnt = 0;
7650 			}
7651 		}
7652 		num_posted++;
7653 
7654 		/* keep track of last sgl's xritag */
7655 		last_xritag = sglq_entry->sli4_xritag;
7656 
7657 		/* end of repost sgl list condition for buffers */
7658 		if (num_posted == total_cnt) {
7659 			if (post_cnt == 0) {
7660 				list_splice_init(&prep_sgl_list,
7661 						 &blck_sgl_list);
7662 				post_cnt = block_cnt;
7663 			} else if (block_cnt == 1) {
7664 				status = lpfc_sli4_post_sgl(phba,
7665 						sglq_entry->phys, 0,
7666 						sglq_entry->sli4_xritag);
7667 				if (!status) {
7668 					/* successful, put sgl to posted list */
7669 					list_add_tail(&sglq_entry->list,
7670 						      &post_sgl_list);
7671 				} else {
7672 					/* Failure, put sgl to free list */
7673 					lpfc_printf_log(phba, KERN_WARNING,
7674 						LOG_SLI,
7675 						"3159 Failed to post "
7676 						"sgl, xritag:x%x\n",
7677 						sglq_entry->sli4_xritag);
7678 					list_add_tail(&sglq_entry->list,
7679 						      &free_sgl_list);
7680 					total_cnt--;
7681 				}
7682 			}
7683 		}
7684 
7685 		/* continue until a nembed page worth of sgls */
7686 		if (post_cnt == 0)
7687 			continue;
7688 
7689 		/* post the buffer list sgls as a block */
7690 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7691 						 post_cnt);
7692 
7693 		if (!status) {
7694 			/* success, put sgl list to posted sgl list */
7695 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7696 		} else {
7697 			/* Failure, put sgl list to free sgl list */
7698 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7699 							    struct lpfc_sglq,
7700 							    list);
7701 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7702 					"3160 Failed to post sgl-list, "
7703 					"xritag:x%x-x%x\n",
7704 					sglq_entry_first->sli4_xritag,
7705 					(sglq_entry_first->sli4_xritag +
7706 					 post_cnt - 1));
7707 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7708 			total_cnt -= post_cnt;
7709 		}
7710 
7711 		/* don't reset xirtag due to hole in xri block */
7712 		if (block_cnt == 0)
7713 			last_xritag = NO_XRI;
7714 
7715 		/* reset sgl post count for next round of posting */
7716 		post_cnt = 0;
7717 	}
7718 
7719 	/* free the sgls failed to post */
7720 	lpfc_free_sgl_list(phba, &free_sgl_list);
7721 
7722 	/* push sgls posted to the available list */
7723 	if (!list_empty(&post_sgl_list)) {
7724 		spin_lock_irq(&phba->hbalock);
7725 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7726 		list_splice_init(&post_sgl_list, sgl_list);
7727 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7728 		spin_unlock_irq(&phba->hbalock);
7729 	} else {
7730 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7731 				"3161 Failure to post sgl to port.\n");
7732 		return -EIO;
7733 	}
7734 
7735 	/* return the number of XRIs actually posted */
7736 	return total_cnt;
7737 }
7738 
7739 /**
7740  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7741  * @phba: pointer to lpfc hba data structure.
7742  *
7743  * This routine walks the list of nvme buffers that have been allocated and
7744  * repost them to the port by using SGL block post. This is needed after a
7745  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7746  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7747  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7748  *
7749  * Returns: 0 = success, non-zero failure.
7750  **/
7751 static int
7752 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7753 {
7754 	LIST_HEAD(post_nblist);
7755 	int num_posted, rc = 0;
7756 
7757 	/* get all NVME buffers need to repost to a local list */
7758 	lpfc_io_buf_flush(phba, &post_nblist);
7759 
7760 	/* post the list of nvme buffer sgls to port if available */
7761 	if (!list_empty(&post_nblist)) {
7762 		num_posted = lpfc_sli4_post_io_sgl_list(
7763 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7764 		/* failed to post any nvme buffer, return error */
7765 		if (num_posted == 0)
7766 			rc = -EIO;
7767 	}
7768 	return rc;
7769 }
7770 
7771 static void
7772 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7773 {
7774 	uint32_t len;
7775 
7776 	len = sizeof(struct lpfc_mbx_set_host_data) -
7777 		sizeof(struct lpfc_sli4_cfg_mhdr);
7778 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7779 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7780 			 LPFC_SLI4_MBX_EMBED);
7781 
7782 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7783 	mbox->u.mqe.un.set_host_data.param_len =
7784 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7785 	snprintf(mbox->u.mqe.un.set_host_data.un.data,
7786 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7787 		 "Linux %s v"LPFC_DRIVER_VERSION,
7788 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7789 }
7790 
7791 int
7792 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7793 		    struct lpfc_queue *drq, int count, int idx)
7794 {
7795 	int rc, i;
7796 	struct lpfc_rqe hrqe;
7797 	struct lpfc_rqe drqe;
7798 	struct lpfc_rqb *rqbp;
7799 	unsigned long flags;
7800 	struct rqb_dmabuf *rqb_buffer;
7801 	LIST_HEAD(rqb_buf_list);
7802 
7803 	rqbp = hrq->rqbp;
7804 	for (i = 0; i < count; i++) {
7805 		spin_lock_irqsave(&phba->hbalock, flags);
7806 		/* IF RQ is already full, don't bother */
7807 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7808 			spin_unlock_irqrestore(&phba->hbalock, flags);
7809 			break;
7810 		}
7811 		spin_unlock_irqrestore(&phba->hbalock, flags);
7812 
7813 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7814 		if (!rqb_buffer)
7815 			break;
7816 		rqb_buffer->hrq = hrq;
7817 		rqb_buffer->drq = drq;
7818 		rqb_buffer->idx = idx;
7819 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7820 	}
7821 
7822 	spin_lock_irqsave(&phba->hbalock, flags);
7823 	while (!list_empty(&rqb_buf_list)) {
7824 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7825 				 hbuf.list);
7826 
7827 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7828 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7829 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7830 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7831 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7832 		if (rc < 0) {
7833 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7834 					"6421 Cannot post to HRQ %d: %x %x %x "
7835 					"DRQ %x %x\n",
7836 					hrq->queue_id,
7837 					hrq->host_index,
7838 					hrq->hba_index,
7839 					hrq->entry_count,
7840 					drq->host_index,
7841 					drq->hba_index);
7842 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7843 		} else {
7844 			list_add_tail(&rqb_buffer->hbuf.list,
7845 				      &rqbp->rqb_buffer_list);
7846 			rqbp->buffer_count++;
7847 		}
7848 	}
7849 	spin_unlock_irqrestore(&phba->hbalock, flags);
7850 	return 1;
7851 }
7852 
7853 static void
7854 lpfc_mbx_cmpl_read_lds_params(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7855 {
7856 	union lpfc_sli4_cfg_shdr *shdr;
7857 	u32 shdr_status, shdr_add_status;
7858 
7859 	shdr = (union lpfc_sli4_cfg_shdr *)
7860 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7861 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7862 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7863 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7864 		lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT | LOG_MBOX,
7865 				"4622 SET_FEATURE (x%x) mbox failed, "
7866 				"status x%x add_status x%x, mbx status x%x\n",
7867 				LPFC_SET_LD_SIGNAL, shdr_status,
7868 				shdr_add_status, pmb->u.mb.mbxStatus);
7869 		phba->degrade_activate_threshold = 0;
7870 		phba->degrade_deactivate_threshold = 0;
7871 		phba->fec_degrade_interval = 0;
7872 		goto out;
7873 	}
7874 
7875 	phba->degrade_activate_threshold = pmb->u.mqe.un.set_feature.word7;
7876 	phba->degrade_deactivate_threshold = pmb->u.mqe.un.set_feature.word8;
7877 	phba->fec_degrade_interval = pmb->u.mqe.un.set_feature.word10;
7878 
7879 	lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT,
7880 			"4624 Success: da x%x dd x%x interval x%x\n",
7881 			phba->degrade_activate_threshold,
7882 			phba->degrade_deactivate_threshold,
7883 			phba->fec_degrade_interval);
7884 out:
7885 	mempool_free(pmb, phba->mbox_mem_pool);
7886 }
7887 
7888 int
7889 lpfc_read_lds_params(struct lpfc_hba *phba)
7890 {
7891 	LPFC_MBOXQ_t *mboxq;
7892 	int rc;
7893 
7894 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7895 	if (!mboxq)
7896 		return -ENOMEM;
7897 
7898 	lpfc_set_features(phba, mboxq, LPFC_SET_LD_SIGNAL);
7899 	mboxq->vport = phba->pport;
7900 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_lds_params;
7901 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7902 	if (rc == MBX_NOT_FINISHED) {
7903 		mempool_free(mboxq, phba->mbox_mem_pool);
7904 		return -EIO;
7905 	}
7906 	return 0;
7907 }
7908 
7909 static void
7910 lpfc_mbx_cmpl_cgn_set_ftrs(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7911 {
7912 	struct lpfc_vport *vport = pmb->vport;
7913 	union lpfc_sli4_cfg_shdr *shdr;
7914 	u32 shdr_status, shdr_add_status;
7915 	u32 sig, acqe;
7916 
7917 	/* Two outcomes. (1) Set featurs was successul and EDC negotiation
7918 	 * is done. (2) Mailbox failed and send FPIN support only.
7919 	 */
7920 	shdr = (union lpfc_sli4_cfg_shdr *)
7921 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7922 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7923 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7924 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7925 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
7926 				"2516 CGN SET_FEATURE mbox failed with "
7927 				"status x%x add_status x%x, mbx status x%x "
7928 				"Reset Congestion to FPINs only\n",
7929 				shdr_status, shdr_add_status,
7930 				pmb->u.mb.mbxStatus);
7931 		/* If there is a mbox error, move on to RDF */
7932 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7933 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7934 		goto out;
7935 	}
7936 
7937 	/* Zero out Congestion Signal ACQE counter */
7938 	phba->cgn_acqe_cnt = 0;
7939 
7940 	acqe = bf_get(lpfc_mbx_set_feature_CGN_acqe_freq,
7941 		      &pmb->u.mqe.un.set_feature);
7942 	sig = bf_get(lpfc_mbx_set_feature_CGN_warn_freq,
7943 		     &pmb->u.mqe.un.set_feature);
7944 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7945 			"4620 SET_FEATURES Success: Freq: %ds %dms "
7946 			" Reg: x%x x%x\n", acqe, sig,
7947 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7948 out:
7949 	mempool_free(pmb, phba->mbox_mem_pool);
7950 
7951 	/* Register for FPIN events from the fabric now that the
7952 	 * EDC common_set_features has completed.
7953 	 */
7954 	lpfc_issue_els_rdf(vport, 0);
7955 }
7956 
7957 int
7958 lpfc_config_cgn_signal(struct lpfc_hba *phba)
7959 {
7960 	LPFC_MBOXQ_t *mboxq;
7961 	u32 rc;
7962 
7963 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7964 	if (!mboxq)
7965 		goto out_rdf;
7966 
7967 	lpfc_set_features(phba, mboxq, LPFC_SET_CGN_SIGNAL);
7968 	mboxq->vport = phba->pport;
7969 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_cgn_set_ftrs;
7970 
7971 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7972 			"4621 SET_FEATURES: FREQ sig x%x acqe x%x: "
7973 			"Reg: x%x x%x\n",
7974 			phba->cgn_sig_freq, lpfc_acqe_cgn_frequency,
7975 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7976 
7977 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7978 	if (rc == MBX_NOT_FINISHED)
7979 		goto out;
7980 	return 0;
7981 
7982 out:
7983 	mempool_free(mboxq, phba->mbox_mem_pool);
7984 out_rdf:
7985 	/* If there is a mbox error, move on to RDF */
7986 	phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7987 	phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7988 	lpfc_issue_els_rdf(phba->pport, 0);
7989 	return -EIO;
7990 }
7991 
7992 /**
7993  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7994  * @phba: pointer to lpfc hba data structure.
7995  *
7996  * This routine initializes the per-cq idle_stat to dynamically dictate
7997  * polling decisions.
7998  *
7999  * Return codes:
8000  *   None
8001  **/
8002 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
8003 {
8004 	int i;
8005 	struct lpfc_sli4_hdw_queue *hdwq;
8006 	struct lpfc_queue *cq;
8007 	struct lpfc_idle_stat *idle_stat;
8008 	u64 wall;
8009 
8010 	for_each_present_cpu(i) {
8011 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
8012 		cq = hdwq->io_cq;
8013 
8014 		/* Skip if we've already handled this cq's primary CPU */
8015 		if (cq->chann != i)
8016 			continue;
8017 
8018 		idle_stat = &phba->sli4_hba.idle_stat[i];
8019 
8020 		idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
8021 		idle_stat->prev_wall = wall;
8022 
8023 		if (phba->nvmet_support ||
8024 		    phba->cmf_active_mode != LPFC_CFG_OFF)
8025 			cq->poll_mode = LPFC_QUEUE_WORK;
8026 		else
8027 			cq->poll_mode = LPFC_IRQ_POLL;
8028 	}
8029 
8030 	if (!phba->nvmet_support)
8031 		schedule_delayed_work(&phba->idle_stat_delay_work,
8032 				      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
8033 }
8034 
8035 static void lpfc_sli4_dip(struct lpfc_hba *phba)
8036 {
8037 	uint32_t if_type;
8038 
8039 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
8040 	if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
8041 	    if_type == LPFC_SLI_INTF_IF_TYPE_6) {
8042 		struct lpfc_register reg_data;
8043 
8044 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
8045 			       &reg_data.word0))
8046 			return;
8047 
8048 		if (bf_get(lpfc_sliport_status_dip, &reg_data))
8049 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8050 					"2904 Firmware Dump Image Present"
8051 					" on Adapter");
8052 	}
8053 }
8054 
8055 /**
8056  * lpfc_rx_monitor_create_ring - Initialize ring buffer for rx_monitor
8057  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8058  * @entries: Number of rx_info_entry objects to allocate in ring
8059  *
8060  * Return:
8061  * 0 - Success
8062  * ENOMEM - Failure to kmalloc
8063  **/
8064 int lpfc_rx_monitor_create_ring(struct lpfc_rx_info_monitor *rx_monitor,
8065 				u32 entries)
8066 {
8067 	rx_monitor->ring = kmalloc_array(entries, sizeof(struct rx_info_entry),
8068 					 GFP_KERNEL);
8069 	if (!rx_monitor->ring)
8070 		return -ENOMEM;
8071 
8072 	rx_monitor->head_idx = 0;
8073 	rx_monitor->tail_idx = 0;
8074 	spin_lock_init(&rx_monitor->lock);
8075 	rx_monitor->entries = entries;
8076 
8077 	return 0;
8078 }
8079 
8080 /**
8081  * lpfc_rx_monitor_destroy_ring - Free ring buffer for rx_monitor
8082  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8083  **/
8084 void lpfc_rx_monitor_destroy_ring(struct lpfc_rx_info_monitor *rx_monitor)
8085 {
8086 	spin_lock(&rx_monitor->lock);
8087 	kfree(rx_monitor->ring);
8088 	rx_monitor->ring = NULL;
8089 	rx_monitor->entries = 0;
8090 	rx_monitor->head_idx = 0;
8091 	rx_monitor->tail_idx = 0;
8092 	spin_unlock(&rx_monitor->lock);
8093 }
8094 
8095 /**
8096  * lpfc_rx_monitor_record - Insert an entry into rx_monitor's ring
8097  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8098  * @entry: Pointer to rx_info_entry
8099  *
8100  * Used to insert an rx_info_entry into rx_monitor's ring.  Note that this is a
8101  * deep copy of rx_info_entry not a shallow copy of the rx_info_entry ptr.
8102  *
8103  * This is called from lpfc_cmf_timer, which is in timer/softirq context.
8104  *
8105  * In cases of old data overflow, we do a best effort of FIFO order.
8106  **/
8107 void lpfc_rx_monitor_record(struct lpfc_rx_info_monitor *rx_monitor,
8108 			    struct rx_info_entry *entry)
8109 {
8110 	struct rx_info_entry *ring = rx_monitor->ring;
8111 	u32 *head_idx = &rx_monitor->head_idx;
8112 	u32 *tail_idx = &rx_monitor->tail_idx;
8113 	spinlock_t *ring_lock = &rx_monitor->lock;
8114 	u32 ring_size = rx_monitor->entries;
8115 
8116 	spin_lock(ring_lock);
8117 	memcpy(&ring[*tail_idx], entry, sizeof(*entry));
8118 	*tail_idx = (*tail_idx + 1) % ring_size;
8119 
8120 	/* Best effort of FIFO saved data */
8121 	if (*tail_idx == *head_idx)
8122 		*head_idx = (*head_idx + 1) % ring_size;
8123 
8124 	spin_unlock(ring_lock);
8125 }
8126 
8127 /**
8128  * lpfc_rx_monitor_report - Read out rx_monitor's ring
8129  * @phba: Pointer to lpfc_hba object
8130  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8131  * @buf: Pointer to char buffer that will contain rx monitor info data
8132  * @buf_len: Length buf including null char
8133  * @max_read_entries: Maximum number of entries to read out of ring
8134  *
8135  * Used to dump/read what's in rx_monitor's ring buffer.
8136  *
8137  * If buf is NULL || buf_len == 0, then it is implied that we want to log the
8138  * information to kmsg instead of filling out buf.
8139  *
8140  * Return:
8141  * Number of entries read out of the ring
8142  **/
8143 u32 lpfc_rx_monitor_report(struct lpfc_hba *phba,
8144 			   struct lpfc_rx_info_monitor *rx_monitor, char *buf,
8145 			   u32 buf_len, u32 max_read_entries)
8146 {
8147 	struct rx_info_entry *ring = rx_monitor->ring;
8148 	struct rx_info_entry *entry;
8149 	u32 *head_idx = &rx_monitor->head_idx;
8150 	u32 *tail_idx = &rx_monitor->tail_idx;
8151 	spinlock_t *ring_lock = &rx_monitor->lock;
8152 	u32 ring_size = rx_monitor->entries;
8153 	u32 cnt = 0;
8154 	char tmp[DBG_LOG_STR_SZ] = {0};
8155 	bool log_to_kmsg = (!buf || !buf_len) ? true : false;
8156 
8157 	if (!log_to_kmsg) {
8158 		/* clear the buffer to be sure */
8159 		memset(buf, 0, buf_len);
8160 
8161 		scnprintf(buf, buf_len, "\t%-16s%-16s%-16s%-16s%-8s%-8s%-8s"
8162 					"%-8s%-8s%-8s%-16s\n",
8163 					"MaxBPI", "Tot_Data_CMF",
8164 					"Tot_Data_Cmd", "Tot_Data_Cmpl",
8165 					"Lat(us)", "Avg_IO", "Max_IO", "Bsy",
8166 					"IO_cnt", "Info", "BWutil(ms)");
8167 	}
8168 
8169 	/* Needs to be _irq because record is called from timer interrupt
8170 	 * context
8171 	 */
8172 	spin_lock_irq(ring_lock);
8173 	while (*head_idx != *tail_idx) {
8174 		entry = &ring[*head_idx];
8175 
8176 		/* Read out this entry's data. */
8177 		if (!log_to_kmsg) {
8178 			/* If !log_to_kmsg, then store to buf. */
8179 			scnprintf(tmp, sizeof(tmp),
8180 				  "%03d:\t%-16llu%-16llu%-16llu%-16llu%-8llu"
8181 				  "%-8llu%-8llu%-8u%-8u%-8u%u(%u)\n",
8182 				  *head_idx, entry->max_bytes_per_interval,
8183 				  entry->cmf_bytes, entry->total_bytes,
8184 				  entry->rcv_bytes, entry->avg_io_latency,
8185 				  entry->avg_io_size, entry->max_read_cnt,
8186 				  entry->cmf_busy, entry->io_cnt,
8187 				  entry->cmf_info, entry->timer_utilization,
8188 				  entry->timer_interval);
8189 
8190 			/* Check for buffer overflow */
8191 			if ((strlen(buf) + strlen(tmp)) >= buf_len)
8192 				break;
8193 
8194 			/* Append entry's data to buffer */
8195 			strlcat(buf, tmp, buf_len);
8196 		} else {
8197 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
8198 					"4410 %02u: MBPI %llu Xmit %llu "
8199 					"Cmpl %llu Lat %llu ASz %llu Info %02u "
8200 					"BWUtil %u Int %u slot %u\n",
8201 					cnt, entry->max_bytes_per_interval,
8202 					entry->total_bytes, entry->rcv_bytes,
8203 					entry->avg_io_latency,
8204 					entry->avg_io_size, entry->cmf_info,
8205 					entry->timer_utilization,
8206 					entry->timer_interval, *head_idx);
8207 		}
8208 
8209 		*head_idx = (*head_idx + 1) % ring_size;
8210 
8211 		/* Don't feed more than max_read_entries */
8212 		cnt++;
8213 		if (cnt >= max_read_entries)
8214 			break;
8215 	}
8216 	spin_unlock_irq(ring_lock);
8217 
8218 	return cnt;
8219 }
8220 
8221 /**
8222  * lpfc_cmf_setup - Initialize idle_stat tracking
8223  * @phba: Pointer to HBA context object.
8224  *
8225  * This is called from HBA setup during driver load or when the HBA
8226  * comes online. this does all the initialization to support CMF and MI.
8227  **/
8228 static int
8229 lpfc_cmf_setup(struct lpfc_hba *phba)
8230 {
8231 	LPFC_MBOXQ_t *mboxq;
8232 	struct lpfc_dmabuf *mp;
8233 	struct lpfc_pc_sli4_params *sli4_params;
8234 	int rc, cmf, mi_ver;
8235 
8236 	rc = lpfc_sli4_refresh_params(phba);
8237 	if (unlikely(rc))
8238 		return rc;
8239 
8240 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8241 	if (!mboxq)
8242 		return -ENOMEM;
8243 
8244 	sli4_params = &phba->sli4_hba.pc_sli4_params;
8245 
8246 	/* Always try to enable MI feature if we can */
8247 	if (sli4_params->mi_ver) {
8248 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_MI);
8249 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8250 		mi_ver = bf_get(lpfc_mbx_set_feature_mi,
8251 				 &mboxq->u.mqe.un.set_feature);
8252 
8253 		if (rc == MBX_SUCCESS) {
8254 			if (mi_ver) {
8255 				lpfc_printf_log(phba,
8256 						KERN_WARNING, LOG_CGN_MGMT,
8257 						"6215 MI is enabled\n");
8258 				sli4_params->mi_ver = mi_ver;
8259 			} else {
8260 				lpfc_printf_log(phba,
8261 						KERN_WARNING, LOG_CGN_MGMT,
8262 						"6338 MI is disabled\n");
8263 				sli4_params->mi_ver = 0;
8264 			}
8265 		} else {
8266 			/* mi_ver is already set from GET_SLI4_PARAMETERS */
8267 			lpfc_printf_log(phba, KERN_INFO,
8268 					LOG_CGN_MGMT | LOG_INIT,
8269 					"6245 Enable MI Mailbox x%x (x%x/x%x) "
8270 					"failed, rc:x%x mi:x%x\n",
8271 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8272 					lpfc_sli_config_mbox_subsys_get
8273 						(phba, mboxq),
8274 					lpfc_sli_config_mbox_opcode_get
8275 						(phba, mboxq),
8276 					rc, sli4_params->mi_ver);
8277 		}
8278 	} else {
8279 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8280 				"6217 MI is disabled\n");
8281 	}
8282 
8283 	/* Ensure FDMI is enabled for MI if enable_mi is set */
8284 	if (sli4_params->mi_ver)
8285 		phba->cfg_fdmi_on = LPFC_FDMI_SUPPORT;
8286 
8287 	/* Always try to enable CMF feature if we can */
8288 	if (sli4_params->cmf) {
8289 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_CMF);
8290 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8291 		cmf = bf_get(lpfc_mbx_set_feature_cmf,
8292 			     &mboxq->u.mqe.un.set_feature);
8293 		if (rc == MBX_SUCCESS && cmf) {
8294 			lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8295 					"6218 CMF is enabled: mode %d\n",
8296 					phba->cmf_active_mode);
8297 		} else {
8298 			lpfc_printf_log(phba, KERN_WARNING,
8299 					LOG_CGN_MGMT | LOG_INIT,
8300 					"6219 Enable CMF Mailbox x%x (x%x/x%x) "
8301 					"failed, rc:x%x dd:x%x\n",
8302 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8303 					lpfc_sli_config_mbox_subsys_get
8304 						(phba, mboxq),
8305 					lpfc_sli_config_mbox_opcode_get
8306 						(phba, mboxq),
8307 					rc, cmf);
8308 			sli4_params->cmf = 0;
8309 			phba->cmf_active_mode = LPFC_CFG_OFF;
8310 			goto no_cmf;
8311 		}
8312 
8313 		/* Allocate Congestion Information Buffer */
8314 		if (!phba->cgn_i) {
8315 			mp = kmalloc(sizeof(*mp), GFP_KERNEL);
8316 			if (mp)
8317 				mp->virt = dma_alloc_coherent
8318 						(&phba->pcidev->dev,
8319 						sizeof(struct lpfc_cgn_info),
8320 						&mp->phys, GFP_KERNEL);
8321 			if (!mp || !mp->virt) {
8322 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8323 						"2640 Failed to alloc memory "
8324 						"for Congestion Info\n");
8325 				kfree(mp);
8326 				sli4_params->cmf = 0;
8327 				phba->cmf_active_mode = LPFC_CFG_OFF;
8328 				goto no_cmf;
8329 			}
8330 			phba->cgn_i = mp;
8331 
8332 			/* initialize congestion buffer info */
8333 			lpfc_init_congestion_buf(phba);
8334 			lpfc_init_congestion_stat(phba);
8335 
8336 			/* Zero out Congestion Signal counters */
8337 			atomic64_set(&phba->cgn_acqe_stat.alarm, 0);
8338 			atomic64_set(&phba->cgn_acqe_stat.warn, 0);
8339 		}
8340 
8341 		rc = lpfc_sli4_cgn_params_read(phba);
8342 		if (rc < 0) {
8343 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8344 					"6242 Error reading Cgn Params (%d)\n",
8345 					rc);
8346 			/* Ensure CGN Mode is off */
8347 			sli4_params->cmf = 0;
8348 		} else if (!rc) {
8349 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8350 					"6243 CGN Event empty object.\n");
8351 			/* Ensure CGN Mode is off */
8352 			sli4_params->cmf = 0;
8353 		}
8354 	} else {
8355 no_cmf:
8356 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8357 				"6220 CMF is disabled\n");
8358 	}
8359 
8360 	/* Only register congestion buffer with firmware if BOTH
8361 	 * CMF and E2E are enabled.
8362 	 */
8363 	if (sli4_params->cmf && sli4_params->mi_ver) {
8364 		rc = lpfc_reg_congestion_buf(phba);
8365 		if (rc) {
8366 			dma_free_coherent(&phba->pcidev->dev,
8367 					  sizeof(struct lpfc_cgn_info),
8368 					  phba->cgn_i->virt, phba->cgn_i->phys);
8369 			kfree(phba->cgn_i);
8370 			phba->cgn_i = NULL;
8371 			/* Ensure CGN Mode is off */
8372 			phba->cmf_active_mode = LPFC_CFG_OFF;
8373 			sli4_params->cmf = 0;
8374 			return 0;
8375 		}
8376 	}
8377 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8378 			"6470 Setup MI version %d CMF %d mode %d\n",
8379 			sli4_params->mi_ver, sli4_params->cmf,
8380 			phba->cmf_active_mode);
8381 
8382 	mempool_free(mboxq, phba->mbox_mem_pool);
8383 
8384 	/* Initialize atomic counters */
8385 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
8386 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
8387 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
8388 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
8389 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
8390 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
8391 	atomic64_set(&phba->cgn_latency_evt, 0);
8392 
8393 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
8394 
8395 	/* Allocate RX Monitor Buffer */
8396 	if (!phba->rx_monitor) {
8397 		phba->rx_monitor = kzalloc(sizeof(*phba->rx_monitor),
8398 					   GFP_KERNEL);
8399 
8400 		if (!phba->rx_monitor) {
8401 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8402 					"2644 Failed to alloc memory "
8403 					"for RX Monitor Buffer\n");
8404 			return -ENOMEM;
8405 		}
8406 
8407 		/* Instruct the rx_monitor object to instantiate its ring */
8408 		if (lpfc_rx_monitor_create_ring(phba->rx_monitor,
8409 						LPFC_MAX_RXMONITOR_ENTRY)) {
8410 			kfree(phba->rx_monitor);
8411 			phba->rx_monitor = NULL;
8412 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8413 					"2645 Failed to alloc memory "
8414 					"for RX Monitor's Ring\n");
8415 			return -ENOMEM;
8416 		}
8417 	}
8418 
8419 	return 0;
8420 }
8421 
8422 static int
8423 lpfc_set_host_tm(struct lpfc_hba *phba)
8424 {
8425 	LPFC_MBOXQ_t *mboxq;
8426 	uint32_t len, rc;
8427 	struct timespec64 cur_time;
8428 	struct tm broken;
8429 	uint32_t month, day, year;
8430 	uint32_t hour, minute, second;
8431 	struct lpfc_mbx_set_host_date_time *tm;
8432 
8433 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8434 	if (!mboxq)
8435 		return -ENOMEM;
8436 
8437 	len = sizeof(struct lpfc_mbx_set_host_data) -
8438 		sizeof(struct lpfc_sli4_cfg_mhdr);
8439 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
8440 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
8441 			 LPFC_SLI4_MBX_EMBED);
8442 
8443 	mboxq->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_DATE_TIME;
8444 	mboxq->u.mqe.un.set_host_data.param_len =
8445 			sizeof(struct lpfc_mbx_set_host_date_time);
8446 	tm = &mboxq->u.mqe.un.set_host_data.un.tm;
8447 	ktime_get_real_ts64(&cur_time);
8448 	time64_to_tm(cur_time.tv_sec, 0, &broken);
8449 	month = broken.tm_mon + 1;
8450 	day = broken.tm_mday;
8451 	year = broken.tm_year - 100;
8452 	hour = broken.tm_hour;
8453 	minute = broken.tm_min;
8454 	second = broken.tm_sec;
8455 	bf_set(lpfc_mbx_set_host_month, tm, month);
8456 	bf_set(lpfc_mbx_set_host_day, tm, day);
8457 	bf_set(lpfc_mbx_set_host_year, tm, year);
8458 	bf_set(lpfc_mbx_set_host_hour, tm, hour);
8459 	bf_set(lpfc_mbx_set_host_min, tm, minute);
8460 	bf_set(lpfc_mbx_set_host_sec, tm, second);
8461 
8462 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8463 	mempool_free(mboxq, phba->mbox_mem_pool);
8464 	return rc;
8465 }
8466 
8467 /**
8468  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
8469  * @phba: Pointer to HBA context object.
8470  *
8471  * This function is the main SLI4 device initialization PCI function. This
8472  * function is called by the HBA initialization code, HBA reset code and
8473  * HBA error attention handler code. Caller is not required to hold any
8474  * locks.
8475  **/
8476 int
8477 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
8478 {
8479 	int rc, i, cnt, len, dd;
8480 	LPFC_MBOXQ_t *mboxq;
8481 	struct lpfc_mqe *mqe;
8482 	uint8_t *vpd;
8483 	uint32_t vpd_size;
8484 	uint32_t ftr_rsp = 0;
8485 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
8486 	struct lpfc_vport *vport = phba->pport;
8487 	struct lpfc_dmabuf *mp;
8488 	struct lpfc_rqb *rqbp;
8489 	u32 flg;
8490 
8491 	/* Perform a PCI function reset to start from clean */
8492 	rc = lpfc_pci_function_reset(phba);
8493 	if (unlikely(rc))
8494 		return -ENODEV;
8495 
8496 	/* Check the HBA Host Status Register for readyness */
8497 	rc = lpfc_sli4_post_status_check(phba);
8498 	if (unlikely(rc))
8499 		return -ENODEV;
8500 	else {
8501 		spin_lock_irq(&phba->hbalock);
8502 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
8503 		flg = phba->sli.sli_flag;
8504 		spin_unlock_irq(&phba->hbalock);
8505 		/* Allow a little time after setting SLI_ACTIVE for any polled
8506 		 * MBX commands to complete via BSG.
8507 		 */
8508 		for (i = 0; i < 50 && (flg & LPFC_SLI_MBOX_ACTIVE); i++) {
8509 			msleep(20);
8510 			spin_lock_irq(&phba->hbalock);
8511 			flg = phba->sli.sli_flag;
8512 			spin_unlock_irq(&phba->hbalock);
8513 		}
8514 	}
8515 
8516 	lpfc_sli4_dip(phba);
8517 
8518 	/*
8519 	 * Allocate a single mailbox container for initializing the
8520 	 * port.
8521 	 */
8522 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8523 	if (!mboxq)
8524 		return -ENOMEM;
8525 
8526 	/* Issue READ_REV to collect vpd and FW information. */
8527 	vpd_size = SLI4_PAGE_SIZE;
8528 	vpd = kzalloc(vpd_size, GFP_KERNEL);
8529 	if (!vpd) {
8530 		rc = -ENOMEM;
8531 		goto out_free_mbox;
8532 	}
8533 
8534 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
8535 	if (unlikely(rc)) {
8536 		kfree(vpd);
8537 		goto out_free_mbox;
8538 	}
8539 
8540 	mqe = &mboxq->u.mqe;
8541 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
8542 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
8543 		phba->hba_flag |= HBA_FCOE_MODE;
8544 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
8545 	} else {
8546 		phba->hba_flag &= ~HBA_FCOE_MODE;
8547 	}
8548 
8549 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
8550 		LPFC_DCBX_CEE_MODE)
8551 		phba->hba_flag |= HBA_FIP_SUPPORT;
8552 	else
8553 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
8554 
8555 	phba->hba_flag &= ~HBA_IOQ_FLUSH;
8556 
8557 	if (phba->sli_rev != LPFC_SLI_REV4) {
8558 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8559 			"0376 READ_REV Error. SLI Level %d "
8560 			"FCoE enabled %d\n",
8561 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
8562 		rc = -EIO;
8563 		kfree(vpd);
8564 		goto out_free_mbox;
8565 	}
8566 
8567 	rc = lpfc_set_host_tm(phba);
8568 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
8569 			"6468 Set host date / time: Status x%x:\n", rc);
8570 
8571 	/*
8572 	 * Continue initialization with default values even if driver failed
8573 	 * to read FCoE param config regions, only read parameters if the
8574 	 * board is FCoE
8575 	 */
8576 	if (phba->hba_flag & HBA_FCOE_MODE &&
8577 	    lpfc_sli4_read_fcoe_params(phba))
8578 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
8579 			"2570 Failed to read FCoE parameters\n");
8580 
8581 	/*
8582 	 * Retrieve sli4 device physical port name, failure of doing it
8583 	 * is considered as non-fatal.
8584 	 */
8585 	rc = lpfc_sli4_retrieve_pport_name(phba);
8586 	if (!rc)
8587 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8588 				"3080 Successful retrieving SLI4 device "
8589 				"physical port name: %s.\n", phba->Port);
8590 
8591 	rc = lpfc_sli4_get_ctl_attr(phba);
8592 	if (!rc)
8593 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8594 				"8351 Successful retrieving SLI4 device "
8595 				"CTL ATTR\n");
8596 
8597 	/*
8598 	 * Evaluate the read rev and vpd data. Populate the driver
8599 	 * state with the results. If this routine fails, the failure
8600 	 * is not fatal as the driver will use generic values.
8601 	 */
8602 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
8603 	if (unlikely(!rc)) {
8604 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8605 				"0377 Error %d parsing vpd. "
8606 				"Using defaults.\n", rc);
8607 		rc = 0;
8608 	}
8609 	kfree(vpd);
8610 
8611 	/* Save information as VPD data */
8612 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
8613 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
8614 
8615 	/*
8616 	 * This is because first G7 ASIC doesn't support the standard
8617 	 * 0x5a NVME cmd descriptor type/subtype
8618 	 */
8619 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8620 			LPFC_SLI_INTF_IF_TYPE_6) &&
8621 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
8622 	    (phba->vpd.rev.smRev == 0) &&
8623 	    (phba->cfg_nvme_embed_cmd == 1))
8624 		phba->cfg_nvme_embed_cmd = 0;
8625 
8626 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
8627 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
8628 					 &mqe->un.read_rev);
8629 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
8630 				       &mqe->un.read_rev);
8631 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
8632 					    &mqe->un.read_rev);
8633 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
8634 					   &mqe->un.read_rev);
8635 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
8636 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
8637 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
8638 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
8639 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
8640 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
8641 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8642 			"(%d):0380 READ_REV Status x%x "
8643 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
8644 			mboxq->vport ? mboxq->vport->vpi : 0,
8645 			bf_get(lpfc_mqe_status, mqe),
8646 			phba->vpd.rev.opFwName,
8647 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
8648 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
8649 
8650 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8651 	    LPFC_SLI_INTF_IF_TYPE_0) {
8652 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
8653 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8654 		if (rc == MBX_SUCCESS) {
8655 			phba->hba_flag |= HBA_RECOVERABLE_UE;
8656 			/* Set 1Sec interval to detect UE */
8657 			phba->eratt_poll_interval = 1;
8658 			phba->sli4_hba.ue_to_sr = bf_get(
8659 					lpfc_mbx_set_feature_UESR,
8660 					&mboxq->u.mqe.un.set_feature);
8661 			phba->sli4_hba.ue_to_rp = bf_get(
8662 					lpfc_mbx_set_feature_UERP,
8663 					&mboxq->u.mqe.un.set_feature);
8664 		}
8665 	}
8666 
8667 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
8668 		/* Enable MDS Diagnostics only if the SLI Port supports it */
8669 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
8670 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8671 		if (rc != MBX_SUCCESS)
8672 			phba->mds_diags_support = 0;
8673 	}
8674 
8675 	/*
8676 	 * Discover the port's supported feature set and match it against the
8677 	 * hosts requests.
8678 	 */
8679 	lpfc_request_features(phba, mboxq);
8680 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8681 	if (unlikely(rc)) {
8682 		rc = -EIO;
8683 		goto out_free_mbox;
8684 	}
8685 
8686 	/* Disable VMID if app header is not supported */
8687 	if (phba->cfg_vmid_app_header && !(bf_get(lpfc_mbx_rq_ftr_rsp_ashdr,
8688 						  &mqe->un.req_ftrs))) {
8689 		bf_set(lpfc_ftr_ashdr, &phba->sli4_hba.sli4_flags, 0);
8690 		phba->cfg_vmid_app_header = 0;
8691 		lpfc_printf_log(phba, KERN_DEBUG, LOG_SLI,
8692 				"1242 vmid feature not supported\n");
8693 	}
8694 
8695 	/*
8696 	 * The port must support FCP initiator mode as this is the
8697 	 * only mode running in the host.
8698 	 */
8699 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
8700 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8701 				"0378 No support for fcpi mode.\n");
8702 		ftr_rsp++;
8703 	}
8704 
8705 	/* Performance Hints are ONLY for FCoE */
8706 	if (phba->hba_flag & HBA_FCOE_MODE) {
8707 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
8708 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
8709 		else
8710 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
8711 	}
8712 
8713 	/*
8714 	 * If the port cannot support the host's requested features
8715 	 * then turn off the global config parameters to disable the
8716 	 * feature in the driver.  This is not a fatal error.
8717 	 */
8718 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8719 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
8720 			phba->cfg_enable_bg = 0;
8721 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
8722 			ftr_rsp++;
8723 		}
8724 	}
8725 
8726 	if (phba->max_vpi && phba->cfg_enable_npiv &&
8727 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8728 		ftr_rsp++;
8729 
8730 	if (ftr_rsp) {
8731 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8732 				"0379 Feature Mismatch Data: x%08x %08x "
8733 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
8734 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
8735 				phba->cfg_enable_npiv, phba->max_vpi);
8736 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
8737 			phba->cfg_enable_bg = 0;
8738 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8739 			phba->cfg_enable_npiv = 0;
8740 	}
8741 
8742 	/* These SLI3 features are assumed in SLI4 */
8743 	spin_lock_irq(&phba->hbalock);
8744 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
8745 	spin_unlock_irq(&phba->hbalock);
8746 
8747 	/* Always try to enable dual dump feature if we can */
8748 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
8749 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8750 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
8751 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
8752 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8753 				"6448 Dual Dump is enabled\n");
8754 	else
8755 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
8756 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
8757 				"rc:x%x dd:x%x\n",
8758 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8759 				lpfc_sli_config_mbox_subsys_get(
8760 					phba, mboxq),
8761 				lpfc_sli_config_mbox_opcode_get(
8762 					phba, mboxq),
8763 				rc, dd);
8764 	/*
8765 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
8766 	 * calls depends on these resources to complete port setup.
8767 	 */
8768 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
8769 	if (rc) {
8770 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8771 				"2920 Failed to alloc Resource IDs "
8772 				"rc = x%x\n", rc);
8773 		goto out_free_mbox;
8774 	}
8775 
8776 	lpfc_set_host_data(phba, mboxq);
8777 
8778 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8779 	if (rc) {
8780 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8781 				"2134 Failed to set host os driver version %x",
8782 				rc);
8783 	}
8784 
8785 	/* Read the port's service parameters. */
8786 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
8787 	if (rc) {
8788 		phba->link_state = LPFC_HBA_ERROR;
8789 		rc = -ENOMEM;
8790 		goto out_free_mbox;
8791 	}
8792 
8793 	mboxq->vport = vport;
8794 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8795 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
8796 	if (rc == MBX_SUCCESS) {
8797 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
8798 		rc = 0;
8799 	}
8800 
8801 	/*
8802 	 * This memory was allocated by the lpfc_read_sparam routine but is
8803 	 * no longer needed.  It is released and ctx_buf NULLed to prevent
8804 	 * unintended pointer access as the mbox is reused.
8805 	 */
8806 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
8807 	kfree(mp);
8808 	mboxq->ctx_buf = NULL;
8809 	if (unlikely(rc)) {
8810 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8811 				"0382 READ_SPARAM command failed "
8812 				"status %d, mbxStatus x%x\n",
8813 				rc, bf_get(lpfc_mqe_status, mqe));
8814 		phba->link_state = LPFC_HBA_ERROR;
8815 		rc = -EIO;
8816 		goto out_free_mbox;
8817 	}
8818 
8819 	lpfc_update_vport_wwn(vport);
8820 
8821 	/* Update the fc_host data structures with new wwn. */
8822 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
8823 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
8824 
8825 	/* Create all the SLI4 queues */
8826 	rc = lpfc_sli4_queue_create(phba);
8827 	if (rc) {
8828 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8829 				"3089 Failed to allocate queues\n");
8830 		rc = -ENODEV;
8831 		goto out_free_mbox;
8832 	}
8833 	/* Set up all the queues to the device */
8834 	rc = lpfc_sli4_queue_setup(phba);
8835 	if (unlikely(rc)) {
8836 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8837 				"0381 Error %d during queue setup.\n ", rc);
8838 		goto out_stop_timers;
8839 	}
8840 	/* Initialize the driver internal SLI layer lists. */
8841 	lpfc_sli4_setup(phba);
8842 	lpfc_sli4_queue_init(phba);
8843 
8844 	/* update host els xri-sgl sizes and mappings */
8845 	rc = lpfc_sli4_els_sgl_update(phba);
8846 	if (unlikely(rc)) {
8847 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8848 				"1400 Failed to update xri-sgl size and "
8849 				"mapping: %d\n", rc);
8850 		goto out_destroy_queue;
8851 	}
8852 
8853 	/* register the els sgl pool to the port */
8854 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
8855 				       phba->sli4_hba.els_xri_cnt);
8856 	if (unlikely(rc < 0)) {
8857 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8858 				"0582 Error %d during els sgl post "
8859 				"operation\n", rc);
8860 		rc = -ENODEV;
8861 		goto out_destroy_queue;
8862 	}
8863 	phba->sli4_hba.els_xri_cnt = rc;
8864 
8865 	if (phba->nvmet_support) {
8866 		/* update host nvmet xri-sgl sizes and mappings */
8867 		rc = lpfc_sli4_nvmet_sgl_update(phba);
8868 		if (unlikely(rc)) {
8869 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8870 					"6308 Failed to update nvmet-sgl size "
8871 					"and mapping: %d\n", rc);
8872 			goto out_destroy_queue;
8873 		}
8874 
8875 		/* register the nvmet sgl pool to the port */
8876 		rc = lpfc_sli4_repost_sgl_list(
8877 			phba,
8878 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
8879 			phba->sli4_hba.nvmet_xri_cnt);
8880 		if (unlikely(rc < 0)) {
8881 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8882 					"3117 Error %d during nvmet "
8883 					"sgl post\n", rc);
8884 			rc = -ENODEV;
8885 			goto out_destroy_queue;
8886 		}
8887 		phba->sli4_hba.nvmet_xri_cnt = rc;
8888 
8889 		/* We allocate an iocbq for every receive context SGL.
8890 		 * The additional allocation is for abort and ls handling.
8891 		 */
8892 		cnt = phba->sli4_hba.nvmet_xri_cnt +
8893 			phba->sli4_hba.max_cfg_param.max_xri;
8894 	} else {
8895 		/* update host common xri-sgl sizes and mappings */
8896 		rc = lpfc_sli4_io_sgl_update(phba);
8897 		if (unlikely(rc)) {
8898 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8899 					"6082 Failed to update nvme-sgl size "
8900 					"and mapping: %d\n", rc);
8901 			goto out_destroy_queue;
8902 		}
8903 
8904 		/* register the allocated common sgl pool to the port */
8905 		rc = lpfc_sli4_repost_io_sgl_list(phba);
8906 		if (unlikely(rc)) {
8907 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8908 					"6116 Error %d during nvme sgl post "
8909 					"operation\n", rc);
8910 			/* Some NVME buffers were moved to abort nvme list */
8911 			/* A pci function reset will repost them */
8912 			rc = -ENODEV;
8913 			goto out_destroy_queue;
8914 		}
8915 		/* Each lpfc_io_buf job structure has an iocbq element.
8916 		 * This cnt provides for abort, els, ct and ls requests.
8917 		 */
8918 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
8919 	}
8920 
8921 	if (!phba->sli.iocbq_lookup) {
8922 		/* Initialize and populate the iocb list per host */
8923 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8924 				"2821 initialize iocb list with %d entries\n",
8925 				cnt);
8926 		rc = lpfc_init_iocb_list(phba, cnt);
8927 		if (rc) {
8928 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8929 					"1413 Failed to init iocb list.\n");
8930 			goto out_destroy_queue;
8931 		}
8932 	}
8933 
8934 	if (phba->nvmet_support)
8935 		lpfc_nvmet_create_targetport(phba);
8936 
8937 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
8938 		/* Post initial buffers to all RQs created */
8939 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
8940 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
8941 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
8942 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
8943 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
8944 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
8945 			rqbp->buffer_count = 0;
8946 
8947 			lpfc_post_rq_buffer(
8948 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
8949 				phba->sli4_hba.nvmet_mrq_data[i],
8950 				phba->cfg_nvmet_mrq_post, i);
8951 		}
8952 	}
8953 
8954 	/* Post the rpi header region to the device. */
8955 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
8956 	if (unlikely(rc)) {
8957 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8958 				"0393 Error %d during rpi post operation\n",
8959 				rc);
8960 		rc = -ENODEV;
8961 		goto out_free_iocblist;
8962 	}
8963 	lpfc_sli4_node_prep(phba);
8964 
8965 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
8966 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
8967 			/*
8968 			 * The FC Port needs to register FCFI (index 0)
8969 			 */
8970 			lpfc_reg_fcfi(phba, mboxq);
8971 			mboxq->vport = phba->pport;
8972 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8973 			if (rc != MBX_SUCCESS)
8974 				goto out_unset_queue;
8975 			rc = 0;
8976 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
8977 						&mboxq->u.mqe.un.reg_fcfi);
8978 		} else {
8979 			/* We are a NVME Target mode with MRQ > 1 */
8980 
8981 			/* First register the FCFI */
8982 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
8983 			mboxq->vport = phba->pport;
8984 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8985 			if (rc != MBX_SUCCESS)
8986 				goto out_unset_queue;
8987 			rc = 0;
8988 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
8989 						&mboxq->u.mqe.un.reg_fcfi_mrq);
8990 
8991 			/* Next register the MRQs */
8992 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
8993 			mboxq->vport = phba->pport;
8994 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8995 			if (rc != MBX_SUCCESS)
8996 				goto out_unset_queue;
8997 			rc = 0;
8998 		}
8999 		/* Check if the port is configured to be disabled */
9000 		lpfc_sli_read_link_ste(phba);
9001 	}
9002 
9003 	/* Don't post more new bufs if repost already recovered
9004 	 * the nvme sgls.
9005 	 */
9006 	if (phba->nvmet_support == 0) {
9007 		if (phba->sli4_hba.io_xri_cnt == 0) {
9008 			len = lpfc_new_io_buf(
9009 					      phba, phba->sli4_hba.io_xri_max);
9010 			if (len == 0) {
9011 				rc = -ENOMEM;
9012 				goto out_unset_queue;
9013 			}
9014 
9015 			if (phba->cfg_xri_rebalancing)
9016 				lpfc_create_multixri_pools(phba);
9017 		}
9018 	} else {
9019 		phba->cfg_xri_rebalancing = 0;
9020 	}
9021 
9022 	/* Allow asynchronous mailbox command to go through */
9023 	spin_lock_irq(&phba->hbalock);
9024 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9025 	spin_unlock_irq(&phba->hbalock);
9026 
9027 	/* Post receive buffers to the device */
9028 	lpfc_sli4_rb_setup(phba);
9029 
9030 	/* Reset HBA FCF states after HBA reset */
9031 	phba->fcf.fcf_flag = 0;
9032 	phba->fcf.current_rec.flag = 0;
9033 
9034 	/* Start the ELS watchdog timer */
9035 	mod_timer(&vport->els_tmofunc,
9036 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
9037 
9038 	/* Start heart beat timer */
9039 	mod_timer(&phba->hb_tmofunc,
9040 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
9041 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
9042 	phba->last_completion_time = jiffies;
9043 
9044 	/* start eq_delay heartbeat */
9045 	if (phba->cfg_auto_imax)
9046 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
9047 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
9048 
9049 	/* start per phba idle_stat_delay heartbeat */
9050 	lpfc_init_idle_stat_hb(phba);
9051 
9052 	/* Start error attention (ERATT) polling timer */
9053 	mod_timer(&phba->eratt_poll,
9054 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
9055 
9056 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
9057 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
9058 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
9059 		if (!rc) {
9060 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9061 					"2829 This device supports "
9062 					"Advanced Error Reporting (AER)\n");
9063 			spin_lock_irq(&phba->hbalock);
9064 			phba->hba_flag |= HBA_AER_ENABLED;
9065 			spin_unlock_irq(&phba->hbalock);
9066 		} else {
9067 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9068 					"2830 This device does not support "
9069 					"Advanced Error Reporting (AER)\n");
9070 			phba->cfg_aer_support = 0;
9071 		}
9072 		rc = 0;
9073 	}
9074 
9075 	/*
9076 	 * The port is ready, set the host's link state to LINK_DOWN
9077 	 * in preparation for link interrupts.
9078 	 */
9079 	spin_lock_irq(&phba->hbalock);
9080 	phba->link_state = LPFC_LINK_DOWN;
9081 
9082 	/* Check if physical ports are trunked */
9083 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
9084 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
9085 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
9086 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
9087 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
9088 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
9089 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
9090 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
9091 	spin_unlock_irq(&phba->hbalock);
9092 
9093 	/* Arm the CQs and then EQs on device */
9094 	lpfc_sli4_arm_cqeq_intr(phba);
9095 
9096 	/* Indicate device interrupt mode */
9097 	phba->sli4_hba.intr_enable = 1;
9098 
9099 	/* Setup CMF after HBA is initialized */
9100 	lpfc_cmf_setup(phba);
9101 
9102 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
9103 	    (phba->hba_flag & LINK_DISABLED)) {
9104 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9105 				"3103 Adapter Link is disabled.\n");
9106 		lpfc_down_link(phba, mboxq);
9107 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9108 		if (rc != MBX_SUCCESS) {
9109 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9110 					"3104 Adapter failed to issue "
9111 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
9112 			goto out_io_buff_free;
9113 		}
9114 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
9115 		/* don't perform init_link on SLI4 FC port loopback test */
9116 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
9117 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
9118 			if (rc)
9119 				goto out_io_buff_free;
9120 		}
9121 	}
9122 	mempool_free(mboxq, phba->mbox_mem_pool);
9123 
9124 	/* Enable RAS FW log support */
9125 	lpfc_sli4_ras_setup(phba);
9126 
9127 	phba->hba_flag |= HBA_SETUP;
9128 	return rc;
9129 
9130 out_io_buff_free:
9131 	/* Free allocated IO Buffers */
9132 	lpfc_io_free(phba);
9133 out_unset_queue:
9134 	/* Unset all the queues set up in this routine when error out */
9135 	lpfc_sli4_queue_unset(phba);
9136 out_free_iocblist:
9137 	lpfc_free_iocb_list(phba);
9138 out_destroy_queue:
9139 	lpfc_sli4_queue_destroy(phba);
9140 out_stop_timers:
9141 	lpfc_stop_hba_timers(phba);
9142 out_free_mbox:
9143 	mempool_free(mboxq, phba->mbox_mem_pool);
9144 	return rc;
9145 }
9146 
9147 /**
9148  * lpfc_mbox_timeout - Timeout call back function for mbox timer
9149  * @t: Context to fetch pointer to hba structure from.
9150  *
9151  * This is the callback function for mailbox timer. The mailbox
9152  * timer is armed when a new mailbox command is issued and the timer
9153  * is deleted when the mailbox complete. The function is called by
9154  * the kernel timer code when a mailbox does not complete within
9155  * expected time. This function wakes up the worker thread to
9156  * process the mailbox timeout and returns. All the processing is
9157  * done by the worker thread function lpfc_mbox_timeout_handler.
9158  **/
9159 void
9160 lpfc_mbox_timeout(struct timer_list *t)
9161 {
9162 	struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
9163 	unsigned long iflag;
9164 	uint32_t tmo_posted;
9165 
9166 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
9167 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
9168 	if (!tmo_posted)
9169 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
9170 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
9171 
9172 	if (!tmo_posted)
9173 		lpfc_worker_wake_up(phba);
9174 	return;
9175 }
9176 
9177 /**
9178  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
9179  *                                    are pending
9180  * @phba: Pointer to HBA context object.
9181  *
9182  * This function checks if any mailbox completions are present on the mailbox
9183  * completion queue.
9184  **/
9185 static bool
9186 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
9187 {
9188 
9189 	uint32_t idx;
9190 	struct lpfc_queue *mcq;
9191 	struct lpfc_mcqe *mcqe;
9192 	bool pending_completions = false;
9193 	uint8_t	qe_valid;
9194 
9195 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9196 		return false;
9197 
9198 	/* Check for completions on mailbox completion queue */
9199 
9200 	mcq = phba->sli4_hba.mbx_cq;
9201 	idx = mcq->hba_index;
9202 	qe_valid = mcq->qe_valid;
9203 	while (bf_get_le32(lpfc_cqe_valid,
9204 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
9205 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
9206 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
9207 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
9208 			pending_completions = true;
9209 			break;
9210 		}
9211 		idx = (idx + 1) % mcq->entry_count;
9212 		if (mcq->hba_index == idx)
9213 			break;
9214 
9215 		/* if the index wrapped around, toggle the valid bit */
9216 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
9217 			qe_valid = (qe_valid) ? 0 : 1;
9218 	}
9219 	return pending_completions;
9220 
9221 }
9222 
9223 /**
9224  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
9225  *					      that were missed.
9226  * @phba: Pointer to HBA context object.
9227  *
9228  * For sli4, it is possible to miss an interrupt. As such mbox completions
9229  * maybe missed causing erroneous mailbox timeouts to occur. This function
9230  * checks to see if mbox completions are on the mailbox completion queue
9231  * and will process all the completions associated with the eq for the
9232  * mailbox completion queue.
9233  **/
9234 static bool
9235 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
9236 {
9237 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
9238 	uint32_t eqidx;
9239 	struct lpfc_queue *fpeq = NULL;
9240 	struct lpfc_queue *eq;
9241 	bool mbox_pending;
9242 
9243 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9244 		return false;
9245 
9246 	/* Find the EQ associated with the mbox CQ */
9247 	if (sli4_hba->hdwq) {
9248 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
9249 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
9250 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
9251 				fpeq = eq;
9252 				break;
9253 			}
9254 		}
9255 	}
9256 	if (!fpeq)
9257 		return false;
9258 
9259 	/* Turn off interrupts from this EQ */
9260 
9261 	sli4_hba->sli4_eq_clr_intr(fpeq);
9262 
9263 	/* Check to see if a mbox completion is pending */
9264 
9265 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
9266 
9267 	/*
9268 	 * If a mbox completion is pending, process all the events on EQ
9269 	 * associated with the mbox completion queue (this could include
9270 	 * mailbox commands, async events, els commands, receive queue data
9271 	 * and fcp commands)
9272 	 */
9273 
9274 	if (mbox_pending)
9275 		/* process and rearm the EQ */
9276 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
9277 	else
9278 		/* Always clear and re-arm the EQ */
9279 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
9280 
9281 	return mbox_pending;
9282 
9283 }
9284 
9285 /**
9286  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
9287  * @phba: Pointer to HBA context object.
9288  *
9289  * This function is called from worker thread when a mailbox command times out.
9290  * The caller is not required to hold any locks. This function will reset the
9291  * HBA and recover all the pending commands.
9292  **/
9293 void
9294 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
9295 {
9296 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
9297 	MAILBOX_t *mb = NULL;
9298 
9299 	struct lpfc_sli *psli = &phba->sli;
9300 
9301 	/* If the mailbox completed, process the completion */
9302 	lpfc_sli4_process_missed_mbox_completions(phba);
9303 
9304 	if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
9305 		return;
9306 
9307 	if (pmbox != NULL)
9308 		mb = &pmbox->u.mb;
9309 	/* Check the pmbox pointer first.  There is a race condition
9310 	 * between the mbox timeout handler getting executed in the
9311 	 * worklist and the mailbox actually completing. When this
9312 	 * race condition occurs, the mbox_active will be NULL.
9313 	 */
9314 	spin_lock_irq(&phba->hbalock);
9315 	if (pmbox == NULL) {
9316 		lpfc_printf_log(phba, KERN_WARNING,
9317 				LOG_MBOX | LOG_SLI,
9318 				"0353 Active Mailbox cleared - mailbox timeout "
9319 				"exiting\n");
9320 		spin_unlock_irq(&phba->hbalock);
9321 		return;
9322 	}
9323 
9324 	/* Mbox cmd <mbxCommand> timeout */
9325 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9326 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
9327 			mb->mbxCommand,
9328 			phba->pport->port_state,
9329 			phba->sli.sli_flag,
9330 			phba->sli.mbox_active);
9331 	spin_unlock_irq(&phba->hbalock);
9332 
9333 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
9334 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
9335 	 * it to fail all outstanding SCSI IO.
9336 	 */
9337 	spin_lock_irq(&phba->pport->work_port_lock);
9338 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9339 	spin_unlock_irq(&phba->pport->work_port_lock);
9340 	spin_lock_irq(&phba->hbalock);
9341 	phba->link_state = LPFC_LINK_UNKNOWN;
9342 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
9343 	spin_unlock_irq(&phba->hbalock);
9344 
9345 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9346 			"0345 Resetting board due to mailbox timeout\n");
9347 
9348 	/* Reset the HBA device */
9349 	lpfc_reset_hba(phba);
9350 }
9351 
9352 /**
9353  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
9354  * @phba: Pointer to HBA context object.
9355  * @pmbox: Pointer to mailbox object.
9356  * @flag: Flag indicating how the mailbox need to be processed.
9357  *
9358  * This function is called by discovery code and HBA management code
9359  * to submit a mailbox command to firmware with SLI-3 interface spec. This
9360  * function gets the hbalock to protect the data structures.
9361  * The mailbox command can be submitted in polling mode, in which case
9362  * this function will wait in a polling loop for the completion of the
9363  * mailbox.
9364  * If the mailbox is submitted in no_wait mode (not polling) the
9365  * function will submit the command and returns immediately without waiting
9366  * for the mailbox completion. The no_wait is supported only when HBA
9367  * is in SLI2/SLI3 mode - interrupts are enabled.
9368  * The SLI interface allows only one mailbox pending at a time. If the
9369  * mailbox is issued in polling mode and there is already a mailbox
9370  * pending, then the function will return an error. If the mailbox is issued
9371  * in NO_WAIT mode and there is a mailbox pending already, the function
9372  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
9373  * The sli layer owns the mailbox object until the completion of mailbox
9374  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
9375  * return codes the caller owns the mailbox command after the return of
9376  * the function.
9377  **/
9378 static int
9379 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
9380 		       uint32_t flag)
9381 {
9382 	MAILBOX_t *mbx;
9383 	struct lpfc_sli *psli = &phba->sli;
9384 	uint32_t status, evtctr;
9385 	uint32_t ha_copy, hc_copy;
9386 	int i;
9387 	unsigned long timeout;
9388 	unsigned long drvr_flag = 0;
9389 	uint32_t word0, ldata;
9390 	void __iomem *to_slim;
9391 	int processing_queue = 0;
9392 
9393 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
9394 	if (!pmbox) {
9395 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9396 		/* processing mbox queue from intr_handler */
9397 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9398 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9399 			return MBX_SUCCESS;
9400 		}
9401 		processing_queue = 1;
9402 		pmbox = lpfc_mbox_get(phba);
9403 		if (!pmbox) {
9404 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9405 			return MBX_SUCCESS;
9406 		}
9407 	}
9408 
9409 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
9410 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
9411 		if(!pmbox->vport) {
9412 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9413 			lpfc_printf_log(phba, KERN_ERR,
9414 					LOG_MBOX | LOG_VPORT,
9415 					"1806 Mbox x%x failed. No vport\n",
9416 					pmbox->u.mb.mbxCommand);
9417 			dump_stack();
9418 			goto out_not_finished;
9419 		}
9420 	}
9421 
9422 	/* If the PCI channel is in offline state, do not post mbox. */
9423 	if (unlikely(pci_channel_offline(phba->pcidev))) {
9424 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9425 		goto out_not_finished;
9426 	}
9427 
9428 	/* If HBA has a deferred error attention, fail the iocb. */
9429 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
9430 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9431 		goto out_not_finished;
9432 	}
9433 
9434 	psli = &phba->sli;
9435 
9436 	mbx = &pmbox->u.mb;
9437 	status = MBX_SUCCESS;
9438 
9439 	if (phba->link_state == LPFC_HBA_ERROR) {
9440 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9441 
9442 		/* Mbox command <mbxCommand> cannot issue */
9443 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9444 				"(%d):0311 Mailbox command x%x cannot "
9445 				"issue Data: x%x x%x\n",
9446 				pmbox->vport ? pmbox->vport->vpi : 0,
9447 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9448 		goto out_not_finished;
9449 	}
9450 
9451 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
9452 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
9453 			!(hc_copy & HC_MBINT_ENA)) {
9454 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9455 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9456 				"(%d):2528 Mailbox command x%x cannot "
9457 				"issue Data: x%x x%x\n",
9458 				pmbox->vport ? pmbox->vport->vpi : 0,
9459 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9460 			goto out_not_finished;
9461 		}
9462 	}
9463 
9464 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9465 		/* Polling for a mbox command when another one is already active
9466 		 * is not allowed in SLI. Also, the driver must have established
9467 		 * SLI2 mode to queue and process multiple mbox commands.
9468 		 */
9469 
9470 		if (flag & MBX_POLL) {
9471 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9472 
9473 			/* Mbox command <mbxCommand> cannot issue */
9474 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9475 					"(%d):2529 Mailbox command x%x "
9476 					"cannot issue Data: x%x x%x\n",
9477 					pmbox->vport ? pmbox->vport->vpi : 0,
9478 					pmbox->u.mb.mbxCommand,
9479 					psli->sli_flag, flag);
9480 			goto out_not_finished;
9481 		}
9482 
9483 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
9484 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9485 			/* Mbox command <mbxCommand> cannot issue */
9486 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9487 					"(%d):2530 Mailbox command x%x "
9488 					"cannot issue Data: x%x x%x\n",
9489 					pmbox->vport ? pmbox->vport->vpi : 0,
9490 					pmbox->u.mb.mbxCommand,
9491 					psli->sli_flag, flag);
9492 			goto out_not_finished;
9493 		}
9494 
9495 		/* Another mailbox command is still being processed, queue this
9496 		 * command to be processed later.
9497 		 */
9498 		lpfc_mbox_put(phba, pmbox);
9499 
9500 		/* Mbox cmd issue - BUSY */
9501 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9502 				"(%d):0308 Mbox cmd issue - BUSY Data: "
9503 				"x%x x%x x%x x%x\n",
9504 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
9505 				mbx->mbxCommand,
9506 				phba->pport ? phba->pport->port_state : 0xff,
9507 				psli->sli_flag, flag);
9508 
9509 		psli->slistat.mbox_busy++;
9510 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9511 
9512 		if (pmbox->vport) {
9513 			lpfc_debugfs_disc_trc(pmbox->vport,
9514 				LPFC_DISC_TRC_MBOX_VPORT,
9515 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
9516 				(uint32_t)mbx->mbxCommand,
9517 				mbx->un.varWords[0], mbx->un.varWords[1]);
9518 		}
9519 		else {
9520 			lpfc_debugfs_disc_trc(phba->pport,
9521 				LPFC_DISC_TRC_MBOX,
9522 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
9523 				(uint32_t)mbx->mbxCommand,
9524 				mbx->un.varWords[0], mbx->un.varWords[1]);
9525 		}
9526 
9527 		return MBX_BUSY;
9528 	}
9529 
9530 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9531 
9532 	/* If we are not polling, we MUST be in SLI2 mode */
9533 	if (flag != MBX_POLL) {
9534 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
9535 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
9536 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9537 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9538 			/* Mbox command <mbxCommand> cannot issue */
9539 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9540 					"(%d):2531 Mailbox command x%x "
9541 					"cannot issue Data: x%x x%x\n",
9542 					pmbox->vport ? pmbox->vport->vpi : 0,
9543 					pmbox->u.mb.mbxCommand,
9544 					psli->sli_flag, flag);
9545 			goto out_not_finished;
9546 		}
9547 		/* timeout active mbox command */
9548 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9549 					   1000);
9550 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
9551 	}
9552 
9553 	/* Mailbox cmd <cmd> issue */
9554 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9555 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
9556 			"x%x\n",
9557 			pmbox->vport ? pmbox->vport->vpi : 0,
9558 			mbx->mbxCommand,
9559 			phba->pport ? phba->pport->port_state : 0xff,
9560 			psli->sli_flag, flag);
9561 
9562 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
9563 		if (pmbox->vport) {
9564 			lpfc_debugfs_disc_trc(pmbox->vport,
9565 				LPFC_DISC_TRC_MBOX_VPORT,
9566 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9567 				(uint32_t)mbx->mbxCommand,
9568 				mbx->un.varWords[0], mbx->un.varWords[1]);
9569 		}
9570 		else {
9571 			lpfc_debugfs_disc_trc(phba->pport,
9572 				LPFC_DISC_TRC_MBOX,
9573 				"MBOX Send:       cmd:x%x mb:x%x x%x",
9574 				(uint32_t)mbx->mbxCommand,
9575 				mbx->un.varWords[0], mbx->un.varWords[1]);
9576 		}
9577 	}
9578 
9579 	psli->slistat.mbox_cmd++;
9580 	evtctr = psli->slistat.mbox_event;
9581 
9582 	/* next set own bit for the adapter and copy over command word */
9583 	mbx->mbxOwner = OWN_CHIP;
9584 
9585 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9586 		/* Populate mbox extension offset word. */
9587 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
9588 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9589 				= (uint8_t *)phba->mbox_ext
9590 				  - (uint8_t *)phba->mbox;
9591 		}
9592 
9593 		/* Copy the mailbox extension data */
9594 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
9595 			lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
9596 					      (uint8_t *)phba->mbox_ext,
9597 					      pmbox->in_ext_byte_len);
9598 		}
9599 		/* Copy command data to host SLIM area */
9600 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
9601 	} else {
9602 		/* Populate mbox extension offset word. */
9603 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
9604 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9605 				= MAILBOX_HBA_EXT_OFFSET;
9606 
9607 		/* Copy the mailbox extension data */
9608 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
9609 			lpfc_memcpy_to_slim(phba->MBslimaddr +
9610 				MAILBOX_HBA_EXT_OFFSET,
9611 				pmbox->ctx_buf, pmbox->in_ext_byte_len);
9612 
9613 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9614 			/* copy command data into host mbox for cmpl */
9615 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
9616 					      MAILBOX_CMD_SIZE);
9617 
9618 		/* First copy mbox command data to HBA SLIM, skip past first
9619 		   word */
9620 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
9621 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
9622 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
9623 
9624 		/* Next copy over first word, with mbxOwner set */
9625 		ldata = *((uint32_t *)mbx);
9626 		to_slim = phba->MBslimaddr;
9627 		writel(ldata, to_slim);
9628 		readl(to_slim); /* flush */
9629 
9630 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9631 			/* switch over to host mailbox */
9632 			psli->sli_flag |= LPFC_SLI_ACTIVE;
9633 	}
9634 
9635 	wmb();
9636 
9637 	switch (flag) {
9638 	case MBX_NOWAIT:
9639 		/* Set up reference to mailbox command */
9640 		psli->mbox_active = pmbox;
9641 		/* Interrupt board to do it */
9642 		writel(CA_MBATT, phba->CAregaddr);
9643 		readl(phba->CAregaddr); /* flush */
9644 		/* Don't wait for it to finish, just return */
9645 		break;
9646 
9647 	case MBX_POLL:
9648 		/* Set up null reference to mailbox command */
9649 		psli->mbox_active = NULL;
9650 		/* Interrupt board to do it */
9651 		writel(CA_MBATT, phba->CAregaddr);
9652 		readl(phba->CAregaddr); /* flush */
9653 
9654 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9655 			/* First read mbox status word */
9656 			word0 = *((uint32_t *)phba->mbox);
9657 			word0 = le32_to_cpu(word0);
9658 		} else {
9659 			/* First read mbox status word */
9660 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
9661 				spin_unlock_irqrestore(&phba->hbalock,
9662 						       drvr_flag);
9663 				goto out_not_finished;
9664 			}
9665 		}
9666 
9667 		/* Read the HBA Host Attention Register */
9668 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9669 			spin_unlock_irqrestore(&phba->hbalock,
9670 						       drvr_flag);
9671 			goto out_not_finished;
9672 		}
9673 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9674 							1000) + jiffies;
9675 		i = 0;
9676 		/* Wait for command to complete */
9677 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
9678 		       (!(ha_copy & HA_MBATT) &&
9679 			(phba->link_state > LPFC_WARM_START))) {
9680 			if (time_after(jiffies, timeout)) {
9681 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9682 				spin_unlock_irqrestore(&phba->hbalock,
9683 						       drvr_flag);
9684 				goto out_not_finished;
9685 			}
9686 
9687 			/* Check if we took a mbox interrupt while we were
9688 			   polling */
9689 			if (((word0 & OWN_CHIP) != OWN_CHIP)
9690 			    && (evtctr != psli->slistat.mbox_event))
9691 				break;
9692 
9693 			if (i++ > 10) {
9694 				spin_unlock_irqrestore(&phba->hbalock,
9695 						       drvr_flag);
9696 				msleep(1);
9697 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
9698 			}
9699 
9700 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9701 				/* First copy command data */
9702 				word0 = *((uint32_t *)phba->mbox);
9703 				word0 = le32_to_cpu(word0);
9704 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
9705 					MAILBOX_t *slimmb;
9706 					uint32_t slimword0;
9707 					/* Check real SLIM for any errors */
9708 					slimword0 = readl(phba->MBslimaddr);
9709 					slimmb = (MAILBOX_t *) & slimword0;
9710 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
9711 					    && slimmb->mbxStatus) {
9712 						psli->sli_flag &=
9713 						    ~LPFC_SLI_ACTIVE;
9714 						word0 = slimword0;
9715 					}
9716 				}
9717 			} else {
9718 				/* First copy command data */
9719 				word0 = readl(phba->MBslimaddr);
9720 			}
9721 			/* Read the HBA Host Attention Register */
9722 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9723 				spin_unlock_irqrestore(&phba->hbalock,
9724 						       drvr_flag);
9725 				goto out_not_finished;
9726 			}
9727 		}
9728 
9729 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9730 			/* copy results back to user */
9731 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
9732 						MAILBOX_CMD_SIZE);
9733 			/* Copy the mailbox extension data */
9734 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9735 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
9736 						      pmbox->ctx_buf,
9737 						      pmbox->out_ext_byte_len);
9738 			}
9739 		} else {
9740 			/* First copy command data */
9741 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
9742 						MAILBOX_CMD_SIZE);
9743 			/* Copy the mailbox extension data */
9744 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9745 				lpfc_memcpy_from_slim(
9746 					pmbox->ctx_buf,
9747 					phba->MBslimaddr +
9748 					MAILBOX_HBA_EXT_OFFSET,
9749 					pmbox->out_ext_byte_len);
9750 			}
9751 		}
9752 
9753 		writel(HA_MBATT, phba->HAregaddr);
9754 		readl(phba->HAregaddr); /* flush */
9755 
9756 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9757 		status = mbx->mbxStatus;
9758 	}
9759 
9760 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9761 	return status;
9762 
9763 out_not_finished:
9764 	if (processing_queue) {
9765 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
9766 		lpfc_mbox_cmpl_put(phba, pmbox);
9767 	}
9768 	return MBX_NOT_FINISHED;
9769 }
9770 
9771 /**
9772  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
9773  * @phba: Pointer to HBA context object.
9774  *
9775  * The function blocks the posting of SLI4 asynchronous mailbox commands from
9776  * the driver internal pending mailbox queue. It will then try to wait out the
9777  * possible outstanding mailbox command before return.
9778  *
9779  * Returns:
9780  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
9781  * 	the outstanding mailbox command timed out.
9782  **/
9783 static int
9784 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
9785 {
9786 	struct lpfc_sli *psli = &phba->sli;
9787 	LPFC_MBOXQ_t *mboxq;
9788 	int rc = 0;
9789 	unsigned long timeout = 0;
9790 	u32 sli_flag;
9791 	u8 cmd, subsys, opcode;
9792 
9793 	/* Mark the asynchronous mailbox command posting as blocked */
9794 	spin_lock_irq(&phba->hbalock);
9795 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
9796 	/* Determine how long we might wait for the active mailbox
9797 	 * command to be gracefully completed by firmware.
9798 	 */
9799 	if (phba->sli.mbox_active)
9800 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
9801 						phba->sli.mbox_active) *
9802 						1000) + jiffies;
9803 	spin_unlock_irq(&phba->hbalock);
9804 
9805 	/* Make sure the mailbox is really active */
9806 	if (timeout)
9807 		lpfc_sli4_process_missed_mbox_completions(phba);
9808 
9809 	/* Wait for the outstanding mailbox command to complete */
9810 	while (phba->sli.mbox_active) {
9811 		/* Check active mailbox complete status every 2ms */
9812 		msleep(2);
9813 		if (time_after(jiffies, timeout)) {
9814 			/* Timeout, mark the outstanding cmd not complete */
9815 
9816 			/* Sanity check sli.mbox_active has not completed or
9817 			 * cancelled from another context during last 2ms sleep,
9818 			 * so take hbalock to be sure before logging.
9819 			 */
9820 			spin_lock_irq(&phba->hbalock);
9821 			if (phba->sli.mbox_active) {
9822 				mboxq = phba->sli.mbox_active;
9823 				cmd = mboxq->u.mb.mbxCommand;
9824 				subsys = lpfc_sli_config_mbox_subsys_get(phba,
9825 									 mboxq);
9826 				opcode = lpfc_sli_config_mbox_opcode_get(phba,
9827 									 mboxq);
9828 				sli_flag = psli->sli_flag;
9829 				spin_unlock_irq(&phba->hbalock);
9830 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9831 						"2352 Mailbox command x%x "
9832 						"(x%x/x%x) sli_flag x%x could "
9833 						"not complete\n",
9834 						cmd, subsys, opcode,
9835 						sli_flag);
9836 			} else {
9837 				spin_unlock_irq(&phba->hbalock);
9838 			}
9839 
9840 			rc = 1;
9841 			break;
9842 		}
9843 	}
9844 
9845 	/* Can not cleanly block async mailbox command, fails it */
9846 	if (rc) {
9847 		spin_lock_irq(&phba->hbalock);
9848 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9849 		spin_unlock_irq(&phba->hbalock);
9850 	}
9851 	return rc;
9852 }
9853 
9854 /**
9855  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
9856  * @phba: Pointer to HBA context object.
9857  *
9858  * The function unblocks and resume posting of SLI4 asynchronous mailbox
9859  * commands from the driver internal pending mailbox queue. It makes sure
9860  * that there is no outstanding mailbox command before resuming posting
9861  * asynchronous mailbox commands. If, for any reason, there is outstanding
9862  * mailbox command, it will try to wait it out before resuming asynchronous
9863  * mailbox command posting.
9864  **/
9865 static void
9866 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
9867 {
9868 	struct lpfc_sli *psli = &phba->sli;
9869 
9870 	spin_lock_irq(&phba->hbalock);
9871 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9872 		/* Asynchronous mailbox posting is not blocked, do nothing */
9873 		spin_unlock_irq(&phba->hbalock);
9874 		return;
9875 	}
9876 
9877 	/* Outstanding synchronous mailbox command is guaranteed to be done,
9878 	 * successful or timeout, after timing-out the outstanding mailbox
9879 	 * command shall always be removed, so just unblock posting async
9880 	 * mailbox command and resume
9881 	 */
9882 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9883 	spin_unlock_irq(&phba->hbalock);
9884 
9885 	/* wake up worker thread to post asynchronous mailbox command */
9886 	lpfc_worker_wake_up(phba);
9887 }
9888 
9889 /**
9890  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
9891  * @phba: Pointer to HBA context object.
9892  * @mboxq: Pointer to mailbox object.
9893  *
9894  * The function waits for the bootstrap mailbox register ready bit from
9895  * port for twice the regular mailbox command timeout value.
9896  *
9897  *      0 - no timeout on waiting for bootstrap mailbox register ready.
9898  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
9899  **/
9900 static int
9901 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9902 {
9903 	uint32_t db_ready;
9904 	unsigned long timeout;
9905 	struct lpfc_register bmbx_reg;
9906 
9907 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
9908 				   * 1000) + jiffies;
9909 
9910 	do {
9911 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
9912 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
9913 		if (!db_ready)
9914 			mdelay(2);
9915 
9916 		if (time_after(jiffies, timeout))
9917 			return MBXERR_ERROR;
9918 	} while (!db_ready);
9919 
9920 	return 0;
9921 }
9922 
9923 /**
9924  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
9925  * @phba: Pointer to HBA context object.
9926  * @mboxq: Pointer to mailbox object.
9927  *
9928  * The function posts a mailbox to the port.  The mailbox is expected
9929  * to be comletely filled in and ready for the port to operate on it.
9930  * This routine executes a synchronous completion operation on the
9931  * mailbox by polling for its completion.
9932  *
9933  * The caller must not be holding any locks when calling this routine.
9934  *
9935  * Returns:
9936  *	MBX_SUCCESS - mailbox posted successfully
9937  *	Any of the MBX error values.
9938  **/
9939 static int
9940 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9941 {
9942 	int rc = MBX_SUCCESS;
9943 	unsigned long iflag;
9944 	uint32_t mcqe_status;
9945 	uint32_t mbx_cmnd;
9946 	struct lpfc_sli *psli = &phba->sli;
9947 	struct lpfc_mqe *mb = &mboxq->u.mqe;
9948 	struct lpfc_bmbx_create *mbox_rgn;
9949 	struct dma_address *dma_address;
9950 
9951 	/*
9952 	 * Only one mailbox can be active to the bootstrap mailbox region
9953 	 * at a time and there is no queueing provided.
9954 	 */
9955 	spin_lock_irqsave(&phba->hbalock, iflag);
9956 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9957 		spin_unlock_irqrestore(&phba->hbalock, iflag);
9958 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9959 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
9960 				"cannot issue Data: x%x x%x\n",
9961 				mboxq->vport ? mboxq->vport->vpi : 0,
9962 				mboxq->u.mb.mbxCommand,
9963 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9964 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9965 				psli->sli_flag, MBX_POLL);
9966 		return MBXERR_ERROR;
9967 	}
9968 	/* The server grabs the token and owns it until release */
9969 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9970 	phba->sli.mbox_active = mboxq;
9971 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9972 
9973 	/* wait for bootstrap mbox register for readyness */
9974 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9975 	if (rc)
9976 		goto exit;
9977 	/*
9978 	 * Initialize the bootstrap memory region to avoid stale data areas
9979 	 * in the mailbox post.  Then copy the caller's mailbox contents to
9980 	 * the bmbx mailbox region.
9981 	 */
9982 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
9983 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
9984 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
9985 			       sizeof(struct lpfc_mqe));
9986 
9987 	/* Post the high mailbox dma address to the port and wait for ready. */
9988 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9989 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
9990 
9991 	/* wait for bootstrap mbox register for hi-address write done */
9992 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9993 	if (rc)
9994 		goto exit;
9995 
9996 	/* Post the low mailbox dma address to the port. */
9997 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
9998 
9999 	/* wait for bootstrap mbox register for low address write done */
10000 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
10001 	if (rc)
10002 		goto exit;
10003 
10004 	/*
10005 	 * Read the CQ to ensure the mailbox has completed.
10006 	 * If so, update the mailbox status so that the upper layers
10007 	 * can complete the request normally.
10008 	 */
10009 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
10010 			       sizeof(struct lpfc_mqe));
10011 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
10012 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
10013 			       sizeof(struct lpfc_mcqe));
10014 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
10015 	/*
10016 	 * When the CQE status indicates a failure and the mailbox status
10017 	 * indicates success then copy the CQE status into the mailbox status
10018 	 * (and prefix it with x4000).
10019 	 */
10020 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
10021 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
10022 			bf_set(lpfc_mqe_status, mb,
10023 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
10024 		rc = MBXERR_ERROR;
10025 	} else
10026 		lpfc_sli4_swap_str(phba, mboxq);
10027 
10028 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10029 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
10030 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
10031 			" x%x x%x CQ: x%x x%x x%x x%x\n",
10032 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10033 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10034 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10035 			bf_get(lpfc_mqe_status, mb),
10036 			mb->un.mb_words[0], mb->un.mb_words[1],
10037 			mb->un.mb_words[2], mb->un.mb_words[3],
10038 			mb->un.mb_words[4], mb->un.mb_words[5],
10039 			mb->un.mb_words[6], mb->un.mb_words[7],
10040 			mb->un.mb_words[8], mb->un.mb_words[9],
10041 			mb->un.mb_words[10], mb->un.mb_words[11],
10042 			mb->un.mb_words[12], mboxq->mcqe.word0,
10043 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
10044 			mboxq->mcqe.trailer);
10045 exit:
10046 	/* We are holding the token, no needed for lock when release */
10047 	spin_lock_irqsave(&phba->hbalock, iflag);
10048 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10049 	phba->sli.mbox_active = NULL;
10050 	spin_unlock_irqrestore(&phba->hbalock, iflag);
10051 	return rc;
10052 }
10053 
10054 /**
10055  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
10056  * @phba: Pointer to HBA context object.
10057  * @mboxq: Pointer to mailbox object.
10058  * @flag: Flag indicating how the mailbox need to be processed.
10059  *
10060  * This function is called by discovery code and HBA management code to submit
10061  * a mailbox command to firmware with SLI-4 interface spec.
10062  *
10063  * Return codes the caller owns the mailbox command after the return of the
10064  * function.
10065  **/
10066 static int
10067 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
10068 		       uint32_t flag)
10069 {
10070 	struct lpfc_sli *psli = &phba->sli;
10071 	unsigned long iflags;
10072 	int rc;
10073 
10074 	/* dump from issue mailbox command if setup */
10075 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
10076 
10077 	rc = lpfc_mbox_dev_check(phba);
10078 	if (unlikely(rc)) {
10079 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10080 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
10081 				"cannot issue Data: x%x x%x\n",
10082 				mboxq->vport ? mboxq->vport->vpi : 0,
10083 				mboxq->u.mb.mbxCommand,
10084 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10085 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10086 				psli->sli_flag, flag);
10087 		goto out_not_finished;
10088 	}
10089 
10090 	/* Detect polling mode and jump to a handler */
10091 	if (!phba->sli4_hba.intr_enable) {
10092 		if (flag == MBX_POLL)
10093 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10094 		else
10095 			rc = -EIO;
10096 		if (rc != MBX_SUCCESS)
10097 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10098 					"(%d):2541 Mailbox command x%x "
10099 					"(x%x/x%x) failure: "
10100 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
10101 					"Data: x%x x%x\n",
10102 					mboxq->vport ? mboxq->vport->vpi : 0,
10103 					mboxq->u.mb.mbxCommand,
10104 					lpfc_sli_config_mbox_subsys_get(phba,
10105 									mboxq),
10106 					lpfc_sli_config_mbox_opcode_get(phba,
10107 									mboxq),
10108 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10109 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10110 					bf_get(lpfc_mcqe_ext_status,
10111 					       &mboxq->mcqe),
10112 					psli->sli_flag, flag);
10113 		return rc;
10114 	} else if (flag == MBX_POLL) {
10115 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10116 				"(%d):2542 Try to issue mailbox command "
10117 				"x%x (x%x/x%x) synchronously ahead of async "
10118 				"mailbox command queue: x%x x%x\n",
10119 				mboxq->vport ? mboxq->vport->vpi : 0,
10120 				mboxq->u.mb.mbxCommand,
10121 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10122 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10123 				psli->sli_flag, flag);
10124 		/* Try to block the asynchronous mailbox posting */
10125 		rc = lpfc_sli4_async_mbox_block(phba);
10126 		if (!rc) {
10127 			/* Successfully blocked, now issue sync mbox cmd */
10128 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10129 			if (rc != MBX_SUCCESS)
10130 				lpfc_printf_log(phba, KERN_WARNING,
10131 					LOG_MBOX | LOG_SLI,
10132 					"(%d):2597 Sync Mailbox command "
10133 					"x%x (x%x/x%x) failure: "
10134 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
10135 					"Data: x%x x%x\n",
10136 					mboxq->vport ? mboxq->vport->vpi : 0,
10137 					mboxq->u.mb.mbxCommand,
10138 					lpfc_sli_config_mbox_subsys_get(phba,
10139 									mboxq),
10140 					lpfc_sli_config_mbox_opcode_get(phba,
10141 									mboxq),
10142 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10143 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10144 					bf_get(lpfc_mcqe_ext_status,
10145 					       &mboxq->mcqe),
10146 					psli->sli_flag, flag);
10147 			/* Unblock the async mailbox posting afterward */
10148 			lpfc_sli4_async_mbox_unblock(phba);
10149 		}
10150 		return rc;
10151 	}
10152 
10153 	/* Now, interrupt mode asynchronous mailbox command */
10154 	rc = lpfc_mbox_cmd_check(phba, mboxq);
10155 	if (rc) {
10156 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10157 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
10158 				"cannot issue Data: x%x x%x\n",
10159 				mboxq->vport ? mboxq->vport->vpi : 0,
10160 				mboxq->u.mb.mbxCommand,
10161 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10162 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10163 				psli->sli_flag, flag);
10164 		goto out_not_finished;
10165 	}
10166 
10167 	/* Put the mailbox command to the driver internal FIFO */
10168 	psli->slistat.mbox_busy++;
10169 	spin_lock_irqsave(&phba->hbalock, iflags);
10170 	lpfc_mbox_put(phba, mboxq);
10171 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10172 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10173 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
10174 			"x%x (x%x/x%x) x%x x%x x%x\n",
10175 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
10176 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
10177 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10178 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10179 			phba->pport->port_state,
10180 			psli->sli_flag, MBX_NOWAIT);
10181 	/* Wake up worker thread to transport mailbox command from head */
10182 	lpfc_worker_wake_up(phba);
10183 
10184 	return MBX_BUSY;
10185 
10186 out_not_finished:
10187 	return MBX_NOT_FINISHED;
10188 }
10189 
10190 /**
10191  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
10192  * @phba: Pointer to HBA context object.
10193  *
10194  * This function is called by worker thread to send a mailbox command to
10195  * SLI4 HBA firmware.
10196  *
10197  **/
10198 int
10199 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
10200 {
10201 	struct lpfc_sli *psli = &phba->sli;
10202 	LPFC_MBOXQ_t *mboxq;
10203 	int rc = MBX_SUCCESS;
10204 	unsigned long iflags;
10205 	struct lpfc_mqe *mqe;
10206 	uint32_t mbx_cmnd;
10207 
10208 	/* Check interrupt mode before post async mailbox command */
10209 	if (unlikely(!phba->sli4_hba.intr_enable))
10210 		return MBX_NOT_FINISHED;
10211 
10212 	/* Check for mailbox command service token */
10213 	spin_lock_irqsave(&phba->hbalock, iflags);
10214 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
10215 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10216 		return MBX_NOT_FINISHED;
10217 	}
10218 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
10219 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10220 		return MBX_NOT_FINISHED;
10221 	}
10222 	if (unlikely(phba->sli.mbox_active)) {
10223 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10224 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10225 				"0384 There is pending active mailbox cmd\n");
10226 		return MBX_NOT_FINISHED;
10227 	}
10228 	/* Take the mailbox command service token */
10229 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
10230 
10231 	/* Get the next mailbox command from head of queue */
10232 	mboxq = lpfc_mbox_get(phba);
10233 
10234 	/* If no more mailbox command waiting for post, we're done */
10235 	if (!mboxq) {
10236 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10237 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10238 		return MBX_SUCCESS;
10239 	}
10240 	phba->sli.mbox_active = mboxq;
10241 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10242 
10243 	/* Check device readiness for posting mailbox command */
10244 	rc = lpfc_mbox_dev_check(phba);
10245 	if (unlikely(rc))
10246 		/* Driver clean routine will clean up pending mailbox */
10247 		goto out_not_finished;
10248 
10249 	/* Prepare the mbox command to be posted */
10250 	mqe = &mboxq->u.mqe;
10251 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
10252 
10253 	/* Start timer for the mbox_tmo and log some mailbox post messages */
10254 	mod_timer(&psli->mbox_tmo, (jiffies +
10255 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
10256 
10257 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10258 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
10259 			"x%x x%x\n",
10260 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10261 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10262 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10263 			phba->pport->port_state, psli->sli_flag);
10264 
10265 	if (mbx_cmnd != MBX_HEARTBEAT) {
10266 		if (mboxq->vport) {
10267 			lpfc_debugfs_disc_trc(mboxq->vport,
10268 				LPFC_DISC_TRC_MBOX_VPORT,
10269 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
10270 				mbx_cmnd, mqe->un.mb_words[0],
10271 				mqe->un.mb_words[1]);
10272 		} else {
10273 			lpfc_debugfs_disc_trc(phba->pport,
10274 				LPFC_DISC_TRC_MBOX,
10275 				"MBOX Send: cmd:x%x mb:x%x x%x",
10276 				mbx_cmnd, mqe->un.mb_words[0],
10277 				mqe->un.mb_words[1]);
10278 		}
10279 	}
10280 	psli->slistat.mbox_cmd++;
10281 
10282 	/* Post the mailbox command to the port */
10283 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
10284 	if (rc != MBX_SUCCESS) {
10285 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10286 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
10287 				"cannot issue Data: x%x x%x\n",
10288 				mboxq->vport ? mboxq->vport->vpi : 0,
10289 				mboxq->u.mb.mbxCommand,
10290 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10291 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10292 				psli->sli_flag, MBX_NOWAIT);
10293 		goto out_not_finished;
10294 	}
10295 
10296 	return rc;
10297 
10298 out_not_finished:
10299 	spin_lock_irqsave(&phba->hbalock, iflags);
10300 	if (phba->sli.mbox_active) {
10301 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
10302 		__lpfc_mbox_cmpl_put(phba, mboxq);
10303 		/* Release the token */
10304 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10305 		phba->sli.mbox_active = NULL;
10306 	}
10307 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10308 
10309 	return MBX_NOT_FINISHED;
10310 }
10311 
10312 /**
10313  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
10314  * @phba: Pointer to HBA context object.
10315  * @pmbox: Pointer to mailbox object.
10316  * @flag: Flag indicating how the mailbox need to be processed.
10317  *
10318  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
10319  * the API jump table function pointer from the lpfc_hba struct.
10320  *
10321  * Return codes the caller owns the mailbox command after the return of the
10322  * function.
10323  **/
10324 int
10325 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
10326 {
10327 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
10328 }
10329 
10330 /**
10331  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
10332  * @phba: The hba struct for which this call is being executed.
10333  * @dev_grp: The HBA PCI-Device group number.
10334  *
10335  * This routine sets up the mbox interface API function jump table in @phba
10336  * struct.
10337  * Returns: 0 - success, -ENODEV - failure.
10338  **/
10339 int
10340 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10341 {
10342 
10343 	switch (dev_grp) {
10344 	case LPFC_PCI_DEV_LP:
10345 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
10346 		phba->lpfc_sli_handle_slow_ring_event =
10347 				lpfc_sli_handle_slow_ring_event_s3;
10348 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
10349 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
10350 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
10351 		break;
10352 	case LPFC_PCI_DEV_OC:
10353 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
10354 		phba->lpfc_sli_handle_slow_ring_event =
10355 				lpfc_sli_handle_slow_ring_event_s4;
10356 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
10357 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
10358 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
10359 		break;
10360 	default:
10361 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10362 				"1420 Invalid HBA PCI-device group: 0x%x\n",
10363 				dev_grp);
10364 		return -ENODEV;
10365 	}
10366 	return 0;
10367 }
10368 
10369 /**
10370  * __lpfc_sli_ringtx_put - Add an iocb to the txq
10371  * @phba: Pointer to HBA context object.
10372  * @pring: Pointer to driver SLI ring object.
10373  * @piocb: Pointer to address of newly added command iocb.
10374  *
10375  * This function is called with hbalock held for SLI3 ports or
10376  * the ring lock held for SLI4 ports to add a command
10377  * iocb to the txq when SLI layer cannot submit the command iocb
10378  * to the ring.
10379  **/
10380 void
10381 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10382 		    struct lpfc_iocbq *piocb)
10383 {
10384 	if (phba->sli_rev == LPFC_SLI_REV4)
10385 		lockdep_assert_held(&pring->ring_lock);
10386 	else
10387 		lockdep_assert_held(&phba->hbalock);
10388 	/* Insert the caller's iocb in the txq tail for later processing. */
10389 	list_add_tail(&piocb->list, &pring->txq);
10390 }
10391 
10392 /**
10393  * lpfc_sli_next_iocb - Get the next iocb in the txq
10394  * @phba: Pointer to HBA context object.
10395  * @pring: Pointer to driver SLI ring object.
10396  * @piocb: Pointer to address of newly added command iocb.
10397  *
10398  * This function is called with hbalock held before a new
10399  * iocb is submitted to the firmware. This function checks
10400  * txq to flush the iocbs in txq to Firmware before
10401  * submitting new iocbs to the Firmware.
10402  * If there are iocbs in the txq which need to be submitted
10403  * to firmware, lpfc_sli_next_iocb returns the first element
10404  * of the txq after dequeuing it from txq.
10405  * If there is no iocb in the txq then the function will return
10406  * *piocb and *piocb is set to NULL. Caller needs to check
10407  * *piocb to find if there are more commands in the txq.
10408  **/
10409 static struct lpfc_iocbq *
10410 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10411 		   struct lpfc_iocbq **piocb)
10412 {
10413 	struct lpfc_iocbq * nextiocb;
10414 
10415 	lockdep_assert_held(&phba->hbalock);
10416 
10417 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
10418 	if (!nextiocb) {
10419 		nextiocb = *piocb;
10420 		*piocb = NULL;
10421 	}
10422 
10423 	return nextiocb;
10424 }
10425 
10426 /**
10427  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
10428  * @phba: Pointer to HBA context object.
10429  * @ring_number: SLI ring number to issue iocb on.
10430  * @piocb: Pointer to command iocb.
10431  * @flag: Flag indicating if this command can be put into txq.
10432  *
10433  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
10434  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
10435  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
10436  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
10437  * this function allows only iocbs for posting buffers. This function finds
10438  * next available slot in the command ring and posts the command to the
10439  * available slot and writes the port attention register to request HBA start
10440  * processing new iocb. If there is no slot available in the ring and
10441  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
10442  * the function returns IOCB_BUSY.
10443  *
10444  * This function is called with hbalock held. The function will return success
10445  * after it successfully submit the iocb to firmware or after adding to the
10446  * txq.
10447  **/
10448 static int
10449 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
10450 		    struct lpfc_iocbq *piocb, uint32_t flag)
10451 {
10452 	struct lpfc_iocbq *nextiocb;
10453 	IOCB_t *iocb;
10454 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
10455 
10456 	lockdep_assert_held(&phba->hbalock);
10457 
10458 	if (piocb->cmd_cmpl && (!piocb->vport) &&
10459 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
10460 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
10461 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10462 				"1807 IOCB x%x failed. No vport\n",
10463 				piocb->iocb.ulpCommand);
10464 		dump_stack();
10465 		return IOCB_ERROR;
10466 	}
10467 
10468 
10469 	/* If the PCI channel is in offline state, do not post iocbs. */
10470 	if (unlikely(pci_channel_offline(phba->pcidev)))
10471 		return IOCB_ERROR;
10472 
10473 	/* If HBA has a deferred error attention, fail the iocb. */
10474 	if (unlikely(phba->hba_flag & DEFER_ERATT))
10475 		return IOCB_ERROR;
10476 
10477 	/*
10478 	 * We should never get an IOCB if we are in a < LINK_DOWN state
10479 	 */
10480 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
10481 		return IOCB_ERROR;
10482 
10483 	/*
10484 	 * Check to see if we are blocking IOCB processing because of a
10485 	 * outstanding event.
10486 	 */
10487 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
10488 		goto iocb_busy;
10489 
10490 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
10491 		/*
10492 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
10493 		 * can be issued if the link is not up.
10494 		 */
10495 		switch (piocb->iocb.ulpCommand) {
10496 		case CMD_QUE_RING_BUF_CN:
10497 		case CMD_QUE_RING_BUF64_CN:
10498 			/*
10499 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
10500 			 * completion, cmd_cmpl MUST be 0.
10501 			 */
10502 			if (piocb->cmd_cmpl)
10503 				piocb->cmd_cmpl = NULL;
10504 			fallthrough;
10505 		case CMD_CREATE_XRI_CR:
10506 		case CMD_CLOSE_XRI_CN:
10507 		case CMD_CLOSE_XRI_CX:
10508 			break;
10509 		default:
10510 			goto iocb_busy;
10511 		}
10512 
10513 	/*
10514 	 * For FCP commands, we must be in a state where we can process link
10515 	 * attention events.
10516 	 */
10517 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
10518 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
10519 		goto iocb_busy;
10520 	}
10521 
10522 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
10523 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
10524 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
10525 
10526 	if (iocb)
10527 		lpfc_sli_update_ring(phba, pring);
10528 	else
10529 		lpfc_sli_update_full_ring(phba, pring);
10530 
10531 	if (!piocb)
10532 		return IOCB_SUCCESS;
10533 
10534 	goto out_busy;
10535 
10536  iocb_busy:
10537 	pring->stats.iocb_cmd_delay++;
10538 
10539  out_busy:
10540 
10541 	if (!(flag & SLI_IOCB_RET_IOCB)) {
10542 		__lpfc_sli_ringtx_put(phba, pring, piocb);
10543 		return IOCB_SUCCESS;
10544 	}
10545 
10546 	return IOCB_BUSY;
10547 }
10548 
10549 /**
10550  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10551  * @phba: Pointer to HBA context object.
10552  * @ring_number: SLI ring number to issue wqe on.
10553  * @piocb: Pointer to command iocb.
10554  * @flag: Flag indicating if this command can be put into txq.
10555  *
10556  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10557  * send  an iocb command to an HBA with SLI-3 interface spec.
10558  *
10559  * This function takes the hbalock before invoking the lockless version.
10560  * The function will return success after it successfully submit the wqe to
10561  * firmware or after adding to the txq.
10562  **/
10563 static int
10564 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10565 			   struct lpfc_iocbq *piocb, uint32_t flag)
10566 {
10567 	unsigned long iflags;
10568 	int rc;
10569 
10570 	spin_lock_irqsave(&phba->hbalock, iflags);
10571 	rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10572 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10573 
10574 	return rc;
10575 }
10576 
10577 /**
10578  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10579  * @phba: Pointer to HBA context object.
10580  * @ring_number: SLI ring number to issue wqe on.
10581  * @piocb: Pointer to command iocb.
10582  * @flag: Flag indicating if this command can be put into txq.
10583  *
10584  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10585  * an wqe command to an HBA with SLI-4 interface spec.
10586  *
10587  * This function is a lockless version. The function will return success
10588  * after it successfully submit the wqe to firmware or after adding to the
10589  * txq.
10590  **/
10591 static int
10592 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10593 			   struct lpfc_iocbq *piocb, uint32_t flag)
10594 {
10595 	struct lpfc_io_buf *lpfc_cmd = piocb->io_buf;
10596 
10597 	lpfc_prep_embed_io(phba, lpfc_cmd);
10598 	return lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
10599 }
10600 
10601 void
10602 lpfc_prep_embed_io(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
10603 {
10604 	struct lpfc_iocbq *piocb = &lpfc_cmd->cur_iocbq;
10605 	union lpfc_wqe128 *wqe = &lpfc_cmd->cur_iocbq.wqe;
10606 	struct sli4_sge *sgl;
10607 
10608 	/* 128 byte wqe support here */
10609 	sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10610 
10611 	if (phba->fcp_embed_io) {
10612 		struct fcp_cmnd *fcp_cmnd;
10613 		u32 *ptr;
10614 
10615 		fcp_cmnd = lpfc_cmd->fcp_cmnd;
10616 
10617 		/* Word 0-2 - FCP_CMND */
10618 		wqe->generic.bde.tus.f.bdeFlags =
10619 			BUFF_TYPE_BDE_IMMED;
10620 		wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10621 		wqe->generic.bde.addrHigh = 0;
10622 		wqe->generic.bde.addrLow =  88;  /* Word 22 */
10623 
10624 		bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10625 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10626 
10627 		/* Word 22-29  FCP CMND Payload */
10628 		ptr = &wqe->words[22];
10629 		memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10630 	} else {
10631 		/* Word 0-2 - Inline BDE */
10632 		wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
10633 		wqe->generic.bde.tus.f.bdeSize = sizeof(struct fcp_cmnd);
10634 		wqe->generic.bde.addrHigh = sgl->addr_hi;
10635 		wqe->generic.bde.addrLow =  sgl->addr_lo;
10636 
10637 		/* Word 10 */
10638 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10639 		bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
10640 	}
10641 
10642 	/* add the VMID tags as per switch response */
10643 	if (unlikely(piocb->cmd_flag & LPFC_IO_VMID)) {
10644 		if (phba->pport->vmid_flag & LPFC_VMID_TYPE_PRIO) {
10645 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
10646 			bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10647 					(piocb->vmid_tag.cs_ctl_vmid));
10648 		} else if (phba->cfg_vmid_app_header) {
10649 			bf_set(wqe_appid, &wqe->fcp_iwrite.wqe_com, 1);
10650 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10651 			wqe->words[31] = piocb->vmid_tag.app_id;
10652 		}
10653 	}
10654 }
10655 
10656 /**
10657  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10658  * @phba: Pointer to HBA context object.
10659  * @ring_number: SLI ring number to issue iocb on.
10660  * @piocb: Pointer to command iocb.
10661  * @flag: Flag indicating if this command can be put into txq.
10662  *
10663  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10664  * an iocb command to an HBA with SLI-4 interface spec.
10665  *
10666  * This function is called with ringlock held. The function will return success
10667  * after it successfully submit the iocb to firmware or after adding to the
10668  * txq.
10669  **/
10670 static int
10671 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10672 			 struct lpfc_iocbq *piocb, uint32_t flag)
10673 {
10674 	struct lpfc_sglq *sglq;
10675 	union lpfc_wqe128 *wqe;
10676 	struct lpfc_queue *wq;
10677 	struct lpfc_sli_ring *pring;
10678 	u32 ulp_command = get_job_cmnd(phba, piocb);
10679 
10680 	/* Get the WQ */
10681 	if ((piocb->cmd_flag & LPFC_IO_FCP) ||
10682 	    (piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
10683 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10684 	} else {
10685 		wq = phba->sli4_hba.els_wq;
10686 	}
10687 
10688 	/* Get corresponding ring */
10689 	pring = wq->pring;
10690 
10691 	/*
10692 	 * The WQE can be either 64 or 128 bytes,
10693 	 */
10694 
10695 	lockdep_assert_held(&pring->ring_lock);
10696 	wqe = &piocb->wqe;
10697 	if (piocb->sli4_xritag == NO_XRI) {
10698 		if (ulp_command == CMD_ABORT_XRI_CX)
10699 			sglq = NULL;
10700 		else {
10701 			sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10702 			if (!sglq) {
10703 				if (!(flag & SLI_IOCB_RET_IOCB)) {
10704 					__lpfc_sli_ringtx_put(phba,
10705 							pring,
10706 							piocb);
10707 					return IOCB_SUCCESS;
10708 				} else {
10709 					return IOCB_BUSY;
10710 				}
10711 			}
10712 		}
10713 	} else if (piocb->cmd_flag &  LPFC_IO_FCP) {
10714 		/* These IO's already have an XRI and a mapped sgl. */
10715 		sglq = NULL;
10716 	}
10717 	else {
10718 		/*
10719 		 * This is a continuation of a commandi,(CX) so this
10720 		 * sglq is on the active list
10721 		 */
10722 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10723 		if (!sglq)
10724 			return IOCB_ERROR;
10725 	}
10726 
10727 	if (sglq) {
10728 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10729 		piocb->sli4_xritag = sglq->sli4_xritag;
10730 
10731 		/* ABTS sent by initiator to CT exchange, the
10732 		 * RX_ID field will be filled with the newly
10733 		 * allocated responder XRI.
10734 		 */
10735 		if (ulp_command == CMD_XMIT_BLS_RSP64_CX &&
10736 		    piocb->abort_bls == LPFC_ABTS_UNSOL_INT)
10737 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10738 			       piocb->sli4_xritag);
10739 
10740 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com,
10741 		       piocb->sli4_xritag);
10742 
10743 		if (lpfc_wqe_bpl2sgl(phba, piocb, sglq) == NO_XRI)
10744 			return IOCB_ERROR;
10745 	}
10746 
10747 	if (lpfc_sli4_wq_put(wq, wqe))
10748 		return IOCB_ERROR;
10749 
10750 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10751 
10752 	return 0;
10753 }
10754 
10755 /*
10756  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
10757  *
10758  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
10759  * or IOCB for sli-3  function.
10760  * pointer from the lpfc_hba struct.
10761  *
10762  * Return codes:
10763  * IOCB_ERROR - Error
10764  * IOCB_SUCCESS - Success
10765  * IOCB_BUSY - Busy
10766  **/
10767 int
10768 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
10769 		      struct lpfc_iocbq *piocb, uint32_t flag)
10770 {
10771 	return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
10772 }
10773 
10774 /*
10775  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10776  *
10777  * This routine wraps the actual lockless version for issusing IOCB function
10778  * pointer from the lpfc_hba struct.
10779  *
10780  * Return codes:
10781  * IOCB_ERROR - Error
10782  * IOCB_SUCCESS - Success
10783  * IOCB_BUSY - Busy
10784  **/
10785 int
10786 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10787 		struct lpfc_iocbq *piocb, uint32_t flag)
10788 {
10789 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10790 }
10791 
10792 static void
10793 __lpfc_sli_prep_els_req_rsp_s3(struct lpfc_iocbq *cmdiocbq,
10794 			       struct lpfc_vport *vport,
10795 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10796 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10797 {
10798 	struct lpfc_hba *phba = vport->phba;
10799 	IOCB_t *cmd;
10800 
10801 	cmd = &cmdiocbq->iocb;
10802 	memset(cmd, 0, sizeof(*cmd));
10803 
10804 	cmd->un.elsreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10805 	cmd->un.elsreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10806 	cmd->un.elsreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10807 
10808 	if (expect_rsp) {
10809 		cmd->un.elsreq64.bdl.bdeSize = (2 * sizeof(struct ulp_bde64));
10810 		cmd->un.elsreq64.remoteID = did; /* DID */
10811 		cmd->ulpCommand = CMD_ELS_REQUEST64_CR;
10812 		cmd->ulpTimeout = tmo;
10813 	} else {
10814 		cmd->un.elsreq64.bdl.bdeSize = sizeof(struct ulp_bde64);
10815 		cmd->un.genreq64.xmit_els_remoteID = did; /* DID */
10816 		cmd->ulpCommand = CMD_XMIT_ELS_RSP64_CX;
10817 		cmd->ulpPU = PARM_NPIV_DID;
10818 	}
10819 	cmd->ulpBdeCount = 1;
10820 	cmd->ulpLe = 1;
10821 	cmd->ulpClass = CLASS3;
10822 
10823 	/* If we have NPIV enabled, we want to send ELS traffic by VPI. */
10824 	if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) {
10825 		if (expect_rsp) {
10826 			cmd->un.elsreq64.myID = vport->fc_myDID;
10827 
10828 			/* For ELS_REQUEST64_CR, use the VPI by default */
10829 			cmd->ulpContext = phba->vpi_ids[vport->vpi];
10830 		}
10831 
10832 		cmd->ulpCt_h = 0;
10833 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10834 		if (elscmd == ELS_CMD_ECHO)
10835 			cmd->ulpCt_l = 0; /* context = invalid RPI */
10836 		else
10837 			cmd->ulpCt_l = 1; /* context = VPI */
10838 	}
10839 }
10840 
10841 static void
10842 __lpfc_sli_prep_els_req_rsp_s4(struct lpfc_iocbq *cmdiocbq,
10843 			       struct lpfc_vport *vport,
10844 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10845 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10846 {
10847 	struct lpfc_hba  *phba = vport->phba;
10848 	union lpfc_wqe128 *wqe;
10849 	struct ulp_bde64_le *bde;
10850 	u8 els_id;
10851 
10852 	wqe = &cmdiocbq->wqe;
10853 	memset(wqe, 0, sizeof(*wqe));
10854 
10855 	/* Word 0 - 2 BDE */
10856 	bde = (struct ulp_bde64_le *)&wqe->generic.bde;
10857 	bde->addr_low = cpu_to_le32(putPaddrLow(bmp->phys));
10858 	bde->addr_high = cpu_to_le32(putPaddrHigh(bmp->phys));
10859 	bde->type_size = cpu_to_le32(cmd_size);
10860 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10861 
10862 	if (expect_rsp) {
10863 		bf_set(wqe_cmnd, &wqe->els_req.wqe_com, CMD_ELS_REQUEST64_WQE);
10864 
10865 		/* Transfer length */
10866 		wqe->els_req.payload_len = cmd_size;
10867 		wqe->els_req.max_response_payload_len = FCELSSIZE;
10868 
10869 		/* DID */
10870 		bf_set(wqe_els_did, &wqe->els_req.wqe_dest, did);
10871 
10872 		/* Word 11 - ELS_ID */
10873 		switch (elscmd) {
10874 		case ELS_CMD_PLOGI:
10875 			els_id = LPFC_ELS_ID_PLOGI;
10876 			break;
10877 		case ELS_CMD_FLOGI:
10878 			els_id = LPFC_ELS_ID_FLOGI;
10879 			break;
10880 		case ELS_CMD_LOGO:
10881 			els_id = LPFC_ELS_ID_LOGO;
10882 			break;
10883 		case ELS_CMD_FDISC:
10884 			if (!vport->fc_myDID) {
10885 				els_id = LPFC_ELS_ID_FDISC;
10886 				break;
10887 			}
10888 			fallthrough;
10889 		default:
10890 			els_id = LPFC_ELS_ID_DEFAULT;
10891 			break;
10892 		}
10893 
10894 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
10895 	} else {
10896 		/* DID */
10897 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest, did);
10898 
10899 		/* Transfer length */
10900 		wqe->xmit_els_rsp.response_payload_len = cmd_size;
10901 
10902 		bf_set(wqe_cmnd, &wqe->xmit_els_rsp.wqe_com,
10903 		       CMD_XMIT_ELS_RSP64_WQE);
10904 	}
10905 
10906 	bf_set(wqe_tmo, &wqe->generic.wqe_com, tmo);
10907 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, cmdiocbq->iotag);
10908 	bf_set(wqe_class, &wqe->generic.wqe_com, CLASS3);
10909 
10910 	/* If we have NPIV enabled, we want to send ELS traffic by VPI.
10911 	 * For SLI4, since the driver controls VPIs we also want to include
10912 	 * all ELS pt2pt protocol traffic as well.
10913 	 */
10914 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) ||
10915 	    (vport->fc_flag & FC_PT2PT)) {
10916 		if (expect_rsp) {
10917 			bf_set(els_req64_sid, &wqe->els_req, vport->fc_myDID);
10918 
10919 			/* For ELS_REQUEST64_WQE, use the VPI by default */
10920 			bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10921 			       phba->vpi_ids[vport->vpi]);
10922 		}
10923 
10924 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10925 		if (elscmd == ELS_CMD_ECHO)
10926 			bf_set(wqe_ct, &wqe->generic.wqe_com, 0);
10927 		else
10928 			bf_set(wqe_ct, &wqe->generic.wqe_com, 1);
10929 	}
10930 }
10931 
10932 void
10933 lpfc_sli_prep_els_req_rsp(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
10934 			  struct lpfc_vport *vport, struct lpfc_dmabuf *bmp,
10935 			  u16 cmd_size, u32 did, u32 elscmd, u8 tmo,
10936 			  u8 expect_rsp)
10937 {
10938 	phba->__lpfc_sli_prep_els_req_rsp(cmdiocbq, vport, bmp, cmd_size, did,
10939 					  elscmd, tmo, expect_rsp);
10940 }
10941 
10942 static void
10943 __lpfc_sli_prep_gen_req_s3(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10944 			   u16 rpi, u32 num_entry, u8 tmo)
10945 {
10946 	IOCB_t *cmd;
10947 
10948 	cmd = &cmdiocbq->iocb;
10949 	memset(cmd, 0, sizeof(*cmd));
10950 
10951 	cmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10952 	cmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10953 	cmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10954 	cmd->un.genreq64.bdl.bdeSize = num_entry * sizeof(struct ulp_bde64);
10955 
10956 	cmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
10957 	cmd->un.genreq64.w5.hcsw.Type = FC_TYPE_CT;
10958 	cmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
10959 
10960 	cmd->ulpContext = rpi;
10961 	cmd->ulpClass = CLASS3;
10962 	cmd->ulpCommand = CMD_GEN_REQUEST64_CR;
10963 	cmd->ulpBdeCount = 1;
10964 	cmd->ulpLe = 1;
10965 	cmd->ulpOwner = OWN_CHIP;
10966 	cmd->ulpTimeout = tmo;
10967 }
10968 
10969 static void
10970 __lpfc_sli_prep_gen_req_s4(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10971 			   u16 rpi, u32 num_entry, u8 tmo)
10972 {
10973 	union lpfc_wqe128 *cmdwqe;
10974 	struct ulp_bde64_le *bde, *bpl;
10975 	u32 xmit_len = 0, total_len = 0, size, type, i;
10976 
10977 	cmdwqe = &cmdiocbq->wqe;
10978 	memset(cmdwqe, 0, sizeof(*cmdwqe));
10979 
10980 	/* Calculate total_len and xmit_len */
10981 	bpl = (struct ulp_bde64_le *)bmp->virt;
10982 	for (i = 0; i < num_entry; i++) {
10983 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10984 		total_len += size;
10985 	}
10986 	for (i = 0; i < num_entry; i++) {
10987 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10988 		type = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_TYPE_MASK;
10989 		if (type != ULP_BDE64_TYPE_BDE_64)
10990 			break;
10991 		xmit_len += size;
10992 	}
10993 
10994 	/* Words 0 - 2 */
10995 	bde = (struct ulp_bde64_le *)&cmdwqe->generic.bde;
10996 	bde->addr_low = bpl->addr_low;
10997 	bde->addr_high = bpl->addr_high;
10998 	bde->type_size = cpu_to_le32(xmit_len);
10999 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
11000 
11001 	/* Word 3 */
11002 	cmdwqe->gen_req.request_payload_len = xmit_len;
11003 
11004 	/* Word 5 */
11005 	bf_set(wqe_type, &cmdwqe->gen_req.wge_ctl, FC_TYPE_CT);
11006 	bf_set(wqe_rctl, &cmdwqe->gen_req.wge_ctl, FC_RCTL_DD_UNSOL_CTL);
11007 	bf_set(wqe_si, &cmdwqe->gen_req.wge_ctl, 1);
11008 	bf_set(wqe_la, &cmdwqe->gen_req.wge_ctl, 1);
11009 
11010 	/* Word 6 */
11011 	bf_set(wqe_ctxt_tag, &cmdwqe->gen_req.wqe_com, rpi);
11012 
11013 	/* Word 7 */
11014 	bf_set(wqe_tmo, &cmdwqe->gen_req.wqe_com, tmo);
11015 	bf_set(wqe_class, &cmdwqe->gen_req.wqe_com, CLASS3);
11016 	bf_set(wqe_cmnd, &cmdwqe->gen_req.wqe_com, CMD_GEN_REQUEST64_CR);
11017 	bf_set(wqe_ct, &cmdwqe->gen_req.wqe_com, SLI4_CT_RPI);
11018 
11019 	/* Word 12 */
11020 	cmdwqe->gen_req.max_response_payload_len = total_len - xmit_len;
11021 }
11022 
11023 void
11024 lpfc_sli_prep_gen_req(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11025 		      struct lpfc_dmabuf *bmp, u16 rpi, u32 num_entry, u8 tmo)
11026 {
11027 	phba->__lpfc_sli_prep_gen_req(cmdiocbq, bmp, rpi, num_entry, tmo);
11028 }
11029 
11030 static void
11031 __lpfc_sli_prep_xmit_seq64_s3(struct lpfc_iocbq *cmdiocbq,
11032 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11033 			      u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11034 {
11035 	IOCB_t *icmd;
11036 
11037 	icmd = &cmdiocbq->iocb;
11038 	memset(icmd, 0, sizeof(*icmd));
11039 
11040 	icmd->un.xseq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
11041 	icmd->un.xseq64.bdl.addrLow = putPaddrLow(bmp->phys);
11042 	icmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
11043 	icmd->un.xseq64.bdl.bdeSize = (num_entry * sizeof(struct ulp_bde64));
11044 	icmd->un.xseq64.w5.hcsw.Fctl = LA;
11045 	if (last_seq)
11046 		icmd->un.xseq64.w5.hcsw.Fctl |= LS;
11047 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
11048 	icmd->un.xseq64.w5.hcsw.Rctl = rctl;
11049 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
11050 
11051 	icmd->ulpBdeCount = 1;
11052 	icmd->ulpLe = 1;
11053 	icmd->ulpClass = CLASS3;
11054 
11055 	switch (cr_cx_cmd) {
11056 	case CMD_XMIT_SEQUENCE64_CR:
11057 		icmd->ulpContext = rpi;
11058 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CR;
11059 		break;
11060 	case CMD_XMIT_SEQUENCE64_CX:
11061 		icmd->ulpContext = ox_id;
11062 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CX;
11063 		break;
11064 	default:
11065 		break;
11066 	}
11067 }
11068 
11069 static void
11070 __lpfc_sli_prep_xmit_seq64_s4(struct lpfc_iocbq *cmdiocbq,
11071 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11072 			      u32 full_size, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11073 {
11074 	union lpfc_wqe128 *wqe;
11075 	struct ulp_bde64 *bpl;
11076 
11077 	wqe = &cmdiocbq->wqe;
11078 	memset(wqe, 0, sizeof(*wqe));
11079 
11080 	/* Words 0 - 2 */
11081 	bpl = (struct ulp_bde64 *)bmp->virt;
11082 	wqe->xmit_sequence.bde.addrHigh = bpl->addrHigh;
11083 	wqe->xmit_sequence.bde.addrLow = bpl->addrLow;
11084 	wqe->xmit_sequence.bde.tus.w = bpl->tus.w;
11085 
11086 	/* Word 5 */
11087 	bf_set(wqe_ls, &wqe->xmit_sequence.wge_ctl, last_seq);
11088 	bf_set(wqe_la, &wqe->xmit_sequence.wge_ctl, 1);
11089 	bf_set(wqe_dfctl, &wqe->xmit_sequence.wge_ctl, 0);
11090 	bf_set(wqe_rctl, &wqe->xmit_sequence.wge_ctl, rctl);
11091 	bf_set(wqe_type, &wqe->xmit_sequence.wge_ctl, FC_TYPE_CT);
11092 
11093 	/* Word 6 */
11094 	bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com, rpi);
11095 
11096 	bf_set(wqe_cmnd, &wqe->xmit_sequence.wqe_com,
11097 	       CMD_XMIT_SEQUENCE64_WQE);
11098 
11099 	/* Word 7 */
11100 	bf_set(wqe_class, &wqe->xmit_sequence.wqe_com, CLASS3);
11101 
11102 	/* Word 9 */
11103 	bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com, ox_id);
11104 
11105 	/* Word 12 */
11106 	if (cmdiocbq->cmd_flag & (LPFC_IO_LIBDFC | LPFC_IO_LOOPBACK))
11107 		wqe->xmit_sequence.xmit_len = full_size;
11108 	else
11109 		wqe->xmit_sequence.xmit_len =
11110 			wqe->xmit_sequence.bde.tus.f.bdeSize;
11111 }
11112 
11113 void
11114 lpfc_sli_prep_xmit_seq64(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11115 			 struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11116 			 u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11117 {
11118 	phba->__lpfc_sli_prep_xmit_seq64(cmdiocbq, bmp, rpi, ox_id, num_entry,
11119 					 rctl, last_seq, cr_cx_cmd);
11120 }
11121 
11122 static void
11123 __lpfc_sli_prep_abort_xri_s3(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11124 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11125 			     bool wqec)
11126 {
11127 	IOCB_t *icmd = NULL;
11128 
11129 	icmd = &cmdiocbq->iocb;
11130 	memset(icmd, 0, sizeof(*icmd));
11131 
11132 	/* Word 5 */
11133 	icmd->un.acxri.abortContextTag = ulp_context;
11134 	icmd->un.acxri.abortIoTag = iotag;
11135 
11136 	if (ia) {
11137 		/* Word 7 */
11138 		icmd->ulpCommand = CMD_CLOSE_XRI_CN;
11139 	} else {
11140 		/* Word 3 */
11141 		icmd->un.acxri.abortType = ABORT_TYPE_ABTS;
11142 
11143 		/* Word 7 */
11144 		icmd->ulpClass = ulp_class;
11145 		icmd->ulpCommand = CMD_ABORT_XRI_CN;
11146 	}
11147 
11148 	/* Word 7 */
11149 	icmd->ulpLe = 1;
11150 }
11151 
11152 static void
11153 __lpfc_sli_prep_abort_xri_s4(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11154 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11155 			     bool wqec)
11156 {
11157 	union lpfc_wqe128 *wqe;
11158 
11159 	wqe = &cmdiocbq->wqe;
11160 	memset(wqe, 0, sizeof(*wqe));
11161 
11162 	/* Word 3 */
11163 	bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
11164 	if (ia)
11165 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
11166 	else
11167 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
11168 
11169 	/* Word 7 */
11170 	bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_WQE);
11171 
11172 	/* Word 8 */
11173 	wqe->abort_cmd.wqe_com.abort_tag = ulp_context;
11174 
11175 	/* Word 9 */
11176 	bf_set(wqe_reqtag, &wqe->abort_cmd.wqe_com, iotag);
11177 
11178 	/* Word 10 */
11179 	bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
11180 
11181 	/* Word 11 */
11182 	if (wqec)
11183 		bf_set(wqe_wqec, &wqe->abort_cmd.wqe_com, 1);
11184 	bf_set(wqe_cqid, &wqe->abort_cmd.wqe_com, cqid);
11185 	bf_set(wqe_cmd_type, &wqe->abort_cmd.wqe_com, OTHER_COMMAND);
11186 }
11187 
11188 void
11189 lpfc_sli_prep_abort_xri(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11190 			u16 ulp_context, u16 iotag, u8 ulp_class, u16 cqid,
11191 			bool ia, bool wqec)
11192 {
11193 	phba->__lpfc_sli_prep_abort_xri(cmdiocbq, ulp_context, iotag, ulp_class,
11194 					cqid, ia, wqec);
11195 }
11196 
11197 /**
11198  * lpfc_sli_api_table_setup - Set up sli api function jump table
11199  * @phba: The hba struct for which this call is being executed.
11200  * @dev_grp: The HBA PCI-Device group number.
11201  *
11202  * This routine sets up the SLI interface API function jump table in @phba
11203  * struct.
11204  * Returns: 0 - success, -ENODEV - failure.
11205  **/
11206 int
11207 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
11208 {
11209 
11210 	switch (dev_grp) {
11211 	case LPFC_PCI_DEV_LP:
11212 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
11213 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
11214 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
11215 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s3;
11216 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s3;
11217 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s3;
11218 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s3;
11219 		break;
11220 	case LPFC_PCI_DEV_OC:
11221 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
11222 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
11223 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
11224 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s4;
11225 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s4;
11226 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s4;
11227 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s4;
11228 		break;
11229 	default:
11230 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11231 				"1419 Invalid HBA PCI-device group: 0x%x\n",
11232 				dev_grp);
11233 		return -ENODEV;
11234 	}
11235 	return 0;
11236 }
11237 
11238 /**
11239  * lpfc_sli4_calc_ring - Calculates which ring to use
11240  * @phba: Pointer to HBA context object.
11241  * @piocb: Pointer to command iocb.
11242  *
11243  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
11244  * hba_wqidx, thus we need to calculate the corresponding ring.
11245  * Since ABORTS must go on the same WQ of the command they are
11246  * aborting, we use command's hba_wqidx.
11247  */
11248 struct lpfc_sli_ring *
11249 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
11250 {
11251 	struct lpfc_io_buf *lpfc_cmd;
11252 
11253 	if (piocb->cmd_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
11254 		if (unlikely(!phba->sli4_hba.hdwq))
11255 			return NULL;
11256 		/*
11257 		 * for abort iocb hba_wqidx should already
11258 		 * be setup based on what work queue we used.
11259 		 */
11260 		if (!(piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
11261 			lpfc_cmd = piocb->io_buf;
11262 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
11263 		}
11264 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
11265 	} else {
11266 		if (unlikely(!phba->sli4_hba.els_wq))
11267 			return NULL;
11268 		piocb->hba_wqidx = 0;
11269 		return phba->sli4_hba.els_wq->pring;
11270 	}
11271 }
11272 
11273 /**
11274  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
11275  * @phba: Pointer to HBA context object.
11276  * @ring_number: Ring number
11277  * @piocb: Pointer to command iocb.
11278  * @flag: Flag indicating if this command can be put into txq.
11279  *
11280  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
11281  * function. This function gets the hbalock and calls
11282  * __lpfc_sli_issue_iocb function and will return the error returned
11283  * by __lpfc_sli_issue_iocb function. This wrapper is used by
11284  * functions which do not hold hbalock.
11285  **/
11286 int
11287 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
11288 		    struct lpfc_iocbq *piocb, uint32_t flag)
11289 {
11290 	struct lpfc_sli_ring *pring;
11291 	struct lpfc_queue *eq;
11292 	unsigned long iflags;
11293 	int rc;
11294 
11295 	/* If the PCI channel is in offline state, do not post iocbs. */
11296 	if (unlikely(pci_channel_offline(phba->pcidev)))
11297 		return IOCB_ERROR;
11298 
11299 	if (phba->sli_rev == LPFC_SLI_REV4) {
11300 		lpfc_sli_prep_wqe(phba, piocb);
11301 
11302 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
11303 
11304 		pring = lpfc_sli4_calc_ring(phba, piocb);
11305 		if (unlikely(pring == NULL))
11306 			return IOCB_ERROR;
11307 
11308 		spin_lock_irqsave(&pring->ring_lock, iflags);
11309 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11310 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11311 
11312 		lpfc_sli4_poll_eq(eq, LPFC_POLL_FASTPATH);
11313 	} else {
11314 		/* For now, SLI2/3 will still use hbalock */
11315 		spin_lock_irqsave(&phba->hbalock, iflags);
11316 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11317 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11318 	}
11319 	return rc;
11320 }
11321 
11322 /**
11323  * lpfc_extra_ring_setup - Extra ring setup function
11324  * @phba: Pointer to HBA context object.
11325  *
11326  * This function is called while driver attaches with the
11327  * HBA to setup the extra ring. The extra ring is used
11328  * only when driver needs to support target mode functionality
11329  * or IP over FC functionalities.
11330  *
11331  * This function is called with no lock held. SLI3 only.
11332  **/
11333 static int
11334 lpfc_extra_ring_setup( struct lpfc_hba *phba)
11335 {
11336 	struct lpfc_sli *psli;
11337 	struct lpfc_sli_ring *pring;
11338 
11339 	psli = &phba->sli;
11340 
11341 	/* Adjust cmd/rsp ring iocb entries more evenly */
11342 
11343 	/* Take some away from the FCP ring */
11344 	pring = &psli->sli3_ring[LPFC_FCP_RING];
11345 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11346 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11347 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11348 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11349 
11350 	/* and give them to the extra ring */
11351 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
11352 
11353 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11354 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11355 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11356 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11357 
11358 	/* Setup default profile for this ring */
11359 	pring->iotag_max = 4096;
11360 	pring->num_mask = 1;
11361 	pring->prt[0].profile = 0;      /* Mask 0 */
11362 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
11363 	pring->prt[0].type = phba->cfg_multi_ring_type;
11364 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
11365 	return 0;
11366 }
11367 
11368 static void
11369 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
11370 			     struct lpfc_nodelist *ndlp)
11371 {
11372 	unsigned long iflags;
11373 	struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
11374 
11375 	spin_lock_irqsave(&phba->hbalock, iflags);
11376 	if (!list_empty(&evtp->evt_listp)) {
11377 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11378 		return;
11379 	}
11380 
11381 	/* Incrementing the reference count until the queued work is done. */
11382 	evtp->evt_arg1  = lpfc_nlp_get(ndlp);
11383 	if (!evtp->evt_arg1) {
11384 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11385 		return;
11386 	}
11387 	evtp->evt = LPFC_EVT_RECOVER_PORT;
11388 	list_add_tail(&evtp->evt_listp, &phba->work_list);
11389 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11390 
11391 	lpfc_worker_wake_up(phba);
11392 }
11393 
11394 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
11395  * @phba: Pointer to HBA context object.
11396  * @iocbq: Pointer to iocb object.
11397  *
11398  * The async_event handler calls this routine when it receives
11399  * an ASYNC_STATUS_CN event from the port.  The port generates
11400  * this event when an Abort Sequence request to an rport fails
11401  * twice in succession.  The abort could be originated by the
11402  * driver or by the port.  The ABTS could have been for an ELS
11403  * or FCP IO.  The port only generates this event when an ABTS
11404  * fails to complete after one retry.
11405  */
11406 static void
11407 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
11408 			  struct lpfc_iocbq *iocbq)
11409 {
11410 	struct lpfc_nodelist *ndlp = NULL;
11411 	uint16_t rpi = 0, vpi = 0;
11412 	struct lpfc_vport *vport = NULL;
11413 
11414 	/* The rpi in the ulpContext is vport-sensitive. */
11415 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
11416 	rpi = iocbq->iocb.ulpContext;
11417 
11418 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11419 			"3092 Port generated ABTS async event "
11420 			"on vpi %d rpi %d status 0x%x\n",
11421 			vpi, rpi, iocbq->iocb.ulpStatus);
11422 
11423 	vport = lpfc_find_vport_by_vpid(phba, vpi);
11424 	if (!vport)
11425 		goto err_exit;
11426 	ndlp = lpfc_findnode_rpi(vport, rpi);
11427 	if (!ndlp)
11428 		goto err_exit;
11429 
11430 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
11431 		lpfc_sli_abts_recover_port(vport, ndlp);
11432 	return;
11433 
11434  err_exit:
11435 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11436 			"3095 Event Context not found, no "
11437 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
11438 			vpi, rpi, iocbq->iocb.ulpStatus,
11439 			iocbq->iocb.ulpContext);
11440 }
11441 
11442 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
11443  * @phba: pointer to HBA context object.
11444  * @ndlp: nodelist pointer for the impacted rport.
11445  * @axri: pointer to the wcqe containing the failed exchange.
11446  *
11447  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
11448  * port.  The port generates this event when an abort exchange request to an
11449  * rport fails twice in succession with no reply.  The abort could be originated
11450  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
11451  */
11452 void
11453 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
11454 			   struct lpfc_nodelist *ndlp,
11455 			   struct sli4_wcqe_xri_aborted *axri)
11456 {
11457 	uint32_t ext_status = 0;
11458 
11459 	if (!ndlp) {
11460 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11461 				"3115 Node Context not found, driver "
11462 				"ignoring abts err event\n");
11463 		return;
11464 	}
11465 
11466 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11467 			"3116 Port generated FCP XRI ABORT event on "
11468 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
11469 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
11470 			bf_get(lpfc_wcqe_xa_xri, axri),
11471 			bf_get(lpfc_wcqe_xa_status, axri),
11472 			axri->parameter);
11473 
11474 	/*
11475 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
11476 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
11477 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
11478 	 */
11479 	ext_status = axri->parameter & IOERR_PARAM_MASK;
11480 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
11481 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
11482 		lpfc_sli_post_recovery_event(phba, ndlp);
11483 }
11484 
11485 /**
11486  * lpfc_sli_async_event_handler - ASYNC iocb handler function
11487  * @phba: Pointer to HBA context object.
11488  * @pring: Pointer to driver SLI ring object.
11489  * @iocbq: Pointer to iocb object.
11490  *
11491  * This function is called by the slow ring event handler
11492  * function when there is an ASYNC event iocb in the ring.
11493  * This function is called with no lock held.
11494  * Currently this function handles only temperature related
11495  * ASYNC events. The function decodes the temperature sensor
11496  * event message and posts events for the management applications.
11497  **/
11498 static void
11499 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
11500 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
11501 {
11502 	IOCB_t *icmd;
11503 	uint16_t evt_code;
11504 	struct temp_event temp_event_data;
11505 	struct Scsi_Host *shost;
11506 	uint32_t *iocb_w;
11507 
11508 	icmd = &iocbq->iocb;
11509 	evt_code = icmd->un.asyncstat.evt_code;
11510 
11511 	switch (evt_code) {
11512 	case ASYNC_TEMP_WARN:
11513 	case ASYNC_TEMP_SAFE:
11514 		temp_event_data.data = (uint32_t) icmd->ulpContext;
11515 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
11516 		if (evt_code == ASYNC_TEMP_WARN) {
11517 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
11518 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11519 				"0347 Adapter is very hot, please take "
11520 				"corrective action. temperature : %d Celsius\n",
11521 				(uint32_t) icmd->ulpContext);
11522 		} else {
11523 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
11524 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11525 				"0340 Adapter temperature is OK now. "
11526 				"temperature : %d Celsius\n",
11527 				(uint32_t) icmd->ulpContext);
11528 		}
11529 
11530 		/* Send temperature change event to applications */
11531 		shost = lpfc_shost_from_vport(phba->pport);
11532 		fc_host_post_vendor_event(shost, fc_get_event_number(),
11533 			sizeof(temp_event_data), (char *) &temp_event_data,
11534 			LPFC_NL_VENDOR_ID);
11535 		break;
11536 	case ASYNC_STATUS_CN:
11537 		lpfc_sli_abts_err_handler(phba, iocbq);
11538 		break;
11539 	default:
11540 		iocb_w = (uint32_t *) icmd;
11541 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11542 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
11543 			" evt_code 0x%x\n"
11544 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
11545 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
11546 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
11547 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
11548 			pring->ringno, icmd->un.asyncstat.evt_code,
11549 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
11550 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
11551 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
11552 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
11553 
11554 		break;
11555 	}
11556 }
11557 
11558 
11559 /**
11560  * lpfc_sli4_setup - SLI ring setup function
11561  * @phba: Pointer to HBA context object.
11562  *
11563  * lpfc_sli_setup sets up rings of the SLI interface with
11564  * number of iocbs per ring and iotags. This function is
11565  * called while driver attach to the HBA and before the
11566  * interrupts are enabled. So there is no need for locking.
11567  *
11568  * This function always returns 0.
11569  **/
11570 int
11571 lpfc_sli4_setup(struct lpfc_hba *phba)
11572 {
11573 	struct lpfc_sli_ring *pring;
11574 
11575 	pring = phba->sli4_hba.els_wq->pring;
11576 	pring->num_mask = LPFC_MAX_RING_MASK;
11577 	pring->prt[0].profile = 0;	/* Mask 0 */
11578 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11579 	pring->prt[0].type = FC_TYPE_ELS;
11580 	pring->prt[0].lpfc_sli_rcv_unsol_event =
11581 	    lpfc_els_unsol_event;
11582 	pring->prt[1].profile = 0;	/* Mask 1 */
11583 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
11584 	pring->prt[1].type = FC_TYPE_ELS;
11585 	pring->prt[1].lpfc_sli_rcv_unsol_event =
11586 	    lpfc_els_unsol_event;
11587 	pring->prt[2].profile = 0;	/* Mask 2 */
11588 	/* NameServer Inquiry */
11589 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11590 	/* NameServer */
11591 	pring->prt[2].type = FC_TYPE_CT;
11592 	pring->prt[2].lpfc_sli_rcv_unsol_event =
11593 	    lpfc_ct_unsol_event;
11594 	pring->prt[3].profile = 0;	/* Mask 3 */
11595 	/* NameServer response */
11596 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11597 	/* NameServer */
11598 	pring->prt[3].type = FC_TYPE_CT;
11599 	pring->prt[3].lpfc_sli_rcv_unsol_event =
11600 	    lpfc_ct_unsol_event;
11601 	return 0;
11602 }
11603 
11604 /**
11605  * lpfc_sli_setup - SLI ring setup function
11606  * @phba: Pointer to HBA context object.
11607  *
11608  * lpfc_sli_setup sets up rings of the SLI interface with
11609  * number of iocbs per ring and iotags. This function is
11610  * called while driver attach to the HBA and before the
11611  * interrupts are enabled. So there is no need for locking.
11612  *
11613  * This function always returns 0. SLI3 only.
11614  **/
11615 int
11616 lpfc_sli_setup(struct lpfc_hba *phba)
11617 {
11618 	int i, totiocbsize = 0;
11619 	struct lpfc_sli *psli = &phba->sli;
11620 	struct lpfc_sli_ring *pring;
11621 
11622 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
11623 	psli->sli_flag = 0;
11624 
11625 	psli->iocbq_lookup = NULL;
11626 	psli->iocbq_lookup_len = 0;
11627 	psli->last_iotag = 0;
11628 
11629 	for (i = 0; i < psli->num_rings; i++) {
11630 		pring = &psli->sli3_ring[i];
11631 		switch (i) {
11632 		case LPFC_FCP_RING:	/* ring 0 - FCP */
11633 			/* numCiocb and numRiocb are used in config_port */
11634 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
11635 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
11636 			pring->sli.sli3.numCiocb +=
11637 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11638 			pring->sli.sli3.numRiocb +=
11639 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11640 			pring->sli.sli3.numCiocb +=
11641 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11642 			pring->sli.sli3.numRiocb +=
11643 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11644 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11645 							SLI3_IOCB_CMD_SIZE :
11646 							SLI2_IOCB_CMD_SIZE;
11647 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11648 							SLI3_IOCB_RSP_SIZE :
11649 							SLI2_IOCB_RSP_SIZE;
11650 			pring->iotag_ctr = 0;
11651 			pring->iotag_max =
11652 			    (phba->cfg_hba_queue_depth * 2);
11653 			pring->fast_iotag = pring->iotag_max;
11654 			pring->num_mask = 0;
11655 			break;
11656 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
11657 			/* numCiocb and numRiocb are used in config_port */
11658 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
11659 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
11660 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11661 							SLI3_IOCB_CMD_SIZE :
11662 							SLI2_IOCB_CMD_SIZE;
11663 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11664 							SLI3_IOCB_RSP_SIZE :
11665 							SLI2_IOCB_RSP_SIZE;
11666 			pring->iotag_max = phba->cfg_hba_queue_depth;
11667 			pring->num_mask = 0;
11668 			break;
11669 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
11670 			/* numCiocb and numRiocb are used in config_port */
11671 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
11672 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
11673 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11674 							SLI3_IOCB_CMD_SIZE :
11675 							SLI2_IOCB_CMD_SIZE;
11676 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11677 							SLI3_IOCB_RSP_SIZE :
11678 							SLI2_IOCB_RSP_SIZE;
11679 			pring->fast_iotag = 0;
11680 			pring->iotag_ctr = 0;
11681 			pring->iotag_max = 4096;
11682 			pring->lpfc_sli_rcv_async_status =
11683 				lpfc_sli_async_event_handler;
11684 			pring->num_mask = LPFC_MAX_RING_MASK;
11685 			pring->prt[0].profile = 0;	/* Mask 0 */
11686 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11687 			pring->prt[0].type = FC_TYPE_ELS;
11688 			pring->prt[0].lpfc_sli_rcv_unsol_event =
11689 			    lpfc_els_unsol_event;
11690 			pring->prt[1].profile = 0;	/* Mask 1 */
11691 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
11692 			pring->prt[1].type = FC_TYPE_ELS;
11693 			pring->prt[1].lpfc_sli_rcv_unsol_event =
11694 			    lpfc_els_unsol_event;
11695 			pring->prt[2].profile = 0;	/* Mask 2 */
11696 			/* NameServer Inquiry */
11697 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11698 			/* NameServer */
11699 			pring->prt[2].type = FC_TYPE_CT;
11700 			pring->prt[2].lpfc_sli_rcv_unsol_event =
11701 			    lpfc_ct_unsol_event;
11702 			pring->prt[3].profile = 0;	/* Mask 3 */
11703 			/* NameServer response */
11704 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11705 			/* NameServer */
11706 			pring->prt[3].type = FC_TYPE_CT;
11707 			pring->prt[3].lpfc_sli_rcv_unsol_event =
11708 			    lpfc_ct_unsol_event;
11709 			break;
11710 		}
11711 		totiocbsize += (pring->sli.sli3.numCiocb *
11712 			pring->sli.sli3.sizeCiocb) +
11713 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
11714 	}
11715 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
11716 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
11717 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
11718 		       "SLI2 SLIM Data: x%x x%lx\n",
11719 		       phba->brd_no, totiocbsize,
11720 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
11721 	}
11722 	if (phba->cfg_multi_ring_support == 2)
11723 		lpfc_extra_ring_setup(phba);
11724 
11725 	return 0;
11726 }
11727 
11728 /**
11729  * lpfc_sli4_queue_init - Queue initialization function
11730  * @phba: Pointer to HBA context object.
11731  *
11732  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
11733  * ring. This function also initializes ring indices of each ring.
11734  * This function is called during the initialization of the SLI
11735  * interface of an HBA.
11736  * This function is called with no lock held and always returns
11737  * 1.
11738  **/
11739 void
11740 lpfc_sli4_queue_init(struct lpfc_hba *phba)
11741 {
11742 	struct lpfc_sli *psli;
11743 	struct lpfc_sli_ring *pring;
11744 	int i;
11745 
11746 	psli = &phba->sli;
11747 	spin_lock_irq(&phba->hbalock);
11748 	INIT_LIST_HEAD(&psli->mboxq);
11749 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11750 	/* Initialize list headers for txq and txcmplq as double linked lists */
11751 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
11752 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
11753 		pring->flag = 0;
11754 		pring->ringno = LPFC_FCP_RING;
11755 		pring->txcmplq_cnt = 0;
11756 		INIT_LIST_HEAD(&pring->txq);
11757 		INIT_LIST_HEAD(&pring->txcmplq);
11758 		INIT_LIST_HEAD(&pring->iocb_continueq);
11759 		spin_lock_init(&pring->ring_lock);
11760 	}
11761 	pring = phba->sli4_hba.els_wq->pring;
11762 	pring->flag = 0;
11763 	pring->ringno = LPFC_ELS_RING;
11764 	pring->txcmplq_cnt = 0;
11765 	INIT_LIST_HEAD(&pring->txq);
11766 	INIT_LIST_HEAD(&pring->txcmplq);
11767 	INIT_LIST_HEAD(&pring->iocb_continueq);
11768 	spin_lock_init(&pring->ring_lock);
11769 
11770 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11771 		pring = phba->sli4_hba.nvmels_wq->pring;
11772 		pring->flag = 0;
11773 		pring->ringno = LPFC_ELS_RING;
11774 		pring->txcmplq_cnt = 0;
11775 		INIT_LIST_HEAD(&pring->txq);
11776 		INIT_LIST_HEAD(&pring->txcmplq);
11777 		INIT_LIST_HEAD(&pring->iocb_continueq);
11778 		spin_lock_init(&pring->ring_lock);
11779 	}
11780 
11781 	spin_unlock_irq(&phba->hbalock);
11782 }
11783 
11784 /**
11785  * lpfc_sli_queue_init - Queue initialization function
11786  * @phba: Pointer to HBA context object.
11787  *
11788  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11789  * ring. This function also initializes ring indices of each ring.
11790  * This function is called during the initialization of the SLI
11791  * interface of an HBA.
11792  * This function is called with no lock held and always returns
11793  * 1.
11794  **/
11795 void
11796 lpfc_sli_queue_init(struct lpfc_hba *phba)
11797 {
11798 	struct lpfc_sli *psli;
11799 	struct lpfc_sli_ring *pring;
11800 	int i;
11801 
11802 	psli = &phba->sli;
11803 	spin_lock_irq(&phba->hbalock);
11804 	INIT_LIST_HEAD(&psli->mboxq);
11805 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11806 	/* Initialize list headers for txq and txcmplq as double linked lists */
11807 	for (i = 0; i < psli->num_rings; i++) {
11808 		pring = &psli->sli3_ring[i];
11809 		pring->ringno = i;
11810 		pring->sli.sli3.next_cmdidx  = 0;
11811 		pring->sli.sli3.local_getidx = 0;
11812 		pring->sli.sli3.cmdidx = 0;
11813 		INIT_LIST_HEAD(&pring->iocb_continueq);
11814 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11815 		INIT_LIST_HEAD(&pring->postbufq);
11816 		pring->flag = 0;
11817 		INIT_LIST_HEAD(&pring->txq);
11818 		INIT_LIST_HEAD(&pring->txcmplq);
11819 		spin_lock_init(&pring->ring_lock);
11820 	}
11821 	spin_unlock_irq(&phba->hbalock);
11822 }
11823 
11824 /**
11825  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11826  * @phba: Pointer to HBA context object.
11827  *
11828  * This routine flushes the mailbox command subsystem. It will unconditionally
11829  * flush all the mailbox commands in the three possible stages in the mailbox
11830  * command sub-system: pending mailbox command queue; the outstanding mailbox
11831  * command; and completed mailbox command queue. It is caller's responsibility
11832  * to make sure that the driver is in the proper state to flush the mailbox
11833  * command sub-system. Namely, the posting of mailbox commands into the
11834  * pending mailbox command queue from the various clients must be stopped;
11835  * either the HBA is in a state that it will never works on the outstanding
11836  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11837  * mailbox command has been completed.
11838  **/
11839 static void
11840 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11841 {
11842 	LIST_HEAD(completions);
11843 	struct lpfc_sli *psli = &phba->sli;
11844 	LPFC_MBOXQ_t *pmb;
11845 	unsigned long iflag;
11846 
11847 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11848 	local_bh_disable();
11849 
11850 	/* Flush all the mailbox commands in the mbox system */
11851 	spin_lock_irqsave(&phba->hbalock, iflag);
11852 
11853 	/* The pending mailbox command queue */
11854 	list_splice_init(&phba->sli.mboxq, &completions);
11855 	/* The outstanding active mailbox command */
11856 	if (psli->mbox_active) {
11857 		list_add_tail(&psli->mbox_active->list, &completions);
11858 		psli->mbox_active = NULL;
11859 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11860 	}
11861 	/* The completed mailbox command queue */
11862 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11863 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11864 
11865 	/* Enable softirqs again, done with phba->hbalock */
11866 	local_bh_enable();
11867 
11868 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11869 	while (!list_empty(&completions)) {
11870 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11871 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11872 		if (pmb->mbox_cmpl)
11873 			pmb->mbox_cmpl(phba, pmb);
11874 	}
11875 }
11876 
11877 /**
11878  * lpfc_sli_host_down - Vport cleanup function
11879  * @vport: Pointer to virtual port object.
11880  *
11881  * lpfc_sli_host_down is called to clean up the resources
11882  * associated with a vport before destroying virtual
11883  * port data structures.
11884  * This function does following operations:
11885  * - Free discovery resources associated with this virtual
11886  *   port.
11887  * - Free iocbs associated with this virtual port in
11888  *   the txq.
11889  * - Send abort for all iocb commands associated with this
11890  *   vport in txcmplq.
11891  *
11892  * This function is called with no lock held and always returns 1.
11893  **/
11894 int
11895 lpfc_sli_host_down(struct lpfc_vport *vport)
11896 {
11897 	LIST_HEAD(completions);
11898 	struct lpfc_hba *phba = vport->phba;
11899 	struct lpfc_sli *psli = &phba->sli;
11900 	struct lpfc_queue *qp = NULL;
11901 	struct lpfc_sli_ring *pring;
11902 	struct lpfc_iocbq *iocb, *next_iocb;
11903 	int i;
11904 	unsigned long flags = 0;
11905 	uint16_t prev_pring_flag;
11906 
11907 	lpfc_cleanup_discovery_resources(vport);
11908 
11909 	spin_lock_irqsave(&phba->hbalock, flags);
11910 
11911 	/*
11912 	 * Error everything on the txq since these iocbs
11913 	 * have not been given to the FW yet.
11914 	 * Also issue ABTS for everything on the txcmplq
11915 	 */
11916 	if (phba->sli_rev != LPFC_SLI_REV4) {
11917 		for (i = 0; i < psli->num_rings; i++) {
11918 			pring = &psli->sli3_ring[i];
11919 			prev_pring_flag = pring->flag;
11920 			/* Only slow rings */
11921 			if (pring->ringno == LPFC_ELS_RING) {
11922 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11923 				/* Set the lpfc data pending flag */
11924 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11925 			}
11926 			list_for_each_entry_safe(iocb, next_iocb,
11927 						 &pring->txq, list) {
11928 				if (iocb->vport != vport)
11929 					continue;
11930 				list_move_tail(&iocb->list, &completions);
11931 			}
11932 			list_for_each_entry_safe(iocb, next_iocb,
11933 						 &pring->txcmplq, list) {
11934 				if (iocb->vport != vport)
11935 					continue;
11936 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11937 							   NULL);
11938 			}
11939 			pring->flag = prev_pring_flag;
11940 		}
11941 	} else {
11942 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11943 			pring = qp->pring;
11944 			if (!pring)
11945 				continue;
11946 			if (pring == phba->sli4_hba.els_wq->pring) {
11947 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11948 				/* Set the lpfc data pending flag */
11949 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11950 			}
11951 			prev_pring_flag = pring->flag;
11952 			spin_lock(&pring->ring_lock);
11953 			list_for_each_entry_safe(iocb, next_iocb,
11954 						 &pring->txq, list) {
11955 				if (iocb->vport != vport)
11956 					continue;
11957 				list_move_tail(&iocb->list, &completions);
11958 			}
11959 			spin_unlock(&pring->ring_lock);
11960 			list_for_each_entry_safe(iocb, next_iocb,
11961 						 &pring->txcmplq, list) {
11962 				if (iocb->vport != vport)
11963 					continue;
11964 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11965 							   NULL);
11966 			}
11967 			pring->flag = prev_pring_flag;
11968 		}
11969 	}
11970 	spin_unlock_irqrestore(&phba->hbalock, flags);
11971 
11972 	/* Make sure HBA is alive */
11973 	lpfc_issue_hb_tmo(phba);
11974 
11975 	/* Cancel all the IOCBs from the completions list */
11976 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11977 			      IOERR_SLI_DOWN);
11978 	return 1;
11979 }
11980 
11981 /**
11982  * lpfc_sli_hba_down - Resource cleanup function for the HBA
11983  * @phba: Pointer to HBA context object.
11984  *
11985  * This function cleans up all iocb, buffers, mailbox commands
11986  * while shutting down the HBA. This function is called with no
11987  * lock held and always returns 1.
11988  * This function does the following to cleanup driver resources:
11989  * - Free discovery resources for each virtual port
11990  * - Cleanup any pending fabric iocbs
11991  * - Iterate through the iocb txq and free each entry
11992  *   in the list.
11993  * - Free up any buffer posted to the HBA
11994  * - Free mailbox commands in the mailbox queue.
11995  **/
11996 int
11997 lpfc_sli_hba_down(struct lpfc_hba *phba)
11998 {
11999 	LIST_HEAD(completions);
12000 	struct lpfc_sli *psli = &phba->sli;
12001 	struct lpfc_queue *qp = NULL;
12002 	struct lpfc_sli_ring *pring;
12003 	struct lpfc_dmabuf *buf_ptr;
12004 	unsigned long flags = 0;
12005 	int i;
12006 
12007 	/* Shutdown the mailbox command sub-system */
12008 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
12009 
12010 	lpfc_hba_down_prep(phba);
12011 
12012 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12013 	local_bh_disable();
12014 
12015 	lpfc_fabric_abort_hba(phba);
12016 
12017 	spin_lock_irqsave(&phba->hbalock, flags);
12018 
12019 	/*
12020 	 * Error everything on the txq since these iocbs
12021 	 * have not been given to the FW yet.
12022 	 */
12023 	if (phba->sli_rev != LPFC_SLI_REV4) {
12024 		for (i = 0; i < psli->num_rings; i++) {
12025 			pring = &psli->sli3_ring[i];
12026 			/* Only slow rings */
12027 			if (pring->ringno == LPFC_ELS_RING) {
12028 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12029 				/* Set the lpfc data pending flag */
12030 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12031 			}
12032 			list_splice_init(&pring->txq, &completions);
12033 		}
12034 	} else {
12035 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12036 			pring = qp->pring;
12037 			if (!pring)
12038 				continue;
12039 			spin_lock(&pring->ring_lock);
12040 			list_splice_init(&pring->txq, &completions);
12041 			spin_unlock(&pring->ring_lock);
12042 			if (pring == phba->sli4_hba.els_wq->pring) {
12043 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12044 				/* Set the lpfc data pending flag */
12045 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12046 			}
12047 		}
12048 	}
12049 	spin_unlock_irqrestore(&phba->hbalock, flags);
12050 
12051 	/* Cancel all the IOCBs from the completions list */
12052 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
12053 			      IOERR_SLI_DOWN);
12054 
12055 	spin_lock_irqsave(&phba->hbalock, flags);
12056 	list_splice_init(&phba->elsbuf, &completions);
12057 	phba->elsbuf_cnt = 0;
12058 	phba->elsbuf_prev_cnt = 0;
12059 	spin_unlock_irqrestore(&phba->hbalock, flags);
12060 
12061 	while (!list_empty(&completions)) {
12062 		list_remove_head(&completions, buf_ptr,
12063 			struct lpfc_dmabuf, list);
12064 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
12065 		kfree(buf_ptr);
12066 	}
12067 
12068 	/* Enable softirqs again, done with phba->hbalock */
12069 	local_bh_enable();
12070 
12071 	/* Return any active mbox cmds */
12072 	del_timer_sync(&psli->mbox_tmo);
12073 
12074 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
12075 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
12076 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
12077 
12078 	return 1;
12079 }
12080 
12081 /**
12082  * lpfc_sli_pcimem_bcopy - SLI memory copy function
12083  * @srcp: Source memory pointer.
12084  * @destp: Destination memory pointer.
12085  * @cnt: Number of words required to be copied.
12086  *
12087  * This function is used for copying data between driver memory
12088  * and the SLI memory. This function also changes the endianness
12089  * of each word if native endianness is different from SLI
12090  * endianness. This function can be called with or without
12091  * lock.
12092  **/
12093 void
12094 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
12095 {
12096 	uint32_t *src = srcp;
12097 	uint32_t *dest = destp;
12098 	uint32_t ldata;
12099 	int i;
12100 
12101 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
12102 		ldata = *src;
12103 		ldata = le32_to_cpu(ldata);
12104 		*dest = ldata;
12105 		src++;
12106 		dest++;
12107 	}
12108 }
12109 
12110 
12111 /**
12112  * lpfc_sli_bemem_bcopy - SLI memory copy function
12113  * @srcp: Source memory pointer.
12114  * @destp: Destination memory pointer.
12115  * @cnt: Number of words required to be copied.
12116  *
12117  * This function is used for copying data between a data structure
12118  * with big endian representation to local endianness.
12119  * This function can be called with or without lock.
12120  **/
12121 void
12122 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
12123 {
12124 	uint32_t *src = srcp;
12125 	uint32_t *dest = destp;
12126 	uint32_t ldata;
12127 	int i;
12128 
12129 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
12130 		ldata = *src;
12131 		ldata = be32_to_cpu(ldata);
12132 		*dest = ldata;
12133 		src++;
12134 		dest++;
12135 	}
12136 }
12137 
12138 /**
12139  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
12140  * @phba: Pointer to HBA context object.
12141  * @pring: Pointer to driver SLI ring object.
12142  * @mp: Pointer to driver buffer object.
12143  *
12144  * This function is called with no lock held.
12145  * It always return zero after adding the buffer to the postbufq
12146  * buffer list.
12147  **/
12148 int
12149 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12150 			 struct lpfc_dmabuf *mp)
12151 {
12152 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
12153 	   later */
12154 	spin_lock_irq(&phba->hbalock);
12155 	list_add_tail(&mp->list, &pring->postbufq);
12156 	pring->postbufq_cnt++;
12157 	spin_unlock_irq(&phba->hbalock);
12158 	return 0;
12159 }
12160 
12161 /**
12162  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
12163  * @phba: Pointer to HBA context object.
12164  *
12165  * When HBQ is enabled, buffers are searched based on tags. This function
12166  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
12167  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
12168  * does not conflict with tags of buffer posted for unsolicited events.
12169  * The function returns the allocated tag. The function is called with
12170  * no locks held.
12171  **/
12172 uint32_t
12173 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
12174 {
12175 	spin_lock_irq(&phba->hbalock);
12176 	phba->buffer_tag_count++;
12177 	/*
12178 	 * Always set the QUE_BUFTAG_BIT to distiguish between
12179 	 * a tag assigned by HBQ.
12180 	 */
12181 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
12182 	spin_unlock_irq(&phba->hbalock);
12183 	return phba->buffer_tag_count;
12184 }
12185 
12186 /**
12187  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
12188  * @phba: Pointer to HBA context object.
12189  * @pring: Pointer to driver SLI ring object.
12190  * @tag: Buffer tag.
12191  *
12192  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
12193  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
12194  * iocb is posted to the response ring with the tag of the buffer.
12195  * This function searches the pring->postbufq list using the tag
12196  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
12197  * iocb. If the buffer is found then lpfc_dmabuf object of the
12198  * buffer is returned to the caller else NULL is returned.
12199  * This function is called with no lock held.
12200  **/
12201 struct lpfc_dmabuf *
12202 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12203 			uint32_t tag)
12204 {
12205 	struct lpfc_dmabuf *mp, *next_mp;
12206 	struct list_head *slp = &pring->postbufq;
12207 
12208 	/* Search postbufq, from the beginning, looking for a match on tag */
12209 	spin_lock_irq(&phba->hbalock);
12210 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12211 		if (mp->buffer_tag == tag) {
12212 			list_del_init(&mp->list);
12213 			pring->postbufq_cnt--;
12214 			spin_unlock_irq(&phba->hbalock);
12215 			return mp;
12216 		}
12217 	}
12218 
12219 	spin_unlock_irq(&phba->hbalock);
12220 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12221 			"0402 Cannot find virtual addr for buffer tag on "
12222 			"ring %d Data x%lx x%px x%px x%x\n",
12223 			pring->ringno, (unsigned long) tag,
12224 			slp->next, slp->prev, pring->postbufq_cnt);
12225 
12226 	return NULL;
12227 }
12228 
12229 /**
12230  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
12231  * @phba: Pointer to HBA context object.
12232  * @pring: Pointer to driver SLI ring object.
12233  * @phys: DMA address of the buffer.
12234  *
12235  * This function searches the buffer list using the dma_address
12236  * of unsolicited event to find the driver's lpfc_dmabuf object
12237  * corresponding to the dma_address. The function returns the
12238  * lpfc_dmabuf object if a buffer is found else it returns NULL.
12239  * This function is called by the ct and els unsolicited event
12240  * handlers to get the buffer associated with the unsolicited
12241  * event.
12242  *
12243  * This function is called with no lock held.
12244  **/
12245 struct lpfc_dmabuf *
12246 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12247 			 dma_addr_t phys)
12248 {
12249 	struct lpfc_dmabuf *mp, *next_mp;
12250 	struct list_head *slp = &pring->postbufq;
12251 
12252 	/* Search postbufq, from the beginning, looking for a match on phys */
12253 	spin_lock_irq(&phba->hbalock);
12254 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12255 		if (mp->phys == phys) {
12256 			list_del_init(&mp->list);
12257 			pring->postbufq_cnt--;
12258 			spin_unlock_irq(&phba->hbalock);
12259 			return mp;
12260 		}
12261 	}
12262 
12263 	spin_unlock_irq(&phba->hbalock);
12264 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12265 			"0410 Cannot find virtual addr for mapped buf on "
12266 			"ring %d Data x%llx x%px x%px x%x\n",
12267 			pring->ringno, (unsigned long long)phys,
12268 			slp->next, slp->prev, pring->postbufq_cnt);
12269 	return NULL;
12270 }
12271 
12272 /**
12273  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
12274  * @phba: Pointer to HBA context object.
12275  * @cmdiocb: Pointer to driver command iocb object.
12276  * @rspiocb: Pointer to driver response iocb object.
12277  *
12278  * This function is the completion handler for the abort iocbs for
12279  * ELS commands. This function is called from the ELS ring event
12280  * handler with no lock held. This function frees memory resources
12281  * associated with the abort iocb.
12282  **/
12283 static void
12284 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12285 			struct lpfc_iocbq *rspiocb)
12286 {
12287 	u32 ulp_status = get_job_ulpstatus(phba, rspiocb);
12288 	u32 ulp_word4 = get_job_word4(phba, rspiocb);
12289 	u8 cmnd = get_job_cmnd(phba, cmdiocb);
12290 
12291 	if (ulp_status) {
12292 		/*
12293 		 * Assume that the port already completed and returned, or
12294 		 * will return the iocb. Just Log the message.
12295 		 */
12296 		if (phba->sli_rev < LPFC_SLI_REV4) {
12297 			if (cmnd == CMD_ABORT_XRI_CX &&
12298 			    ulp_status == IOSTAT_LOCAL_REJECT &&
12299 			    ulp_word4 == IOERR_ABORT_REQUESTED) {
12300 				goto release_iocb;
12301 			}
12302 		}
12303 
12304 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
12305 				"0327 Cannot abort els iocb x%px "
12306 				"with io cmd xri %x abort tag : x%x, "
12307 				"abort status %x abort code %x\n",
12308 				cmdiocb, get_job_abtsiotag(phba, cmdiocb),
12309 				(phba->sli_rev == LPFC_SLI_REV4) ?
12310 				get_wqe_reqtag(cmdiocb) :
12311 				cmdiocb->iocb.un.acxri.abortContextTag,
12312 				ulp_status, ulp_word4);
12313 
12314 	}
12315 release_iocb:
12316 	lpfc_sli_release_iocbq(phba, cmdiocb);
12317 	return;
12318 }
12319 
12320 /**
12321  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
12322  * @phba: Pointer to HBA context object.
12323  * @cmdiocb: Pointer to driver command iocb object.
12324  * @rspiocb: Pointer to driver response iocb object.
12325  *
12326  * The function is called from SLI ring event handler with no
12327  * lock held. This function is the completion handler for ELS commands
12328  * which are aborted. The function frees memory resources used for
12329  * the aborted ELS commands.
12330  **/
12331 void
12332 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12333 		     struct lpfc_iocbq *rspiocb)
12334 {
12335 	struct lpfc_nodelist *ndlp = cmdiocb->ndlp;
12336 	IOCB_t *irsp;
12337 	LPFC_MBOXQ_t *mbox;
12338 	u32 ulp_command, ulp_status, ulp_word4, iotag;
12339 
12340 	ulp_command = get_job_cmnd(phba, cmdiocb);
12341 	ulp_status = get_job_ulpstatus(phba, rspiocb);
12342 	ulp_word4 = get_job_word4(phba, rspiocb);
12343 
12344 	if (phba->sli_rev == LPFC_SLI_REV4) {
12345 		iotag = get_wqe_reqtag(cmdiocb);
12346 	} else {
12347 		irsp = &rspiocb->iocb;
12348 		iotag = irsp->ulpIoTag;
12349 
12350 		/* It is possible a PLOGI_RJT for NPIV ports to get aborted.
12351 		 * The MBX_REG_LOGIN64 mbox command is freed back to the
12352 		 * mbox_mem_pool here.
12353 		 */
12354 		if (cmdiocb->context_un.mbox) {
12355 			mbox = cmdiocb->context_un.mbox;
12356 			lpfc_mbox_rsrc_cleanup(phba, mbox, MBOX_THD_UNLOCKED);
12357 			cmdiocb->context_un.mbox = NULL;
12358 		}
12359 	}
12360 
12361 	/* ELS cmd tag <ulpIoTag> completes */
12362 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
12363 			"0139 Ignoring ELS cmd code x%x completion Data: "
12364 			"x%x x%x x%x x%px\n",
12365 			ulp_command, ulp_status, ulp_word4, iotag,
12366 			cmdiocb->ndlp);
12367 	/*
12368 	 * Deref the ndlp after free_iocb. sli_release_iocb will access the ndlp
12369 	 * if exchange is busy.
12370 	 */
12371 	if (ulp_command == CMD_GEN_REQUEST64_CR)
12372 		lpfc_ct_free_iocb(phba, cmdiocb);
12373 	else
12374 		lpfc_els_free_iocb(phba, cmdiocb);
12375 
12376 	lpfc_nlp_put(ndlp);
12377 }
12378 
12379 /**
12380  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
12381  * @phba: Pointer to HBA context object.
12382  * @pring: Pointer to driver SLI ring object.
12383  * @cmdiocb: Pointer to driver command iocb object.
12384  * @cmpl: completion function.
12385  *
12386  * This function issues an abort iocb for the provided command iocb. In case
12387  * of unloading, the abort iocb will not be issued to commands on the ELS
12388  * ring. Instead, the callback function shall be changed to those commands
12389  * so that nothing happens when them finishes. This function is called with
12390  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
12391  * when the command iocb is an abort request.
12392  *
12393  **/
12394 int
12395 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12396 			   struct lpfc_iocbq *cmdiocb, void *cmpl)
12397 {
12398 	struct lpfc_vport *vport = cmdiocb->vport;
12399 	struct lpfc_iocbq *abtsiocbp;
12400 	int retval = IOCB_ERROR;
12401 	unsigned long iflags;
12402 	struct lpfc_nodelist *ndlp = NULL;
12403 	u32 ulp_command = get_job_cmnd(phba, cmdiocb);
12404 	u16 ulp_context, iotag;
12405 	bool ia;
12406 
12407 	/*
12408 	 * There are certain command types we don't want to abort.  And we
12409 	 * don't want to abort commands that are already in the process of
12410 	 * being aborted.
12411 	 */
12412 	if (ulp_command == CMD_ABORT_XRI_WQE ||
12413 	    ulp_command == CMD_ABORT_XRI_CN ||
12414 	    ulp_command == CMD_CLOSE_XRI_CN ||
12415 	    cmdiocb->cmd_flag & LPFC_DRIVER_ABORTED)
12416 		return IOCB_ABORTING;
12417 
12418 	if (!pring) {
12419 		if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12420 			cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12421 		else
12422 			cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12423 		return retval;
12424 	}
12425 
12426 	/*
12427 	 * If we're unloading, don't abort iocb on the ELS ring, but change
12428 	 * the callback so that nothing happens when it finishes.
12429 	 */
12430 	if ((vport->load_flag & FC_UNLOADING) &&
12431 	    pring->ringno == LPFC_ELS_RING) {
12432 		if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12433 			cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12434 		else
12435 			cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12436 		return retval;
12437 	}
12438 
12439 	/* issue ABTS for this IOCB based on iotag */
12440 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
12441 	if (abtsiocbp == NULL)
12442 		return IOCB_NORESOURCE;
12443 
12444 	/* This signals the response to set the correct status
12445 	 * before calling the completion handler
12446 	 */
12447 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
12448 
12449 	if (phba->sli_rev == LPFC_SLI_REV4) {
12450 		ulp_context = cmdiocb->sli4_xritag;
12451 		iotag = abtsiocbp->iotag;
12452 	} else {
12453 		iotag = cmdiocb->iocb.ulpIoTag;
12454 		if (pring->ringno == LPFC_ELS_RING) {
12455 			ndlp = cmdiocb->ndlp;
12456 			ulp_context = ndlp->nlp_rpi;
12457 		} else {
12458 			ulp_context = cmdiocb->iocb.ulpContext;
12459 		}
12460 	}
12461 
12462 	if (phba->link_state < LPFC_LINK_UP ||
12463 	    (phba->sli_rev == LPFC_SLI_REV4 &&
12464 	     phba->sli4_hba.link_state.status == LPFC_FC_LA_TYPE_LINK_DOWN) ||
12465 	    (phba->link_flag & LS_EXTERNAL_LOOPBACK))
12466 		ia = true;
12467 	else
12468 		ia = false;
12469 
12470 	lpfc_sli_prep_abort_xri(phba, abtsiocbp, ulp_context, iotag,
12471 				cmdiocb->iocb.ulpClass,
12472 				LPFC_WQE_CQ_ID_DEFAULT, ia, false);
12473 
12474 	abtsiocbp->vport = vport;
12475 
12476 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12477 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
12478 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
12479 		abtsiocbp->cmd_flag |= (LPFC_IO_FCP | LPFC_USE_FCPWQIDX);
12480 
12481 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
12482 		abtsiocbp->cmd_flag |= LPFC_IO_FOF;
12483 
12484 	if (cmpl)
12485 		abtsiocbp->cmd_cmpl = cmpl;
12486 	else
12487 		abtsiocbp->cmd_cmpl = lpfc_sli_abort_els_cmpl;
12488 	abtsiocbp->vport = vport;
12489 
12490 	if (phba->sli_rev == LPFC_SLI_REV4) {
12491 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
12492 		if (unlikely(pring == NULL))
12493 			goto abort_iotag_exit;
12494 		/* Note: both hbalock and ring_lock need to be set here */
12495 		spin_lock_irqsave(&pring->ring_lock, iflags);
12496 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12497 			abtsiocbp, 0);
12498 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
12499 	} else {
12500 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12501 			abtsiocbp, 0);
12502 	}
12503 
12504 abort_iotag_exit:
12505 
12506 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
12507 			 "0339 Abort IO XRI x%x, Original iotag x%x, "
12508 			 "abort tag x%x Cmdjob : x%px Abortjob : x%px "
12509 			 "retval x%x\n",
12510 			 ulp_context, (phba->sli_rev == LPFC_SLI_REV4) ?
12511 			 cmdiocb->iotag : iotag, iotag, cmdiocb, abtsiocbp,
12512 			 retval);
12513 	if (retval) {
12514 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
12515 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
12516 	}
12517 
12518 	/*
12519 	 * Caller to this routine should check for IOCB_ERROR
12520 	 * and handle it properly.  This routine no longer removes
12521 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
12522 	 */
12523 	return retval;
12524 }
12525 
12526 /**
12527  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
12528  * @phba: pointer to lpfc HBA data structure.
12529  *
12530  * This routine will abort all pending and outstanding iocbs to an HBA.
12531  **/
12532 void
12533 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
12534 {
12535 	struct lpfc_sli *psli = &phba->sli;
12536 	struct lpfc_sli_ring *pring;
12537 	struct lpfc_queue *qp = NULL;
12538 	int i;
12539 
12540 	if (phba->sli_rev != LPFC_SLI_REV4) {
12541 		for (i = 0; i < psli->num_rings; i++) {
12542 			pring = &psli->sli3_ring[i];
12543 			lpfc_sli_abort_iocb_ring(phba, pring);
12544 		}
12545 		return;
12546 	}
12547 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12548 		pring = qp->pring;
12549 		if (!pring)
12550 			continue;
12551 		lpfc_sli_abort_iocb_ring(phba, pring);
12552 	}
12553 }
12554 
12555 /**
12556  * lpfc_sli_validate_fcp_iocb_for_abort - filter iocbs appropriate for FCP aborts
12557  * @iocbq: Pointer to iocb object.
12558  * @vport: Pointer to driver virtual port object.
12559  *
12560  * This function acts as an iocb filter for functions which abort FCP iocbs.
12561  *
12562  * Return values
12563  * -ENODEV, if a null iocb or vport ptr is encountered
12564  * -EINVAL, if the iocb is not an FCP I/O, not on the TX cmpl queue, premarked as
12565  *          driver already started the abort process, or is an abort iocb itself
12566  * 0, passes criteria for aborting the FCP I/O iocb
12567  **/
12568 static int
12569 lpfc_sli_validate_fcp_iocb_for_abort(struct lpfc_iocbq *iocbq,
12570 				     struct lpfc_vport *vport)
12571 {
12572 	u8 ulp_command;
12573 
12574 	/* No null ptr vports */
12575 	if (!iocbq || iocbq->vport != vport)
12576 		return -ENODEV;
12577 
12578 	/* iocb must be for FCP IO, already exists on the TX cmpl queue,
12579 	 * can't be premarked as driver aborted, nor be an ABORT iocb itself
12580 	 */
12581 	ulp_command = get_job_cmnd(vport->phba, iocbq);
12582 	if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12583 	    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ) ||
12584 	    (iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12585 	    (ulp_command == CMD_ABORT_XRI_CN ||
12586 	     ulp_command == CMD_CLOSE_XRI_CN ||
12587 	     ulp_command == CMD_ABORT_XRI_WQE))
12588 		return -EINVAL;
12589 
12590 	return 0;
12591 }
12592 
12593 /**
12594  * lpfc_sli_validate_fcp_iocb - validate commands associated with a SCSI target
12595  * @iocbq: Pointer to driver iocb object.
12596  * @vport: Pointer to driver virtual port object.
12597  * @tgt_id: SCSI ID of the target.
12598  * @lun_id: LUN ID of the scsi device.
12599  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
12600  *
12601  * This function acts as an iocb filter for validating a lun/SCSI target/SCSI
12602  * host.
12603  *
12604  * It will return
12605  * 0 if the filtering criteria is met for the given iocb and will return
12606  * 1 if the filtering criteria is not met.
12607  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
12608  * given iocb is for the SCSI device specified by vport, tgt_id and
12609  * lun_id parameter.
12610  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
12611  * given iocb is for the SCSI target specified by vport and tgt_id
12612  * parameters.
12613  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
12614  * given iocb is for the SCSI host associated with the given vport.
12615  * This function is called with no locks held.
12616  **/
12617 static int
12618 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
12619 			   uint16_t tgt_id, uint64_t lun_id,
12620 			   lpfc_ctx_cmd ctx_cmd)
12621 {
12622 	struct lpfc_io_buf *lpfc_cmd;
12623 	int rc = 1;
12624 
12625 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12626 
12627 	if (lpfc_cmd->pCmd == NULL)
12628 		return rc;
12629 
12630 	switch (ctx_cmd) {
12631 	case LPFC_CTX_LUN:
12632 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12633 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
12634 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
12635 			rc = 0;
12636 		break;
12637 	case LPFC_CTX_TGT:
12638 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12639 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
12640 			rc = 0;
12641 		break;
12642 	case LPFC_CTX_HOST:
12643 		rc = 0;
12644 		break;
12645 	default:
12646 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
12647 			__func__, ctx_cmd);
12648 		break;
12649 	}
12650 
12651 	return rc;
12652 }
12653 
12654 /**
12655  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
12656  * @vport: Pointer to virtual port.
12657  * @tgt_id: SCSI ID of the target.
12658  * @lun_id: LUN ID of the scsi device.
12659  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12660  *
12661  * This function returns number of FCP commands pending for the vport.
12662  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
12663  * commands pending on the vport associated with SCSI device specified
12664  * by tgt_id and lun_id parameters.
12665  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
12666  * commands pending on the vport associated with SCSI target specified
12667  * by tgt_id parameter.
12668  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
12669  * commands pending on the vport.
12670  * This function returns the number of iocbs which satisfy the filter.
12671  * This function is called without any lock held.
12672  **/
12673 int
12674 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
12675 		  lpfc_ctx_cmd ctx_cmd)
12676 {
12677 	struct lpfc_hba *phba = vport->phba;
12678 	struct lpfc_iocbq *iocbq;
12679 	int sum, i;
12680 	unsigned long iflags;
12681 	u8 ulp_command;
12682 
12683 	spin_lock_irqsave(&phba->hbalock, iflags);
12684 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
12685 		iocbq = phba->sli.iocbq_lookup[i];
12686 
12687 		if (!iocbq || iocbq->vport != vport)
12688 			continue;
12689 		if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12690 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ))
12691 			continue;
12692 
12693 		/* Include counting outstanding aborts */
12694 		ulp_command = get_job_cmnd(phba, iocbq);
12695 		if (ulp_command == CMD_ABORT_XRI_CN ||
12696 		    ulp_command == CMD_CLOSE_XRI_CN ||
12697 		    ulp_command == CMD_ABORT_XRI_WQE) {
12698 			sum++;
12699 			continue;
12700 		}
12701 
12702 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12703 					       ctx_cmd) == 0)
12704 			sum++;
12705 	}
12706 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12707 
12708 	return sum;
12709 }
12710 
12711 /**
12712  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
12713  * @phba: Pointer to HBA context object
12714  * @cmdiocb: Pointer to command iocb object.
12715  * @rspiocb: Pointer to response iocb object.
12716  *
12717  * This function is called when an aborted FCP iocb completes. This
12718  * function is called by the ring event handler with no lock held.
12719  * This function frees the iocb.
12720  **/
12721 void
12722 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12723 			struct lpfc_iocbq *rspiocb)
12724 {
12725 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12726 			"3096 ABORT_XRI_CX completing on rpi x%x "
12727 			"original iotag x%x, abort cmd iotag x%x "
12728 			"status 0x%x, reason 0x%x\n",
12729 			(phba->sli_rev == LPFC_SLI_REV4) ?
12730 			cmdiocb->sli4_xritag :
12731 			cmdiocb->iocb.un.acxri.abortContextTag,
12732 			get_job_abtsiotag(phba, cmdiocb),
12733 			cmdiocb->iotag, get_job_ulpstatus(phba, rspiocb),
12734 			get_job_word4(phba, rspiocb));
12735 	lpfc_sli_release_iocbq(phba, cmdiocb);
12736 	return;
12737 }
12738 
12739 /**
12740  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
12741  * @vport: Pointer to virtual port.
12742  * @tgt_id: SCSI ID of the target.
12743  * @lun_id: LUN ID of the scsi device.
12744  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12745  *
12746  * This function sends an abort command for every SCSI command
12747  * associated with the given virtual port pending on the ring
12748  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12749  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12750  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12751  * followed by lpfc_sli_validate_fcp_iocb.
12752  *
12753  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
12754  * FCP iocbs associated with lun specified by tgt_id and lun_id
12755  * parameters
12756  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
12757  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12758  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
12759  * FCP iocbs associated with virtual port.
12760  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
12761  * lpfc_sli4_calc_ring is used.
12762  * This function returns number of iocbs it failed to abort.
12763  * This function is called with no locks held.
12764  **/
12765 int
12766 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
12767 		    lpfc_ctx_cmd abort_cmd)
12768 {
12769 	struct lpfc_hba *phba = vport->phba;
12770 	struct lpfc_sli_ring *pring = NULL;
12771 	struct lpfc_iocbq *iocbq;
12772 	int errcnt = 0, ret_val = 0;
12773 	unsigned long iflags;
12774 	int i;
12775 
12776 	/* all I/Os are in process of being flushed */
12777 	if (phba->hba_flag & HBA_IOQ_FLUSH)
12778 		return errcnt;
12779 
12780 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12781 		iocbq = phba->sli.iocbq_lookup[i];
12782 
12783 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12784 			continue;
12785 
12786 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12787 					       abort_cmd) != 0)
12788 			continue;
12789 
12790 		spin_lock_irqsave(&phba->hbalock, iflags);
12791 		if (phba->sli_rev == LPFC_SLI_REV3) {
12792 			pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12793 		} else if (phba->sli_rev == LPFC_SLI_REV4) {
12794 			pring = lpfc_sli4_calc_ring(phba, iocbq);
12795 		}
12796 		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
12797 						     lpfc_sli_abort_fcp_cmpl);
12798 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12799 		if (ret_val != IOCB_SUCCESS)
12800 			errcnt++;
12801 	}
12802 
12803 	return errcnt;
12804 }
12805 
12806 /**
12807  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12808  * @vport: Pointer to virtual port.
12809  * @pring: Pointer to driver SLI ring object.
12810  * @tgt_id: SCSI ID of the target.
12811  * @lun_id: LUN ID of the scsi device.
12812  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12813  *
12814  * This function sends an abort command for every SCSI command
12815  * associated with the given virtual port pending on the ring
12816  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12817  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12818  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12819  * followed by lpfc_sli_validate_fcp_iocb.
12820  *
12821  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12822  * FCP iocbs associated with lun specified by tgt_id and lun_id
12823  * parameters
12824  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12825  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12826  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12827  * FCP iocbs associated with virtual port.
12828  * This function returns number of iocbs it aborted .
12829  * This function is called with no locks held right after a taskmgmt
12830  * command is sent.
12831  **/
12832 int
12833 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12834 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12835 {
12836 	struct lpfc_hba *phba = vport->phba;
12837 	struct lpfc_io_buf *lpfc_cmd;
12838 	struct lpfc_iocbq *abtsiocbq;
12839 	struct lpfc_nodelist *ndlp = NULL;
12840 	struct lpfc_iocbq *iocbq;
12841 	int sum, i, ret_val;
12842 	unsigned long iflags;
12843 	struct lpfc_sli_ring *pring_s4 = NULL;
12844 	u16 ulp_context, iotag, cqid = LPFC_WQE_CQ_ID_DEFAULT;
12845 	bool ia;
12846 
12847 	spin_lock_irqsave(&phba->hbalock, iflags);
12848 
12849 	/* all I/Os are in process of being flushed */
12850 	if (phba->hba_flag & HBA_IOQ_FLUSH) {
12851 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12852 		return 0;
12853 	}
12854 	sum = 0;
12855 
12856 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12857 		iocbq = phba->sli.iocbq_lookup[i];
12858 
12859 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12860 			continue;
12861 
12862 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12863 					       cmd) != 0)
12864 			continue;
12865 
12866 		/* Guard against IO completion being called at same time */
12867 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12868 		spin_lock(&lpfc_cmd->buf_lock);
12869 
12870 		if (!lpfc_cmd->pCmd) {
12871 			spin_unlock(&lpfc_cmd->buf_lock);
12872 			continue;
12873 		}
12874 
12875 		if (phba->sli_rev == LPFC_SLI_REV4) {
12876 			pring_s4 =
12877 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12878 			if (!pring_s4) {
12879 				spin_unlock(&lpfc_cmd->buf_lock);
12880 				continue;
12881 			}
12882 			/* Note: both hbalock and ring_lock must be set here */
12883 			spin_lock(&pring_s4->ring_lock);
12884 		}
12885 
12886 		/*
12887 		 * If the iocbq is already being aborted, don't take a second
12888 		 * action, but do count it.
12889 		 */
12890 		if ((iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12891 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ)) {
12892 			if (phba->sli_rev == LPFC_SLI_REV4)
12893 				spin_unlock(&pring_s4->ring_lock);
12894 			spin_unlock(&lpfc_cmd->buf_lock);
12895 			continue;
12896 		}
12897 
12898 		/* issue ABTS for this IOCB based on iotag */
12899 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
12900 		if (!abtsiocbq) {
12901 			if (phba->sli_rev == LPFC_SLI_REV4)
12902 				spin_unlock(&pring_s4->ring_lock);
12903 			spin_unlock(&lpfc_cmd->buf_lock);
12904 			continue;
12905 		}
12906 
12907 		if (phba->sli_rev == LPFC_SLI_REV4) {
12908 			iotag = abtsiocbq->iotag;
12909 			ulp_context = iocbq->sli4_xritag;
12910 			cqid = lpfc_cmd->hdwq->io_cq_map;
12911 		} else {
12912 			iotag = iocbq->iocb.ulpIoTag;
12913 			if (pring->ringno == LPFC_ELS_RING) {
12914 				ndlp = iocbq->ndlp;
12915 				ulp_context = ndlp->nlp_rpi;
12916 			} else {
12917 				ulp_context = iocbq->iocb.ulpContext;
12918 			}
12919 		}
12920 
12921 		ndlp = lpfc_cmd->rdata->pnode;
12922 
12923 		if (lpfc_is_link_up(phba) &&
12924 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE) &&
12925 		    !(phba->link_flag & LS_EXTERNAL_LOOPBACK))
12926 			ia = false;
12927 		else
12928 			ia = true;
12929 
12930 		lpfc_sli_prep_abort_xri(phba, abtsiocbq, ulp_context, iotag,
12931 					iocbq->iocb.ulpClass, cqid,
12932 					ia, false);
12933 
12934 		abtsiocbq->vport = vport;
12935 
12936 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12937 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12938 		if (iocbq->cmd_flag & LPFC_IO_FCP)
12939 			abtsiocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
12940 		if (iocbq->cmd_flag & LPFC_IO_FOF)
12941 			abtsiocbq->cmd_flag |= LPFC_IO_FOF;
12942 
12943 		/* Setup callback routine and issue the command. */
12944 		abtsiocbq->cmd_cmpl = lpfc_sli_abort_fcp_cmpl;
12945 
12946 		/*
12947 		 * Indicate the IO is being aborted by the driver and set
12948 		 * the caller's flag into the aborted IO.
12949 		 */
12950 		iocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
12951 
12952 		if (phba->sli_rev == LPFC_SLI_REV4) {
12953 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
12954 							abtsiocbq, 0);
12955 			spin_unlock(&pring_s4->ring_lock);
12956 		} else {
12957 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
12958 							abtsiocbq, 0);
12959 		}
12960 
12961 		spin_unlock(&lpfc_cmd->buf_lock);
12962 
12963 		if (ret_val == IOCB_ERROR)
12964 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
12965 		else
12966 			sum++;
12967 	}
12968 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12969 	return sum;
12970 }
12971 
12972 /**
12973  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
12974  * @phba: Pointer to HBA context object.
12975  * @cmdiocbq: Pointer to command iocb.
12976  * @rspiocbq: Pointer to response iocb.
12977  *
12978  * This function is the completion handler for iocbs issued using
12979  * lpfc_sli_issue_iocb_wait function. This function is called by the
12980  * ring event handler function without any lock held. This function
12981  * can be called from both worker thread context and interrupt
12982  * context. This function also can be called from other thread which
12983  * cleans up the SLI layer objects.
12984  * This function copy the contents of the response iocb to the
12985  * response iocb memory object provided by the caller of
12986  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
12987  * sleeps for the iocb completion.
12988  **/
12989 static void
12990 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
12991 			struct lpfc_iocbq *cmdiocbq,
12992 			struct lpfc_iocbq *rspiocbq)
12993 {
12994 	wait_queue_head_t *pdone_q;
12995 	unsigned long iflags;
12996 	struct lpfc_io_buf *lpfc_cmd;
12997 	size_t offset = offsetof(struct lpfc_iocbq, wqe);
12998 
12999 	spin_lock_irqsave(&phba->hbalock, iflags);
13000 	if (cmdiocbq->cmd_flag & LPFC_IO_WAKE_TMO) {
13001 
13002 		/*
13003 		 * A time out has occurred for the iocb.  If a time out
13004 		 * completion handler has been supplied, call it.  Otherwise,
13005 		 * just free the iocbq.
13006 		 */
13007 
13008 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13009 		cmdiocbq->cmd_cmpl = cmdiocbq->wait_cmd_cmpl;
13010 		cmdiocbq->wait_cmd_cmpl = NULL;
13011 		if (cmdiocbq->cmd_cmpl)
13012 			cmdiocbq->cmd_cmpl(phba, cmdiocbq, NULL);
13013 		else
13014 			lpfc_sli_release_iocbq(phba, cmdiocbq);
13015 		return;
13016 	}
13017 
13018 	/* Copy the contents of the local rspiocb into the caller's buffer. */
13019 	cmdiocbq->cmd_flag |= LPFC_IO_WAKE;
13020 	if (cmdiocbq->rsp_iocb && rspiocbq)
13021 		memcpy((char *)cmdiocbq->rsp_iocb + offset,
13022 		       (char *)rspiocbq + offset, sizeof(*rspiocbq) - offset);
13023 
13024 	/* Set the exchange busy flag for task management commands */
13025 	if ((cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
13026 	    !(cmdiocbq->cmd_flag & LPFC_IO_LIBDFC)) {
13027 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
13028 					cur_iocbq);
13029 		if (rspiocbq && (rspiocbq->cmd_flag & LPFC_EXCHANGE_BUSY))
13030 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
13031 		else
13032 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
13033 	}
13034 
13035 	pdone_q = cmdiocbq->context_un.wait_queue;
13036 	if (pdone_q)
13037 		wake_up(pdone_q);
13038 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13039 	return;
13040 }
13041 
13042 /**
13043  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
13044  * @phba: Pointer to HBA context object..
13045  * @piocbq: Pointer to command iocb.
13046  * @flag: Flag to test.
13047  *
13048  * This routine grabs the hbalock and then test the cmd_flag to
13049  * see if the passed in flag is set.
13050  * Returns:
13051  * 1 if flag is set.
13052  * 0 if flag is not set.
13053  **/
13054 static int
13055 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
13056 		 struct lpfc_iocbq *piocbq, uint32_t flag)
13057 {
13058 	unsigned long iflags;
13059 	int ret;
13060 
13061 	spin_lock_irqsave(&phba->hbalock, iflags);
13062 	ret = piocbq->cmd_flag & flag;
13063 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13064 	return ret;
13065 
13066 }
13067 
13068 /**
13069  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
13070  * @phba: Pointer to HBA context object..
13071  * @ring_number: Ring number
13072  * @piocb: Pointer to command iocb.
13073  * @prspiocbq: Pointer to response iocb.
13074  * @timeout: Timeout in number of seconds.
13075  *
13076  * This function issues the iocb to firmware and waits for the
13077  * iocb to complete. The cmd_cmpl field of the shall be used
13078  * to handle iocbs which time out. If the field is NULL, the
13079  * function shall free the iocbq structure.  If more clean up is
13080  * needed, the caller is expected to provide a completion function
13081  * that will provide the needed clean up.  If the iocb command is
13082  * not completed within timeout seconds, the function will either
13083  * free the iocbq structure (if cmd_cmpl == NULL) or execute the
13084  * completion function set in the cmd_cmpl field and then return
13085  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
13086  * resources if this function returns IOCB_TIMEDOUT.
13087  * The function waits for the iocb completion using an
13088  * non-interruptible wait.
13089  * This function will sleep while waiting for iocb completion.
13090  * So, this function should not be called from any context which
13091  * does not allow sleeping. Due to the same reason, this function
13092  * cannot be called with interrupt disabled.
13093  * This function assumes that the iocb completions occur while
13094  * this function sleep. So, this function cannot be called from
13095  * the thread which process iocb completion for this ring.
13096  * This function clears the cmd_flag of the iocb object before
13097  * issuing the iocb and the iocb completion handler sets this
13098  * flag and wakes this thread when the iocb completes.
13099  * The contents of the response iocb will be copied to prspiocbq
13100  * by the completion handler when the command completes.
13101  * This function returns IOCB_SUCCESS when success.
13102  * This function is called with no lock held.
13103  **/
13104 int
13105 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
13106 			 uint32_t ring_number,
13107 			 struct lpfc_iocbq *piocb,
13108 			 struct lpfc_iocbq *prspiocbq,
13109 			 uint32_t timeout)
13110 {
13111 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
13112 	long timeleft, timeout_req = 0;
13113 	int retval = IOCB_SUCCESS;
13114 	uint32_t creg_val;
13115 	struct lpfc_iocbq *iocb;
13116 	int txq_cnt = 0;
13117 	int txcmplq_cnt = 0;
13118 	struct lpfc_sli_ring *pring;
13119 	unsigned long iflags;
13120 	bool iocb_completed = true;
13121 
13122 	if (phba->sli_rev >= LPFC_SLI_REV4) {
13123 		lpfc_sli_prep_wqe(phba, piocb);
13124 
13125 		pring = lpfc_sli4_calc_ring(phba, piocb);
13126 	} else
13127 		pring = &phba->sli.sli3_ring[ring_number];
13128 	/*
13129 	 * If the caller has provided a response iocbq buffer, then rsp_iocb
13130 	 * is NULL or its an error.
13131 	 */
13132 	if (prspiocbq) {
13133 		if (piocb->rsp_iocb)
13134 			return IOCB_ERROR;
13135 		piocb->rsp_iocb = prspiocbq;
13136 	}
13137 
13138 	piocb->wait_cmd_cmpl = piocb->cmd_cmpl;
13139 	piocb->cmd_cmpl = lpfc_sli_wake_iocb_wait;
13140 	piocb->context_un.wait_queue = &done_q;
13141 	piocb->cmd_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
13142 
13143 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13144 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13145 			return IOCB_ERROR;
13146 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
13147 		writel(creg_val, phba->HCregaddr);
13148 		readl(phba->HCregaddr); /* flush */
13149 	}
13150 
13151 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
13152 				     SLI_IOCB_RET_IOCB);
13153 	if (retval == IOCB_SUCCESS) {
13154 		timeout_req = msecs_to_jiffies(timeout * 1000);
13155 		timeleft = wait_event_timeout(done_q,
13156 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
13157 				timeout_req);
13158 		spin_lock_irqsave(&phba->hbalock, iflags);
13159 		if (!(piocb->cmd_flag & LPFC_IO_WAKE)) {
13160 
13161 			/*
13162 			 * IOCB timed out.  Inform the wake iocb wait
13163 			 * completion function and set local status
13164 			 */
13165 
13166 			iocb_completed = false;
13167 			piocb->cmd_flag |= LPFC_IO_WAKE_TMO;
13168 		}
13169 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13170 		if (iocb_completed) {
13171 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13172 					"0331 IOCB wake signaled\n");
13173 			/* Note: we are not indicating if the IOCB has a success
13174 			 * status or not - that's for the caller to check.
13175 			 * IOCB_SUCCESS means just that the command was sent and
13176 			 * completed. Not that it completed successfully.
13177 			 * */
13178 		} else if (timeleft == 0) {
13179 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13180 					"0338 IOCB wait timeout error - no "
13181 					"wake response Data x%x\n", timeout);
13182 			retval = IOCB_TIMEDOUT;
13183 		} else {
13184 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13185 					"0330 IOCB wake NOT set, "
13186 					"Data x%x x%lx\n",
13187 					timeout, (timeleft / jiffies));
13188 			retval = IOCB_TIMEDOUT;
13189 		}
13190 	} else if (retval == IOCB_BUSY) {
13191 		if (phba->cfg_log_verbose & LOG_SLI) {
13192 			list_for_each_entry(iocb, &pring->txq, list) {
13193 				txq_cnt++;
13194 			}
13195 			list_for_each_entry(iocb, &pring->txcmplq, list) {
13196 				txcmplq_cnt++;
13197 			}
13198 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13199 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
13200 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
13201 		}
13202 		return retval;
13203 	} else {
13204 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13205 				"0332 IOCB wait issue failed, Data x%x\n",
13206 				retval);
13207 		retval = IOCB_ERROR;
13208 	}
13209 
13210 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13211 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13212 			return IOCB_ERROR;
13213 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
13214 		writel(creg_val, phba->HCregaddr);
13215 		readl(phba->HCregaddr); /* flush */
13216 	}
13217 
13218 	if (prspiocbq)
13219 		piocb->rsp_iocb = NULL;
13220 
13221 	piocb->context_un.wait_queue = NULL;
13222 	piocb->cmd_cmpl = NULL;
13223 	return retval;
13224 }
13225 
13226 /**
13227  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
13228  * @phba: Pointer to HBA context object.
13229  * @pmboxq: Pointer to driver mailbox object.
13230  * @timeout: Timeout in number of seconds.
13231  *
13232  * This function issues the mailbox to firmware and waits for the
13233  * mailbox command to complete. If the mailbox command is not
13234  * completed within timeout seconds, it returns MBX_TIMEOUT.
13235  * The function waits for the mailbox completion using an
13236  * interruptible wait. If the thread is woken up due to a
13237  * signal, MBX_TIMEOUT error is returned to the caller. Caller
13238  * should not free the mailbox resources, if this function returns
13239  * MBX_TIMEOUT.
13240  * This function will sleep while waiting for mailbox completion.
13241  * So, this function should not be called from any context which
13242  * does not allow sleeping. Due to the same reason, this function
13243  * cannot be called with interrupt disabled.
13244  * This function assumes that the mailbox completion occurs while
13245  * this function sleep. So, this function cannot be called from
13246  * the worker thread which processes mailbox completion.
13247  * This function is called in the context of HBA management
13248  * applications.
13249  * This function returns MBX_SUCCESS when successful.
13250  * This function is called with no lock held.
13251  **/
13252 int
13253 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
13254 			 uint32_t timeout)
13255 {
13256 	struct completion mbox_done;
13257 	int retval;
13258 	unsigned long flag;
13259 
13260 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
13261 	/* setup wake call as IOCB callback */
13262 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
13263 
13264 	/* setup context3 field to pass wait_queue pointer to wake function  */
13265 	init_completion(&mbox_done);
13266 	pmboxq->context3 = &mbox_done;
13267 	/* now issue the command */
13268 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
13269 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
13270 		wait_for_completion_timeout(&mbox_done,
13271 					    msecs_to_jiffies(timeout * 1000));
13272 
13273 		spin_lock_irqsave(&phba->hbalock, flag);
13274 		pmboxq->context3 = NULL;
13275 		/*
13276 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
13277 		 * else do not free the resources.
13278 		 */
13279 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
13280 			retval = MBX_SUCCESS;
13281 		} else {
13282 			retval = MBX_TIMEOUT;
13283 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13284 		}
13285 		spin_unlock_irqrestore(&phba->hbalock, flag);
13286 	}
13287 	return retval;
13288 }
13289 
13290 /**
13291  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
13292  * @phba: Pointer to HBA context.
13293  * @mbx_action: Mailbox shutdown options.
13294  *
13295  * This function is called to shutdown the driver's mailbox sub-system.
13296  * It first marks the mailbox sub-system is in a block state to prevent
13297  * the asynchronous mailbox command from issued off the pending mailbox
13298  * command queue. If the mailbox command sub-system shutdown is due to
13299  * HBA error conditions such as EEH or ERATT, this routine shall invoke
13300  * the mailbox sub-system flush routine to forcefully bring down the
13301  * mailbox sub-system. Otherwise, if it is due to normal condition (such
13302  * as with offline or HBA function reset), this routine will wait for the
13303  * outstanding mailbox command to complete before invoking the mailbox
13304  * sub-system flush routine to gracefully bring down mailbox sub-system.
13305  **/
13306 void
13307 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
13308 {
13309 	struct lpfc_sli *psli = &phba->sli;
13310 	unsigned long timeout;
13311 
13312 	if (mbx_action == LPFC_MBX_NO_WAIT) {
13313 		/* delay 100ms for port state */
13314 		msleep(100);
13315 		lpfc_sli_mbox_sys_flush(phba);
13316 		return;
13317 	}
13318 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
13319 
13320 	/* Disable softirqs, including timers from obtaining phba->hbalock */
13321 	local_bh_disable();
13322 
13323 	spin_lock_irq(&phba->hbalock);
13324 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13325 
13326 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
13327 		/* Determine how long we might wait for the active mailbox
13328 		 * command to be gracefully completed by firmware.
13329 		 */
13330 		if (phba->sli.mbox_active)
13331 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
13332 						phba->sli.mbox_active) *
13333 						1000) + jiffies;
13334 		spin_unlock_irq(&phba->hbalock);
13335 
13336 		/* Enable softirqs again, done with phba->hbalock */
13337 		local_bh_enable();
13338 
13339 		while (phba->sli.mbox_active) {
13340 			/* Check active mailbox complete status every 2ms */
13341 			msleep(2);
13342 			if (time_after(jiffies, timeout))
13343 				/* Timeout, let the mailbox flush routine to
13344 				 * forcefully release active mailbox command
13345 				 */
13346 				break;
13347 		}
13348 	} else {
13349 		spin_unlock_irq(&phba->hbalock);
13350 
13351 		/* Enable softirqs again, done with phba->hbalock */
13352 		local_bh_enable();
13353 	}
13354 
13355 	lpfc_sli_mbox_sys_flush(phba);
13356 }
13357 
13358 /**
13359  * lpfc_sli_eratt_read - read sli-3 error attention events
13360  * @phba: Pointer to HBA context.
13361  *
13362  * This function is called to read the SLI3 device error attention registers
13363  * for possible error attention events. The caller must hold the hostlock
13364  * with spin_lock_irq().
13365  *
13366  * This function returns 1 when there is Error Attention in the Host Attention
13367  * Register and returns 0 otherwise.
13368  **/
13369 static int
13370 lpfc_sli_eratt_read(struct lpfc_hba *phba)
13371 {
13372 	uint32_t ha_copy;
13373 
13374 	/* Read chip Host Attention (HA) register */
13375 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
13376 		goto unplug_err;
13377 
13378 	if (ha_copy & HA_ERATT) {
13379 		/* Read host status register to retrieve error event */
13380 		if (lpfc_sli_read_hs(phba))
13381 			goto unplug_err;
13382 
13383 		/* Check if there is a deferred error condition is active */
13384 		if ((HS_FFER1 & phba->work_hs) &&
13385 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13386 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
13387 			phba->hba_flag |= DEFER_ERATT;
13388 			/* Clear all interrupt enable conditions */
13389 			writel(0, phba->HCregaddr);
13390 			readl(phba->HCregaddr);
13391 		}
13392 
13393 		/* Set the driver HA work bitmap */
13394 		phba->work_ha |= HA_ERATT;
13395 		/* Indicate polling handles this ERATT */
13396 		phba->hba_flag |= HBA_ERATT_HANDLED;
13397 		return 1;
13398 	}
13399 	return 0;
13400 
13401 unplug_err:
13402 	/* Set the driver HS work bitmap */
13403 	phba->work_hs |= UNPLUG_ERR;
13404 	/* Set the driver HA work bitmap */
13405 	phba->work_ha |= HA_ERATT;
13406 	/* Indicate polling handles this ERATT */
13407 	phba->hba_flag |= HBA_ERATT_HANDLED;
13408 	return 1;
13409 }
13410 
13411 /**
13412  * lpfc_sli4_eratt_read - read sli-4 error attention events
13413  * @phba: Pointer to HBA context.
13414  *
13415  * This function is called to read the SLI4 device error attention registers
13416  * for possible error attention events. The caller must hold the hostlock
13417  * with spin_lock_irq().
13418  *
13419  * This function returns 1 when there is Error Attention in the Host Attention
13420  * Register and returns 0 otherwise.
13421  **/
13422 static int
13423 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
13424 {
13425 	uint32_t uerr_sta_hi, uerr_sta_lo;
13426 	uint32_t if_type, portsmphr;
13427 	struct lpfc_register portstat_reg;
13428 	u32 logmask;
13429 
13430 	/*
13431 	 * For now, use the SLI4 device internal unrecoverable error
13432 	 * registers for error attention. This can be changed later.
13433 	 */
13434 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
13435 	switch (if_type) {
13436 	case LPFC_SLI_INTF_IF_TYPE_0:
13437 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
13438 			&uerr_sta_lo) ||
13439 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
13440 			&uerr_sta_hi)) {
13441 			phba->work_hs |= UNPLUG_ERR;
13442 			phba->work_ha |= HA_ERATT;
13443 			phba->hba_flag |= HBA_ERATT_HANDLED;
13444 			return 1;
13445 		}
13446 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
13447 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
13448 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13449 					"1423 HBA Unrecoverable error: "
13450 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
13451 					"ue_mask_lo_reg=0x%x, "
13452 					"ue_mask_hi_reg=0x%x\n",
13453 					uerr_sta_lo, uerr_sta_hi,
13454 					phba->sli4_hba.ue_mask_lo,
13455 					phba->sli4_hba.ue_mask_hi);
13456 			phba->work_status[0] = uerr_sta_lo;
13457 			phba->work_status[1] = uerr_sta_hi;
13458 			phba->work_ha |= HA_ERATT;
13459 			phba->hba_flag |= HBA_ERATT_HANDLED;
13460 			return 1;
13461 		}
13462 		break;
13463 	case LPFC_SLI_INTF_IF_TYPE_2:
13464 	case LPFC_SLI_INTF_IF_TYPE_6:
13465 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
13466 			&portstat_reg.word0) ||
13467 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
13468 			&portsmphr)){
13469 			phba->work_hs |= UNPLUG_ERR;
13470 			phba->work_ha |= HA_ERATT;
13471 			phba->hba_flag |= HBA_ERATT_HANDLED;
13472 			return 1;
13473 		}
13474 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
13475 			phba->work_status[0] =
13476 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
13477 			phba->work_status[1] =
13478 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
13479 			logmask = LOG_TRACE_EVENT;
13480 			if (phba->work_status[0] ==
13481 				SLIPORT_ERR1_REG_ERR_CODE_2 &&
13482 			    phba->work_status[1] == SLIPORT_ERR2_REG_FW_RESTART)
13483 				logmask = LOG_SLI;
13484 			lpfc_printf_log(phba, KERN_ERR, logmask,
13485 					"2885 Port Status Event: "
13486 					"port status reg 0x%x, "
13487 					"port smphr reg 0x%x, "
13488 					"error 1=0x%x, error 2=0x%x\n",
13489 					portstat_reg.word0,
13490 					portsmphr,
13491 					phba->work_status[0],
13492 					phba->work_status[1]);
13493 			phba->work_ha |= HA_ERATT;
13494 			phba->hba_flag |= HBA_ERATT_HANDLED;
13495 			return 1;
13496 		}
13497 		break;
13498 	case LPFC_SLI_INTF_IF_TYPE_1:
13499 	default:
13500 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13501 				"2886 HBA Error Attention on unsupported "
13502 				"if type %d.", if_type);
13503 		return 1;
13504 	}
13505 
13506 	return 0;
13507 }
13508 
13509 /**
13510  * lpfc_sli_check_eratt - check error attention events
13511  * @phba: Pointer to HBA context.
13512  *
13513  * This function is called from timer soft interrupt context to check HBA's
13514  * error attention register bit for error attention events.
13515  *
13516  * This function returns 1 when there is Error Attention in the Host Attention
13517  * Register and returns 0 otherwise.
13518  **/
13519 int
13520 lpfc_sli_check_eratt(struct lpfc_hba *phba)
13521 {
13522 	uint32_t ha_copy;
13523 
13524 	/* If somebody is waiting to handle an eratt, don't process it
13525 	 * here. The brdkill function will do this.
13526 	 */
13527 	if (phba->link_flag & LS_IGNORE_ERATT)
13528 		return 0;
13529 
13530 	/* Check if interrupt handler handles this ERATT */
13531 	spin_lock_irq(&phba->hbalock);
13532 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
13533 		/* Interrupt handler has handled ERATT */
13534 		spin_unlock_irq(&phba->hbalock);
13535 		return 0;
13536 	}
13537 
13538 	/*
13539 	 * If there is deferred error attention, do not check for error
13540 	 * attention
13541 	 */
13542 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13543 		spin_unlock_irq(&phba->hbalock);
13544 		return 0;
13545 	}
13546 
13547 	/* If PCI channel is offline, don't process it */
13548 	if (unlikely(pci_channel_offline(phba->pcidev))) {
13549 		spin_unlock_irq(&phba->hbalock);
13550 		return 0;
13551 	}
13552 
13553 	switch (phba->sli_rev) {
13554 	case LPFC_SLI_REV2:
13555 	case LPFC_SLI_REV3:
13556 		/* Read chip Host Attention (HA) register */
13557 		ha_copy = lpfc_sli_eratt_read(phba);
13558 		break;
13559 	case LPFC_SLI_REV4:
13560 		/* Read device Uncoverable Error (UERR) registers */
13561 		ha_copy = lpfc_sli4_eratt_read(phba);
13562 		break;
13563 	default:
13564 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13565 				"0299 Invalid SLI revision (%d)\n",
13566 				phba->sli_rev);
13567 		ha_copy = 0;
13568 		break;
13569 	}
13570 	spin_unlock_irq(&phba->hbalock);
13571 
13572 	return ha_copy;
13573 }
13574 
13575 /**
13576  * lpfc_intr_state_check - Check device state for interrupt handling
13577  * @phba: Pointer to HBA context.
13578  *
13579  * This inline routine checks whether a device or its PCI slot is in a state
13580  * that the interrupt should be handled.
13581  *
13582  * This function returns 0 if the device or the PCI slot is in a state that
13583  * interrupt should be handled, otherwise -EIO.
13584  */
13585 static inline int
13586 lpfc_intr_state_check(struct lpfc_hba *phba)
13587 {
13588 	/* If the pci channel is offline, ignore all the interrupts */
13589 	if (unlikely(pci_channel_offline(phba->pcidev)))
13590 		return -EIO;
13591 
13592 	/* Update device level interrupt statistics */
13593 	phba->sli.slistat.sli_intr++;
13594 
13595 	/* Ignore all interrupts during initialization. */
13596 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
13597 		return -EIO;
13598 
13599 	return 0;
13600 }
13601 
13602 /**
13603  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
13604  * @irq: Interrupt number.
13605  * @dev_id: The device context pointer.
13606  *
13607  * This function is directly called from the PCI layer as an interrupt
13608  * service routine when device with SLI-3 interface spec is enabled with
13609  * MSI-X multi-message interrupt mode and there are slow-path events in
13610  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
13611  * interrupt mode, this function is called as part of the device-level
13612  * interrupt handler. When the PCI slot is in error recovery or the HBA
13613  * is undergoing initialization, the interrupt handler will not process
13614  * the interrupt. The link attention and ELS ring attention events are
13615  * handled by the worker thread. The interrupt handler signals the worker
13616  * thread and returns for these events. This function is called without
13617  * any lock held. It gets the hbalock to access and update SLI data
13618  * structures.
13619  *
13620  * This function returns IRQ_HANDLED when interrupt is handled else it
13621  * returns IRQ_NONE.
13622  **/
13623 irqreturn_t
13624 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
13625 {
13626 	struct lpfc_hba  *phba;
13627 	uint32_t ha_copy, hc_copy;
13628 	uint32_t work_ha_copy;
13629 	unsigned long status;
13630 	unsigned long iflag;
13631 	uint32_t control;
13632 
13633 	MAILBOX_t *mbox, *pmbox;
13634 	struct lpfc_vport *vport;
13635 	struct lpfc_nodelist *ndlp;
13636 	struct lpfc_dmabuf *mp;
13637 	LPFC_MBOXQ_t *pmb;
13638 	int rc;
13639 
13640 	/*
13641 	 * Get the driver's phba structure from the dev_id and
13642 	 * assume the HBA is not interrupting.
13643 	 */
13644 	phba = (struct lpfc_hba *)dev_id;
13645 
13646 	if (unlikely(!phba))
13647 		return IRQ_NONE;
13648 
13649 	/*
13650 	 * Stuff needs to be attented to when this function is invoked as an
13651 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13652 	 */
13653 	if (phba->intr_type == MSIX) {
13654 		/* Check device state for handling interrupt */
13655 		if (lpfc_intr_state_check(phba))
13656 			return IRQ_NONE;
13657 		/* Need to read HA REG for slow-path events */
13658 		spin_lock_irqsave(&phba->hbalock, iflag);
13659 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13660 			goto unplug_error;
13661 		/* If somebody is waiting to handle an eratt don't process it
13662 		 * here. The brdkill function will do this.
13663 		 */
13664 		if (phba->link_flag & LS_IGNORE_ERATT)
13665 			ha_copy &= ~HA_ERATT;
13666 		/* Check the need for handling ERATT in interrupt handler */
13667 		if (ha_copy & HA_ERATT) {
13668 			if (phba->hba_flag & HBA_ERATT_HANDLED)
13669 				/* ERATT polling has handled ERATT */
13670 				ha_copy &= ~HA_ERATT;
13671 			else
13672 				/* Indicate interrupt handler handles ERATT */
13673 				phba->hba_flag |= HBA_ERATT_HANDLED;
13674 		}
13675 
13676 		/*
13677 		 * If there is deferred error attention, do not check for any
13678 		 * interrupt.
13679 		 */
13680 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13681 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13682 			return IRQ_NONE;
13683 		}
13684 
13685 		/* Clear up only attention source related to slow-path */
13686 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
13687 			goto unplug_error;
13688 
13689 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
13690 			HC_LAINT_ENA | HC_ERINT_ENA),
13691 			phba->HCregaddr);
13692 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
13693 			phba->HAregaddr);
13694 		writel(hc_copy, phba->HCregaddr);
13695 		readl(phba->HAregaddr); /* flush */
13696 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13697 	} else
13698 		ha_copy = phba->ha_copy;
13699 
13700 	work_ha_copy = ha_copy & phba->work_ha_mask;
13701 
13702 	if (work_ha_copy) {
13703 		if (work_ha_copy & HA_LATT) {
13704 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
13705 				/*
13706 				 * Turn off Link Attention interrupts
13707 				 * until CLEAR_LA done
13708 				 */
13709 				spin_lock_irqsave(&phba->hbalock, iflag);
13710 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
13711 				if (lpfc_readl(phba->HCregaddr, &control))
13712 					goto unplug_error;
13713 				control &= ~HC_LAINT_ENA;
13714 				writel(control, phba->HCregaddr);
13715 				readl(phba->HCregaddr); /* flush */
13716 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13717 			}
13718 			else
13719 				work_ha_copy &= ~HA_LATT;
13720 		}
13721 
13722 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
13723 			/*
13724 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
13725 			 * the only slow ring.
13726 			 */
13727 			status = (work_ha_copy &
13728 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
13729 			status >>= (4*LPFC_ELS_RING);
13730 			if (status & HA_RXMASK) {
13731 				spin_lock_irqsave(&phba->hbalock, iflag);
13732 				if (lpfc_readl(phba->HCregaddr, &control))
13733 					goto unplug_error;
13734 
13735 				lpfc_debugfs_slow_ring_trc(phba,
13736 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
13737 				control, status,
13738 				(uint32_t)phba->sli.slistat.sli_intr);
13739 
13740 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
13741 					lpfc_debugfs_slow_ring_trc(phba,
13742 						"ISR Disable ring:"
13743 						"pwork:x%x hawork:x%x wait:x%x",
13744 						phba->work_ha, work_ha_copy,
13745 						(uint32_t)((unsigned long)
13746 						&phba->work_waitq));
13747 
13748 					control &=
13749 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
13750 					writel(control, phba->HCregaddr);
13751 					readl(phba->HCregaddr); /* flush */
13752 				}
13753 				else {
13754 					lpfc_debugfs_slow_ring_trc(phba,
13755 						"ISR slow ring:   pwork:"
13756 						"x%x hawork:x%x wait:x%x",
13757 						phba->work_ha, work_ha_copy,
13758 						(uint32_t)((unsigned long)
13759 						&phba->work_waitq));
13760 				}
13761 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13762 			}
13763 		}
13764 		spin_lock_irqsave(&phba->hbalock, iflag);
13765 		if (work_ha_copy & HA_ERATT) {
13766 			if (lpfc_sli_read_hs(phba))
13767 				goto unplug_error;
13768 			/*
13769 			 * Check if there is a deferred error condition
13770 			 * is active
13771 			 */
13772 			if ((HS_FFER1 & phba->work_hs) &&
13773 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13774 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
13775 				  phba->work_hs)) {
13776 				phba->hba_flag |= DEFER_ERATT;
13777 				/* Clear all interrupt enable conditions */
13778 				writel(0, phba->HCregaddr);
13779 				readl(phba->HCregaddr);
13780 			}
13781 		}
13782 
13783 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
13784 			pmb = phba->sli.mbox_active;
13785 			pmbox = &pmb->u.mb;
13786 			mbox = phba->mbox;
13787 			vport = pmb->vport;
13788 
13789 			/* First check out the status word */
13790 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
13791 			if (pmbox->mbxOwner != OWN_HOST) {
13792 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13793 				/*
13794 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
13795 				 * mbxStatus <status>
13796 				 */
13797 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13798 						"(%d):0304 Stray Mailbox "
13799 						"Interrupt mbxCommand x%x "
13800 						"mbxStatus x%x\n",
13801 						(vport ? vport->vpi : 0),
13802 						pmbox->mbxCommand,
13803 						pmbox->mbxStatus);
13804 				/* clear mailbox attention bit */
13805 				work_ha_copy &= ~HA_MBATT;
13806 			} else {
13807 				phba->sli.mbox_active = NULL;
13808 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13809 				phba->last_completion_time = jiffies;
13810 				del_timer(&phba->sli.mbox_tmo);
13811 				if (pmb->mbox_cmpl) {
13812 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
13813 							MAILBOX_CMD_SIZE);
13814 					if (pmb->out_ext_byte_len &&
13815 						pmb->ctx_buf)
13816 						lpfc_sli_pcimem_bcopy(
13817 						phba->mbox_ext,
13818 						pmb->ctx_buf,
13819 						pmb->out_ext_byte_len);
13820 				}
13821 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13822 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13823 
13824 					lpfc_debugfs_disc_trc(vport,
13825 						LPFC_DISC_TRC_MBOX_VPORT,
13826 						"MBOX dflt rpi: : "
13827 						"status:x%x rpi:x%x",
13828 						(uint32_t)pmbox->mbxStatus,
13829 						pmbox->un.varWords[0], 0);
13830 
13831 					if (!pmbox->mbxStatus) {
13832 						mp = (struct lpfc_dmabuf *)
13833 							(pmb->ctx_buf);
13834 						ndlp = (struct lpfc_nodelist *)
13835 							pmb->ctx_ndlp;
13836 
13837 						/* Reg_LOGIN of dflt RPI was
13838 						 * successful. new lets get
13839 						 * rid of the RPI using the
13840 						 * same mbox buffer.
13841 						 */
13842 						lpfc_unreg_login(phba,
13843 							vport->vpi,
13844 							pmbox->un.varWords[0],
13845 							pmb);
13846 						pmb->mbox_cmpl =
13847 							lpfc_mbx_cmpl_dflt_rpi;
13848 						pmb->ctx_buf = mp;
13849 						pmb->ctx_ndlp = ndlp;
13850 						pmb->vport = vport;
13851 						rc = lpfc_sli_issue_mbox(phba,
13852 								pmb,
13853 								MBX_NOWAIT);
13854 						if (rc != MBX_BUSY)
13855 							lpfc_printf_log(phba,
13856 							KERN_ERR,
13857 							LOG_TRACE_EVENT,
13858 							"0350 rc should have"
13859 							"been MBX_BUSY\n");
13860 						if (rc != MBX_NOT_FINISHED)
13861 							goto send_current_mbox;
13862 					}
13863 				}
13864 				spin_lock_irqsave(
13865 						&phba->pport->work_port_lock,
13866 						iflag);
13867 				phba->pport->work_port_events &=
13868 					~WORKER_MBOX_TMO;
13869 				spin_unlock_irqrestore(
13870 						&phba->pport->work_port_lock,
13871 						iflag);
13872 
13873 				/* Do NOT queue MBX_HEARTBEAT to the worker
13874 				 * thread for processing.
13875 				 */
13876 				if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13877 					/* Process mbox now */
13878 					phba->sli.mbox_active = NULL;
13879 					phba->sli.sli_flag &=
13880 						~LPFC_SLI_MBOX_ACTIVE;
13881 					if (pmb->mbox_cmpl)
13882 						pmb->mbox_cmpl(phba, pmb);
13883 				} else {
13884 					/* Queue to worker thread to process */
13885 					lpfc_mbox_cmpl_put(phba, pmb);
13886 				}
13887 			}
13888 		} else
13889 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13890 
13891 		if ((work_ha_copy & HA_MBATT) &&
13892 		    (phba->sli.mbox_active == NULL)) {
13893 send_current_mbox:
13894 			/* Process next mailbox command if there is one */
13895 			do {
13896 				rc = lpfc_sli_issue_mbox(phba, NULL,
13897 							 MBX_NOWAIT);
13898 			} while (rc == MBX_NOT_FINISHED);
13899 			if (rc != MBX_SUCCESS)
13900 				lpfc_printf_log(phba, KERN_ERR,
13901 						LOG_TRACE_EVENT,
13902 						"0349 rc should be "
13903 						"MBX_SUCCESS\n");
13904 		}
13905 
13906 		spin_lock_irqsave(&phba->hbalock, iflag);
13907 		phba->work_ha |= work_ha_copy;
13908 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13909 		lpfc_worker_wake_up(phba);
13910 	}
13911 	return IRQ_HANDLED;
13912 unplug_error:
13913 	spin_unlock_irqrestore(&phba->hbalock, iflag);
13914 	return IRQ_HANDLED;
13915 
13916 } /* lpfc_sli_sp_intr_handler */
13917 
13918 /**
13919  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13920  * @irq: Interrupt number.
13921  * @dev_id: The device context pointer.
13922  *
13923  * This function is directly called from the PCI layer as an interrupt
13924  * service routine when device with SLI-3 interface spec is enabled with
13925  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13926  * ring event in the HBA. However, when the device is enabled with either
13927  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13928  * device-level interrupt handler. When the PCI slot is in error recovery
13929  * or the HBA is undergoing initialization, the interrupt handler will not
13930  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13931  * the intrrupt context. This function is called without any lock held.
13932  * It gets the hbalock to access and update SLI data structures.
13933  *
13934  * This function returns IRQ_HANDLED when interrupt is handled else it
13935  * returns IRQ_NONE.
13936  **/
13937 irqreturn_t
13938 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13939 {
13940 	struct lpfc_hba  *phba;
13941 	uint32_t ha_copy;
13942 	unsigned long status;
13943 	unsigned long iflag;
13944 	struct lpfc_sli_ring *pring;
13945 
13946 	/* Get the driver's phba structure from the dev_id and
13947 	 * assume the HBA is not interrupting.
13948 	 */
13949 	phba = (struct lpfc_hba *) dev_id;
13950 
13951 	if (unlikely(!phba))
13952 		return IRQ_NONE;
13953 
13954 	/*
13955 	 * Stuff needs to be attented to when this function is invoked as an
13956 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13957 	 */
13958 	if (phba->intr_type == MSIX) {
13959 		/* Check device state for handling interrupt */
13960 		if (lpfc_intr_state_check(phba))
13961 			return IRQ_NONE;
13962 		/* Need to read HA REG for FCP ring and other ring events */
13963 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13964 			return IRQ_HANDLED;
13965 		/* Clear up only attention source related to fast-path */
13966 		spin_lock_irqsave(&phba->hbalock, iflag);
13967 		/*
13968 		 * If there is deferred error attention, do not check for
13969 		 * any interrupt.
13970 		 */
13971 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13972 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13973 			return IRQ_NONE;
13974 		}
13975 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
13976 			phba->HAregaddr);
13977 		readl(phba->HAregaddr); /* flush */
13978 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13979 	} else
13980 		ha_copy = phba->ha_copy;
13981 
13982 	/*
13983 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
13984 	 */
13985 	ha_copy &= ~(phba->work_ha_mask);
13986 
13987 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13988 	status >>= (4*LPFC_FCP_RING);
13989 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
13990 	if (status & HA_RXMASK)
13991 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
13992 
13993 	if (phba->cfg_multi_ring_support == 2) {
13994 		/*
13995 		 * Process all events on extra ring. Take the optimized path
13996 		 * for extra ring IO.
13997 		 */
13998 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13999 		status >>= (4*LPFC_EXTRA_RING);
14000 		if (status & HA_RXMASK) {
14001 			lpfc_sli_handle_fast_ring_event(phba,
14002 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
14003 					status);
14004 		}
14005 	}
14006 	return IRQ_HANDLED;
14007 }  /* lpfc_sli_fp_intr_handler */
14008 
14009 /**
14010  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
14011  * @irq: Interrupt number.
14012  * @dev_id: The device context pointer.
14013  *
14014  * This function is the HBA device-level interrupt handler to device with
14015  * SLI-3 interface spec, called from the PCI layer when either MSI or
14016  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
14017  * requires driver attention. This function invokes the slow-path interrupt
14018  * attention handling function and fast-path interrupt attention handling
14019  * function in turn to process the relevant HBA attention events. This
14020  * function is called without any lock held. It gets the hbalock to access
14021  * and update SLI data structures.
14022  *
14023  * This function returns IRQ_HANDLED when interrupt is handled, else it
14024  * returns IRQ_NONE.
14025  **/
14026 irqreturn_t
14027 lpfc_sli_intr_handler(int irq, void *dev_id)
14028 {
14029 	struct lpfc_hba  *phba;
14030 	irqreturn_t sp_irq_rc, fp_irq_rc;
14031 	unsigned long status1, status2;
14032 	uint32_t hc_copy;
14033 
14034 	/*
14035 	 * Get the driver's phba structure from the dev_id and
14036 	 * assume the HBA is not interrupting.
14037 	 */
14038 	phba = (struct lpfc_hba *) dev_id;
14039 
14040 	if (unlikely(!phba))
14041 		return IRQ_NONE;
14042 
14043 	/* Check device state for handling interrupt */
14044 	if (lpfc_intr_state_check(phba))
14045 		return IRQ_NONE;
14046 
14047 	spin_lock(&phba->hbalock);
14048 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
14049 		spin_unlock(&phba->hbalock);
14050 		return IRQ_HANDLED;
14051 	}
14052 
14053 	if (unlikely(!phba->ha_copy)) {
14054 		spin_unlock(&phba->hbalock);
14055 		return IRQ_NONE;
14056 	} else if (phba->ha_copy & HA_ERATT) {
14057 		if (phba->hba_flag & HBA_ERATT_HANDLED)
14058 			/* ERATT polling has handled ERATT */
14059 			phba->ha_copy &= ~HA_ERATT;
14060 		else
14061 			/* Indicate interrupt handler handles ERATT */
14062 			phba->hba_flag |= HBA_ERATT_HANDLED;
14063 	}
14064 
14065 	/*
14066 	 * If there is deferred error attention, do not check for any interrupt.
14067 	 */
14068 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
14069 		spin_unlock(&phba->hbalock);
14070 		return IRQ_NONE;
14071 	}
14072 
14073 	/* Clear attention sources except link and error attentions */
14074 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
14075 		spin_unlock(&phba->hbalock);
14076 		return IRQ_HANDLED;
14077 	}
14078 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
14079 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
14080 		phba->HCregaddr);
14081 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
14082 	writel(hc_copy, phba->HCregaddr);
14083 	readl(phba->HAregaddr); /* flush */
14084 	spin_unlock(&phba->hbalock);
14085 
14086 	/*
14087 	 * Invokes slow-path host attention interrupt handling as appropriate.
14088 	 */
14089 
14090 	/* status of events with mailbox and link attention */
14091 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
14092 
14093 	/* status of events with ELS ring */
14094 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
14095 	status2 >>= (4*LPFC_ELS_RING);
14096 
14097 	if (status1 || (status2 & HA_RXMASK))
14098 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
14099 	else
14100 		sp_irq_rc = IRQ_NONE;
14101 
14102 	/*
14103 	 * Invoke fast-path host attention interrupt handling as appropriate.
14104 	 */
14105 
14106 	/* status of events with FCP ring */
14107 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
14108 	status1 >>= (4*LPFC_FCP_RING);
14109 
14110 	/* status of events with extra ring */
14111 	if (phba->cfg_multi_ring_support == 2) {
14112 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14113 		status2 >>= (4*LPFC_EXTRA_RING);
14114 	} else
14115 		status2 = 0;
14116 
14117 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
14118 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
14119 	else
14120 		fp_irq_rc = IRQ_NONE;
14121 
14122 	/* Return device-level interrupt handling status */
14123 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
14124 }  /* lpfc_sli_intr_handler */
14125 
14126 /**
14127  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
14128  * @phba: pointer to lpfc hba data structure.
14129  *
14130  * This routine is invoked by the worker thread to process all the pending
14131  * SLI4 els abort xri events.
14132  **/
14133 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
14134 {
14135 	struct lpfc_cq_event *cq_event;
14136 	unsigned long iflags;
14137 
14138 	/* First, declare the els xri abort event has been handled */
14139 	spin_lock_irqsave(&phba->hbalock, iflags);
14140 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
14141 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14142 
14143 	/* Now, handle all the els xri abort events */
14144 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14145 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
14146 		/* Get the first event from the head of the event queue */
14147 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
14148 				 cq_event, struct lpfc_cq_event, list);
14149 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14150 				       iflags);
14151 		/* Notify aborted XRI for ELS work queue */
14152 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
14153 
14154 		/* Free the event processed back to the free pool */
14155 		lpfc_sli4_cq_event_release(phba, cq_event);
14156 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14157 				  iflags);
14158 	}
14159 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14160 }
14161 
14162 /**
14163  * lpfc_sli4_els_preprocess_rspiocbq - Get response iocbq from els wcqe
14164  * @phba: Pointer to HBA context object.
14165  * @irspiocbq: Pointer to work-queue completion queue entry.
14166  *
14167  * This routine handles an ELS work-queue completion event and construct
14168  * a pseudo response ELS IOCBQ from the SLI4 ELS WCQE for the common
14169  * discovery engine to handle.
14170  *
14171  * Return: Pointer to the receive IOCBQ, NULL otherwise.
14172  **/
14173 static struct lpfc_iocbq *
14174 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
14175 				  struct lpfc_iocbq *irspiocbq)
14176 {
14177 	struct lpfc_sli_ring *pring;
14178 	struct lpfc_iocbq *cmdiocbq;
14179 	struct lpfc_wcqe_complete *wcqe;
14180 	unsigned long iflags;
14181 
14182 	pring = lpfc_phba_elsring(phba);
14183 	if (unlikely(!pring))
14184 		return NULL;
14185 
14186 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
14187 	spin_lock_irqsave(&pring->ring_lock, iflags);
14188 	pring->stats.iocb_event++;
14189 	/* Look up the ELS command IOCB and create pseudo response IOCB */
14190 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14191 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14192 	if (unlikely(!cmdiocbq)) {
14193 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
14194 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14195 				"0386 ELS complete with no corresponding "
14196 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
14197 				wcqe->word0, wcqe->total_data_placed,
14198 				wcqe->parameter, wcqe->word3);
14199 		lpfc_sli_release_iocbq(phba, irspiocbq);
14200 		return NULL;
14201 	}
14202 
14203 	memcpy(&irspiocbq->wqe, &cmdiocbq->wqe, sizeof(union lpfc_wqe128));
14204 	memcpy(&irspiocbq->wcqe_cmpl, wcqe, sizeof(*wcqe));
14205 
14206 	/* Put the iocb back on the txcmplq */
14207 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
14208 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
14209 
14210 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
14211 		spin_lock_irqsave(&phba->hbalock, iflags);
14212 		irspiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
14213 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14214 	}
14215 
14216 	return irspiocbq;
14217 }
14218 
14219 inline struct lpfc_cq_event *
14220 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
14221 {
14222 	struct lpfc_cq_event *cq_event;
14223 
14224 	/* Allocate a new internal CQ_EVENT entry */
14225 	cq_event = lpfc_sli4_cq_event_alloc(phba);
14226 	if (!cq_event) {
14227 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14228 				"0602 Failed to alloc CQ_EVENT entry\n");
14229 		return NULL;
14230 	}
14231 
14232 	/* Move the CQE into the event */
14233 	memcpy(&cq_event->cqe, entry, size);
14234 	return cq_event;
14235 }
14236 
14237 /**
14238  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
14239  * @phba: Pointer to HBA context object.
14240  * @mcqe: Pointer to mailbox completion queue entry.
14241  *
14242  * This routine process a mailbox completion queue entry with asynchronous
14243  * event.
14244  *
14245  * Return: true if work posted to worker thread, otherwise false.
14246  **/
14247 static bool
14248 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14249 {
14250 	struct lpfc_cq_event *cq_event;
14251 	unsigned long iflags;
14252 
14253 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14254 			"0392 Async Event: word0:x%x, word1:x%x, "
14255 			"word2:x%x, word3:x%x\n", mcqe->word0,
14256 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
14257 
14258 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
14259 	if (!cq_event)
14260 		return false;
14261 
14262 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
14263 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
14264 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
14265 
14266 	/* Set the async event flag */
14267 	spin_lock_irqsave(&phba->hbalock, iflags);
14268 	phba->hba_flag |= ASYNC_EVENT;
14269 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14270 
14271 	return true;
14272 }
14273 
14274 /**
14275  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
14276  * @phba: Pointer to HBA context object.
14277  * @mcqe: Pointer to mailbox completion queue entry.
14278  *
14279  * This routine process a mailbox completion queue entry with mailbox
14280  * completion event.
14281  *
14282  * Return: true if work posted to worker thread, otherwise false.
14283  **/
14284 static bool
14285 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14286 {
14287 	uint32_t mcqe_status;
14288 	MAILBOX_t *mbox, *pmbox;
14289 	struct lpfc_mqe *mqe;
14290 	struct lpfc_vport *vport;
14291 	struct lpfc_nodelist *ndlp;
14292 	struct lpfc_dmabuf *mp;
14293 	unsigned long iflags;
14294 	LPFC_MBOXQ_t *pmb;
14295 	bool workposted = false;
14296 	int rc;
14297 
14298 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
14299 	if (!bf_get(lpfc_trailer_completed, mcqe))
14300 		goto out_no_mqe_complete;
14301 
14302 	/* Get the reference to the active mbox command */
14303 	spin_lock_irqsave(&phba->hbalock, iflags);
14304 	pmb = phba->sli.mbox_active;
14305 	if (unlikely(!pmb)) {
14306 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14307 				"1832 No pending MBOX command to handle\n");
14308 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14309 		goto out_no_mqe_complete;
14310 	}
14311 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14312 	mqe = &pmb->u.mqe;
14313 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
14314 	mbox = phba->mbox;
14315 	vport = pmb->vport;
14316 
14317 	/* Reset heartbeat timer */
14318 	phba->last_completion_time = jiffies;
14319 	del_timer(&phba->sli.mbox_tmo);
14320 
14321 	/* Move mbox data to caller's mailbox region, do endian swapping */
14322 	if (pmb->mbox_cmpl && mbox)
14323 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
14324 
14325 	/*
14326 	 * For mcqe errors, conditionally move a modified error code to
14327 	 * the mbox so that the error will not be missed.
14328 	 */
14329 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
14330 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
14331 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
14332 			bf_set(lpfc_mqe_status, mqe,
14333 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
14334 	}
14335 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
14336 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
14337 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
14338 				      "MBOX dflt rpi: status:x%x rpi:x%x",
14339 				      mcqe_status,
14340 				      pmbox->un.varWords[0], 0);
14341 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
14342 			mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
14343 			ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
14344 
14345 			/* Reg_LOGIN of dflt RPI was successful. Mark the
14346 			 * node as having an UNREG_LOGIN in progress to stop
14347 			 * an unsolicited PLOGI from the same NPortId from
14348 			 * starting another mailbox transaction.
14349 			 */
14350 			spin_lock_irqsave(&ndlp->lock, iflags);
14351 			ndlp->nlp_flag |= NLP_UNREG_INP;
14352 			spin_unlock_irqrestore(&ndlp->lock, iflags);
14353 			lpfc_unreg_login(phba, vport->vpi,
14354 					 pmbox->un.varWords[0], pmb);
14355 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
14356 			pmb->ctx_buf = mp;
14357 
14358 			/* No reference taken here.  This is a default
14359 			 * RPI reg/immediate unreg cycle. The reference was
14360 			 * taken in the reg rpi path and is released when
14361 			 * this mailbox completes.
14362 			 */
14363 			pmb->ctx_ndlp = ndlp;
14364 			pmb->vport = vport;
14365 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
14366 			if (rc != MBX_BUSY)
14367 				lpfc_printf_log(phba, KERN_ERR,
14368 						LOG_TRACE_EVENT,
14369 						"0385 rc should "
14370 						"have been MBX_BUSY\n");
14371 			if (rc != MBX_NOT_FINISHED)
14372 				goto send_current_mbox;
14373 		}
14374 	}
14375 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
14376 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
14377 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
14378 
14379 	/* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
14380 	if (pmbox->mbxCommand == MBX_HEARTBEAT) {
14381 		spin_lock_irqsave(&phba->hbalock, iflags);
14382 		/* Release the mailbox command posting token */
14383 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14384 		phba->sli.mbox_active = NULL;
14385 		if (bf_get(lpfc_trailer_consumed, mcqe))
14386 			lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14387 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14388 
14389 		/* Post the next mbox command, if there is one */
14390 		lpfc_sli4_post_async_mbox(phba);
14391 
14392 		/* Process cmpl now */
14393 		if (pmb->mbox_cmpl)
14394 			pmb->mbox_cmpl(phba, pmb);
14395 		return false;
14396 	}
14397 
14398 	/* There is mailbox completion work to queue to the worker thread */
14399 	spin_lock_irqsave(&phba->hbalock, iflags);
14400 	__lpfc_mbox_cmpl_put(phba, pmb);
14401 	phba->work_ha |= HA_MBATT;
14402 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14403 	workposted = true;
14404 
14405 send_current_mbox:
14406 	spin_lock_irqsave(&phba->hbalock, iflags);
14407 	/* Release the mailbox command posting token */
14408 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14409 	/* Setting active mailbox pointer need to be in sync to flag clear */
14410 	phba->sli.mbox_active = NULL;
14411 	if (bf_get(lpfc_trailer_consumed, mcqe))
14412 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14413 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14414 	/* Wake up worker thread to post the next pending mailbox command */
14415 	lpfc_worker_wake_up(phba);
14416 	return workposted;
14417 
14418 out_no_mqe_complete:
14419 	spin_lock_irqsave(&phba->hbalock, iflags);
14420 	if (bf_get(lpfc_trailer_consumed, mcqe))
14421 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14422 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14423 	return false;
14424 }
14425 
14426 /**
14427  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
14428  * @phba: Pointer to HBA context object.
14429  * @cq: Pointer to associated CQ
14430  * @cqe: Pointer to mailbox completion queue entry.
14431  *
14432  * This routine process a mailbox completion queue entry, it invokes the
14433  * proper mailbox complete handling or asynchronous event handling routine
14434  * according to the MCQE's async bit.
14435  *
14436  * Return: true if work posted to worker thread, otherwise false.
14437  **/
14438 static bool
14439 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14440 			 struct lpfc_cqe *cqe)
14441 {
14442 	struct lpfc_mcqe mcqe;
14443 	bool workposted;
14444 
14445 	cq->CQ_mbox++;
14446 
14447 	/* Copy the mailbox MCQE and convert endian order as needed */
14448 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
14449 
14450 	/* Invoke the proper event handling routine */
14451 	if (!bf_get(lpfc_trailer_async, &mcqe))
14452 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
14453 	else
14454 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
14455 	return workposted;
14456 }
14457 
14458 /**
14459  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
14460  * @phba: Pointer to HBA context object.
14461  * @cq: Pointer to associated CQ
14462  * @wcqe: Pointer to work-queue completion queue entry.
14463  *
14464  * This routine handles an ELS work-queue completion event.
14465  *
14466  * Return: true if work posted to worker thread, otherwise false.
14467  **/
14468 static bool
14469 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14470 			     struct lpfc_wcqe_complete *wcqe)
14471 {
14472 	struct lpfc_iocbq *irspiocbq;
14473 	unsigned long iflags;
14474 	struct lpfc_sli_ring *pring = cq->pring;
14475 	int txq_cnt = 0;
14476 	int txcmplq_cnt = 0;
14477 
14478 	/* Check for response status */
14479 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14480 		/* Log the error status */
14481 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14482 				"0357 ELS CQE error: status=x%x: "
14483 				"CQE: %08x %08x %08x %08x\n",
14484 				bf_get(lpfc_wcqe_c_status, wcqe),
14485 				wcqe->word0, wcqe->total_data_placed,
14486 				wcqe->parameter, wcqe->word3);
14487 	}
14488 
14489 	/* Get an irspiocbq for later ELS response processing use */
14490 	irspiocbq = lpfc_sli_get_iocbq(phba);
14491 	if (!irspiocbq) {
14492 		if (!list_empty(&pring->txq))
14493 			txq_cnt++;
14494 		if (!list_empty(&pring->txcmplq))
14495 			txcmplq_cnt++;
14496 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14497 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
14498 			"els_txcmplq_cnt=%d\n",
14499 			txq_cnt, phba->iocb_cnt,
14500 			txcmplq_cnt);
14501 		return false;
14502 	}
14503 
14504 	/* Save off the slow-path queue event for work thread to process */
14505 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
14506 	spin_lock_irqsave(&phba->hbalock, iflags);
14507 	list_add_tail(&irspiocbq->cq_event.list,
14508 		      &phba->sli4_hba.sp_queue_event);
14509 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
14510 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14511 
14512 	return true;
14513 }
14514 
14515 /**
14516  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
14517  * @phba: Pointer to HBA context object.
14518  * @wcqe: Pointer to work-queue completion queue entry.
14519  *
14520  * This routine handles slow-path WQ entry consumed event by invoking the
14521  * proper WQ release routine to the slow-path WQ.
14522  **/
14523 static void
14524 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
14525 			     struct lpfc_wcqe_release *wcqe)
14526 {
14527 	/* sanity check on queue memory */
14528 	if (unlikely(!phba->sli4_hba.els_wq))
14529 		return;
14530 	/* Check for the slow-path ELS work queue */
14531 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
14532 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
14533 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14534 	else
14535 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14536 				"2579 Slow-path wqe consume event carries "
14537 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
14538 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
14539 				phba->sli4_hba.els_wq->queue_id);
14540 }
14541 
14542 /**
14543  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
14544  * @phba: Pointer to HBA context object.
14545  * @cq: Pointer to a WQ completion queue.
14546  * @wcqe: Pointer to work-queue completion queue entry.
14547  *
14548  * This routine handles an XRI abort event.
14549  *
14550  * Return: true if work posted to worker thread, otherwise false.
14551  **/
14552 static bool
14553 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
14554 				   struct lpfc_queue *cq,
14555 				   struct sli4_wcqe_xri_aborted *wcqe)
14556 {
14557 	bool workposted = false;
14558 	struct lpfc_cq_event *cq_event;
14559 	unsigned long iflags;
14560 
14561 	switch (cq->subtype) {
14562 	case LPFC_IO:
14563 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
14564 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14565 			/* Notify aborted XRI for NVME work queue */
14566 			if (phba->nvmet_support)
14567 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
14568 		}
14569 		workposted = false;
14570 		break;
14571 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
14572 	case LPFC_ELS:
14573 		cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
14574 		if (!cq_event) {
14575 			workposted = false;
14576 			break;
14577 		}
14578 		cq_event->hdwq = cq->hdwq;
14579 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14580 				  iflags);
14581 		list_add_tail(&cq_event->list,
14582 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
14583 		/* Set the els xri abort event flag */
14584 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
14585 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14586 				       iflags);
14587 		workposted = true;
14588 		break;
14589 	default:
14590 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14591 				"0603 Invalid CQ subtype %d: "
14592 				"%08x %08x %08x %08x\n",
14593 				cq->subtype, wcqe->word0, wcqe->parameter,
14594 				wcqe->word2, wcqe->word3);
14595 		workposted = false;
14596 		break;
14597 	}
14598 	return workposted;
14599 }
14600 
14601 #define FC_RCTL_MDS_DIAGS	0xF4
14602 
14603 /**
14604  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
14605  * @phba: Pointer to HBA context object.
14606  * @rcqe: Pointer to receive-queue completion queue entry.
14607  *
14608  * This routine process a receive-queue completion queue entry.
14609  *
14610  * Return: true if work posted to worker thread, otherwise false.
14611  **/
14612 static bool
14613 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
14614 {
14615 	bool workposted = false;
14616 	struct fc_frame_header *fc_hdr;
14617 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
14618 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
14619 	struct lpfc_nvmet_tgtport *tgtp;
14620 	struct hbq_dmabuf *dma_buf;
14621 	uint32_t status, rq_id;
14622 	unsigned long iflags;
14623 
14624 	/* sanity check on queue memory */
14625 	if (unlikely(!hrq) || unlikely(!drq))
14626 		return workposted;
14627 
14628 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14629 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14630 	else
14631 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14632 	if (rq_id != hrq->queue_id)
14633 		goto out;
14634 
14635 	status = bf_get(lpfc_rcqe_status, rcqe);
14636 	switch (status) {
14637 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14638 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14639 				"2537 Receive Frame Truncated!!\n");
14640 		fallthrough;
14641 	case FC_STATUS_RQ_SUCCESS:
14642 		spin_lock_irqsave(&phba->hbalock, iflags);
14643 		lpfc_sli4_rq_release(hrq, drq);
14644 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14645 		if (!dma_buf) {
14646 			hrq->RQ_no_buf_found++;
14647 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14648 			goto out;
14649 		}
14650 		hrq->RQ_rcv_buf++;
14651 		hrq->RQ_buf_posted--;
14652 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
14653 
14654 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14655 
14656 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
14657 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
14658 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14659 			/* Handle MDS Loopback frames */
14660 			if  (!(phba->pport->load_flag & FC_UNLOADING))
14661 				lpfc_sli4_handle_mds_loopback(phba->pport,
14662 							      dma_buf);
14663 			else
14664 				lpfc_in_buf_free(phba, &dma_buf->dbuf);
14665 			break;
14666 		}
14667 
14668 		/* save off the frame for the work thread to process */
14669 		list_add_tail(&dma_buf->cq_event.list,
14670 			      &phba->sli4_hba.sp_queue_event);
14671 		/* Frame received */
14672 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
14673 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14674 		workposted = true;
14675 		break;
14676 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14677 		if (phba->nvmet_support) {
14678 			tgtp = phba->targetport->private;
14679 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14680 					"6402 RQE Error x%x, posted %d err_cnt "
14681 					"%d: %x %x %x\n",
14682 					status, hrq->RQ_buf_posted,
14683 					hrq->RQ_no_posted_buf,
14684 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14685 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14686 					atomic_read(&tgtp->xmt_fcp_release));
14687 		}
14688 		fallthrough;
14689 
14690 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14691 		hrq->RQ_no_posted_buf++;
14692 		/* Post more buffers if possible */
14693 		spin_lock_irqsave(&phba->hbalock, iflags);
14694 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
14695 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14696 		workposted = true;
14697 		break;
14698 	}
14699 out:
14700 	return workposted;
14701 }
14702 
14703 /**
14704  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
14705  * @phba: Pointer to HBA context object.
14706  * @cq: Pointer to the completion queue.
14707  * @cqe: Pointer to a completion queue entry.
14708  *
14709  * This routine process a slow-path work-queue or receive queue completion queue
14710  * entry.
14711  *
14712  * Return: true if work posted to worker thread, otherwise false.
14713  **/
14714 static bool
14715 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14716 			 struct lpfc_cqe *cqe)
14717 {
14718 	struct lpfc_cqe cqevt;
14719 	bool workposted = false;
14720 
14721 	/* Copy the work queue CQE and convert endian order if needed */
14722 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14723 
14724 	/* Check and process for different type of WCQE and dispatch */
14725 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
14726 	case CQE_CODE_COMPL_WQE:
14727 		/* Process the WQ/RQ complete event */
14728 		phba->last_completion_time = jiffies;
14729 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14730 				(struct lpfc_wcqe_complete *)&cqevt);
14731 		break;
14732 	case CQE_CODE_RELEASE_WQE:
14733 		/* Process the WQ release event */
14734 		lpfc_sli4_sp_handle_rel_wcqe(phba,
14735 				(struct lpfc_wcqe_release *)&cqevt);
14736 		break;
14737 	case CQE_CODE_XRI_ABORTED:
14738 		/* Process the WQ XRI abort event */
14739 		phba->last_completion_time = jiffies;
14740 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14741 				(struct sli4_wcqe_xri_aborted *)&cqevt);
14742 		break;
14743 	case CQE_CODE_RECEIVE:
14744 	case CQE_CODE_RECEIVE_V1:
14745 		/* Process the RQ event */
14746 		phba->last_completion_time = jiffies;
14747 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
14748 				(struct lpfc_rcqe *)&cqevt);
14749 		break;
14750 	default:
14751 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14752 				"0388 Not a valid WCQE code: x%x\n",
14753 				bf_get(lpfc_cqe_code, &cqevt));
14754 		break;
14755 	}
14756 	return workposted;
14757 }
14758 
14759 /**
14760  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14761  * @phba: Pointer to HBA context object.
14762  * @eqe: Pointer to fast-path event queue entry.
14763  * @speq: Pointer to slow-path event queue.
14764  *
14765  * This routine process a event queue entry from the slow-path event queue.
14766  * It will check the MajorCode and MinorCode to determine this is for a
14767  * completion event on a completion queue, if not, an error shall be logged
14768  * and just return. Otherwise, it will get to the corresponding completion
14769  * queue and process all the entries on that completion queue, rearm the
14770  * completion queue, and then return.
14771  *
14772  **/
14773 static void
14774 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14775 	struct lpfc_queue *speq)
14776 {
14777 	struct lpfc_queue *cq = NULL, *childq;
14778 	uint16_t cqid;
14779 	int ret = 0;
14780 
14781 	/* Get the reference to the corresponding CQ */
14782 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14783 
14784 	list_for_each_entry(childq, &speq->child_list, list) {
14785 		if (childq->queue_id == cqid) {
14786 			cq = childq;
14787 			break;
14788 		}
14789 	}
14790 	if (unlikely(!cq)) {
14791 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14792 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14793 					"0365 Slow-path CQ identifier "
14794 					"(%d) does not exist\n", cqid);
14795 		return;
14796 	}
14797 
14798 	/* Save EQ associated with this CQ */
14799 	cq->assoc_qp = speq;
14800 
14801 	if (is_kdump_kernel())
14802 		ret = queue_work(phba->wq, &cq->spwork);
14803 	else
14804 		ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14805 
14806 	if (!ret)
14807 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14808 				"0390 Cannot schedule queue work "
14809 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14810 				cqid, cq->queue_id, raw_smp_processor_id());
14811 }
14812 
14813 /**
14814  * __lpfc_sli4_process_cq - Process elements of a CQ
14815  * @phba: Pointer to HBA context object.
14816  * @cq: Pointer to CQ to be processed
14817  * @handler: Routine to process each cqe
14818  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14819  * @poll_mode: Polling mode we were called from
14820  *
14821  * This routine processes completion queue entries in a CQ. While a valid
14822  * queue element is found, the handler is called. During processing checks
14823  * are made for periodic doorbell writes to let the hardware know of
14824  * element consumption.
14825  *
14826  * If the max limit on cqes to process is hit, or there are no more valid
14827  * entries, the loop stops. If we processed a sufficient number of elements,
14828  * meaning there is sufficient load, rather than rearming and generating
14829  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14830  * indicates no rescheduling.
14831  *
14832  * Returns True if work scheduled, False otherwise.
14833  **/
14834 static bool
14835 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14836 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14837 			struct lpfc_cqe *), unsigned long *delay,
14838 			enum lpfc_poll_mode poll_mode)
14839 {
14840 	struct lpfc_cqe *cqe;
14841 	bool workposted = false;
14842 	int count = 0, consumed = 0;
14843 	bool arm = true;
14844 
14845 	/* default - no reschedule */
14846 	*delay = 0;
14847 
14848 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14849 		goto rearm_and_exit;
14850 
14851 	/* Process all the entries to the CQ */
14852 	cq->q_flag = 0;
14853 	cqe = lpfc_sli4_cq_get(cq);
14854 	while (cqe) {
14855 		workposted |= handler(phba, cq, cqe);
14856 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
14857 
14858 		consumed++;
14859 		if (!(++count % cq->max_proc_limit))
14860 			break;
14861 
14862 		if (!(count % cq->notify_interval)) {
14863 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14864 						LPFC_QUEUE_NOARM);
14865 			consumed = 0;
14866 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14867 		}
14868 
14869 		if (count == LPFC_NVMET_CQ_NOTIFY)
14870 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14871 
14872 		cqe = lpfc_sli4_cq_get(cq);
14873 	}
14874 	if (count >= phba->cfg_cq_poll_threshold) {
14875 		*delay = 1;
14876 		arm = false;
14877 	}
14878 
14879 	/* Note: complete the irq_poll softirq before rearming CQ */
14880 	if (poll_mode == LPFC_IRQ_POLL)
14881 		irq_poll_complete(&cq->iop);
14882 
14883 	/* Track the max number of CQEs processed in 1 EQ */
14884 	if (count > cq->CQ_max_cqe)
14885 		cq->CQ_max_cqe = count;
14886 
14887 	cq->assoc_qp->EQ_cqe_cnt += count;
14888 
14889 	/* Catch the no cq entry condition */
14890 	if (unlikely(count == 0))
14891 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14892 				"0369 No entry from completion queue "
14893 				"qid=%d\n", cq->queue_id);
14894 
14895 	xchg(&cq->queue_claimed, 0);
14896 
14897 rearm_and_exit:
14898 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14899 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14900 
14901 	return workposted;
14902 }
14903 
14904 /**
14905  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14906  * @cq: pointer to CQ to process
14907  *
14908  * This routine calls the cq processing routine with a handler specific
14909  * to the type of queue bound to it.
14910  *
14911  * The CQ routine returns two values: the first is the calling status,
14912  * which indicates whether work was queued to the  background discovery
14913  * thread. If true, the routine should wakeup the discovery thread;
14914  * the second is the delay parameter. If non-zero, rather than rearming
14915  * the CQ and yet another interrupt, the CQ handler should be queued so
14916  * that it is processed in a subsequent polling action. The value of
14917  * the delay indicates when to reschedule it.
14918  **/
14919 static void
14920 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14921 {
14922 	struct lpfc_hba *phba = cq->phba;
14923 	unsigned long delay;
14924 	bool workposted = false;
14925 	int ret = 0;
14926 
14927 	/* Process and rearm the CQ */
14928 	switch (cq->type) {
14929 	case LPFC_MCQ:
14930 		workposted |= __lpfc_sli4_process_cq(phba, cq,
14931 						lpfc_sli4_sp_handle_mcqe,
14932 						&delay, LPFC_QUEUE_WORK);
14933 		break;
14934 	case LPFC_WCQ:
14935 		if (cq->subtype == LPFC_IO)
14936 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14937 						lpfc_sli4_fp_handle_cqe,
14938 						&delay, LPFC_QUEUE_WORK);
14939 		else
14940 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14941 						lpfc_sli4_sp_handle_cqe,
14942 						&delay, LPFC_QUEUE_WORK);
14943 		break;
14944 	default:
14945 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14946 				"0370 Invalid completion queue type (%d)\n",
14947 				cq->type);
14948 		return;
14949 	}
14950 
14951 	if (delay) {
14952 		if (is_kdump_kernel())
14953 			ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
14954 						delay);
14955 		else
14956 			ret = queue_delayed_work_on(cq->chann, phba->wq,
14957 						&cq->sched_spwork, delay);
14958 		if (!ret)
14959 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14960 				"0394 Cannot schedule queue work "
14961 				"for cqid=%d on CPU %d\n",
14962 				cq->queue_id, cq->chann);
14963 	}
14964 
14965 	/* wake up worker thread if there are works to be done */
14966 	if (workposted)
14967 		lpfc_worker_wake_up(phba);
14968 }
14969 
14970 /**
14971  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
14972  *   interrupt
14973  * @work: pointer to work element
14974  *
14975  * translates from the work handler and calls the slow-path handler.
14976  **/
14977 static void
14978 lpfc_sli4_sp_process_cq(struct work_struct *work)
14979 {
14980 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
14981 
14982 	__lpfc_sli4_sp_process_cq(cq);
14983 }
14984 
14985 /**
14986  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
14987  * @work: pointer to work element
14988  *
14989  * translates from the work handler and calls the slow-path handler.
14990  **/
14991 static void
14992 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
14993 {
14994 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
14995 					struct lpfc_queue, sched_spwork);
14996 
14997 	__lpfc_sli4_sp_process_cq(cq);
14998 }
14999 
15000 /**
15001  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
15002  * @phba: Pointer to HBA context object.
15003  * @cq: Pointer to associated CQ
15004  * @wcqe: Pointer to work-queue completion queue entry.
15005  *
15006  * This routine process a fast-path work queue completion entry from fast-path
15007  * event queue for FCP command response completion.
15008  **/
15009 static void
15010 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15011 			     struct lpfc_wcqe_complete *wcqe)
15012 {
15013 	struct lpfc_sli_ring *pring = cq->pring;
15014 	struct lpfc_iocbq *cmdiocbq;
15015 	unsigned long iflags;
15016 
15017 	/* Check for response status */
15018 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
15019 		/* If resource errors reported from HBA, reduce queue
15020 		 * depth of the SCSI device.
15021 		 */
15022 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
15023 		     IOSTAT_LOCAL_REJECT)) &&
15024 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
15025 		     IOERR_NO_RESOURCES))
15026 			phba->lpfc_rampdown_queue_depth(phba);
15027 
15028 		/* Log the cmpl status */
15029 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15030 				"0373 FCP CQE cmpl: status=x%x: "
15031 				"CQE: %08x %08x %08x %08x\n",
15032 				bf_get(lpfc_wcqe_c_status, wcqe),
15033 				wcqe->word0, wcqe->total_data_placed,
15034 				wcqe->parameter, wcqe->word3);
15035 	}
15036 
15037 	/* Look up the FCP command IOCB and create pseudo response IOCB */
15038 	spin_lock_irqsave(&pring->ring_lock, iflags);
15039 	pring->stats.iocb_event++;
15040 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
15041 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15042 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
15043 	if (unlikely(!cmdiocbq)) {
15044 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15045 				"0374 FCP complete with no corresponding "
15046 				"cmdiocb: iotag (%d)\n",
15047 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15048 		return;
15049 	}
15050 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
15051 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
15052 #endif
15053 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
15054 		spin_lock_irqsave(&phba->hbalock, iflags);
15055 		cmdiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
15056 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15057 	}
15058 
15059 	if (cmdiocbq->cmd_cmpl) {
15060 		/* For FCP the flag is cleared in cmd_cmpl */
15061 		if (!(cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
15062 		    cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED) {
15063 			spin_lock_irqsave(&phba->hbalock, iflags);
15064 			cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
15065 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15066 		}
15067 
15068 		/* Pass the cmd_iocb and the wcqe to the upper layer */
15069 		memcpy(&cmdiocbq->wcqe_cmpl, wcqe,
15070 		       sizeof(struct lpfc_wcqe_complete));
15071 		cmdiocbq->cmd_cmpl(phba, cmdiocbq, cmdiocbq);
15072 	} else {
15073 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15074 				"0375 FCP cmdiocb not callback function "
15075 				"iotag: (%d)\n",
15076 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15077 	}
15078 }
15079 
15080 /**
15081  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
15082  * @phba: Pointer to HBA context object.
15083  * @cq: Pointer to completion queue.
15084  * @wcqe: Pointer to work-queue completion queue entry.
15085  *
15086  * This routine handles an fast-path WQ entry consumed event by invoking the
15087  * proper WQ release routine to the slow-path WQ.
15088  **/
15089 static void
15090 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15091 			     struct lpfc_wcqe_release *wcqe)
15092 {
15093 	struct lpfc_queue *childwq;
15094 	bool wqid_matched = false;
15095 	uint16_t hba_wqid;
15096 
15097 	/* Check for fast-path FCP work queue release */
15098 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
15099 	list_for_each_entry(childwq, &cq->child_list, list) {
15100 		if (childwq->queue_id == hba_wqid) {
15101 			lpfc_sli4_wq_release(childwq,
15102 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
15103 			if (childwq->q_flag & HBA_NVMET_WQFULL)
15104 				lpfc_nvmet_wqfull_process(phba, childwq);
15105 			wqid_matched = true;
15106 			break;
15107 		}
15108 	}
15109 	/* Report warning log message if no match found */
15110 	if (wqid_matched != true)
15111 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15112 				"2580 Fast-path wqe consume event carries "
15113 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
15114 }
15115 
15116 /**
15117  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
15118  * @phba: Pointer to HBA context object.
15119  * @cq: Pointer to completion queue.
15120  * @rcqe: Pointer to receive-queue completion queue entry.
15121  *
15122  * This routine process a receive-queue completion queue entry.
15123  *
15124  * Return: true if work posted to worker thread, otherwise false.
15125  **/
15126 static bool
15127 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15128 			    struct lpfc_rcqe *rcqe)
15129 {
15130 	bool workposted = false;
15131 	struct lpfc_queue *hrq;
15132 	struct lpfc_queue *drq;
15133 	struct rqb_dmabuf *dma_buf;
15134 	struct fc_frame_header *fc_hdr;
15135 	struct lpfc_nvmet_tgtport *tgtp;
15136 	uint32_t status, rq_id;
15137 	unsigned long iflags;
15138 	uint32_t fctl, idx;
15139 
15140 	if ((phba->nvmet_support == 0) ||
15141 	    (phba->sli4_hba.nvmet_cqset == NULL))
15142 		return workposted;
15143 
15144 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
15145 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
15146 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
15147 
15148 	/* sanity check on queue memory */
15149 	if (unlikely(!hrq) || unlikely(!drq))
15150 		return workposted;
15151 
15152 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
15153 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
15154 	else
15155 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
15156 
15157 	if ((phba->nvmet_support == 0) ||
15158 	    (rq_id != hrq->queue_id))
15159 		return workposted;
15160 
15161 	status = bf_get(lpfc_rcqe_status, rcqe);
15162 	switch (status) {
15163 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
15164 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15165 				"6126 Receive Frame Truncated!!\n");
15166 		fallthrough;
15167 	case FC_STATUS_RQ_SUCCESS:
15168 		spin_lock_irqsave(&phba->hbalock, iflags);
15169 		lpfc_sli4_rq_release(hrq, drq);
15170 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15171 		if (!dma_buf) {
15172 			hrq->RQ_no_buf_found++;
15173 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15174 			goto out;
15175 		}
15176 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15177 		hrq->RQ_rcv_buf++;
15178 		hrq->RQ_buf_posted--;
15179 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
15180 
15181 		/* Just some basic sanity checks on FCP Command frame */
15182 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
15183 			fc_hdr->fh_f_ctl[1] << 8 |
15184 			fc_hdr->fh_f_ctl[2]);
15185 		if (((fctl &
15186 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
15187 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
15188 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
15189 			goto drop;
15190 
15191 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
15192 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
15193 			lpfc_nvmet_unsol_fcp_event(
15194 				phba, idx, dma_buf, cq->isr_timestamp,
15195 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
15196 			return false;
15197 		}
15198 drop:
15199 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15200 		break;
15201 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
15202 		if (phba->nvmet_support) {
15203 			tgtp = phba->targetport->private;
15204 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15205 					"6401 RQE Error x%x, posted %d err_cnt "
15206 					"%d: %x %x %x\n",
15207 					status, hrq->RQ_buf_posted,
15208 					hrq->RQ_no_posted_buf,
15209 					atomic_read(&tgtp->rcv_fcp_cmd_in),
15210 					atomic_read(&tgtp->rcv_fcp_cmd_out),
15211 					atomic_read(&tgtp->xmt_fcp_release));
15212 		}
15213 		fallthrough;
15214 
15215 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
15216 		hrq->RQ_no_posted_buf++;
15217 		/* Post more buffers if possible */
15218 		break;
15219 	}
15220 out:
15221 	return workposted;
15222 }
15223 
15224 /**
15225  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
15226  * @phba: adapter with cq
15227  * @cq: Pointer to the completion queue.
15228  * @cqe: Pointer to fast-path completion queue entry.
15229  *
15230  * This routine process a fast-path work queue completion entry from fast-path
15231  * event queue for FCP command response completion.
15232  *
15233  * Return: true if work posted to worker thread, otherwise false.
15234  **/
15235 static bool
15236 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15237 			 struct lpfc_cqe *cqe)
15238 {
15239 	struct lpfc_wcqe_release wcqe;
15240 	bool workposted = false;
15241 
15242 	/* Copy the work queue CQE and convert endian order if needed */
15243 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
15244 
15245 	/* Check and process for different type of WCQE and dispatch */
15246 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
15247 	case CQE_CODE_COMPL_WQE:
15248 	case CQE_CODE_NVME_ERSP:
15249 		cq->CQ_wq++;
15250 		/* Process the WQ complete event */
15251 		phba->last_completion_time = jiffies;
15252 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
15253 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
15254 				(struct lpfc_wcqe_complete *)&wcqe);
15255 		break;
15256 	case CQE_CODE_RELEASE_WQE:
15257 		cq->CQ_release_wqe++;
15258 		/* Process the WQ release event */
15259 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
15260 				(struct lpfc_wcqe_release *)&wcqe);
15261 		break;
15262 	case CQE_CODE_XRI_ABORTED:
15263 		cq->CQ_xri_aborted++;
15264 		/* Process the WQ XRI abort event */
15265 		phba->last_completion_time = jiffies;
15266 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
15267 				(struct sli4_wcqe_xri_aborted *)&wcqe);
15268 		break;
15269 	case CQE_CODE_RECEIVE_V1:
15270 	case CQE_CODE_RECEIVE:
15271 		phba->last_completion_time = jiffies;
15272 		if (cq->subtype == LPFC_NVMET) {
15273 			workposted = lpfc_sli4_nvmet_handle_rcqe(
15274 				phba, cq, (struct lpfc_rcqe *)&wcqe);
15275 		}
15276 		break;
15277 	default:
15278 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15279 				"0144 Not a valid CQE code: x%x\n",
15280 				bf_get(lpfc_wcqe_c_code, &wcqe));
15281 		break;
15282 	}
15283 	return workposted;
15284 }
15285 
15286 /**
15287  * lpfc_sli4_sched_cq_work - Schedules cq work
15288  * @phba: Pointer to HBA context object.
15289  * @cq: Pointer to CQ
15290  * @cqid: CQ ID
15291  *
15292  * This routine checks the poll mode of the CQ corresponding to
15293  * cq->chann, then either schedules a softirq or queue_work to complete
15294  * cq work.
15295  *
15296  * queue_work path is taken if in NVMET mode, or if poll_mode is in
15297  * LPFC_QUEUE_WORK mode.  Otherwise, softirq path is taken.
15298  *
15299  **/
15300 static void lpfc_sli4_sched_cq_work(struct lpfc_hba *phba,
15301 				    struct lpfc_queue *cq, uint16_t cqid)
15302 {
15303 	int ret = 0;
15304 
15305 	switch (cq->poll_mode) {
15306 	case LPFC_IRQ_POLL:
15307 		/* CGN mgmt is mutually exclusive from softirq processing */
15308 		if (phba->cmf_active_mode == LPFC_CFG_OFF) {
15309 			irq_poll_sched(&cq->iop);
15310 			break;
15311 		}
15312 		fallthrough;
15313 	case LPFC_QUEUE_WORK:
15314 	default:
15315 		if (is_kdump_kernel())
15316 			ret = queue_work(phba->wq, &cq->irqwork);
15317 		else
15318 			ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
15319 		if (!ret)
15320 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15321 					"0383 Cannot schedule queue work "
15322 					"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
15323 					cqid, cq->queue_id,
15324 					raw_smp_processor_id());
15325 	}
15326 }
15327 
15328 /**
15329  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
15330  * @phba: Pointer to HBA context object.
15331  * @eq: Pointer to the queue structure.
15332  * @eqe: Pointer to fast-path event queue entry.
15333  *
15334  * This routine process a event queue entry from the fast-path event queue.
15335  * It will check the MajorCode and MinorCode to determine this is for a
15336  * completion event on a completion queue, if not, an error shall be logged
15337  * and just return. Otherwise, it will get to the corresponding completion
15338  * queue and process all the entries on the completion queue, rearm the
15339  * completion queue, and then return.
15340  **/
15341 static void
15342 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
15343 			 struct lpfc_eqe *eqe)
15344 {
15345 	struct lpfc_queue *cq = NULL;
15346 	uint32_t qidx = eq->hdwq;
15347 	uint16_t cqid, id;
15348 
15349 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
15350 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15351 				"0366 Not a valid completion "
15352 				"event: majorcode=x%x, minorcode=x%x\n",
15353 				bf_get_le32(lpfc_eqe_major_code, eqe),
15354 				bf_get_le32(lpfc_eqe_minor_code, eqe));
15355 		return;
15356 	}
15357 
15358 	/* Get the reference to the corresponding CQ */
15359 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
15360 
15361 	/* Use the fast lookup method first */
15362 	if (cqid <= phba->sli4_hba.cq_max) {
15363 		cq = phba->sli4_hba.cq_lookup[cqid];
15364 		if (cq)
15365 			goto  work_cq;
15366 	}
15367 
15368 	/* Next check for NVMET completion */
15369 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
15370 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
15371 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
15372 			/* Process NVMET unsol rcv */
15373 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
15374 			goto  process_cq;
15375 		}
15376 	}
15377 
15378 	if (phba->sli4_hba.nvmels_cq &&
15379 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
15380 		/* Process NVME unsol rcv */
15381 		cq = phba->sli4_hba.nvmels_cq;
15382 	}
15383 
15384 	/* Otherwise this is a Slow path event */
15385 	if (cq == NULL) {
15386 		lpfc_sli4_sp_handle_eqe(phba, eqe,
15387 					phba->sli4_hba.hdwq[qidx].hba_eq);
15388 		return;
15389 	}
15390 
15391 process_cq:
15392 	if (unlikely(cqid != cq->queue_id)) {
15393 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15394 				"0368 Miss-matched fast-path completion "
15395 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
15396 				cqid, cq->queue_id);
15397 		return;
15398 	}
15399 
15400 work_cq:
15401 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
15402 	if (phba->ktime_on)
15403 		cq->isr_timestamp = ktime_get_ns();
15404 	else
15405 		cq->isr_timestamp = 0;
15406 #endif
15407 	lpfc_sli4_sched_cq_work(phba, cq, cqid);
15408 }
15409 
15410 /**
15411  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
15412  * @cq: Pointer to CQ to be processed
15413  * @poll_mode: Enum lpfc_poll_state to determine poll mode
15414  *
15415  * This routine calls the cq processing routine with the handler for
15416  * fast path CQEs.
15417  *
15418  * The CQ routine returns two values: the first is the calling status,
15419  * which indicates whether work was queued to the  background discovery
15420  * thread. If true, the routine should wakeup the discovery thread;
15421  * the second is the delay parameter. If non-zero, rather than rearming
15422  * the CQ and yet another interrupt, the CQ handler should be queued so
15423  * that it is processed in a subsequent polling action. The value of
15424  * the delay indicates when to reschedule it.
15425  **/
15426 static void
15427 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq,
15428 			   enum lpfc_poll_mode poll_mode)
15429 {
15430 	struct lpfc_hba *phba = cq->phba;
15431 	unsigned long delay;
15432 	bool workposted = false;
15433 	int ret = 0;
15434 
15435 	/* process and rearm the CQ */
15436 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
15437 					     &delay, poll_mode);
15438 
15439 	if (delay) {
15440 		if (is_kdump_kernel())
15441 			ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
15442 						delay);
15443 		else
15444 			ret = queue_delayed_work_on(cq->chann, phba->wq,
15445 						&cq->sched_irqwork, delay);
15446 		if (!ret)
15447 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15448 					"0367 Cannot schedule queue work "
15449 					"for cqid=%d on CPU %d\n",
15450 					cq->queue_id, cq->chann);
15451 	}
15452 
15453 	/* wake up worker thread if there are works to be done */
15454 	if (workposted)
15455 		lpfc_worker_wake_up(phba);
15456 }
15457 
15458 /**
15459  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
15460  *   interrupt
15461  * @work: pointer to work element
15462  *
15463  * translates from the work handler and calls the fast-path handler.
15464  **/
15465 static void
15466 lpfc_sli4_hba_process_cq(struct work_struct *work)
15467 {
15468 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
15469 
15470 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
15471 }
15472 
15473 /**
15474  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
15475  * @work: pointer to work element
15476  *
15477  * translates from the work handler and calls the fast-path handler.
15478  **/
15479 static void
15480 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
15481 {
15482 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15483 					struct lpfc_queue, sched_irqwork);
15484 
15485 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
15486 }
15487 
15488 /**
15489  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
15490  * @irq: Interrupt number.
15491  * @dev_id: The device context pointer.
15492  *
15493  * This function is directly called from the PCI layer as an interrupt
15494  * service routine when device with SLI-4 interface spec is enabled with
15495  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
15496  * ring event in the HBA. However, when the device is enabled with either
15497  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
15498  * device-level interrupt handler. When the PCI slot is in error recovery
15499  * or the HBA is undergoing initialization, the interrupt handler will not
15500  * process the interrupt. The SCSI FCP fast-path ring event are handled in
15501  * the intrrupt context. This function is called without any lock held.
15502  * It gets the hbalock to access and update SLI data structures. Note that,
15503  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
15504  * equal to that of FCP CQ index.
15505  *
15506  * The link attention and ELS ring attention events are handled
15507  * by the worker thread. The interrupt handler signals the worker thread
15508  * and returns for these events. This function is called without any lock
15509  * held. It gets the hbalock to access and update SLI data structures.
15510  *
15511  * This function returns IRQ_HANDLED when interrupt is handled else it
15512  * returns IRQ_NONE.
15513  **/
15514 irqreturn_t
15515 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
15516 {
15517 	struct lpfc_hba *phba;
15518 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
15519 	struct lpfc_queue *fpeq;
15520 	unsigned long iflag;
15521 	int ecount = 0;
15522 	int hba_eqidx;
15523 	struct lpfc_eq_intr_info *eqi;
15524 
15525 	/* Get the driver's phba structure from the dev_id */
15526 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
15527 	phba = hba_eq_hdl->phba;
15528 	hba_eqidx = hba_eq_hdl->idx;
15529 
15530 	if (unlikely(!phba))
15531 		return IRQ_NONE;
15532 	if (unlikely(!phba->sli4_hba.hdwq))
15533 		return IRQ_NONE;
15534 
15535 	/* Get to the EQ struct associated with this vector */
15536 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
15537 	if (unlikely(!fpeq))
15538 		return IRQ_NONE;
15539 
15540 	/* Check device state for handling interrupt */
15541 	if (unlikely(lpfc_intr_state_check(phba))) {
15542 		/* Check again for link_state with lock held */
15543 		spin_lock_irqsave(&phba->hbalock, iflag);
15544 		if (phba->link_state < LPFC_LINK_DOWN)
15545 			/* Flush, clear interrupt, and rearm the EQ */
15546 			lpfc_sli4_eqcq_flush(phba, fpeq);
15547 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15548 		return IRQ_NONE;
15549 	}
15550 
15551 	eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
15552 	eqi->icnt++;
15553 
15554 	fpeq->last_cpu = raw_smp_processor_id();
15555 
15556 	if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
15557 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
15558 	    phba->cfg_auto_imax &&
15559 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
15560 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
15561 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
15562 
15563 	/* process and rearm the EQ */
15564 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
15565 
15566 	if (unlikely(ecount == 0)) {
15567 		fpeq->EQ_no_entry++;
15568 		if (phba->intr_type == MSIX)
15569 			/* MSI-X treated interrupt served as no EQ share INT */
15570 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15571 					"0358 MSI-X interrupt with no EQE\n");
15572 		else
15573 			/* Non MSI-X treated on interrupt as EQ share INT */
15574 			return IRQ_NONE;
15575 	}
15576 
15577 	return IRQ_HANDLED;
15578 } /* lpfc_sli4_hba_intr_handler */
15579 
15580 /**
15581  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
15582  * @irq: Interrupt number.
15583  * @dev_id: The device context pointer.
15584  *
15585  * This function is the device-level interrupt handler to device with SLI-4
15586  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
15587  * interrupt mode is enabled and there is an event in the HBA which requires
15588  * driver attention. This function invokes the slow-path interrupt attention
15589  * handling function and fast-path interrupt attention handling function in
15590  * turn to process the relevant HBA attention events. This function is called
15591  * without any lock held. It gets the hbalock to access and update SLI data
15592  * structures.
15593  *
15594  * This function returns IRQ_HANDLED when interrupt is handled, else it
15595  * returns IRQ_NONE.
15596  **/
15597 irqreturn_t
15598 lpfc_sli4_intr_handler(int irq, void *dev_id)
15599 {
15600 	struct lpfc_hba  *phba;
15601 	irqreturn_t hba_irq_rc;
15602 	bool hba_handled = false;
15603 	int qidx;
15604 
15605 	/* Get the driver's phba structure from the dev_id */
15606 	phba = (struct lpfc_hba *)dev_id;
15607 
15608 	if (unlikely(!phba))
15609 		return IRQ_NONE;
15610 
15611 	/*
15612 	 * Invoke fast-path host attention interrupt handling as appropriate.
15613 	 */
15614 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
15615 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
15616 					&phba->sli4_hba.hba_eq_hdl[qidx]);
15617 		if (hba_irq_rc == IRQ_HANDLED)
15618 			hba_handled |= true;
15619 	}
15620 
15621 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
15622 } /* lpfc_sli4_intr_handler */
15623 
15624 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
15625 {
15626 	struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
15627 	struct lpfc_queue *eq;
15628 	int i = 0;
15629 
15630 	rcu_read_lock();
15631 
15632 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
15633 		i += lpfc_sli4_poll_eq(eq, LPFC_POLL_SLOWPATH);
15634 	if (!list_empty(&phba->poll_list))
15635 		mod_timer(&phba->cpuhp_poll_timer,
15636 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15637 
15638 	rcu_read_unlock();
15639 }
15640 
15641 inline int lpfc_sli4_poll_eq(struct lpfc_queue *eq, uint8_t path)
15642 {
15643 	struct lpfc_hba *phba = eq->phba;
15644 	int i = 0;
15645 
15646 	/*
15647 	 * Unlocking an irq is one of the entry point to check
15648 	 * for re-schedule, but we are good for io submission
15649 	 * path as midlayer does a get_cpu to glue us in. Flush
15650 	 * out the invalidate queue so we can see the updated
15651 	 * value for flag.
15652 	 */
15653 	smp_rmb();
15654 
15655 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
15656 		/* We will not likely get the completion for the caller
15657 		 * during this iteration but i guess that's fine.
15658 		 * Future io's coming on this eq should be able to
15659 		 * pick it up.  As for the case of single io's, they
15660 		 * will be handled through a sched from polling timer
15661 		 * function which is currently triggered every 1msec.
15662 		 */
15663 		i = lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM);
15664 
15665 	return i;
15666 }
15667 
15668 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
15669 {
15670 	struct lpfc_hba *phba = eq->phba;
15671 
15672 	/* kickstart slowpath processing if needed */
15673 	if (list_empty(&phba->poll_list))
15674 		mod_timer(&phba->cpuhp_poll_timer,
15675 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15676 
15677 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
15678 	synchronize_rcu();
15679 }
15680 
15681 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
15682 {
15683 	struct lpfc_hba *phba = eq->phba;
15684 
15685 	/* Disable slowpath processing for this eq.  Kick start the eq
15686 	 * by RE-ARMING the eq's ASAP
15687 	 */
15688 	list_del_rcu(&eq->_poll_list);
15689 	synchronize_rcu();
15690 
15691 	if (list_empty(&phba->poll_list))
15692 		del_timer_sync(&phba->cpuhp_poll_timer);
15693 }
15694 
15695 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
15696 {
15697 	struct lpfc_queue *eq, *next;
15698 
15699 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
15700 		list_del(&eq->_poll_list);
15701 
15702 	INIT_LIST_HEAD(&phba->poll_list);
15703 	synchronize_rcu();
15704 }
15705 
15706 static inline void
15707 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
15708 {
15709 	if (mode == eq->mode)
15710 		return;
15711 	/*
15712 	 * currently this function is only called during a hotplug
15713 	 * event and the cpu on which this function is executing
15714 	 * is going offline.  By now the hotplug has instructed
15715 	 * the scheduler to remove this cpu from cpu active mask.
15716 	 * So we don't need to work about being put aside by the
15717 	 * scheduler for a high priority process.  Yes, the inte-
15718 	 * rrupts could come but they are known to retire ASAP.
15719 	 */
15720 
15721 	/* Disable polling in the fastpath */
15722 	WRITE_ONCE(eq->mode, mode);
15723 	/* flush out the store buffer */
15724 	smp_wmb();
15725 
15726 	/*
15727 	 * Add this eq to the polling list and start polling. For
15728 	 * a grace period both interrupt handler and poller will
15729 	 * try to process the eq _but_ that's fine.  We have a
15730 	 * synchronization mechanism in place (queue_claimed) to
15731 	 * deal with it.  This is just a draining phase for int-
15732 	 * errupt handler (not eq's) as we have guranteed through
15733 	 * barrier that all the CPUs have seen the new CQ_POLLED
15734 	 * state. which will effectively disable the REARMING of
15735 	 * the EQ.  The whole idea is eq's die off eventually as
15736 	 * we are not rearming EQ's anymore.
15737 	 */
15738 	mode ? lpfc_sli4_add_to_poll_list(eq) :
15739 	       lpfc_sli4_remove_from_poll_list(eq);
15740 }
15741 
15742 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15743 {
15744 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15745 }
15746 
15747 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15748 {
15749 	struct lpfc_hba *phba = eq->phba;
15750 
15751 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15752 
15753 	/* Kick start for the pending io's in h/w.
15754 	 * Once we switch back to interrupt processing on a eq
15755 	 * the io path completion will only arm eq's when it
15756 	 * receives a completion.  But since eq's are in disa-
15757 	 * rmed state it doesn't receive a completion.  This
15758 	 * creates a deadlock scenaro.
15759 	 */
15760 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15761 }
15762 
15763 /**
15764  * lpfc_sli4_queue_free - free a queue structure and associated memory
15765  * @queue: The queue structure to free.
15766  *
15767  * This function frees a queue structure and the DMAable memory used for
15768  * the host resident queue. This function must be called after destroying the
15769  * queue on the HBA.
15770  **/
15771 void
15772 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15773 {
15774 	struct lpfc_dmabuf *dmabuf;
15775 
15776 	if (!queue)
15777 		return;
15778 
15779 	if (!list_empty(&queue->wq_list))
15780 		list_del(&queue->wq_list);
15781 
15782 	while (!list_empty(&queue->page_list)) {
15783 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15784 				 list);
15785 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15786 				  dmabuf->virt, dmabuf->phys);
15787 		kfree(dmabuf);
15788 	}
15789 	if (queue->rqbp) {
15790 		lpfc_free_rq_buffer(queue->phba, queue);
15791 		kfree(queue->rqbp);
15792 	}
15793 
15794 	if (!list_empty(&queue->cpu_list))
15795 		list_del(&queue->cpu_list);
15796 
15797 	kfree(queue);
15798 	return;
15799 }
15800 
15801 /**
15802  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15803  * @phba: The HBA that this queue is being created on.
15804  * @page_size: The size of a queue page
15805  * @entry_size: The size of each queue entry for this queue.
15806  * @entry_count: The number of entries that this queue will handle.
15807  * @cpu: The cpu that will primarily utilize this queue.
15808  *
15809  * This function allocates a queue structure and the DMAable memory used for
15810  * the host resident queue. This function must be called before creating the
15811  * queue on the HBA.
15812  **/
15813 struct lpfc_queue *
15814 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15815 		      uint32_t entry_size, uint32_t entry_count, int cpu)
15816 {
15817 	struct lpfc_queue *queue;
15818 	struct lpfc_dmabuf *dmabuf;
15819 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15820 	uint16_t x, pgcnt;
15821 
15822 	if (!phba->sli4_hba.pc_sli4_params.supported)
15823 		hw_page_size = page_size;
15824 
15825 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15826 
15827 	/* If needed, Adjust page count to match the max the adapter supports */
15828 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15829 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15830 
15831 	queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
15832 			     GFP_KERNEL, cpu_to_node(cpu));
15833 	if (!queue)
15834 		return NULL;
15835 
15836 	INIT_LIST_HEAD(&queue->list);
15837 	INIT_LIST_HEAD(&queue->_poll_list);
15838 	INIT_LIST_HEAD(&queue->wq_list);
15839 	INIT_LIST_HEAD(&queue->wqfull_list);
15840 	INIT_LIST_HEAD(&queue->page_list);
15841 	INIT_LIST_HEAD(&queue->child_list);
15842 	INIT_LIST_HEAD(&queue->cpu_list);
15843 
15844 	/* Set queue parameters now.  If the system cannot provide memory
15845 	 * resources, the free routine needs to know what was allocated.
15846 	 */
15847 	queue->page_count = pgcnt;
15848 	queue->q_pgs = (void **)&queue[1];
15849 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
15850 	queue->entry_size = entry_size;
15851 	queue->entry_count = entry_count;
15852 	queue->page_size = hw_page_size;
15853 	queue->phba = phba;
15854 
15855 	for (x = 0; x < queue->page_count; x++) {
15856 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15857 				      dev_to_node(&phba->pcidev->dev));
15858 		if (!dmabuf)
15859 			goto out_fail;
15860 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15861 						  hw_page_size, &dmabuf->phys,
15862 						  GFP_KERNEL);
15863 		if (!dmabuf->virt) {
15864 			kfree(dmabuf);
15865 			goto out_fail;
15866 		}
15867 		dmabuf->buffer_tag = x;
15868 		list_add_tail(&dmabuf->list, &queue->page_list);
15869 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
15870 		queue->q_pgs[x] = dmabuf->virt;
15871 	}
15872 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15873 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15874 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15875 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15876 
15877 	/* notify_interval will be set during q creation */
15878 
15879 	return queue;
15880 out_fail:
15881 	lpfc_sli4_queue_free(queue);
15882 	return NULL;
15883 }
15884 
15885 /**
15886  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15887  * @phba: HBA structure that indicates port to create a queue on.
15888  * @pci_barset: PCI BAR set flag.
15889  *
15890  * This function shall perform iomap of the specified PCI BAR address to host
15891  * memory address if not already done so and return it. The returned host
15892  * memory address can be NULL.
15893  */
15894 static void __iomem *
15895 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15896 {
15897 	if (!phba->pcidev)
15898 		return NULL;
15899 
15900 	switch (pci_barset) {
15901 	case WQ_PCI_BAR_0_AND_1:
15902 		return phba->pci_bar0_memmap_p;
15903 	case WQ_PCI_BAR_2_AND_3:
15904 		return phba->pci_bar2_memmap_p;
15905 	case WQ_PCI_BAR_4_AND_5:
15906 		return phba->pci_bar4_memmap_p;
15907 	default:
15908 		break;
15909 	}
15910 	return NULL;
15911 }
15912 
15913 /**
15914  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
15915  * @phba: HBA structure that EQs are on.
15916  * @startq: The starting EQ index to modify
15917  * @numq: The number of EQs (consecutive indexes) to modify
15918  * @usdelay: amount of delay
15919  *
15920  * This function revises the EQ delay on 1 or more EQs. The EQ delay
15921  * is set either by writing to a register (if supported by the SLI Port)
15922  * or by mailbox command. The mailbox command allows several EQs to be
15923  * updated at once.
15924  *
15925  * The @phba struct is used to send a mailbox command to HBA. The @startq
15926  * is used to get the starting EQ index to change. The @numq value is
15927  * used to specify how many consecutive EQ indexes, starting at EQ index,
15928  * are to be changed. This function is asynchronous and will wait for any
15929  * mailbox commands to finish before returning.
15930  *
15931  * On success this function will return a zero. If unable to allocate
15932  * enough memory this function will return -ENOMEM. If a mailbox command
15933  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
15934  * have had their delay multipler changed.
15935  **/
15936 void
15937 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
15938 			 uint32_t numq, uint32_t usdelay)
15939 {
15940 	struct lpfc_mbx_modify_eq_delay *eq_delay;
15941 	LPFC_MBOXQ_t *mbox;
15942 	struct lpfc_queue *eq;
15943 	int cnt = 0, rc, length;
15944 	uint32_t shdr_status, shdr_add_status;
15945 	uint32_t dmult;
15946 	int qidx;
15947 	union lpfc_sli4_cfg_shdr *shdr;
15948 
15949 	if (startq >= phba->cfg_irq_chann)
15950 		return;
15951 
15952 	if (usdelay > 0xFFFF) {
15953 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
15954 				"6429 usdelay %d too large. Scaled down to "
15955 				"0xFFFF.\n", usdelay);
15956 		usdelay = 0xFFFF;
15957 	}
15958 
15959 	/* set values by EQ_DELAY register if supported */
15960 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
15961 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15962 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15963 			if (!eq)
15964 				continue;
15965 
15966 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
15967 
15968 			if (++cnt >= numq)
15969 				break;
15970 		}
15971 		return;
15972 	}
15973 
15974 	/* Otherwise, set values by mailbox cmd */
15975 
15976 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15977 	if (!mbox) {
15978 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15979 				"6428 Failed allocating mailbox cmd buffer."
15980 				" EQ delay was not set.\n");
15981 		return;
15982 	}
15983 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
15984 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15985 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15986 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
15987 			 length, LPFC_SLI4_MBX_EMBED);
15988 	eq_delay = &mbox->u.mqe.un.eq_delay;
15989 
15990 	/* Calculate delay multiper from maximum interrupt per second */
15991 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
15992 	if (dmult)
15993 		dmult--;
15994 	if (dmult > LPFC_DMULT_MAX)
15995 		dmult = LPFC_DMULT_MAX;
15996 
15997 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15998 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15999 		if (!eq)
16000 			continue;
16001 		eq->q_mode = usdelay;
16002 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
16003 		eq_delay->u.request.eq[cnt].phase = 0;
16004 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
16005 
16006 		if (++cnt >= numq)
16007 			break;
16008 	}
16009 	eq_delay->u.request.num_eq = cnt;
16010 
16011 	mbox->vport = phba->pport;
16012 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16013 	mbox->ctx_ndlp = NULL;
16014 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16015 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
16016 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16017 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16018 	if (shdr_status || shdr_add_status || rc) {
16019 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16020 				"2512 MODIFY_EQ_DELAY mailbox failed with "
16021 				"status x%x add_status x%x, mbx status x%x\n",
16022 				shdr_status, shdr_add_status, rc);
16023 	}
16024 	mempool_free(mbox, phba->mbox_mem_pool);
16025 	return;
16026 }
16027 
16028 /**
16029  * lpfc_eq_create - Create an Event Queue on the HBA
16030  * @phba: HBA structure that indicates port to create a queue on.
16031  * @eq: The queue structure to use to create the event queue.
16032  * @imax: The maximum interrupt per second limit.
16033  *
16034  * This function creates an event queue, as detailed in @eq, on a port,
16035  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
16036  *
16037  * The @phba struct is used to send mailbox command to HBA. The @eq struct
16038  * is used to get the entry count and entry size that are necessary to
16039  * determine the number of pages to allocate and use for this queue. This
16040  * function will send the EQ_CREATE mailbox command to the HBA to setup the
16041  * event queue. This function is asynchronous and will wait for the mailbox
16042  * command to finish before continuing.
16043  *
16044  * On success this function will return a zero. If unable to allocate enough
16045  * memory this function will return -ENOMEM. If the queue create mailbox command
16046  * fails this function will return -ENXIO.
16047  **/
16048 int
16049 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
16050 {
16051 	struct lpfc_mbx_eq_create *eq_create;
16052 	LPFC_MBOXQ_t *mbox;
16053 	int rc, length, status = 0;
16054 	struct lpfc_dmabuf *dmabuf;
16055 	uint32_t shdr_status, shdr_add_status;
16056 	union lpfc_sli4_cfg_shdr *shdr;
16057 	uint16_t dmult;
16058 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16059 
16060 	/* sanity check on queue memory */
16061 	if (!eq)
16062 		return -ENODEV;
16063 	if (!phba->sli4_hba.pc_sli4_params.supported)
16064 		hw_page_size = SLI4_PAGE_SIZE;
16065 
16066 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16067 	if (!mbox)
16068 		return -ENOMEM;
16069 	length = (sizeof(struct lpfc_mbx_eq_create) -
16070 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16071 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16072 			 LPFC_MBOX_OPCODE_EQ_CREATE,
16073 			 length, LPFC_SLI4_MBX_EMBED);
16074 	eq_create = &mbox->u.mqe.un.eq_create;
16075 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
16076 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
16077 	       eq->page_count);
16078 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
16079 	       LPFC_EQE_SIZE);
16080 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
16081 
16082 	/* Use version 2 of CREATE_EQ if eqav is set */
16083 	if (phba->sli4_hba.pc_sli4_params.eqav) {
16084 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16085 		       LPFC_Q_CREATE_VERSION_2);
16086 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
16087 		       phba->sli4_hba.pc_sli4_params.eqav);
16088 	}
16089 
16090 	/* don't setup delay multiplier using EQ_CREATE */
16091 	dmult = 0;
16092 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
16093 	       dmult);
16094 	switch (eq->entry_count) {
16095 	default:
16096 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16097 				"0360 Unsupported EQ count. (%d)\n",
16098 				eq->entry_count);
16099 		if (eq->entry_count < 256) {
16100 			status = -EINVAL;
16101 			goto out;
16102 		}
16103 		fallthrough;	/* otherwise default to smallest count */
16104 	case 256:
16105 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16106 		       LPFC_EQ_CNT_256);
16107 		break;
16108 	case 512:
16109 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16110 		       LPFC_EQ_CNT_512);
16111 		break;
16112 	case 1024:
16113 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16114 		       LPFC_EQ_CNT_1024);
16115 		break;
16116 	case 2048:
16117 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16118 		       LPFC_EQ_CNT_2048);
16119 		break;
16120 	case 4096:
16121 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16122 		       LPFC_EQ_CNT_4096);
16123 		break;
16124 	}
16125 	list_for_each_entry(dmabuf, &eq->page_list, list) {
16126 		memset(dmabuf->virt, 0, hw_page_size);
16127 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16128 					putPaddrLow(dmabuf->phys);
16129 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16130 					putPaddrHigh(dmabuf->phys);
16131 	}
16132 	mbox->vport = phba->pport;
16133 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16134 	mbox->ctx_buf = NULL;
16135 	mbox->ctx_ndlp = NULL;
16136 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16137 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16138 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16139 	if (shdr_status || shdr_add_status || rc) {
16140 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16141 				"2500 EQ_CREATE mailbox failed with "
16142 				"status x%x add_status x%x, mbx status x%x\n",
16143 				shdr_status, shdr_add_status, rc);
16144 		status = -ENXIO;
16145 	}
16146 	eq->type = LPFC_EQ;
16147 	eq->subtype = LPFC_NONE;
16148 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
16149 	if (eq->queue_id == 0xFFFF)
16150 		status = -ENXIO;
16151 	eq->host_index = 0;
16152 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
16153 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
16154 out:
16155 	mempool_free(mbox, phba->mbox_mem_pool);
16156 	return status;
16157 }
16158 
16159 static int lpfc_cq_poll_hdler(struct irq_poll *iop, int budget)
16160 {
16161 	struct lpfc_queue *cq = container_of(iop, struct lpfc_queue, iop);
16162 
16163 	__lpfc_sli4_hba_process_cq(cq, LPFC_IRQ_POLL);
16164 
16165 	return 1;
16166 }
16167 
16168 /**
16169  * lpfc_cq_create - Create a Completion Queue on the HBA
16170  * @phba: HBA structure that indicates port to create a queue on.
16171  * @cq: The queue structure to use to create the completion queue.
16172  * @eq: The event queue to bind this completion queue to.
16173  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16174  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16175  *
16176  * This function creates a completion queue, as detailed in @wq, on a port,
16177  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
16178  *
16179  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16180  * is used to get the entry count and entry size that are necessary to
16181  * determine the number of pages to allocate and use for this queue. The @eq
16182  * is used to indicate which event queue to bind this completion queue to. This
16183  * function will send the CQ_CREATE mailbox command to the HBA to setup the
16184  * completion queue. This function is asynchronous and will wait for the mailbox
16185  * command to finish before continuing.
16186  *
16187  * On success this function will return a zero. If unable to allocate enough
16188  * memory this function will return -ENOMEM. If the queue create mailbox command
16189  * fails this function will return -ENXIO.
16190  **/
16191 int
16192 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
16193 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
16194 {
16195 	struct lpfc_mbx_cq_create *cq_create;
16196 	struct lpfc_dmabuf *dmabuf;
16197 	LPFC_MBOXQ_t *mbox;
16198 	int rc, length, status = 0;
16199 	uint32_t shdr_status, shdr_add_status;
16200 	union lpfc_sli4_cfg_shdr *shdr;
16201 
16202 	/* sanity check on queue memory */
16203 	if (!cq || !eq)
16204 		return -ENODEV;
16205 
16206 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16207 	if (!mbox)
16208 		return -ENOMEM;
16209 	length = (sizeof(struct lpfc_mbx_cq_create) -
16210 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16211 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16212 			 LPFC_MBOX_OPCODE_CQ_CREATE,
16213 			 length, LPFC_SLI4_MBX_EMBED);
16214 	cq_create = &mbox->u.mqe.un.cq_create;
16215 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
16216 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
16217 		    cq->page_count);
16218 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
16219 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
16220 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16221 	       phba->sli4_hba.pc_sli4_params.cqv);
16222 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
16223 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
16224 		       (cq->page_size / SLI4_PAGE_SIZE));
16225 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
16226 		       eq->queue_id);
16227 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
16228 		       phba->sli4_hba.pc_sli4_params.cqav);
16229 	} else {
16230 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
16231 		       eq->queue_id);
16232 	}
16233 	switch (cq->entry_count) {
16234 	case 2048:
16235 	case 4096:
16236 		if (phba->sli4_hba.pc_sli4_params.cqv ==
16237 		    LPFC_Q_CREATE_VERSION_2) {
16238 			cq_create->u.request.context.lpfc_cq_context_count =
16239 				cq->entry_count;
16240 			bf_set(lpfc_cq_context_count,
16241 			       &cq_create->u.request.context,
16242 			       LPFC_CQ_CNT_WORD7);
16243 			break;
16244 		}
16245 		fallthrough;
16246 	default:
16247 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16248 				"0361 Unsupported CQ count: "
16249 				"entry cnt %d sz %d pg cnt %d\n",
16250 				cq->entry_count, cq->entry_size,
16251 				cq->page_count);
16252 		if (cq->entry_count < 256) {
16253 			status = -EINVAL;
16254 			goto out;
16255 		}
16256 		fallthrough;	/* otherwise default to smallest count */
16257 	case 256:
16258 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16259 		       LPFC_CQ_CNT_256);
16260 		break;
16261 	case 512:
16262 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16263 		       LPFC_CQ_CNT_512);
16264 		break;
16265 	case 1024:
16266 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16267 		       LPFC_CQ_CNT_1024);
16268 		break;
16269 	}
16270 	list_for_each_entry(dmabuf, &cq->page_list, list) {
16271 		memset(dmabuf->virt, 0, cq->page_size);
16272 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16273 					putPaddrLow(dmabuf->phys);
16274 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16275 					putPaddrHigh(dmabuf->phys);
16276 	}
16277 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16278 
16279 	/* The IOCTL status is embedded in the mailbox subheader. */
16280 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16281 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16282 	if (shdr_status || shdr_add_status || rc) {
16283 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16284 				"2501 CQ_CREATE mailbox failed with "
16285 				"status x%x add_status x%x, mbx status x%x\n",
16286 				shdr_status, shdr_add_status, rc);
16287 		status = -ENXIO;
16288 		goto out;
16289 	}
16290 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16291 	if (cq->queue_id == 0xFFFF) {
16292 		status = -ENXIO;
16293 		goto out;
16294 	}
16295 	/* link the cq onto the parent eq child list */
16296 	list_add_tail(&cq->list, &eq->child_list);
16297 	/* Set up completion queue's type and subtype */
16298 	cq->type = type;
16299 	cq->subtype = subtype;
16300 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16301 	cq->assoc_qid = eq->queue_id;
16302 	cq->assoc_qp = eq;
16303 	cq->host_index = 0;
16304 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16305 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
16306 
16307 	if (cq->queue_id > phba->sli4_hba.cq_max)
16308 		phba->sli4_hba.cq_max = cq->queue_id;
16309 
16310 	irq_poll_init(&cq->iop, LPFC_IRQ_POLL_WEIGHT, lpfc_cq_poll_hdler);
16311 out:
16312 	mempool_free(mbox, phba->mbox_mem_pool);
16313 	return status;
16314 }
16315 
16316 /**
16317  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
16318  * @phba: HBA structure that indicates port to create a queue on.
16319  * @cqp: The queue structure array to use to create the completion queues.
16320  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
16321  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16322  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16323  *
16324  * This function creates a set of  completion queue, s to support MRQ
16325  * as detailed in @cqp, on a port,
16326  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
16327  *
16328  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16329  * is used to get the entry count and entry size that are necessary to
16330  * determine the number of pages to allocate and use for this queue. The @eq
16331  * is used to indicate which event queue to bind this completion queue to. This
16332  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
16333  * completion queue. This function is asynchronous and will wait for the mailbox
16334  * command to finish before continuing.
16335  *
16336  * On success this function will return a zero. If unable to allocate enough
16337  * memory this function will return -ENOMEM. If the queue create mailbox command
16338  * fails this function will return -ENXIO.
16339  **/
16340 int
16341 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
16342 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
16343 		   uint32_t subtype)
16344 {
16345 	struct lpfc_queue *cq;
16346 	struct lpfc_queue *eq;
16347 	struct lpfc_mbx_cq_create_set *cq_set;
16348 	struct lpfc_dmabuf *dmabuf;
16349 	LPFC_MBOXQ_t *mbox;
16350 	int rc, length, alloclen, status = 0;
16351 	int cnt, idx, numcq, page_idx = 0;
16352 	uint32_t shdr_status, shdr_add_status;
16353 	union lpfc_sli4_cfg_shdr *shdr;
16354 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16355 
16356 	/* sanity check on queue memory */
16357 	numcq = phba->cfg_nvmet_mrq;
16358 	if (!cqp || !hdwq || !numcq)
16359 		return -ENODEV;
16360 
16361 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16362 	if (!mbox)
16363 		return -ENOMEM;
16364 
16365 	length = sizeof(struct lpfc_mbx_cq_create_set);
16366 	length += ((numcq * cqp[0]->page_count) *
16367 		   sizeof(struct dma_address));
16368 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16369 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
16370 			LPFC_SLI4_MBX_NEMBED);
16371 	if (alloclen < length) {
16372 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16373 				"3098 Allocated DMA memory size (%d) is "
16374 				"less than the requested DMA memory size "
16375 				"(%d)\n", alloclen, length);
16376 		status = -ENOMEM;
16377 		goto out;
16378 	}
16379 	cq_set = mbox->sge_array->addr[0];
16380 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
16381 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
16382 
16383 	for (idx = 0; idx < numcq; idx++) {
16384 		cq = cqp[idx];
16385 		eq = hdwq[idx].hba_eq;
16386 		if (!cq || !eq) {
16387 			status = -ENOMEM;
16388 			goto out;
16389 		}
16390 		if (!phba->sli4_hba.pc_sli4_params.supported)
16391 			hw_page_size = cq->page_size;
16392 
16393 		switch (idx) {
16394 		case 0:
16395 			bf_set(lpfc_mbx_cq_create_set_page_size,
16396 			       &cq_set->u.request,
16397 			       (hw_page_size / SLI4_PAGE_SIZE));
16398 			bf_set(lpfc_mbx_cq_create_set_num_pages,
16399 			       &cq_set->u.request, cq->page_count);
16400 			bf_set(lpfc_mbx_cq_create_set_evt,
16401 			       &cq_set->u.request, 1);
16402 			bf_set(lpfc_mbx_cq_create_set_valid,
16403 			       &cq_set->u.request, 1);
16404 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
16405 			       &cq_set->u.request, 0);
16406 			bf_set(lpfc_mbx_cq_create_set_num_cq,
16407 			       &cq_set->u.request, numcq);
16408 			bf_set(lpfc_mbx_cq_create_set_autovalid,
16409 			       &cq_set->u.request,
16410 			       phba->sli4_hba.pc_sli4_params.cqav);
16411 			switch (cq->entry_count) {
16412 			case 2048:
16413 			case 4096:
16414 				if (phba->sli4_hba.pc_sli4_params.cqv ==
16415 				    LPFC_Q_CREATE_VERSION_2) {
16416 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16417 					       &cq_set->u.request,
16418 						cq->entry_count);
16419 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16420 					       &cq_set->u.request,
16421 					       LPFC_CQ_CNT_WORD7);
16422 					break;
16423 				}
16424 				fallthrough;
16425 			default:
16426 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16427 						"3118 Bad CQ count. (%d)\n",
16428 						cq->entry_count);
16429 				if (cq->entry_count < 256) {
16430 					status = -EINVAL;
16431 					goto out;
16432 				}
16433 				fallthrough;	/* otherwise default to smallest */
16434 			case 256:
16435 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16436 				       &cq_set->u.request, LPFC_CQ_CNT_256);
16437 				break;
16438 			case 512:
16439 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16440 				       &cq_set->u.request, LPFC_CQ_CNT_512);
16441 				break;
16442 			case 1024:
16443 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16444 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
16445 				break;
16446 			}
16447 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
16448 			       &cq_set->u.request, eq->queue_id);
16449 			break;
16450 		case 1:
16451 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
16452 			       &cq_set->u.request, eq->queue_id);
16453 			break;
16454 		case 2:
16455 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
16456 			       &cq_set->u.request, eq->queue_id);
16457 			break;
16458 		case 3:
16459 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
16460 			       &cq_set->u.request, eq->queue_id);
16461 			break;
16462 		case 4:
16463 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
16464 			       &cq_set->u.request, eq->queue_id);
16465 			break;
16466 		case 5:
16467 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
16468 			       &cq_set->u.request, eq->queue_id);
16469 			break;
16470 		case 6:
16471 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
16472 			       &cq_set->u.request, eq->queue_id);
16473 			break;
16474 		case 7:
16475 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
16476 			       &cq_set->u.request, eq->queue_id);
16477 			break;
16478 		case 8:
16479 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
16480 			       &cq_set->u.request, eq->queue_id);
16481 			break;
16482 		case 9:
16483 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
16484 			       &cq_set->u.request, eq->queue_id);
16485 			break;
16486 		case 10:
16487 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
16488 			       &cq_set->u.request, eq->queue_id);
16489 			break;
16490 		case 11:
16491 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
16492 			       &cq_set->u.request, eq->queue_id);
16493 			break;
16494 		case 12:
16495 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
16496 			       &cq_set->u.request, eq->queue_id);
16497 			break;
16498 		case 13:
16499 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
16500 			       &cq_set->u.request, eq->queue_id);
16501 			break;
16502 		case 14:
16503 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
16504 			       &cq_set->u.request, eq->queue_id);
16505 			break;
16506 		case 15:
16507 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
16508 			       &cq_set->u.request, eq->queue_id);
16509 			break;
16510 		}
16511 
16512 		/* link the cq onto the parent eq child list */
16513 		list_add_tail(&cq->list, &eq->child_list);
16514 		/* Set up completion queue's type and subtype */
16515 		cq->type = type;
16516 		cq->subtype = subtype;
16517 		cq->assoc_qid = eq->queue_id;
16518 		cq->assoc_qp = eq;
16519 		cq->host_index = 0;
16520 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16521 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
16522 					 cq->entry_count);
16523 		cq->chann = idx;
16524 
16525 		rc = 0;
16526 		list_for_each_entry(dmabuf, &cq->page_list, list) {
16527 			memset(dmabuf->virt, 0, hw_page_size);
16528 			cnt = page_idx + dmabuf->buffer_tag;
16529 			cq_set->u.request.page[cnt].addr_lo =
16530 					putPaddrLow(dmabuf->phys);
16531 			cq_set->u.request.page[cnt].addr_hi =
16532 					putPaddrHigh(dmabuf->phys);
16533 			rc++;
16534 		}
16535 		page_idx += rc;
16536 	}
16537 
16538 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16539 
16540 	/* The IOCTL status is embedded in the mailbox subheader. */
16541 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16542 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16543 	if (shdr_status || shdr_add_status || rc) {
16544 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16545 				"3119 CQ_CREATE_SET mailbox failed with "
16546 				"status x%x add_status x%x, mbx status x%x\n",
16547 				shdr_status, shdr_add_status, rc);
16548 		status = -ENXIO;
16549 		goto out;
16550 	}
16551 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
16552 	if (rc == 0xFFFF) {
16553 		status = -ENXIO;
16554 		goto out;
16555 	}
16556 
16557 	for (idx = 0; idx < numcq; idx++) {
16558 		cq = cqp[idx];
16559 		cq->queue_id = rc + idx;
16560 		if (cq->queue_id > phba->sli4_hba.cq_max)
16561 			phba->sli4_hba.cq_max = cq->queue_id;
16562 	}
16563 
16564 out:
16565 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16566 	return status;
16567 }
16568 
16569 /**
16570  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
16571  * @phba: HBA structure that indicates port to create a queue on.
16572  * @mq: The queue structure to use to create the mailbox queue.
16573  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
16574  * @cq: The completion queue to associate with this cq.
16575  *
16576  * This function provides failback (fb) functionality when the
16577  * mq_create_ext fails on older FW generations.  It's purpose is identical
16578  * to mq_create_ext otherwise.
16579  *
16580  * This routine cannot fail as all attributes were previously accessed and
16581  * initialized in mq_create_ext.
16582  **/
16583 static void
16584 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
16585 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
16586 {
16587 	struct lpfc_mbx_mq_create *mq_create;
16588 	struct lpfc_dmabuf *dmabuf;
16589 	int length;
16590 
16591 	length = (sizeof(struct lpfc_mbx_mq_create) -
16592 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16593 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16594 			 LPFC_MBOX_OPCODE_MQ_CREATE,
16595 			 length, LPFC_SLI4_MBX_EMBED);
16596 	mq_create = &mbox->u.mqe.un.mq_create;
16597 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
16598 	       mq->page_count);
16599 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
16600 	       cq->queue_id);
16601 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
16602 	switch (mq->entry_count) {
16603 	case 16:
16604 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16605 		       LPFC_MQ_RING_SIZE_16);
16606 		break;
16607 	case 32:
16608 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16609 		       LPFC_MQ_RING_SIZE_32);
16610 		break;
16611 	case 64:
16612 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16613 		       LPFC_MQ_RING_SIZE_64);
16614 		break;
16615 	case 128:
16616 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16617 		       LPFC_MQ_RING_SIZE_128);
16618 		break;
16619 	}
16620 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16621 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16622 			putPaddrLow(dmabuf->phys);
16623 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16624 			putPaddrHigh(dmabuf->phys);
16625 	}
16626 }
16627 
16628 /**
16629  * lpfc_mq_create - Create a mailbox Queue on the HBA
16630  * @phba: HBA structure that indicates port to create a queue on.
16631  * @mq: The queue structure to use to create the mailbox queue.
16632  * @cq: The completion queue to associate with this cq.
16633  * @subtype: The queue's subtype.
16634  *
16635  * This function creates a mailbox queue, as detailed in @mq, on a port,
16636  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
16637  *
16638  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16639  * is used to get the entry count and entry size that are necessary to
16640  * determine the number of pages to allocate and use for this queue. This
16641  * function will send the MQ_CREATE mailbox command to the HBA to setup the
16642  * mailbox queue. This function is asynchronous and will wait for the mailbox
16643  * command to finish before continuing.
16644  *
16645  * On success this function will return a zero. If unable to allocate enough
16646  * memory this function will return -ENOMEM. If the queue create mailbox command
16647  * fails this function will return -ENXIO.
16648  **/
16649 int32_t
16650 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
16651 	       struct lpfc_queue *cq, uint32_t subtype)
16652 {
16653 	struct lpfc_mbx_mq_create *mq_create;
16654 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
16655 	struct lpfc_dmabuf *dmabuf;
16656 	LPFC_MBOXQ_t *mbox;
16657 	int rc, length, status = 0;
16658 	uint32_t shdr_status, shdr_add_status;
16659 	union lpfc_sli4_cfg_shdr *shdr;
16660 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16661 
16662 	/* sanity check on queue memory */
16663 	if (!mq || !cq)
16664 		return -ENODEV;
16665 	if (!phba->sli4_hba.pc_sli4_params.supported)
16666 		hw_page_size = SLI4_PAGE_SIZE;
16667 
16668 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16669 	if (!mbox)
16670 		return -ENOMEM;
16671 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
16672 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16673 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16674 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
16675 			 length, LPFC_SLI4_MBX_EMBED);
16676 
16677 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
16678 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
16679 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
16680 	       &mq_create_ext->u.request, mq->page_count);
16681 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
16682 	       &mq_create_ext->u.request, 1);
16683 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
16684 	       &mq_create_ext->u.request, 1);
16685 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
16686 	       &mq_create_ext->u.request, 1);
16687 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
16688 	       &mq_create_ext->u.request, 1);
16689 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
16690 	       &mq_create_ext->u.request, 1);
16691 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
16692 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16693 	       phba->sli4_hba.pc_sli4_params.mqv);
16694 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
16695 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
16696 		       cq->queue_id);
16697 	else
16698 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
16699 		       cq->queue_id);
16700 	switch (mq->entry_count) {
16701 	default:
16702 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16703 				"0362 Unsupported MQ count. (%d)\n",
16704 				mq->entry_count);
16705 		if (mq->entry_count < 16) {
16706 			status = -EINVAL;
16707 			goto out;
16708 		}
16709 		fallthrough;	/* otherwise default to smallest count */
16710 	case 16:
16711 		bf_set(lpfc_mq_context_ring_size,
16712 		       &mq_create_ext->u.request.context,
16713 		       LPFC_MQ_RING_SIZE_16);
16714 		break;
16715 	case 32:
16716 		bf_set(lpfc_mq_context_ring_size,
16717 		       &mq_create_ext->u.request.context,
16718 		       LPFC_MQ_RING_SIZE_32);
16719 		break;
16720 	case 64:
16721 		bf_set(lpfc_mq_context_ring_size,
16722 		       &mq_create_ext->u.request.context,
16723 		       LPFC_MQ_RING_SIZE_64);
16724 		break;
16725 	case 128:
16726 		bf_set(lpfc_mq_context_ring_size,
16727 		       &mq_create_ext->u.request.context,
16728 		       LPFC_MQ_RING_SIZE_128);
16729 		break;
16730 	}
16731 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16732 		memset(dmabuf->virt, 0, hw_page_size);
16733 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16734 					putPaddrLow(dmabuf->phys);
16735 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16736 					putPaddrHigh(dmabuf->phys);
16737 	}
16738 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16739 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16740 			      &mq_create_ext->u.response);
16741 	if (rc != MBX_SUCCESS) {
16742 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16743 				"2795 MQ_CREATE_EXT failed with "
16744 				"status x%x. Failback to MQ_CREATE.\n",
16745 				rc);
16746 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16747 		mq_create = &mbox->u.mqe.un.mq_create;
16748 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16749 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16750 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16751 				      &mq_create->u.response);
16752 	}
16753 
16754 	/* The IOCTL status is embedded in the mailbox subheader. */
16755 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16756 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16757 	if (shdr_status || shdr_add_status || rc) {
16758 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16759 				"2502 MQ_CREATE mailbox failed with "
16760 				"status x%x add_status x%x, mbx status x%x\n",
16761 				shdr_status, shdr_add_status, rc);
16762 		status = -ENXIO;
16763 		goto out;
16764 	}
16765 	if (mq->queue_id == 0xFFFF) {
16766 		status = -ENXIO;
16767 		goto out;
16768 	}
16769 	mq->type = LPFC_MQ;
16770 	mq->assoc_qid = cq->queue_id;
16771 	mq->subtype = subtype;
16772 	mq->host_index = 0;
16773 	mq->hba_index = 0;
16774 
16775 	/* link the mq onto the parent cq child list */
16776 	list_add_tail(&mq->list, &cq->child_list);
16777 out:
16778 	mempool_free(mbox, phba->mbox_mem_pool);
16779 	return status;
16780 }
16781 
16782 /**
16783  * lpfc_wq_create - Create a Work Queue on the HBA
16784  * @phba: HBA structure that indicates port to create a queue on.
16785  * @wq: The queue structure to use to create the work queue.
16786  * @cq: The completion queue to bind this work queue to.
16787  * @subtype: The subtype of the work queue indicating its functionality.
16788  *
16789  * This function creates a work queue, as detailed in @wq, on a port, described
16790  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16791  *
16792  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16793  * is used to get the entry count and entry size that are necessary to
16794  * determine the number of pages to allocate and use for this queue. The @cq
16795  * is used to indicate which completion queue to bind this work queue to. This
16796  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16797  * work queue. This function is asynchronous and will wait for the mailbox
16798  * command to finish before continuing.
16799  *
16800  * On success this function will return a zero. If unable to allocate enough
16801  * memory this function will return -ENOMEM. If the queue create mailbox command
16802  * fails this function will return -ENXIO.
16803  **/
16804 int
16805 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16806 	       struct lpfc_queue *cq, uint32_t subtype)
16807 {
16808 	struct lpfc_mbx_wq_create *wq_create;
16809 	struct lpfc_dmabuf *dmabuf;
16810 	LPFC_MBOXQ_t *mbox;
16811 	int rc, length, status = 0;
16812 	uint32_t shdr_status, shdr_add_status;
16813 	union lpfc_sli4_cfg_shdr *shdr;
16814 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16815 	struct dma_address *page;
16816 	void __iomem *bar_memmap_p;
16817 	uint32_t db_offset;
16818 	uint16_t pci_barset;
16819 	uint8_t dpp_barset;
16820 	uint32_t dpp_offset;
16821 	uint8_t wq_create_version;
16822 #ifdef CONFIG_X86
16823 	unsigned long pg_addr;
16824 #endif
16825 
16826 	/* sanity check on queue memory */
16827 	if (!wq || !cq)
16828 		return -ENODEV;
16829 	if (!phba->sli4_hba.pc_sli4_params.supported)
16830 		hw_page_size = wq->page_size;
16831 
16832 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16833 	if (!mbox)
16834 		return -ENOMEM;
16835 	length = (sizeof(struct lpfc_mbx_wq_create) -
16836 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16837 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16838 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16839 			 length, LPFC_SLI4_MBX_EMBED);
16840 	wq_create = &mbox->u.mqe.un.wq_create;
16841 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16842 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16843 		    wq->page_count);
16844 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16845 		    cq->queue_id);
16846 
16847 	/* wqv is the earliest version supported, NOT the latest */
16848 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16849 	       phba->sli4_hba.pc_sli4_params.wqv);
16850 
16851 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16852 	    (wq->page_size > SLI4_PAGE_SIZE))
16853 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
16854 	else
16855 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
16856 
16857 	switch (wq_create_version) {
16858 	case LPFC_Q_CREATE_VERSION_1:
16859 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
16860 		       wq->entry_count);
16861 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16862 		       LPFC_Q_CREATE_VERSION_1);
16863 
16864 		switch (wq->entry_size) {
16865 		default:
16866 		case 64:
16867 			bf_set(lpfc_mbx_wq_create_wqe_size,
16868 			       &wq_create->u.request_1,
16869 			       LPFC_WQ_WQE_SIZE_64);
16870 			break;
16871 		case 128:
16872 			bf_set(lpfc_mbx_wq_create_wqe_size,
16873 			       &wq_create->u.request_1,
16874 			       LPFC_WQ_WQE_SIZE_128);
16875 			break;
16876 		}
16877 		/* Request DPP by default */
16878 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
16879 		bf_set(lpfc_mbx_wq_create_page_size,
16880 		       &wq_create->u.request_1,
16881 		       (wq->page_size / SLI4_PAGE_SIZE));
16882 		page = wq_create->u.request_1.page;
16883 		break;
16884 	default:
16885 		page = wq_create->u.request.page;
16886 		break;
16887 	}
16888 
16889 	list_for_each_entry(dmabuf, &wq->page_list, list) {
16890 		memset(dmabuf->virt, 0, hw_page_size);
16891 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
16892 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
16893 	}
16894 
16895 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16896 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
16897 
16898 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16899 	/* The IOCTL status is embedded in the mailbox subheader. */
16900 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16901 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16902 	if (shdr_status || shdr_add_status || rc) {
16903 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16904 				"2503 WQ_CREATE mailbox failed with "
16905 				"status x%x add_status x%x, mbx status x%x\n",
16906 				shdr_status, shdr_add_status, rc);
16907 		status = -ENXIO;
16908 		goto out;
16909 	}
16910 
16911 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
16912 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
16913 					&wq_create->u.response);
16914 	else
16915 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
16916 					&wq_create->u.response_1);
16917 
16918 	if (wq->queue_id == 0xFFFF) {
16919 		status = -ENXIO;
16920 		goto out;
16921 	}
16922 
16923 	wq->db_format = LPFC_DB_LIST_FORMAT;
16924 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
16925 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16926 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
16927 					       &wq_create->u.response);
16928 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
16929 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
16930 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16931 						"3265 WQ[%d] doorbell format "
16932 						"not supported: x%x\n",
16933 						wq->queue_id, wq->db_format);
16934 				status = -EINVAL;
16935 				goto out;
16936 			}
16937 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
16938 					    &wq_create->u.response);
16939 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16940 								   pci_barset);
16941 			if (!bar_memmap_p) {
16942 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16943 						"3263 WQ[%d] failed to memmap "
16944 						"pci barset:x%x\n",
16945 						wq->queue_id, pci_barset);
16946 				status = -ENOMEM;
16947 				goto out;
16948 			}
16949 			db_offset = wq_create->u.response.doorbell_offset;
16950 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
16951 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
16952 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16953 						"3252 WQ[%d] doorbell offset "
16954 						"not supported: x%x\n",
16955 						wq->queue_id, db_offset);
16956 				status = -EINVAL;
16957 				goto out;
16958 			}
16959 			wq->db_regaddr = bar_memmap_p + db_offset;
16960 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16961 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
16962 					"format:x%x\n", wq->queue_id,
16963 					pci_barset, db_offset, wq->db_format);
16964 		} else
16965 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
16966 	} else {
16967 		/* Check if DPP was honored by the firmware */
16968 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
16969 				    &wq_create->u.response_1);
16970 		if (wq->dpp_enable) {
16971 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
16972 					    &wq_create->u.response_1);
16973 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16974 								   pci_barset);
16975 			if (!bar_memmap_p) {
16976 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16977 						"3267 WQ[%d] failed to memmap "
16978 						"pci barset:x%x\n",
16979 						wq->queue_id, pci_barset);
16980 				status = -ENOMEM;
16981 				goto out;
16982 			}
16983 			db_offset = wq_create->u.response_1.doorbell_offset;
16984 			wq->db_regaddr = bar_memmap_p + db_offset;
16985 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
16986 					    &wq_create->u.response_1);
16987 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
16988 					    &wq_create->u.response_1);
16989 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16990 								   dpp_barset);
16991 			if (!bar_memmap_p) {
16992 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16993 						"3268 WQ[%d] failed to memmap "
16994 						"pci barset:x%x\n",
16995 						wq->queue_id, dpp_barset);
16996 				status = -ENOMEM;
16997 				goto out;
16998 			}
16999 			dpp_offset = wq_create->u.response_1.dpp_offset;
17000 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
17001 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17002 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
17003 					"dpp_id:x%x dpp_barset:x%x "
17004 					"dpp_offset:x%x\n",
17005 					wq->queue_id, pci_barset, db_offset,
17006 					wq->dpp_id, dpp_barset, dpp_offset);
17007 
17008 #ifdef CONFIG_X86
17009 			/* Enable combined writes for DPP aperture */
17010 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
17011 			rc = set_memory_wc(pg_addr, 1);
17012 			if (rc) {
17013 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17014 					"3272 Cannot setup Combined "
17015 					"Write on WQ[%d] - disable DPP\n",
17016 					wq->queue_id);
17017 				phba->cfg_enable_dpp = 0;
17018 			}
17019 #else
17020 			phba->cfg_enable_dpp = 0;
17021 #endif
17022 		} else
17023 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17024 	}
17025 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
17026 	if (wq->pring == NULL) {
17027 		status = -ENOMEM;
17028 		goto out;
17029 	}
17030 	wq->type = LPFC_WQ;
17031 	wq->assoc_qid = cq->queue_id;
17032 	wq->subtype = subtype;
17033 	wq->host_index = 0;
17034 	wq->hba_index = 0;
17035 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
17036 
17037 	/* link the wq onto the parent cq child list */
17038 	list_add_tail(&wq->list, &cq->child_list);
17039 out:
17040 	mempool_free(mbox, phba->mbox_mem_pool);
17041 	return status;
17042 }
17043 
17044 /**
17045  * lpfc_rq_create - Create a Receive Queue on the HBA
17046  * @phba: HBA structure that indicates port to create a queue on.
17047  * @hrq: The queue structure to use to create the header receive queue.
17048  * @drq: The queue structure to use to create the data receive queue.
17049  * @cq: The completion queue to bind this work queue to.
17050  * @subtype: The subtype of the work queue indicating its functionality.
17051  *
17052  * This function creates a receive buffer queue pair , as detailed in @hrq and
17053  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17054  * to the HBA.
17055  *
17056  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17057  * struct is used to get the entry count that is necessary to determine the
17058  * number of pages to use for this queue. The @cq is used to indicate which
17059  * completion queue to bind received buffers that are posted to these queues to.
17060  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17061  * receive queue pair. This function is asynchronous and will wait for the
17062  * mailbox command to finish before continuing.
17063  *
17064  * On success this function will return a zero. If unable to allocate enough
17065  * memory this function will return -ENOMEM. If the queue create mailbox command
17066  * fails this function will return -ENXIO.
17067  **/
17068 int
17069 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17070 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
17071 {
17072 	struct lpfc_mbx_rq_create *rq_create;
17073 	struct lpfc_dmabuf *dmabuf;
17074 	LPFC_MBOXQ_t *mbox;
17075 	int rc, length, status = 0;
17076 	uint32_t shdr_status, shdr_add_status;
17077 	union lpfc_sli4_cfg_shdr *shdr;
17078 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17079 	void __iomem *bar_memmap_p;
17080 	uint32_t db_offset;
17081 	uint16_t pci_barset;
17082 
17083 	/* sanity check on queue memory */
17084 	if (!hrq || !drq || !cq)
17085 		return -ENODEV;
17086 	if (!phba->sli4_hba.pc_sli4_params.supported)
17087 		hw_page_size = SLI4_PAGE_SIZE;
17088 
17089 	if (hrq->entry_count != drq->entry_count)
17090 		return -EINVAL;
17091 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17092 	if (!mbox)
17093 		return -ENOMEM;
17094 	length = (sizeof(struct lpfc_mbx_rq_create) -
17095 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17096 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17097 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17098 			 length, LPFC_SLI4_MBX_EMBED);
17099 	rq_create = &mbox->u.mqe.un.rq_create;
17100 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17101 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17102 	       phba->sli4_hba.pc_sli4_params.rqv);
17103 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17104 		bf_set(lpfc_rq_context_rqe_count_1,
17105 		       &rq_create->u.request.context,
17106 		       hrq->entry_count);
17107 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
17108 		bf_set(lpfc_rq_context_rqe_size,
17109 		       &rq_create->u.request.context,
17110 		       LPFC_RQE_SIZE_8);
17111 		bf_set(lpfc_rq_context_page_size,
17112 		       &rq_create->u.request.context,
17113 		       LPFC_RQ_PAGE_SIZE_4096);
17114 	} else {
17115 		switch (hrq->entry_count) {
17116 		default:
17117 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17118 					"2535 Unsupported RQ count. (%d)\n",
17119 					hrq->entry_count);
17120 			if (hrq->entry_count < 512) {
17121 				status = -EINVAL;
17122 				goto out;
17123 			}
17124 			fallthrough;	/* otherwise default to smallest count */
17125 		case 512:
17126 			bf_set(lpfc_rq_context_rqe_count,
17127 			       &rq_create->u.request.context,
17128 			       LPFC_RQ_RING_SIZE_512);
17129 			break;
17130 		case 1024:
17131 			bf_set(lpfc_rq_context_rqe_count,
17132 			       &rq_create->u.request.context,
17133 			       LPFC_RQ_RING_SIZE_1024);
17134 			break;
17135 		case 2048:
17136 			bf_set(lpfc_rq_context_rqe_count,
17137 			       &rq_create->u.request.context,
17138 			       LPFC_RQ_RING_SIZE_2048);
17139 			break;
17140 		case 4096:
17141 			bf_set(lpfc_rq_context_rqe_count,
17142 			       &rq_create->u.request.context,
17143 			       LPFC_RQ_RING_SIZE_4096);
17144 			break;
17145 		}
17146 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
17147 		       LPFC_HDR_BUF_SIZE);
17148 	}
17149 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17150 	       cq->queue_id);
17151 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17152 	       hrq->page_count);
17153 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
17154 		memset(dmabuf->virt, 0, hw_page_size);
17155 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17156 					putPaddrLow(dmabuf->phys);
17157 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17158 					putPaddrHigh(dmabuf->phys);
17159 	}
17160 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17161 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17162 
17163 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17164 	/* The IOCTL status is embedded in the mailbox subheader. */
17165 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17166 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17167 	if (shdr_status || shdr_add_status || rc) {
17168 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17169 				"2504 RQ_CREATE mailbox failed with "
17170 				"status x%x add_status x%x, mbx status x%x\n",
17171 				shdr_status, shdr_add_status, rc);
17172 		status = -ENXIO;
17173 		goto out;
17174 	}
17175 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17176 	if (hrq->queue_id == 0xFFFF) {
17177 		status = -ENXIO;
17178 		goto out;
17179 	}
17180 
17181 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
17182 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
17183 					&rq_create->u.response);
17184 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
17185 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
17186 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17187 					"3262 RQ [%d] doorbell format not "
17188 					"supported: x%x\n", hrq->queue_id,
17189 					hrq->db_format);
17190 			status = -EINVAL;
17191 			goto out;
17192 		}
17193 
17194 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
17195 				    &rq_create->u.response);
17196 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
17197 		if (!bar_memmap_p) {
17198 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17199 					"3269 RQ[%d] failed to memmap pci "
17200 					"barset:x%x\n", hrq->queue_id,
17201 					pci_barset);
17202 			status = -ENOMEM;
17203 			goto out;
17204 		}
17205 
17206 		db_offset = rq_create->u.response.doorbell_offset;
17207 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
17208 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
17209 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17210 					"3270 RQ[%d] doorbell offset not "
17211 					"supported: x%x\n", hrq->queue_id,
17212 					db_offset);
17213 			status = -EINVAL;
17214 			goto out;
17215 		}
17216 		hrq->db_regaddr = bar_memmap_p + db_offset;
17217 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17218 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
17219 				"format:x%x\n", hrq->queue_id, pci_barset,
17220 				db_offset, hrq->db_format);
17221 	} else {
17222 		hrq->db_format = LPFC_DB_RING_FORMAT;
17223 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17224 	}
17225 	hrq->type = LPFC_HRQ;
17226 	hrq->assoc_qid = cq->queue_id;
17227 	hrq->subtype = subtype;
17228 	hrq->host_index = 0;
17229 	hrq->hba_index = 0;
17230 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17231 
17232 	/* now create the data queue */
17233 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17234 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17235 			 length, LPFC_SLI4_MBX_EMBED);
17236 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17237 	       phba->sli4_hba.pc_sli4_params.rqv);
17238 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17239 		bf_set(lpfc_rq_context_rqe_count_1,
17240 		       &rq_create->u.request.context, hrq->entry_count);
17241 		if (subtype == LPFC_NVMET)
17242 			rq_create->u.request.context.buffer_size =
17243 				LPFC_NVMET_DATA_BUF_SIZE;
17244 		else
17245 			rq_create->u.request.context.buffer_size =
17246 				LPFC_DATA_BUF_SIZE;
17247 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
17248 		       LPFC_RQE_SIZE_8);
17249 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
17250 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
17251 	} else {
17252 		switch (drq->entry_count) {
17253 		default:
17254 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17255 					"2536 Unsupported RQ count. (%d)\n",
17256 					drq->entry_count);
17257 			if (drq->entry_count < 512) {
17258 				status = -EINVAL;
17259 				goto out;
17260 			}
17261 			fallthrough;	/* otherwise default to smallest count */
17262 		case 512:
17263 			bf_set(lpfc_rq_context_rqe_count,
17264 			       &rq_create->u.request.context,
17265 			       LPFC_RQ_RING_SIZE_512);
17266 			break;
17267 		case 1024:
17268 			bf_set(lpfc_rq_context_rqe_count,
17269 			       &rq_create->u.request.context,
17270 			       LPFC_RQ_RING_SIZE_1024);
17271 			break;
17272 		case 2048:
17273 			bf_set(lpfc_rq_context_rqe_count,
17274 			       &rq_create->u.request.context,
17275 			       LPFC_RQ_RING_SIZE_2048);
17276 			break;
17277 		case 4096:
17278 			bf_set(lpfc_rq_context_rqe_count,
17279 			       &rq_create->u.request.context,
17280 			       LPFC_RQ_RING_SIZE_4096);
17281 			break;
17282 		}
17283 		if (subtype == LPFC_NVMET)
17284 			bf_set(lpfc_rq_context_buf_size,
17285 			       &rq_create->u.request.context,
17286 			       LPFC_NVMET_DATA_BUF_SIZE);
17287 		else
17288 			bf_set(lpfc_rq_context_buf_size,
17289 			       &rq_create->u.request.context,
17290 			       LPFC_DATA_BUF_SIZE);
17291 	}
17292 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17293 	       cq->queue_id);
17294 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17295 	       drq->page_count);
17296 	list_for_each_entry(dmabuf, &drq->page_list, list) {
17297 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17298 					putPaddrLow(dmabuf->phys);
17299 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17300 					putPaddrHigh(dmabuf->phys);
17301 	}
17302 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17303 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17304 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17305 	/* The IOCTL status is embedded in the mailbox subheader. */
17306 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17307 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17308 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17309 	if (shdr_status || shdr_add_status || rc) {
17310 		status = -ENXIO;
17311 		goto out;
17312 	}
17313 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17314 	if (drq->queue_id == 0xFFFF) {
17315 		status = -ENXIO;
17316 		goto out;
17317 	}
17318 	drq->type = LPFC_DRQ;
17319 	drq->assoc_qid = cq->queue_id;
17320 	drq->subtype = subtype;
17321 	drq->host_index = 0;
17322 	drq->hba_index = 0;
17323 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17324 
17325 	/* link the header and data RQs onto the parent cq child list */
17326 	list_add_tail(&hrq->list, &cq->child_list);
17327 	list_add_tail(&drq->list, &cq->child_list);
17328 
17329 out:
17330 	mempool_free(mbox, phba->mbox_mem_pool);
17331 	return status;
17332 }
17333 
17334 /**
17335  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
17336  * @phba: HBA structure that indicates port to create a queue on.
17337  * @hrqp: The queue structure array to use to create the header receive queues.
17338  * @drqp: The queue structure array to use to create the data receive queues.
17339  * @cqp: The completion queue array to bind these receive queues to.
17340  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
17341  *
17342  * This function creates a receive buffer queue pair , as detailed in @hrq and
17343  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17344  * to the HBA.
17345  *
17346  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17347  * struct is used to get the entry count that is necessary to determine the
17348  * number of pages to use for this queue. The @cq is used to indicate which
17349  * completion queue to bind received buffers that are posted to these queues to.
17350  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17351  * receive queue pair. This function is asynchronous and will wait for the
17352  * mailbox command to finish before continuing.
17353  *
17354  * On success this function will return a zero. If unable to allocate enough
17355  * memory this function will return -ENOMEM. If the queue create mailbox command
17356  * fails this function will return -ENXIO.
17357  **/
17358 int
17359 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
17360 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
17361 		uint32_t subtype)
17362 {
17363 	struct lpfc_queue *hrq, *drq, *cq;
17364 	struct lpfc_mbx_rq_create_v2 *rq_create;
17365 	struct lpfc_dmabuf *dmabuf;
17366 	LPFC_MBOXQ_t *mbox;
17367 	int rc, length, alloclen, status = 0;
17368 	int cnt, idx, numrq, page_idx = 0;
17369 	uint32_t shdr_status, shdr_add_status;
17370 	union lpfc_sli4_cfg_shdr *shdr;
17371 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17372 
17373 	numrq = phba->cfg_nvmet_mrq;
17374 	/* sanity check on array memory */
17375 	if (!hrqp || !drqp || !cqp || !numrq)
17376 		return -ENODEV;
17377 	if (!phba->sli4_hba.pc_sli4_params.supported)
17378 		hw_page_size = SLI4_PAGE_SIZE;
17379 
17380 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17381 	if (!mbox)
17382 		return -ENOMEM;
17383 
17384 	length = sizeof(struct lpfc_mbx_rq_create_v2);
17385 	length += ((2 * numrq * hrqp[0]->page_count) *
17386 		   sizeof(struct dma_address));
17387 
17388 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17389 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
17390 				    LPFC_SLI4_MBX_NEMBED);
17391 	if (alloclen < length) {
17392 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17393 				"3099 Allocated DMA memory size (%d) is "
17394 				"less than the requested DMA memory size "
17395 				"(%d)\n", alloclen, length);
17396 		status = -ENOMEM;
17397 		goto out;
17398 	}
17399 
17400 
17401 
17402 	rq_create = mbox->sge_array->addr[0];
17403 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
17404 
17405 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
17406 	cnt = 0;
17407 
17408 	for (idx = 0; idx < numrq; idx++) {
17409 		hrq = hrqp[idx];
17410 		drq = drqp[idx];
17411 		cq  = cqp[idx];
17412 
17413 		/* sanity check on queue memory */
17414 		if (!hrq || !drq || !cq) {
17415 			status = -ENODEV;
17416 			goto out;
17417 		}
17418 
17419 		if (hrq->entry_count != drq->entry_count) {
17420 			status = -EINVAL;
17421 			goto out;
17422 		}
17423 
17424 		if (idx == 0) {
17425 			bf_set(lpfc_mbx_rq_create_num_pages,
17426 			       &rq_create->u.request,
17427 			       hrq->page_count);
17428 			bf_set(lpfc_mbx_rq_create_rq_cnt,
17429 			       &rq_create->u.request, (numrq * 2));
17430 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
17431 			       1);
17432 			bf_set(lpfc_rq_context_base_cq,
17433 			       &rq_create->u.request.context,
17434 			       cq->queue_id);
17435 			bf_set(lpfc_rq_context_data_size,
17436 			       &rq_create->u.request.context,
17437 			       LPFC_NVMET_DATA_BUF_SIZE);
17438 			bf_set(lpfc_rq_context_hdr_size,
17439 			       &rq_create->u.request.context,
17440 			       LPFC_HDR_BUF_SIZE);
17441 			bf_set(lpfc_rq_context_rqe_count_1,
17442 			       &rq_create->u.request.context,
17443 			       hrq->entry_count);
17444 			bf_set(lpfc_rq_context_rqe_size,
17445 			       &rq_create->u.request.context,
17446 			       LPFC_RQE_SIZE_8);
17447 			bf_set(lpfc_rq_context_page_size,
17448 			       &rq_create->u.request.context,
17449 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
17450 		}
17451 		rc = 0;
17452 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
17453 			memset(dmabuf->virt, 0, hw_page_size);
17454 			cnt = page_idx + dmabuf->buffer_tag;
17455 			rq_create->u.request.page[cnt].addr_lo =
17456 					putPaddrLow(dmabuf->phys);
17457 			rq_create->u.request.page[cnt].addr_hi =
17458 					putPaddrHigh(dmabuf->phys);
17459 			rc++;
17460 		}
17461 		page_idx += rc;
17462 
17463 		rc = 0;
17464 		list_for_each_entry(dmabuf, &drq->page_list, list) {
17465 			memset(dmabuf->virt, 0, hw_page_size);
17466 			cnt = page_idx + dmabuf->buffer_tag;
17467 			rq_create->u.request.page[cnt].addr_lo =
17468 					putPaddrLow(dmabuf->phys);
17469 			rq_create->u.request.page[cnt].addr_hi =
17470 					putPaddrHigh(dmabuf->phys);
17471 			rc++;
17472 		}
17473 		page_idx += rc;
17474 
17475 		hrq->db_format = LPFC_DB_RING_FORMAT;
17476 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17477 		hrq->type = LPFC_HRQ;
17478 		hrq->assoc_qid = cq->queue_id;
17479 		hrq->subtype = subtype;
17480 		hrq->host_index = 0;
17481 		hrq->hba_index = 0;
17482 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17483 
17484 		drq->db_format = LPFC_DB_RING_FORMAT;
17485 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17486 		drq->type = LPFC_DRQ;
17487 		drq->assoc_qid = cq->queue_id;
17488 		drq->subtype = subtype;
17489 		drq->host_index = 0;
17490 		drq->hba_index = 0;
17491 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17492 
17493 		list_add_tail(&hrq->list, &cq->child_list);
17494 		list_add_tail(&drq->list, &cq->child_list);
17495 	}
17496 
17497 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17498 	/* The IOCTL status is embedded in the mailbox subheader. */
17499 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17500 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17501 	if (shdr_status || shdr_add_status || rc) {
17502 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17503 				"3120 RQ_CREATE mailbox failed with "
17504 				"status x%x add_status x%x, mbx status x%x\n",
17505 				shdr_status, shdr_add_status, rc);
17506 		status = -ENXIO;
17507 		goto out;
17508 	}
17509 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17510 	if (rc == 0xFFFF) {
17511 		status = -ENXIO;
17512 		goto out;
17513 	}
17514 
17515 	/* Initialize all RQs with associated queue id */
17516 	for (idx = 0; idx < numrq; idx++) {
17517 		hrq = hrqp[idx];
17518 		hrq->queue_id = rc + (2 * idx);
17519 		drq = drqp[idx];
17520 		drq->queue_id = rc + (2 * idx) + 1;
17521 	}
17522 
17523 out:
17524 	lpfc_sli4_mbox_cmd_free(phba, mbox);
17525 	return status;
17526 }
17527 
17528 /**
17529  * lpfc_eq_destroy - Destroy an event Queue on the HBA
17530  * @phba: HBA structure that indicates port to destroy a queue on.
17531  * @eq: The queue structure associated with the queue to destroy.
17532  *
17533  * This function destroys a queue, as detailed in @eq by sending an mailbox
17534  * command, specific to the type of queue, to the HBA.
17535  *
17536  * The @eq struct is used to get the queue ID of the queue to destroy.
17537  *
17538  * On success this function will return a zero. If the queue destroy mailbox
17539  * command fails this function will return -ENXIO.
17540  **/
17541 int
17542 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
17543 {
17544 	LPFC_MBOXQ_t *mbox;
17545 	int rc, length, status = 0;
17546 	uint32_t shdr_status, shdr_add_status;
17547 	union lpfc_sli4_cfg_shdr *shdr;
17548 
17549 	/* sanity check on queue memory */
17550 	if (!eq)
17551 		return -ENODEV;
17552 
17553 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
17554 	if (!mbox)
17555 		return -ENOMEM;
17556 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
17557 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17558 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17559 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
17560 			 length, LPFC_SLI4_MBX_EMBED);
17561 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
17562 	       eq->queue_id);
17563 	mbox->vport = eq->phba->pport;
17564 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17565 
17566 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
17567 	/* The IOCTL status is embedded in the mailbox subheader. */
17568 	shdr = (union lpfc_sli4_cfg_shdr *)
17569 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
17570 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17571 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17572 	if (shdr_status || shdr_add_status || rc) {
17573 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17574 				"2505 EQ_DESTROY mailbox failed with "
17575 				"status x%x add_status x%x, mbx status x%x\n",
17576 				shdr_status, shdr_add_status, rc);
17577 		status = -ENXIO;
17578 	}
17579 
17580 	/* Remove eq from any list */
17581 	list_del_init(&eq->list);
17582 	mempool_free(mbox, eq->phba->mbox_mem_pool);
17583 	return status;
17584 }
17585 
17586 /**
17587  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
17588  * @phba: HBA structure that indicates port to destroy a queue on.
17589  * @cq: The queue structure associated with the queue to destroy.
17590  *
17591  * This function destroys a queue, as detailed in @cq by sending an mailbox
17592  * command, specific to the type of queue, to the HBA.
17593  *
17594  * The @cq struct is used to get the queue ID of the queue to destroy.
17595  *
17596  * On success this function will return a zero. If the queue destroy mailbox
17597  * command fails this function will return -ENXIO.
17598  **/
17599 int
17600 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
17601 {
17602 	LPFC_MBOXQ_t *mbox;
17603 	int rc, length, status = 0;
17604 	uint32_t shdr_status, shdr_add_status;
17605 	union lpfc_sli4_cfg_shdr *shdr;
17606 
17607 	/* sanity check on queue memory */
17608 	if (!cq)
17609 		return -ENODEV;
17610 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
17611 	if (!mbox)
17612 		return -ENOMEM;
17613 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
17614 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17615 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17616 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
17617 			 length, LPFC_SLI4_MBX_EMBED);
17618 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
17619 	       cq->queue_id);
17620 	mbox->vport = cq->phba->pport;
17621 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17622 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
17623 	/* The IOCTL status is embedded in the mailbox subheader. */
17624 	shdr = (union lpfc_sli4_cfg_shdr *)
17625 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
17626 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17627 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17628 	if (shdr_status || shdr_add_status || rc) {
17629 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17630 				"2506 CQ_DESTROY mailbox failed with "
17631 				"status x%x add_status x%x, mbx status x%x\n",
17632 				shdr_status, shdr_add_status, rc);
17633 		status = -ENXIO;
17634 	}
17635 	/* Remove cq from any list */
17636 	list_del_init(&cq->list);
17637 	mempool_free(mbox, cq->phba->mbox_mem_pool);
17638 	return status;
17639 }
17640 
17641 /**
17642  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
17643  * @phba: HBA structure that indicates port to destroy a queue on.
17644  * @mq: The queue structure associated with the queue to destroy.
17645  *
17646  * This function destroys a queue, as detailed in @mq by sending an mailbox
17647  * command, specific to the type of queue, to the HBA.
17648  *
17649  * The @mq struct is used to get the queue ID of the queue to destroy.
17650  *
17651  * On success this function will return a zero. If the queue destroy mailbox
17652  * command fails this function will return -ENXIO.
17653  **/
17654 int
17655 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
17656 {
17657 	LPFC_MBOXQ_t *mbox;
17658 	int rc, length, status = 0;
17659 	uint32_t shdr_status, shdr_add_status;
17660 	union lpfc_sli4_cfg_shdr *shdr;
17661 
17662 	/* sanity check on queue memory */
17663 	if (!mq)
17664 		return -ENODEV;
17665 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
17666 	if (!mbox)
17667 		return -ENOMEM;
17668 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
17669 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17670 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17671 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
17672 			 length, LPFC_SLI4_MBX_EMBED);
17673 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
17674 	       mq->queue_id);
17675 	mbox->vport = mq->phba->pport;
17676 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17677 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
17678 	/* The IOCTL status is embedded in the mailbox subheader. */
17679 	shdr = (union lpfc_sli4_cfg_shdr *)
17680 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
17681 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17682 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17683 	if (shdr_status || shdr_add_status || rc) {
17684 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17685 				"2507 MQ_DESTROY mailbox failed with "
17686 				"status x%x add_status x%x, mbx status x%x\n",
17687 				shdr_status, shdr_add_status, rc);
17688 		status = -ENXIO;
17689 	}
17690 	/* Remove mq from any list */
17691 	list_del_init(&mq->list);
17692 	mempool_free(mbox, mq->phba->mbox_mem_pool);
17693 	return status;
17694 }
17695 
17696 /**
17697  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
17698  * @phba: HBA structure that indicates port to destroy a queue on.
17699  * @wq: The queue structure associated with the queue to destroy.
17700  *
17701  * This function destroys a queue, as detailed in @wq by sending an mailbox
17702  * command, specific to the type of queue, to the HBA.
17703  *
17704  * The @wq struct is used to get the queue ID of the queue to destroy.
17705  *
17706  * On success this function will return a zero. If the queue destroy mailbox
17707  * command fails this function will return -ENXIO.
17708  **/
17709 int
17710 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
17711 {
17712 	LPFC_MBOXQ_t *mbox;
17713 	int rc, length, status = 0;
17714 	uint32_t shdr_status, shdr_add_status;
17715 	union lpfc_sli4_cfg_shdr *shdr;
17716 
17717 	/* sanity check on queue memory */
17718 	if (!wq)
17719 		return -ENODEV;
17720 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17721 	if (!mbox)
17722 		return -ENOMEM;
17723 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
17724 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17725 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17726 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17727 			 length, LPFC_SLI4_MBX_EMBED);
17728 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17729 	       wq->queue_id);
17730 	mbox->vport = wq->phba->pport;
17731 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17732 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17733 	shdr = (union lpfc_sli4_cfg_shdr *)
17734 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17735 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17736 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17737 	if (shdr_status || shdr_add_status || rc) {
17738 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17739 				"2508 WQ_DESTROY mailbox failed with "
17740 				"status x%x add_status x%x, mbx status x%x\n",
17741 				shdr_status, shdr_add_status, rc);
17742 		status = -ENXIO;
17743 	}
17744 	/* Remove wq from any list */
17745 	list_del_init(&wq->list);
17746 	kfree(wq->pring);
17747 	wq->pring = NULL;
17748 	mempool_free(mbox, wq->phba->mbox_mem_pool);
17749 	return status;
17750 }
17751 
17752 /**
17753  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17754  * @phba: HBA structure that indicates port to destroy a queue on.
17755  * @hrq: The queue structure associated with the queue to destroy.
17756  * @drq: The queue structure associated with the queue to destroy.
17757  *
17758  * This function destroys a queue, as detailed in @rq by sending an mailbox
17759  * command, specific to the type of queue, to the HBA.
17760  *
17761  * The @rq struct is used to get the queue ID of the queue to destroy.
17762  *
17763  * On success this function will return a zero. If the queue destroy mailbox
17764  * command fails this function will return -ENXIO.
17765  **/
17766 int
17767 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17768 		struct lpfc_queue *drq)
17769 {
17770 	LPFC_MBOXQ_t *mbox;
17771 	int rc, length, status = 0;
17772 	uint32_t shdr_status, shdr_add_status;
17773 	union lpfc_sli4_cfg_shdr *shdr;
17774 
17775 	/* sanity check on queue memory */
17776 	if (!hrq || !drq)
17777 		return -ENODEV;
17778 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17779 	if (!mbox)
17780 		return -ENOMEM;
17781 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
17782 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17783 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17784 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17785 			 length, LPFC_SLI4_MBX_EMBED);
17786 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17787 	       hrq->queue_id);
17788 	mbox->vport = hrq->phba->pport;
17789 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17790 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17791 	/* The IOCTL status is embedded in the mailbox subheader. */
17792 	shdr = (union lpfc_sli4_cfg_shdr *)
17793 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17794 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17795 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17796 	if (shdr_status || shdr_add_status || rc) {
17797 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17798 				"2509 RQ_DESTROY mailbox failed with "
17799 				"status x%x add_status x%x, mbx status x%x\n",
17800 				shdr_status, shdr_add_status, rc);
17801 		mempool_free(mbox, hrq->phba->mbox_mem_pool);
17802 		return -ENXIO;
17803 	}
17804 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17805 	       drq->queue_id);
17806 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17807 	shdr = (union lpfc_sli4_cfg_shdr *)
17808 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17809 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17810 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17811 	if (shdr_status || shdr_add_status || rc) {
17812 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17813 				"2510 RQ_DESTROY mailbox failed with "
17814 				"status x%x add_status x%x, mbx status x%x\n",
17815 				shdr_status, shdr_add_status, rc);
17816 		status = -ENXIO;
17817 	}
17818 	list_del_init(&hrq->list);
17819 	list_del_init(&drq->list);
17820 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
17821 	return status;
17822 }
17823 
17824 /**
17825  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17826  * @phba: The virtual port for which this call being executed.
17827  * @pdma_phys_addr0: Physical address of the 1st SGL page.
17828  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
17829  * @xritag: the xritag that ties this io to the SGL pages.
17830  *
17831  * This routine will post the sgl pages for the IO that has the xritag
17832  * that is in the iocbq structure. The xritag is assigned during iocbq
17833  * creation and persists for as long as the driver is loaded.
17834  * if the caller has fewer than 256 scatter gather segments to map then
17835  * pdma_phys_addr1 should be 0.
17836  * If the caller needs to map more than 256 scatter gather segment then
17837  * pdma_phys_addr1 should be a valid physical address.
17838  * physical address for SGLs must be 64 byte aligned.
17839  * If you are going to map 2 SGL's then the first one must have 256 entries
17840  * the second sgl can have between 1 and 256 entries.
17841  *
17842  * Return codes:
17843  * 	0 - Success
17844  * 	-ENXIO, -ENOMEM - Failure
17845  **/
17846 int
17847 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
17848 		dma_addr_t pdma_phys_addr0,
17849 		dma_addr_t pdma_phys_addr1,
17850 		uint16_t xritag)
17851 {
17852 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
17853 	LPFC_MBOXQ_t *mbox;
17854 	int rc;
17855 	uint32_t shdr_status, shdr_add_status;
17856 	uint32_t mbox_tmo;
17857 	union lpfc_sli4_cfg_shdr *shdr;
17858 
17859 	if (xritag == NO_XRI) {
17860 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17861 				"0364 Invalid param:\n");
17862 		return -EINVAL;
17863 	}
17864 
17865 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17866 	if (!mbox)
17867 		return -ENOMEM;
17868 
17869 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17870 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17871 			sizeof(struct lpfc_mbx_post_sgl_pages) -
17872 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17873 
17874 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
17875 				&mbox->u.mqe.un.post_sgl_pages;
17876 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
17877 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
17878 
17879 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
17880 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
17881 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
17882 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
17883 
17884 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
17885 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
17886 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
17887 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
17888 	if (!phba->sli4_hba.intr_enable)
17889 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17890 	else {
17891 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17892 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17893 	}
17894 	/* The IOCTL status is embedded in the mailbox subheader. */
17895 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
17896 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17897 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17898 	if (!phba->sli4_hba.intr_enable)
17899 		mempool_free(mbox, phba->mbox_mem_pool);
17900 	else if (rc != MBX_TIMEOUT)
17901 		mempool_free(mbox, phba->mbox_mem_pool);
17902 	if (shdr_status || shdr_add_status || rc) {
17903 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17904 				"2511 POST_SGL mailbox failed with "
17905 				"status x%x add_status x%x, mbx status x%x\n",
17906 				shdr_status, shdr_add_status, rc);
17907 	}
17908 	return 0;
17909 }
17910 
17911 /**
17912  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
17913  * @phba: pointer to lpfc hba data structure.
17914  *
17915  * This routine is invoked to post rpi header templates to the
17916  * HBA consistent with the SLI-4 interface spec.  This routine
17917  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
17918  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
17919  *
17920  * Returns
17921  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
17922  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
17923  **/
17924 static uint16_t
17925 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
17926 {
17927 	unsigned long xri;
17928 
17929 	/*
17930 	 * Fetch the next logical xri.  Because this index is logical,
17931 	 * the driver starts at 0 each time.
17932 	 */
17933 	spin_lock_irq(&phba->hbalock);
17934 	xri = find_first_zero_bit(phba->sli4_hba.xri_bmask,
17935 				 phba->sli4_hba.max_cfg_param.max_xri);
17936 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
17937 		spin_unlock_irq(&phba->hbalock);
17938 		return NO_XRI;
17939 	} else {
17940 		set_bit(xri, phba->sli4_hba.xri_bmask);
17941 		phba->sli4_hba.max_cfg_param.xri_used++;
17942 	}
17943 	spin_unlock_irq(&phba->hbalock);
17944 	return xri;
17945 }
17946 
17947 /**
17948  * __lpfc_sli4_free_xri - Release an xri for reuse.
17949  * @phba: pointer to lpfc hba data structure.
17950  * @xri: xri to release.
17951  *
17952  * This routine is invoked to release an xri to the pool of
17953  * available rpis maintained by the driver.
17954  **/
17955 static void
17956 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
17957 {
17958 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
17959 		phba->sli4_hba.max_cfg_param.xri_used--;
17960 	}
17961 }
17962 
17963 /**
17964  * lpfc_sli4_free_xri - Release an xri for reuse.
17965  * @phba: pointer to lpfc hba data structure.
17966  * @xri: xri to release.
17967  *
17968  * This routine is invoked to release an xri to the pool of
17969  * available rpis maintained by the driver.
17970  **/
17971 void
17972 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
17973 {
17974 	spin_lock_irq(&phba->hbalock);
17975 	__lpfc_sli4_free_xri(phba, xri);
17976 	spin_unlock_irq(&phba->hbalock);
17977 }
17978 
17979 /**
17980  * lpfc_sli4_next_xritag - Get an xritag for the io
17981  * @phba: Pointer to HBA context object.
17982  *
17983  * This function gets an xritag for the iocb. If there is no unused xritag
17984  * it will return 0xffff.
17985  * The function returns the allocated xritag if successful, else returns zero.
17986  * Zero is not a valid xritag.
17987  * The caller is not required to hold any lock.
17988  **/
17989 uint16_t
17990 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
17991 {
17992 	uint16_t xri_index;
17993 
17994 	xri_index = lpfc_sli4_alloc_xri(phba);
17995 	if (xri_index == NO_XRI)
17996 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
17997 				"2004 Failed to allocate XRI.last XRITAG is %d"
17998 				" Max XRI is %d, Used XRI is %d\n",
17999 				xri_index,
18000 				phba->sli4_hba.max_cfg_param.max_xri,
18001 				phba->sli4_hba.max_cfg_param.xri_used);
18002 	return xri_index;
18003 }
18004 
18005 /**
18006  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
18007  * @phba: pointer to lpfc hba data structure.
18008  * @post_sgl_list: pointer to els sgl entry list.
18009  * @post_cnt: number of els sgl entries on the list.
18010  *
18011  * This routine is invoked to post a block of driver's sgl pages to the
18012  * HBA using non-embedded mailbox command. No Lock is held. This routine
18013  * is only called when the driver is loading and after all IO has been
18014  * stopped.
18015  **/
18016 static int
18017 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
18018 			    struct list_head *post_sgl_list,
18019 			    int post_cnt)
18020 {
18021 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
18022 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18023 	struct sgl_page_pairs *sgl_pg_pairs;
18024 	void *viraddr;
18025 	LPFC_MBOXQ_t *mbox;
18026 	uint32_t reqlen, alloclen, pg_pairs;
18027 	uint32_t mbox_tmo;
18028 	uint16_t xritag_start = 0;
18029 	int rc = 0;
18030 	uint32_t shdr_status, shdr_add_status;
18031 	union lpfc_sli4_cfg_shdr *shdr;
18032 
18033 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
18034 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18035 	if (reqlen > SLI4_PAGE_SIZE) {
18036 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18037 				"2559 Block sgl registration required DMA "
18038 				"size (%d) great than a page\n", reqlen);
18039 		return -ENOMEM;
18040 	}
18041 
18042 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18043 	if (!mbox)
18044 		return -ENOMEM;
18045 
18046 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18047 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18048 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
18049 			 LPFC_SLI4_MBX_NEMBED);
18050 
18051 	if (alloclen < reqlen) {
18052 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18053 				"0285 Allocated DMA memory size (%d) is "
18054 				"less than the requested DMA memory "
18055 				"size (%d)\n", alloclen, reqlen);
18056 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18057 		return -ENOMEM;
18058 	}
18059 	/* Set up the SGL pages in the non-embedded DMA pages */
18060 	viraddr = mbox->sge_array->addr[0];
18061 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18062 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18063 
18064 	pg_pairs = 0;
18065 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
18066 		/* Set up the sge entry */
18067 		sgl_pg_pairs->sgl_pg0_addr_lo =
18068 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
18069 		sgl_pg_pairs->sgl_pg0_addr_hi =
18070 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
18071 		sgl_pg_pairs->sgl_pg1_addr_lo =
18072 				cpu_to_le32(putPaddrLow(0));
18073 		sgl_pg_pairs->sgl_pg1_addr_hi =
18074 				cpu_to_le32(putPaddrHigh(0));
18075 
18076 		/* Keep the first xritag on the list */
18077 		if (pg_pairs == 0)
18078 			xritag_start = sglq_entry->sli4_xritag;
18079 		sgl_pg_pairs++;
18080 		pg_pairs++;
18081 	}
18082 
18083 	/* Complete initialization and perform endian conversion. */
18084 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18085 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
18086 	sgl->word0 = cpu_to_le32(sgl->word0);
18087 
18088 	if (!phba->sli4_hba.intr_enable)
18089 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18090 	else {
18091 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18092 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18093 	}
18094 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
18095 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18096 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18097 	if (!phba->sli4_hba.intr_enable)
18098 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18099 	else if (rc != MBX_TIMEOUT)
18100 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18101 	if (shdr_status || shdr_add_status || rc) {
18102 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18103 				"2513 POST_SGL_BLOCK mailbox command failed "
18104 				"status x%x add_status x%x mbx status x%x\n",
18105 				shdr_status, shdr_add_status, rc);
18106 		rc = -ENXIO;
18107 	}
18108 	return rc;
18109 }
18110 
18111 /**
18112  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
18113  * @phba: pointer to lpfc hba data structure.
18114  * @nblist: pointer to nvme buffer list.
18115  * @count: number of scsi buffers on the list.
18116  *
18117  * This routine is invoked to post a block of @count scsi sgl pages from a
18118  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
18119  * No Lock is held.
18120  *
18121  **/
18122 static int
18123 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
18124 			    int count)
18125 {
18126 	struct lpfc_io_buf *lpfc_ncmd;
18127 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18128 	struct sgl_page_pairs *sgl_pg_pairs;
18129 	void *viraddr;
18130 	LPFC_MBOXQ_t *mbox;
18131 	uint32_t reqlen, alloclen, pg_pairs;
18132 	uint32_t mbox_tmo;
18133 	uint16_t xritag_start = 0;
18134 	int rc = 0;
18135 	uint32_t shdr_status, shdr_add_status;
18136 	dma_addr_t pdma_phys_bpl1;
18137 	union lpfc_sli4_cfg_shdr *shdr;
18138 
18139 	/* Calculate the requested length of the dma memory */
18140 	reqlen = count * sizeof(struct sgl_page_pairs) +
18141 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18142 	if (reqlen > SLI4_PAGE_SIZE) {
18143 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
18144 				"6118 Block sgl registration required DMA "
18145 				"size (%d) great than a page\n", reqlen);
18146 		return -ENOMEM;
18147 	}
18148 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18149 	if (!mbox) {
18150 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18151 				"6119 Failed to allocate mbox cmd memory\n");
18152 		return -ENOMEM;
18153 	}
18154 
18155 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18156 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18157 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
18158 				    reqlen, LPFC_SLI4_MBX_NEMBED);
18159 
18160 	if (alloclen < reqlen) {
18161 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18162 				"6120 Allocated DMA memory size (%d) is "
18163 				"less than the requested DMA memory "
18164 				"size (%d)\n", alloclen, reqlen);
18165 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18166 		return -ENOMEM;
18167 	}
18168 
18169 	/* Get the first SGE entry from the non-embedded DMA memory */
18170 	viraddr = mbox->sge_array->addr[0];
18171 
18172 	/* Set up the SGL pages in the non-embedded DMA pages */
18173 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18174 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18175 
18176 	pg_pairs = 0;
18177 	list_for_each_entry(lpfc_ncmd, nblist, list) {
18178 		/* Set up the sge entry */
18179 		sgl_pg_pairs->sgl_pg0_addr_lo =
18180 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
18181 		sgl_pg_pairs->sgl_pg0_addr_hi =
18182 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
18183 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
18184 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
18185 						SGL_PAGE_SIZE;
18186 		else
18187 			pdma_phys_bpl1 = 0;
18188 		sgl_pg_pairs->sgl_pg1_addr_lo =
18189 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
18190 		sgl_pg_pairs->sgl_pg1_addr_hi =
18191 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
18192 		/* Keep the first xritag on the list */
18193 		if (pg_pairs == 0)
18194 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
18195 		sgl_pg_pairs++;
18196 		pg_pairs++;
18197 	}
18198 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18199 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
18200 	/* Perform endian conversion if necessary */
18201 	sgl->word0 = cpu_to_le32(sgl->word0);
18202 
18203 	if (!phba->sli4_hba.intr_enable) {
18204 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18205 	} else {
18206 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18207 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18208 	}
18209 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
18210 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18211 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18212 	if (!phba->sli4_hba.intr_enable)
18213 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18214 	else if (rc != MBX_TIMEOUT)
18215 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18216 	if (shdr_status || shdr_add_status || rc) {
18217 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18218 				"6125 POST_SGL_BLOCK mailbox command failed "
18219 				"status x%x add_status x%x mbx status x%x\n",
18220 				shdr_status, shdr_add_status, rc);
18221 		rc = -ENXIO;
18222 	}
18223 	return rc;
18224 }
18225 
18226 /**
18227  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
18228  * @phba: pointer to lpfc hba data structure.
18229  * @post_nblist: pointer to the nvme buffer list.
18230  * @sb_count: number of nvme buffers.
18231  *
18232  * This routine walks a list of nvme buffers that was passed in. It attempts
18233  * to construct blocks of nvme buffer sgls which contains contiguous xris and
18234  * uses the non-embedded SGL block post mailbox commands to post to the port.
18235  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
18236  * embedded SGL post mailbox command for posting. The @post_nblist passed in
18237  * must be local list, thus no lock is needed when manipulate the list.
18238  *
18239  * Returns: 0 = failure, non-zero number of successfully posted buffers.
18240  **/
18241 int
18242 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
18243 			   struct list_head *post_nblist, int sb_count)
18244 {
18245 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
18246 	int status, sgl_size;
18247 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
18248 	dma_addr_t pdma_phys_sgl1;
18249 	int last_xritag = NO_XRI;
18250 	int cur_xritag;
18251 	LIST_HEAD(prep_nblist);
18252 	LIST_HEAD(blck_nblist);
18253 	LIST_HEAD(nvme_nblist);
18254 
18255 	/* sanity check */
18256 	if (sb_count <= 0)
18257 		return -EINVAL;
18258 
18259 	sgl_size = phba->cfg_sg_dma_buf_size;
18260 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
18261 		list_del_init(&lpfc_ncmd->list);
18262 		block_cnt++;
18263 		if ((last_xritag != NO_XRI) &&
18264 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
18265 			/* a hole in xri block, form a sgl posting block */
18266 			list_splice_init(&prep_nblist, &blck_nblist);
18267 			post_cnt = block_cnt - 1;
18268 			/* prepare list for next posting block */
18269 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18270 			block_cnt = 1;
18271 		} else {
18272 			/* prepare list for next posting block */
18273 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18274 			/* enough sgls for non-embed sgl mbox command */
18275 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
18276 				list_splice_init(&prep_nblist, &blck_nblist);
18277 				post_cnt = block_cnt;
18278 				block_cnt = 0;
18279 			}
18280 		}
18281 		num_posting++;
18282 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18283 
18284 		/* end of repost sgl list condition for NVME buffers */
18285 		if (num_posting == sb_count) {
18286 			if (post_cnt == 0) {
18287 				/* last sgl posting block */
18288 				list_splice_init(&prep_nblist, &blck_nblist);
18289 				post_cnt = block_cnt;
18290 			} else if (block_cnt == 1) {
18291 				/* last single sgl with non-contiguous xri */
18292 				if (sgl_size > SGL_PAGE_SIZE)
18293 					pdma_phys_sgl1 =
18294 						lpfc_ncmd->dma_phys_sgl +
18295 						SGL_PAGE_SIZE;
18296 				else
18297 					pdma_phys_sgl1 = 0;
18298 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18299 				status = lpfc_sli4_post_sgl(
18300 						phba, lpfc_ncmd->dma_phys_sgl,
18301 						pdma_phys_sgl1, cur_xritag);
18302 				if (status) {
18303 					/* Post error.  Buffer unavailable. */
18304 					lpfc_ncmd->flags |=
18305 						LPFC_SBUF_NOT_POSTED;
18306 				} else {
18307 					/* Post success. Bffer available. */
18308 					lpfc_ncmd->flags &=
18309 						~LPFC_SBUF_NOT_POSTED;
18310 					lpfc_ncmd->status = IOSTAT_SUCCESS;
18311 					num_posted++;
18312 				}
18313 				/* success, put on NVME buffer sgl list */
18314 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18315 			}
18316 		}
18317 
18318 		/* continue until a nembed page worth of sgls */
18319 		if (post_cnt == 0)
18320 			continue;
18321 
18322 		/* post block of NVME buffer list sgls */
18323 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
18324 						     post_cnt);
18325 
18326 		/* don't reset xirtag due to hole in xri block */
18327 		if (block_cnt == 0)
18328 			last_xritag = NO_XRI;
18329 
18330 		/* reset NVME buffer post count for next round of posting */
18331 		post_cnt = 0;
18332 
18333 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
18334 		while (!list_empty(&blck_nblist)) {
18335 			list_remove_head(&blck_nblist, lpfc_ncmd,
18336 					 struct lpfc_io_buf, list);
18337 			if (status) {
18338 				/* Post error.  Mark buffer unavailable. */
18339 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
18340 			} else {
18341 				/* Post success, Mark buffer available. */
18342 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
18343 				lpfc_ncmd->status = IOSTAT_SUCCESS;
18344 				num_posted++;
18345 			}
18346 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18347 		}
18348 	}
18349 	/* Push NVME buffers with sgl posted to the available list */
18350 	lpfc_io_buf_replenish(phba, &nvme_nblist);
18351 
18352 	return num_posted;
18353 }
18354 
18355 /**
18356  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
18357  * @phba: pointer to lpfc_hba struct that the frame was received on
18358  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18359  *
18360  * This function checks the fields in the @fc_hdr to see if the FC frame is a
18361  * valid type of frame that the LPFC driver will handle. This function will
18362  * return a zero if the frame is a valid frame or a non zero value when the
18363  * frame does not pass the check.
18364  **/
18365 static int
18366 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
18367 {
18368 	/*  make rctl_names static to save stack space */
18369 	struct fc_vft_header *fc_vft_hdr;
18370 	uint32_t *header = (uint32_t *) fc_hdr;
18371 
18372 #define FC_RCTL_MDS_DIAGS	0xF4
18373 
18374 	switch (fc_hdr->fh_r_ctl) {
18375 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
18376 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
18377 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
18378 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
18379 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
18380 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
18381 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
18382 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
18383 	case FC_RCTL_ELS_REQ:	/* extended link services request */
18384 	case FC_RCTL_ELS_REP:	/* extended link services reply */
18385 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
18386 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
18387 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
18388 	case FC_RCTL_BA_RMC: 	/* remove connection */
18389 	case FC_RCTL_BA_ACC:	/* basic accept */
18390 	case FC_RCTL_BA_RJT:	/* basic reject */
18391 	case FC_RCTL_BA_PRMT:
18392 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
18393 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
18394 	case FC_RCTL_P_RJT:	/* port reject */
18395 	case FC_RCTL_F_RJT:	/* fabric reject */
18396 	case FC_RCTL_P_BSY:	/* port busy */
18397 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
18398 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
18399 	case FC_RCTL_LCR:	/* link credit reset */
18400 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
18401 	case FC_RCTL_END:	/* end */
18402 		break;
18403 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
18404 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18405 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
18406 		return lpfc_fc_frame_check(phba, fc_hdr);
18407 	case FC_RCTL_BA_NOP:	/* basic link service NOP */
18408 	default:
18409 		goto drop;
18410 	}
18411 
18412 	switch (fc_hdr->fh_type) {
18413 	case FC_TYPE_BLS:
18414 	case FC_TYPE_ELS:
18415 	case FC_TYPE_FCP:
18416 	case FC_TYPE_CT:
18417 	case FC_TYPE_NVME:
18418 		break;
18419 	case FC_TYPE_IP:
18420 	case FC_TYPE_ILS:
18421 	default:
18422 		goto drop;
18423 	}
18424 
18425 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
18426 			"2538 Received frame rctl:x%x, type:x%x, "
18427 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
18428 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
18429 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
18430 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
18431 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
18432 			be32_to_cpu(header[6]));
18433 	return 0;
18434 drop:
18435 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
18436 			"2539 Dropped frame rctl:x%x type:x%x\n",
18437 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18438 	return 1;
18439 }
18440 
18441 /**
18442  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
18443  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18444  *
18445  * This function processes the FC header to retrieve the VFI from the VF
18446  * header, if one exists. This function will return the VFI if one exists
18447  * or 0 if no VSAN Header exists.
18448  **/
18449 static uint32_t
18450 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
18451 {
18452 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18453 
18454 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
18455 		return 0;
18456 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
18457 }
18458 
18459 /**
18460  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
18461  * @phba: Pointer to the HBA structure to search for the vport on
18462  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18463  * @fcfi: The FC Fabric ID that the frame came from
18464  * @did: Destination ID to match against
18465  *
18466  * This function searches the @phba for a vport that matches the content of the
18467  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
18468  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
18469  * returns the matching vport pointer or NULL if unable to match frame to a
18470  * vport.
18471  **/
18472 static struct lpfc_vport *
18473 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
18474 		       uint16_t fcfi, uint32_t did)
18475 {
18476 	struct lpfc_vport **vports;
18477 	struct lpfc_vport *vport = NULL;
18478 	int i;
18479 
18480 	if (did == Fabric_DID)
18481 		return phba->pport;
18482 	if ((phba->pport->fc_flag & FC_PT2PT) &&
18483 		!(phba->link_state == LPFC_HBA_READY))
18484 		return phba->pport;
18485 
18486 	vports = lpfc_create_vport_work_array(phba);
18487 	if (vports != NULL) {
18488 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
18489 			if (phba->fcf.fcfi == fcfi &&
18490 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
18491 			    vports[i]->fc_myDID == did) {
18492 				vport = vports[i];
18493 				break;
18494 			}
18495 		}
18496 	}
18497 	lpfc_destroy_vport_work_array(phba, vports);
18498 	return vport;
18499 }
18500 
18501 /**
18502  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
18503  * @vport: The vport to work on.
18504  *
18505  * This function updates the receive sequence time stamp for this vport. The
18506  * receive sequence time stamp indicates the time that the last frame of the
18507  * the sequence that has been idle for the longest amount of time was received.
18508  * the driver uses this time stamp to indicate if any received sequences have
18509  * timed out.
18510  **/
18511 static void
18512 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
18513 {
18514 	struct lpfc_dmabuf *h_buf;
18515 	struct hbq_dmabuf *dmabuf = NULL;
18516 
18517 	/* get the oldest sequence on the rcv list */
18518 	h_buf = list_get_first(&vport->rcv_buffer_list,
18519 			       struct lpfc_dmabuf, list);
18520 	if (!h_buf)
18521 		return;
18522 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18523 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
18524 }
18525 
18526 /**
18527  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
18528  * @vport: The vport that the received sequences were sent to.
18529  *
18530  * This function cleans up all outstanding received sequences. This is called
18531  * by the driver when a link event or user action invalidates all the received
18532  * sequences.
18533  **/
18534 void
18535 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
18536 {
18537 	struct lpfc_dmabuf *h_buf, *hnext;
18538 	struct lpfc_dmabuf *d_buf, *dnext;
18539 	struct hbq_dmabuf *dmabuf = NULL;
18540 
18541 	/* start with the oldest sequence on the rcv list */
18542 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18543 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18544 		list_del_init(&dmabuf->hbuf.list);
18545 		list_for_each_entry_safe(d_buf, dnext,
18546 					 &dmabuf->dbuf.list, list) {
18547 			list_del_init(&d_buf->list);
18548 			lpfc_in_buf_free(vport->phba, d_buf);
18549 		}
18550 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18551 	}
18552 }
18553 
18554 /**
18555  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
18556  * @vport: The vport that the received sequences were sent to.
18557  *
18558  * This function determines whether any received sequences have timed out by
18559  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
18560  * indicates that there is at least one timed out sequence this routine will
18561  * go through the received sequences one at a time from most inactive to most
18562  * active to determine which ones need to be cleaned up. Once it has determined
18563  * that a sequence needs to be cleaned up it will simply free up the resources
18564  * without sending an abort.
18565  **/
18566 void
18567 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
18568 {
18569 	struct lpfc_dmabuf *h_buf, *hnext;
18570 	struct lpfc_dmabuf *d_buf, *dnext;
18571 	struct hbq_dmabuf *dmabuf = NULL;
18572 	unsigned long timeout;
18573 	int abort_count = 0;
18574 
18575 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18576 		   vport->rcv_buffer_time_stamp);
18577 	if (list_empty(&vport->rcv_buffer_list) ||
18578 	    time_before(jiffies, timeout))
18579 		return;
18580 	/* start with the oldest sequence on the rcv list */
18581 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18582 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18583 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18584 			   dmabuf->time_stamp);
18585 		if (time_before(jiffies, timeout))
18586 			break;
18587 		abort_count++;
18588 		list_del_init(&dmabuf->hbuf.list);
18589 		list_for_each_entry_safe(d_buf, dnext,
18590 					 &dmabuf->dbuf.list, list) {
18591 			list_del_init(&d_buf->list);
18592 			lpfc_in_buf_free(vport->phba, d_buf);
18593 		}
18594 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18595 	}
18596 	if (abort_count)
18597 		lpfc_update_rcv_time_stamp(vport);
18598 }
18599 
18600 /**
18601  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
18602  * @vport: pointer to a vitural port
18603  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
18604  *
18605  * This function searches through the existing incomplete sequences that have
18606  * been sent to this @vport. If the frame matches one of the incomplete
18607  * sequences then the dbuf in the @dmabuf is added to the list of frames that
18608  * make up that sequence. If no sequence is found that matches this frame then
18609  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
18610  * This function returns a pointer to the first dmabuf in the sequence list that
18611  * the frame was linked to.
18612  **/
18613 static struct hbq_dmabuf *
18614 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18615 {
18616 	struct fc_frame_header *new_hdr;
18617 	struct fc_frame_header *temp_hdr;
18618 	struct lpfc_dmabuf *d_buf;
18619 	struct lpfc_dmabuf *h_buf;
18620 	struct hbq_dmabuf *seq_dmabuf = NULL;
18621 	struct hbq_dmabuf *temp_dmabuf = NULL;
18622 	uint8_t	found = 0;
18623 
18624 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18625 	dmabuf->time_stamp = jiffies;
18626 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18627 
18628 	/* Use the hdr_buf to find the sequence that this frame belongs to */
18629 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18630 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18631 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18632 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18633 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18634 			continue;
18635 		/* found a pending sequence that matches this frame */
18636 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18637 		break;
18638 	}
18639 	if (!seq_dmabuf) {
18640 		/*
18641 		 * This indicates first frame received for this sequence.
18642 		 * Queue the buffer on the vport's rcv_buffer_list.
18643 		 */
18644 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18645 		lpfc_update_rcv_time_stamp(vport);
18646 		return dmabuf;
18647 	}
18648 	temp_hdr = seq_dmabuf->hbuf.virt;
18649 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
18650 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18651 		list_del_init(&seq_dmabuf->hbuf.list);
18652 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18653 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18654 		lpfc_update_rcv_time_stamp(vport);
18655 		return dmabuf;
18656 	}
18657 	/* move this sequence to the tail to indicate a young sequence */
18658 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
18659 	seq_dmabuf->time_stamp = jiffies;
18660 	lpfc_update_rcv_time_stamp(vport);
18661 	if (list_empty(&seq_dmabuf->dbuf.list)) {
18662 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18663 		return seq_dmabuf;
18664 	}
18665 	/* find the correct place in the sequence to insert this frame */
18666 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
18667 	while (!found) {
18668 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18669 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
18670 		/*
18671 		 * If the frame's sequence count is greater than the frame on
18672 		 * the list then insert the frame right after this frame
18673 		 */
18674 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
18675 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18676 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
18677 			found = 1;
18678 			break;
18679 		}
18680 
18681 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
18682 			break;
18683 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
18684 	}
18685 
18686 	if (found)
18687 		return seq_dmabuf;
18688 	return NULL;
18689 }
18690 
18691 /**
18692  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
18693  * @vport: pointer to a vitural port
18694  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18695  *
18696  * This function tries to abort from the partially assembed sequence, described
18697  * by the information from basic abbort @dmabuf. It checks to see whether such
18698  * partially assembled sequence held by the driver. If so, it shall free up all
18699  * the frames from the partially assembled sequence.
18700  *
18701  * Return
18702  * true  -- if there is matching partially assembled sequence present and all
18703  *          the frames freed with the sequence;
18704  * false -- if there is no matching partially assembled sequence present so
18705  *          nothing got aborted in the lower layer driver
18706  **/
18707 static bool
18708 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
18709 			    struct hbq_dmabuf *dmabuf)
18710 {
18711 	struct fc_frame_header *new_hdr;
18712 	struct fc_frame_header *temp_hdr;
18713 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
18714 	struct hbq_dmabuf *seq_dmabuf = NULL;
18715 
18716 	/* Use the hdr_buf to find the sequence that matches this frame */
18717 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18718 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
18719 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18720 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18721 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18722 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18723 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18724 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18725 			continue;
18726 		/* found a pending sequence that matches this frame */
18727 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18728 		break;
18729 	}
18730 
18731 	/* Free up all the frames from the partially assembled sequence */
18732 	if (seq_dmabuf) {
18733 		list_for_each_entry_safe(d_buf, n_buf,
18734 					 &seq_dmabuf->dbuf.list, list) {
18735 			list_del_init(&d_buf->list);
18736 			lpfc_in_buf_free(vport->phba, d_buf);
18737 		}
18738 		return true;
18739 	}
18740 	return false;
18741 }
18742 
18743 /**
18744  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18745  * @vport: pointer to a vitural port
18746  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18747  *
18748  * This function tries to abort from the assembed sequence from upper level
18749  * protocol, described by the information from basic abbort @dmabuf. It
18750  * checks to see whether such pending context exists at upper level protocol.
18751  * If so, it shall clean up the pending context.
18752  *
18753  * Return
18754  * true  -- if there is matching pending context of the sequence cleaned
18755  *          at ulp;
18756  * false -- if there is no matching pending context of the sequence present
18757  *          at ulp.
18758  **/
18759 static bool
18760 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18761 {
18762 	struct lpfc_hba *phba = vport->phba;
18763 	int handled;
18764 
18765 	/* Accepting abort at ulp with SLI4 only */
18766 	if (phba->sli_rev < LPFC_SLI_REV4)
18767 		return false;
18768 
18769 	/* Register all caring upper level protocols to attend abort */
18770 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18771 	if (handled)
18772 		return true;
18773 
18774 	return false;
18775 }
18776 
18777 /**
18778  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18779  * @phba: Pointer to HBA context object.
18780  * @cmd_iocbq: pointer to the command iocbq structure.
18781  * @rsp_iocbq: pointer to the response iocbq structure.
18782  *
18783  * This function handles the sequence abort response iocb command complete
18784  * event. It properly releases the memory allocated to the sequence abort
18785  * accept iocb.
18786  **/
18787 static void
18788 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18789 			     struct lpfc_iocbq *cmd_iocbq,
18790 			     struct lpfc_iocbq *rsp_iocbq)
18791 {
18792 	if (cmd_iocbq) {
18793 		lpfc_nlp_put(cmd_iocbq->ndlp);
18794 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
18795 	}
18796 
18797 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
18798 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18799 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18800 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
18801 			get_job_ulpstatus(phba, rsp_iocbq),
18802 			get_job_word4(phba, rsp_iocbq));
18803 }
18804 
18805 /**
18806  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
18807  * @phba: Pointer to HBA context object.
18808  * @xri: xri id in transaction.
18809  *
18810  * This function validates the xri maps to the known range of XRIs allocated an
18811  * used by the driver.
18812  **/
18813 uint16_t
18814 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
18815 		      uint16_t xri)
18816 {
18817 	uint16_t i;
18818 
18819 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
18820 		if (xri == phba->sli4_hba.xri_ids[i])
18821 			return i;
18822 	}
18823 	return NO_XRI;
18824 }
18825 
18826 /**
18827  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
18828  * @vport: pointer to a virtual port.
18829  * @fc_hdr: pointer to a FC frame header.
18830  * @aborted: was the partially assembled receive sequence successfully aborted
18831  *
18832  * This function sends a basic response to a previous unsol sequence abort
18833  * event after aborting the sequence handling.
18834  **/
18835 void
18836 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
18837 			struct fc_frame_header *fc_hdr, bool aborted)
18838 {
18839 	struct lpfc_hba *phba = vport->phba;
18840 	struct lpfc_iocbq *ctiocb = NULL;
18841 	struct lpfc_nodelist *ndlp;
18842 	uint16_t oxid, rxid, xri, lxri;
18843 	uint32_t sid, fctl;
18844 	union lpfc_wqe128 *icmd;
18845 	int rc;
18846 
18847 	if (!lpfc_is_link_up(phba))
18848 		return;
18849 
18850 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18851 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
18852 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
18853 
18854 	ndlp = lpfc_findnode_did(vport, sid);
18855 	if (!ndlp) {
18856 		ndlp = lpfc_nlp_init(vport, sid);
18857 		if (!ndlp) {
18858 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
18859 					 "1268 Failed to allocate ndlp for "
18860 					 "oxid:x%x SID:x%x\n", oxid, sid);
18861 			return;
18862 		}
18863 		/* Put ndlp onto pport node list */
18864 		lpfc_enqueue_node(vport, ndlp);
18865 	}
18866 
18867 	/* Allocate buffer for rsp iocb */
18868 	ctiocb = lpfc_sli_get_iocbq(phba);
18869 	if (!ctiocb)
18870 		return;
18871 
18872 	icmd = &ctiocb->wqe;
18873 
18874 	/* Extract the F_CTL field from FC_HDR */
18875 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
18876 
18877 	ctiocb->ndlp = lpfc_nlp_get(ndlp);
18878 	if (!ctiocb->ndlp) {
18879 		lpfc_sli_release_iocbq(phba, ctiocb);
18880 		return;
18881 	}
18882 
18883 	ctiocb->vport = phba->pport;
18884 	ctiocb->cmd_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
18885 	ctiocb->sli4_lxritag = NO_XRI;
18886 	ctiocb->sli4_xritag = NO_XRI;
18887 	ctiocb->abort_rctl = FC_RCTL_BA_ACC;
18888 
18889 	if (fctl & FC_FC_EX_CTX)
18890 		/* Exchange responder sent the abort so we
18891 		 * own the oxid.
18892 		 */
18893 		xri = oxid;
18894 	else
18895 		xri = rxid;
18896 	lxri = lpfc_sli4_xri_inrange(phba, xri);
18897 	if (lxri != NO_XRI)
18898 		lpfc_set_rrq_active(phba, ndlp, lxri,
18899 			(xri == oxid) ? rxid : oxid, 0);
18900 	/* For BA_ABTS from exchange responder, if the logical xri with
18901 	 * the oxid maps to the FCP XRI range, the port no longer has
18902 	 * that exchange context, send a BLS_RJT. Override the IOCB for
18903 	 * a BA_RJT.
18904 	 */
18905 	if ((fctl & FC_FC_EX_CTX) &&
18906 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
18907 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
18908 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
18909 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
18910 		       FC_BA_RJT_INV_XID);
18911 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
18912 		       FC_BA_RJT_UNABLE);
18913 	}
18914 
18915 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
18916 	 * the driver no longer has that exchange, send a BLS_RJT. Override
18917 	 * the IOCB for a BA_RJT.
18918 	 */
18919 	if (aborted == false) {
18920 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
18921 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
18922 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
18923 		       FC_BA_RJT_INV_XID);
18924 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
18925 		       FC_BA_RJT_UNABLE);
18926 	}
18927 
18928 	if (fctl & FC_FC_EX_CTX) {
18929 		/* ABTS sent by responder to CT exchange, construction
18930 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
18931 		 * field and RX_ID from ABTS for RX_ID field.
18932 		 */
18933 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_RSP;
18934 		bf_set(xmit_bls_rsp64_rxid, &icmd->xmit_bls_rsp, rxid);
18935 	} else {
18936 		/* ABTS sent by initiator to CT exchange, construction
18937 		 * of BA_ACC will need to allocate a new XRI as for the
18938 		 * XRI_TAG field.
18939 		 */
18940 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_INT;
18941 	}
18942 
18943 	/* OX_ID is invariable to who sent ABTS to CT exchange */
18944 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, oxid);
18945 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, rxid);
18946 
18947 	/* Use CT=VPI */
18948 	bf_set(wqe_els_did, &icmd->xmit_bls_rsp.wqe_dest,
18949 	       ndlp->nlp_DID);
18950 	bf_set(xmit_bls_rsp64_temprpi, &icmd->xmit_bls_rsp,
18951 	       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
18952 	bf_set(wqe_cmnd, &icmd->generic.wqe_com, CMD_XMIT_BLS_RSP64_CX);
18953 
18954 	/* Xmit CT abts response on exchange <xid> */
18955 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
18956 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
18957 			 ctiocb->abort_rctl, oxid, phba->link_state);
18958 
18959 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
18960 	if (rc == IOCB_ERROR) {
18961 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
18962 				 "2925 Failed to issue CT ABTS RSP x%x on "
18963 				 "xri x%x, Data x%x\n",
18964 				 ctiocb->abort_rctl, oxid,
18965 				 phba->link_state);
18966 		lpfc_nlp_put(ndlp);
18967 		ctiocb->ndlp = NULL;
18968 		lpfc_sli_release_iocbq(phba, ctiocb);
18969 	}
18970 }
18971 
18972 /**
18973  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
18974  * @vport: Pointer to the vport on which this sequence was received
18975  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18976  *
18977  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
18978  * receive sequence is only partially assembed by the driver, it shall abort
18979  * the partially assembled frames for the sequence. Otherwise, if the
18980  * unsolicited receive sequence has been completely assembled and passed to
18981  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
18982  * unsolicited sequence has been aborted. After that, it will issue a basic
18983  * accept to accept the abort.
18984  **/
18985 static void
18986 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
18987 			     struct hbq_dmabuf *dmabuf)
18988 {
18989 	struct lpfc_hba *phba = vport->phba;
18990 	struct fc_frame_header fc_hdr;
18991 	uint32_t fctl;
18992 	bool aborted;
18993 
18994 	/* Make a copy of fc_hdr before the dmabuf being released */
18995 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
18996 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
18997 
18998 	if (fctl & FC_FC_EX_CTX) {
18999 		/* ABTS by responder to exchange, no cleanup needed */
19000 		aborted = true;
19001 	} else {
19002 		/* ABTS by initiator to exchange, need to do cleanup */
19003 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
19004 		if (aborted == false)
19005 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
19006 	}
19007 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19008 
19009 	if (phba->nvmet_support) {
19010 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
19011 		return;
19012 	}
19013 
19014 	/* Respond with BA_ACC or BA_RJT accordingly */
19015 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
19016 }
19017 
19018 /**
19019  * lpfc_seq_complete - Indicates if a sequence is complete
19020  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19021  *
19022  * This function checks the sequence, starting with the frame described by
19023  * @dmabuf, to see if all the frames associated with this sequence are present.
19024  * the frames associated with this sequence are linked to the @dmabuf using the
19025  * dbuf list. This function looks for two major things. 1) That the first frame
19026  * has a sequence count of zero. 2) There is a frame with last frame of sequence
19027  * set. 3) That there are no holes in the sequence count. The function will
19028  * return 1 when the sequence is complete, otherwise it will return 0.
19029  **/
19030 static int
19031 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
19032 {
19033 	struct fc_frame_header *hdr;
19034 	struct lpfc_dmabuf *d_buf;
19035 	struct hbq_dmabuf *seq_dmabuf;
19036 	uint32_t fctl;
19037 	int seq_count = 0;
19038 
19039 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19040 	/* make sure first fame of sequence has a sequence count of zero */
19041 	if (hdr->fh_seq_cnt != seq_count)
19042 		return 0;
19043 	fctl = (hdr->fh_f_ctl[0] << 16 |
19044 		hdr->fh_f_ctl[1] << 8 |
19045 		hdr->fh_f_ctl[2]);
19046 	/* If last frame of sequence we can return success. */
19047 	if (fctl & FC_FC_END_SEQ)
19048 		return 1;
19049 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
19050 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19051 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19052 		/* If there is a hole in the sequence count then fail. */
19053 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
19054 			return 0;
19055 		fctl = (hdr->fh_f_ctl[0] << 16 |
19056 			hdr->fh_f_ctl[1] << 8 |
19057 			hdr->fh_f_ctl[2]);
19058 		/* If last frame of sequence we can return success. */
19059 		if (fctl & FC_FC_END_SEQ)
19060 			return 1;
19061 	}
19062 	return 0;
19063 }
19064 
19065 /**
19066  * lpfc_prep_seq - Prep sequence for ULP processing
19067  * @vport: Pointer to the vport on which this sequence was received
19068  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
19069  *
19070  * This function takes a sequence, described by a list of frames, and creates
19071  * a list of iocbq structures to describe the sequence. This iocbq list will be
19072  * used to issue to the generic unsolicited sequence handler. This routine
19073  * returns a pointer to the first iocbq in the list. If the function is unable
19074  * to allocate an iocbq then it throw out the received frames that were not
19075  * able to be described and return a pointer to the first iocbq. If unable to
19076  * allocate any iocbqs (including the first) this function will return NULL.
19077  **/
19078 static struct lpfc_iocbq *
19079 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
19080 {
19081 	struct hbq_dmabuf *hbq_buf;
19082 	struct lpfc_dmabuf *d_buf, *n_buf;
19083 	struct lpfc_iocbq *first_iocbq, *iocbq;
19084 	struct fc_frame_header *fc_hdr;
19085 	uint32_t sid;
19086 	uint32_t len, tot_len;
19087 
19088 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19089 	/* remove from receive buffer list */
19090 	list_del_init(&seq_dmabuf->hbuf.list);
19091 	lpfc_update_rcv_time_stamp(vport);
19092 	/* get the Remote Port's SID */
19093 	sid = sli4_sid_from_fc_hdr(fc_hdr);
19094 	tot_len = 0;
19095 	/* Get an iocbq struct to fill in. */
19096 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
19097 	if (first_iocbq) {
19098 		/* Initialize the first IOCB. */
19099 		first_iocbq->wcqe_cmpl.total_data_placed = 0;
19100 		bf_set(lpfc_wcqe_c_status, &first_iocbq->wcqe_cmpl,
19101 		       IOSTAT_SUCCESS);
19102 		first_iocbq->vport = vport;
19103 
19104 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
19105 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
19106 			bf_set(els_rsp64_sid, &first_iocbq->wqe.xmit_els_rsp,
19107 			       sli4_did_from_fc_hdr(fc_hdr));
19108 		}
19109 
19110 		bf_set(wqe_ctxt_tag, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19111 		       NO_XRI);
19112 		bf_set(wqe_rcvoxid, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19113 		       be16_to_cpu(fc_hdr->fh_ox_id));
19114 
19115 		/* put the first buffer into the first iocb */
19116 		tot_len = bf_get(lpfc_rcqe_length,
19117 				 &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
19118 
19119 		first_iocbq->cmd_dmabuf = &seq_dmabuf->dbuf;
19120 		first_iocbq->bpl_dmabuf = NULL;
19121 		/* Keep track of the BDE count */
19122 		first_iocbq->wcqe_cmpl.word3 = 1;
19123 
19124 		if (tot_len > LPFC_DATA_BUF_SIZE)
19125 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize =
19126 				LPFC_DATA_BUF_SIZE;
19127 		else
19128 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize = tot_len;
19129 
19130 		first_iocbq->wcqe_cmpl.total_data_placed = tot_len;
19131 		bf_set(wqe_els_did, &first_iocbq->wqe.xmit_els_rsp.wqe_dest,
19132 		       sid);
19133 	}
19134 	iocbq = first_iocbq;
19135 	/*
19136 	 * Each IOCBq can have two Buffers assigned, so go through the list
19137 	 * of buffers for this sequence and save two buffers in each IOCBq
19138 	 */
19139 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
19140 		if (!iocbq) {
19141 			lpfc_in_buf_free(vport->phba, d_buf);
19142 			continue;
19143 		}
19144 		if (!iocbq->bpl_dmabuf) {
19145 			iocbq->bpl_dmabuf = d_buf;
19146 			iocbq->wcqe_cmpl.word3++;
19147 			/* We need to get the size out of the right CQE */
19148 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19149 			len = bf_get(lpfc_rcqe_length,
19150 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19151 			iocbq->unsol_rcv_len = len;
19152 			iocbq->wcqe_cmpl.total_data_placed += len;
19153 			tot_len += len;
19154 		} else {
19155 			iocbq = lpfc_sli_get_iocbq(vport->phba);
19156 			if (!iocbq) {
19157 				if (first_iocbq) {
19158 					bf_set(lpfc_wcqe_c_status,
19159 					       &first_iocbq->wcqe_cmpl,
19160 					       IOSTAT_SUCCESS);
19161 					first_iocbq->wcqe_cmpl.parameter =
19162 						IOERR_NO_RESOURCES;
19163 				}
19164 				lpfc_in_buf_free(vport->phba, d_buf);
19165 				continue;
19166 			}
19167 			/* We need to get the size out of the right CQE */
19168 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19169 			len = bf_get(lpfc_rcqe_length,
19170 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19171 			iocbq->cmd_dmabuf = d_buf;
19172 			iocbq->bpl_dmabuf = NULL;
19173 			iocbq->wcqe_cmpl.word3 = 1;
19174 
19175 			if (len > LPFC_DATA_BUF_SIZE)
19176 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19177 					LPFC_DATA_BUF_SIZE;
19178 			else
19179 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19180 					len;
19181 
19182 			tot_len += len;
19183 			iocbq->wcqe_cmpl.total_data_placed = tot_len;
19184 			bf_set(wqe_els_did, &iocbq->wqe.xmit_els_rsp.wqe_dest,
19185 			       sid);
19186 			list_add_tail(&iocbq->list, &first_iocbq->list);
19187 		}
19188 	}
19189 	/* Free the sequence's header buffer */
19190 	if (!first_iocbq)
19191 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
19192 
19193 	return first_iocbq;
19194 }
19195 
19196 static void
19197 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
19198 			  struct hbq_dmabuf *seq_dmabuf)
19199 {
19200 	struct fc_frame_header *fc_hdr;
19201 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
19202 	struct lpfc_hba *phba = vport->phba;
19203 
19204 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19205 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
19206 	if (!iocbq) {
19207 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19208 				"2707 Ring %d handler: Failed to allocate "
19209 				"iocb Rctl x%x Type x%x received\n",
19210 				LPFC_ELS_RING,
19211 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19212 		return;
19213 	}
19214 	if (!lpfc_complete_unsol_iocb(phba,
19215 				      phba->sli4_hba.els_wq->pring,
19216 				      iocbq, fc_hdr->fh_r_ctl,
19217 				      fc_hdr->fh_type)) {
19218 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19219 				"2540 Ring %d handler: unexpected Rctl "
19220 				"x%x Type x%x received\n",
19221 				LPFC_ELS_RING,
19222 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19223 		lpfc_in_buf_free(phba, &seq_dmabuf->dbuf);
19224 	}
19225 
19226 	/* Free iocb created in lpfc_prep_seq */
19227 	list_for_each_entry_safe(curr_iocb, next_iocb,
19228 				 &iocbq->list, list) {
19229 		list_del_init(&curr_iocb->list);
19230 		lpfc_sli_release_iocbq(phba, curr_iocb);
19231 	}
19232 	lpfc_sli_release_iocbq(phba, iocbq);
19233 }
19234 
19235 static void
19236 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
19237 			    struct lpfc_iocbq *rspiocb)
19238 {
19239 	struct lpfc_dmabuf *pcmd = cmdiocb->cmd_dmabuf;
19240 
19241 	if (pcmd && pcmd->virt)
19242 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19243 	kfree(pcmd);
19244 	lpfc_sli_release_iocbq(phba, cmdiocb);
19245 	lpfc_drain_txq(phba);
19246 }
19247 
19248 static void
19249 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
19250 			      struct hbq_dmabuf *dmabuf)
19251 {
19252 	struct fc_frame_header *fc_hdr;
19253 	struct lpfc_hba *phba = vport->phba;
19254 	struct lpfc_iocbq *iocbq = NULL;
19255 	union  lpfc_wqe128 *pwqe;
19256 	struct lpfc_dmabuf *pcmd = NULL;
19257 	uint32_t frame_len;
19258 	int rc;
19259 	unsigned long iflags;
19260 
19261 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19262 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
19263 
19264 	/* Send the received frame back */
19265 	iocbq = lpfc_sli_get_iocbq(phba);
19266 	if (!iocbq) {
19267 		/* Queue cq event and wakeup worker thread to process it */
19268 		spin_lock_irqsave(&phba->hbalock, iflags);
19269 		list_add_tail(&dmabuf->cq_event.list,
19270 			      &phba->sli4_hba.sp_queue_event);
19271 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
19272 		spin_unlock_irqrestore(&phba->hbalock, iflags);
19273 		lpfc_worker_wake_up(phba);
19274 		return;
19275 	}
19276 
19277 	/* Allocate buffer for command payload */
19278 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
19279 	if (pcmd)
19280 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
19281 					    &pcmd->phys);
19282 	if (!pcmd || !pcmd->virt)
19283 		goto exit;
19284 
19285 	INIT_LIST_HEAD(&pcmd->list);
19286 
19287 	/* copyin the payload */
19288 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
19289 
19290 	iocbq->cmd_dmabuf = pcmd;
19291 	iocbq->vport = vport;
19292 	iocbq->cmd_flag &= ~LPFC_FIP_ELS_ID_MASK;
19293 	iocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
19294 	iocbq->num_bdes = 0;
19295 
19296 	pwqe = &iocbq->wqe;
19297 	/* fill in BDE's for command */
19298 	pwqe->gen_req.bde.addrHigh = putPaddrHigh(pcmd->phys);
19299 	pwqe->gen_req.bde.addrLow = putPaddrLow(pcmd->phys);
19300 	pwqe->gen_req.bde.tus.f.bdeSize = frame_len;
19301 	pwqe->gen_req.bde.tus.f.bdeFlags = BUFF_TYPE_BDE_64;
19302 
19303 	pwqe->send_frame.frame_len = frame_len;
19304 	pwqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((__be32 *)fc_hdr));
19305 	pwqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((__be32 *)fc_hdr + 1));
19306 	pwqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((__be32 *)fc_hdr + 2));
19307 	pwqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((__be32 *)fc_hdr + 3));
19308 	pwqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((__be32 *)fc_hdr + 4));
19309 	pwqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((__be32 *)fc_hdr + 5));
19310 
19311 	pwqe->generic.wqe_com.word7 = 0;
19312 	pwqe->generic.wqe_com.word10 = 0;
19313 
19314 	bf_set(wqe_cmnd, &pwqe->generic.wqe_com, CMD_SEND_FRAME);
19315 	bf_set(wqe_sof, &pwqe->generic.wqe_com, 0x2E); /* SOF byte */
19316 	bf_set(wqe_eof, &pwqe->generic.wqe_com, 0x41); /* EOF byte */
19317 	bf_set(wqe_lenloc, &pwqe->generic.wqe_com, 1);
19318 	bf_set(wqe_xbl, &pwqe->generic.wqe_com, 1);
19319 	bf_set(wqe_dbde, &pwqe->generic.wqe_com, 1);
19320 	bf_set(wqe_xc, &pwqe->generic.wqe_com, 1);
19321 	bf_set(wqe_cmd_type, &pwqe->generic.wqe_com, 0xA);
19322 	bf_set(wqe_cqid, &pwqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
19323 	bf_set(wqe_xri_tag, &pwqe->generic.wqe_com, iocbq->sli4_xritag);
19324 	bf_set(wqe_reqtag, &pwqe->generic.wqe_com, iocbq->iotag);
19325 	bf_set(wqe_class, &pwqe->generic.wqe_com, CLASS3);
19326 	pwqe->generic.wqe_com.abort_tag = iocbq->iotag;
19327 
19328 	iocbq->cmd_cmpl = lpfc_sli4_mds_loopback_cmpl;
19329 
19330 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
19331 	if (rc == IOCB_ERROR)
19332 		goto exit;
19333 
19334 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19335 	return;
19336 
19337 exit:
19338 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
19339 			"2023 Unable to process MDS loopback frame\n");
19340 	if (pcmd && pcmd->virt)
19341 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19342 	kfree(pcmd);
19343 	if (iocbq)
19344 		lpfc_sli_release_iocbq(phba, iocbq);
19345 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19346 }
19347 
19348 /**
19349  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
19350  * @phba: Pointer to HBA context object.
19351  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
19352  *
19353  * This function is called with no lock held. This function processes all
19354  * the received buffers and gives it to upper layers when a received buffer
19355  * indicates that it is the final frame in the sequence. The interrupt
19356  * service routine processes received buffers at interrupt contexts.
19357  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
19358  * appropriate receive function when the final frame in a sequence is received.
19359  **/
19360 void
19361 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
19362 				 struct hbq_dmabuf *dmabuf)
19363 {
19364 	struct hbq_dmabuf *seq_dmabuf;
19365 	struct fc_frame_header *fc_hdr;
19366 	struct lpfc_vport *vport;
19367 	uint32_t fcfi;
19368 	uint32_t did;
19369 
19370 	/* Process each received buffer */
19371 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19372 
19373 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
19374 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
19375 		vport = phba->pport;
19376 		/* Handle MDS Loopback frames */
19377 		if  (!(phba->pport->load_flag & FC_UNLOADING))
19378 			lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19379 		else
19380 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19381 		return;
19382 	}
19383 
19384 	/* check to see if this a valid type of frame */
19385 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
19386 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19387 		return;
19388 	}
19389 
19390 	if ((bf_get(lpfc_cqe_code,
19391 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
19392 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
19393 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19394 	else
19395 		fcfi = bf_get(lpfc_rcqe_fcf_id,
19396 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19397 
19398 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
19399 		vport = phba->pport;
19400 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
19401 				"2023 MDS Loopback %d bytes\n",
19402 				bf_get(lpfc_rcqe_length,
19403 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
19404 		/* Handle MDS Loopback frames */
19405 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19406 		return;
19407 	}
19408 
19409 	/* d_id this frame is directed to */
19410 	did = sli4_did_from_fc_hdr(fc_hdr);
19411 
19412 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
19413 	if (!vport) {
19414 		/* throw out the frame */
19415 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19416 		return;
19417 	}
19418 
19419 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
19420 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
19421 		(did != Fabric_DID)) {
19422 		/*
19423 		 * Throw out the frame if we are not pt2pt.
19424 		 * The pt2pt protocol allows for discovery frames
19425 		 * to be received without a registered VPI.
19426 		 */
19427 		if (!(vport->fc_flag & FC_PT2PT) ||
19428 			(phba->link_state == LPFC_HBA_READY)) {
19429 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19430 			return;
19431 		}
19432 	}
19433 
19434 	/* Handle the basic abort sequence (BA_ABTS) event */
19435 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
19436 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
19437 		return;
19438 	}
19439 
19440 	/* Link this frame */
19441 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
19442 	if (!seq_dmabuf) {
19443 		/* unable to add frame to vport - throw it out */
19444 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19445 		return;
19446 	}
19447 	/* If not last frame in sequence continue processing frames. */
19448 	if (!lpfc_seq_complete(seq_dmabuf))
19449 		return;
19450 
19451 	/* Send the complete sequence to the upper layer protocol */
19452 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
19453 }
19454 
19455 /**
19456  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
19457  * @phba: pointer to lpfc hba data structure.
19458  *
19459  * This routine is invoked to post rpi header templates to the
19460  * HBA consistent with the SLI-4 interface spec.  This routine
19461  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19462  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19463  *
19464  * This routine does not require any locks.  It's usage is expected
19465  * to be driver load or reset recovery when the driver is
19466  * sequential.
19467  *
19468  * Return codes
19469  * 	0 - successful
19470  *      -EIO - The mailbox failed to complete successfully.
19471  * 	When this error occurs, the driver is not guaranteed
19472  *	to have any rpi regions posted to the device and
19473  *	must either attempt to repost the regions or take a
19474  *	fatal error.
19475  **/
19476 int
19477 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
19478 {
19479 	struct lpfc_rpi_hdr *rpi_page;
19480 	uint32_t rc = 0;
19481 	uint16_t lrpi = 0;
19482 
19483 	/* SLI4 ports that support extents do not require RPI headers. */
19484 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19485 		goto exit;
19486 	if (phba->sli4_hba.extents_in_use)
19487 		return -EIO;
19488 
19489 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
19490 		/*
19491 		 * Assign the rpi headers a physical rpi only if the driver
19492 		 * has not initialized those resources.  A port reset only
19493 		 * needs the headers posted.
19494 		 */
19495 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
19496 		    LPFC_RPI_RSRC_RDY)
19497 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19498 
19499 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
19500 		if (rc != MBX_SUCCESS) {
19501 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19502 					"2008 Error %d posting all rpi "
19503 					"headers\n", rc);
19504 			rc = -EIO;
19505 			break;
19506 		}
19507 	}
19508 
19509  exit:
19510 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
19511 	       LPFC_RPI_RSRC_RDY);
19512 	return rc;
19513 }
19514 
19515 /**
19516  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
19517  * @phba: pointer to lpfc hba data structure.
19518  * @rpi_page:  pointer to the rpi memory region.
19519  *
19520  * This routine is invoked to post a single rpi header to the
19521  * HBA consistent with the SLI-4 interface spec.  This memory region
19522  * maps up to 64 rpi context regions.
19523  *
19524  * Return codes
19525  * 	0 - successful
19526  * 	-ENOMEM - No available memory
19527  *      -EIO - The mailbox failed to complete successfully.
19528  **/
19529 int
19530 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
19531 {
19532 	LPFC_MBOXQ_t *mboxq;
19533 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
19534 	uint32_t rc = 0;
19535 	uint32_t shdr_status, shdr_add_status;
19536 	union lpfc_sli4_cfg_shdr *shdr;
19537 
19538 	/* SLI4 ports that support extents do not require RPI headers. */
19539 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19540 		return rc;
19541 	if (phba->sli4_hba.extents_in_use)
19542 		return -EIO;
19543 
19544 	/* The port is notified of the header region via a mailbox command. */
19545 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19546 	if (!mboxq) {
19547 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19548 				"2001 Unable to allocate memory for issuing "
19549 				"SLI_CONFIG_SPECIAL mailbox command\n");
19550 		return -ENOMEM;
19551 	}
19552 
19553 	/* Post all rpi memory regions to the port. */
19554 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
19555 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19556 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
19557 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
19558 			 sizeof(struct lpfc_sli4_cfg_mhdr),
19559 			 LPFC_SLI4_MBX_EMBED);
19560 
19561 
19562 	/* Post the physical rpi to the port for this rpi header. */
19563 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
19564 	       rpi_page->start_rpi);
19565 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
19566 	       hdr_tmpl, rpi_page->page_count);
19567 
19568 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
19569 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
19570 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19571 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
19572 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19573 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19574 	mempool_free(mboxq, phba->mbox_mem_pool);
19575 	if (shdr_status || shdr_add_status || rc) {
19576 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19577 				"2514 POST_RPI_HDR mailbox failed with "
19578 				"status x%x add_status x%x, mbx status x%x\n",
19579 				shdr_status, shdr_add_status, rc);
19580 		rc = -ENXIO;
19581 	} else {
19582 		/*
19583 		 * The next_rpi stores the next logical module-64 rpi value used
19584 		 * to post physical rpis in subsequent rpi postings.
19585 		 */
19586 		spin_lock_irq(&phba->hbalock);
19587 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
19588 		spin_unlock_irq(&phba->hbalock);
19589 	}
19590 	return rc;
19591 }
19592 
19593 /**
19594  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
19595  * @phba: pointer to lpfc hba data structure.
19596  *
19597  * This routine is invoked to post rpi header templates to the
19598  * HBA consistent with the SLI-4 interface spec.  This routine
19599  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19600  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19601  *
19602  * Returns
19603  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
19604  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
19605  **/
19606 int
19607 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
19608 {
19609 	unsigned long rpi;
19610 	uint16_t max_rpi, rpi_limit;
19611 	uint16_t rpi_remaining, lrpi = 0;
19612 	struct lpfc_rpi_hdr *rpi_hdr;
19613 	unsigned long iflag;
19614 
19615 	/*
19616 	 * Fetch the next logical rpi.  Because this index is logical,
19617 	 * the  driver starts at 0 each time.
19618 	 */
19619 	spin_lock_irqsave(&phba->hbalock, iflag);
19620 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
19621 	rpi_limit = phba->sli4_hba.next_rpi;
19622 
19623 	rpi = find_first_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit);
19624 	if (rpi >= rpi_limit)
19625 		rpi = LPFC_RPI_ALLOC_ERROR;
19626 	else {
19627 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
19628 		phba->sli4_hba.max_cfg_param.rpi_used++;
19629 		phba->sli4_hba.rpi_count++;
19630 	}
19631 	lpfc_printf_log(phba, KERN_INFO,
19632 			LOG_NODE | LOG_DISCOVERY,
19633 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
19634 			(int) rpi, max_rpi, rpi_limit);
19635 
19636 	/*
19637 	 * Don't try to allocate more rpi header regions if the device limit
19638 	 * has been exhausted.
19639 	 */
19640 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
19641 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
19642 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19643 		return rpi;
19644 	}
19645 
19646 	/*
19647 	 * RPI header postings are not required for SLI4 ports capable of
19648 	 * extents.
19649 	 */
19650 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
19651 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19652 		return rpi;
19653 	}
19654 
19655 	/*
19656 	 * If the driver is running low on rpi resources, allocate another
19657 	 * page now.  Note that the next_rpi value is used because
19658 	 * it represents how many are actually in use whereas max_rpi notes
19659 	 * how many are supported max by the device.
19660 	 */
19661 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
19662 	spin_unlock_irqrestore(&phba->hbalock, iflag);
19663 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
19664 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
19665 		if (!rpi_hdr) {
19666 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19667 					"2002 Error Could not grow rpi "
19668 					"count\n");
19669 		} else {
19670 			lrpi = rpi_hdr->start_rpi;
19671 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19672 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
19673 		}
19674 	}
19675 
19676 	return rpi;
19677 }
19678 
19679 /**
19680  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
19681  * @phba: pointer to lpfc hba data structure.
19682  * @rpi: rpi to free
19683  *
19684  * This routine is invoked to release an rpi to the pool of
19685  * available rpis maintained by the driver.
19686  **/
19687 static void
19688 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19689 {
19690 	/*
19691 	 * if the rpi value indicates a prior unreg has already
19692 	 * been done, skip the unreg.
19693 	 */
19694 	if (rpi == LPFC_RPI_ALLOC_ERROR)
19695 		return;
19696 
19697 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
19698 		phba->sli4_hba.rpi_count--;
19699 		phba->sli4_hba.max_cfg_param.rpi_used--;
19700 	} else {
19701 		lpfc_printf_log(phba, KERN_INFO,
19702 				LOG_NODE | LOG_DISCOVERY,
19703 				"2016 rpi %x not inuse\n",
19704 				rpi);
19705 	}
19706 }
19707 
19708 /**
19709  * lpfc_sli4_free_rpi - Release an rpi for reuse.
19710  * @phba: pointer to lpfc hba data structure.
19711  * @rpi: rpi to free
19712  *
19713  * This routine is invoked to release an rpi to the pool of
19714  * available rpis maintained by the driver.
19715  **/
19716 void
19717 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19718 {
19719 	spin_lock_irq(&phba->hbalock);
19720 	__lpfc_sli4_free_rpi(phba, rpi);
19721 	spin_unlock_irq(&phba->hbalock);
19722 }
19723 
19724 /**
19725  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19726  * @phba: pointer to lpfc hba data structure.
19727  *
19728  * This routine is invoked to remove the memory region that
19729  * provided rpi via a bitmask.
19730  **/
19731 void
19732 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19733 {
19734 	kfree(phba->sli4_hba.rpi_bmask);
19735 	kfree(phba->sli4_hba.rpi_ids);
19736 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19737 }
19738 
19739 /**
19740  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
19741  * @ndlp: pointer to lpfc nodelist data structure.
19742  * @cmpl: completion call-back.
19743  * @arg: data to load as MBox 'caller buffer information'
19744  *
19745  * This routine is invoked to remove the memory region that
19746  * provided rpi via a bitmask.
19747  **/
19748 int
19749 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19750 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
19751 {
19752 	LPFC_MBOXQ_t *mboxq;
19753 	struct lpfc_hba *phba = ndlp->phba;
19754 	int rc;
19755 
19756 	/* The port is notified of the header region via a mailbox command. */
19757 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19758 	if (!mboxq)
19759 		return -ENOMEM;
19760 
19761 	/* If cmpl assigned, then this nlp_get pairs with
19762 	 * lpfc_mbx_cmpl_resume_rpi.
19763 	 *
19764 	 * Else cmpl is NULL, then this nlp_get pairs with
19765 	 * lpfc_sli_def_mbox_cmpl.
19766 	 */
19767 	if (!lpfc_nlp_get(ndlp)) {
19768 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19769 				"2122 %s: Failed to get nlp ref\n",
19770 				__func__);
19771 		mempool_free(mboxq, phba->mbox_mem_pool);
19772 		return -EIO;
19773 	}
19774 
19775 	/* Post all rpi memory regions to the port. */
19776 	lpfc_resume_rpi(mboxq, ndlp);
19777 	if (cmpl) {
19778 		mboxq->mbox_cmpl = cmpl;
19779 		mboxq->ctx_buf = arg;
19780 	} else
19781 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19782 	mboxq->ctx_ndlp = ndlp;
19783 	mboxq->vport = ndlp->vport;
19784 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19785 	if (rc == MBX_NOT_FINISHED) {
19786 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19787 				"2010 Resume RPI Mailbox failed "
19788 				"status %d, mbxStatus x%x\n", rc,
19789 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19790 		lpfc_nlp_put(ndlp);
19791 		mempool_free(mboxq, phba->mbox_mem_pool);
19792 		return -EIO;
19793 	}
19794 	return 0;
19795 }
19796 
19797 /**
19798  * lpfc_sli4_init_vpi - Initialize a vpi with the port
19799  * @vport: Pointer to the vport for which the vpi is being initialized
19800  *
19801  * This routine is invoked to activate a vpi with the port.
19802  *
19803  * Returns:
19804  *    0 success
19805  *    -Evalue otherwise
19806  **/
19807 int
19808 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
19809 {
19810 	LPFC_MBOXQ_t *mboxq;
19811 	int rc = 0;
19812 	int retval = MBX_SUCCESS;
19813 	uint32_t mbox_tmo;
19814 	struct lpfc_hba *phba = vport->phba;
19815 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19816 	if (!mboxq)
19817 		return -ENOMEM;
19818 	lpfc_init_vpi(phba, mboxq, vport->vpi);
19819 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
19820 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
19821 	if (rc != MBX_SUCCESS) {
19822 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19823 				"2022 INIT VPI Mailbox failed "
19824 				"status %d, mbxStatus x%x\n", rc,
19825 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19826 		retval = -EIO;
19827 	}
19828 	if (rc != MBX_TIMEOUT)
19829 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
19830 
19831 	return retval;
19832 }
19833 
19834 /**
19835  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
19836  * @phba: pointer to lpfc hba data structure.
19837  * @mboxq: Pointer to mailbox object.
19838  *
19839  * This routine is invoked to manually add a single FCF record. The caller
19840  * must pass a completely initialized FCF_Record.  This routine takes
19841  * care of the nonembedded mailbox operations.
19842  **/
19843 static void
19844 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
19845 {
19846 	void *virt_addr;
19847 	union lpfc_sli4_cfg_shdr *shdr;
19848 	uint32_t shdr_status, shdr_add_status;
19849 
19850 	virt_addr = mboxq->sge_array->addr[0];
19851 	/* The IOCTL status is embedded in the mailbox subheader. */
19852 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
19853 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19854 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19855 
19856 	if ((shdr_status || shdr_add_status) &&
19857 		(shdr_status != STATUS_FCF_IN_USE))
19858 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19859 			"2558 ADD_FCF_RECORD mailbox failed with "
19860 			"status x%x add_status x%x\n",
19861 			shdr_status, shdr_add_status);
19862 
19863 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
19864 }
19865 
19866 /**
19867  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
19868  * @phba: pointer to lpfc hba data structure.
19869  * @fcf_record:  pointer to the initialized fcf record to add.
19870  *
19871  * This routine is invoked to manually add a single FCF record. The caller
19872  * must pass a completely initialized FCF_Record.  This routine takes
19873  * care of the nonembedded mailbox operations.
19874  **/
19875 int
19876 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
19877 {
19878 	int rc = 0;
19879 	LPFC_MBOXQ_t *mboxq;
19880 	uint8_t *bytep;
19881 	void *virt_addr;
19882 	struct lpfc_mbx_sge sge;
19883 	uint32_t alloc_len, req_len;
19884 	uint32_t fcfindex;
19885 
19886 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19887 	if (!mboxq) {
19888 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19889 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
19890 		return -ENOMEM;
19891 	}
19892 
19893 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
19894 		  sizeof(uint32_t);
19895 
19896 	/* Allocate DMA memory and set up the non-embedded mailbox command */
19897 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19898 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
19899 				     req_len, LPFC_SLI4_MBX_NEMBED);
19900 	if (alloc_len < req_len) {
19901 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19902 			"2523 Allocated DMA memory size (x%x) is "
19903 			"less than the requested DMA memory "
19904 			"size (x%x)\n", alloc_len, req_len);
19905 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19906 		return -ENOMEM;
19907 	}
19908 
19909 	/*
19910 	 * Get the first SGE entry from the non-embedded DMA memory.  This
19911 	 * routine only uses a single SGE.
19912 	 */
19913 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
19914 	virt_addr = mboxq->sge_array->addr[0];
19915 	/*
19916 	 * Configure the FCF record for FCFI 0.  This is the driver's
19917 	 * hardcoded default and gets used in nonFIP mode.
19918 	 */
19919 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
19920 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
19921 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
19922 
19923 	/*
19924 	 * Copy the fcf_index and the FCF Record Data. The data starts after
19925 	 * the FCoE header plus word10. The data copy needs to be endian
19926 	 * correct.
19927 	 */
19928 	bytep += sizeof(uint32_t);
19929 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
19930 	mboxq->vport = phba->pport;
19931 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
19932 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19933 	if (rc == MBX_NOT_FINISHED) {
19934 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19935 			"2515 ADD_FCF_RECORD mailbox failed with "
19936 			"status 0x%x\n", rc);
19937 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19938 		rc = -EIO;
19939 	} else
19940 		rc = 0;
19941 
19942 	return rc;
19943 }
19944 
19945 /**
19946  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
19947  * @phba: pointer to lpfc hba data structure.
19948  * @fcf_record:  pointer to the fcf record to write the default data.
19949  * @fcf_index: FCF table entry index.
19950  *
19951  * This routine is invoked to build the driver's default FCF record.  The
19952  * values used are hardcoded.  This routine handles memory initialization.
19953  *
19954  **/
19955 void
19956 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
19957 				struct fcf_record *fcf_record,
19958 				uint16_t fcf_index)
19959 {
19960 	memset(fcf_record, 0, sizeof(struct fcf_record));
19961 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
19962 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
19963 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
19964 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
19965 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
19966 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
19967 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
19968 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
19969 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
19970 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
19971 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
19972 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
19973 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
19974 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
19975 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
19976 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
19977 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
19978 	/* Set the VLAN bit map */
19979 	if (phba->valid_vlan) {
19980 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
19981 			= 1 << (phba->vlan_id % 8);
19982 	}
19983 }
19984 
19985 /**
19986  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
19987  * @phba: pointer to lpfc hba data structure.
19988  * @fcf_index: FCF table entry offset.
19989  *
19990  * This routine is invoked to scan the entire FCF table by reading FCF
19991  * record and processing it one at a time starting from the @fcf_index
19992  * for initial FCF discovery or fast FCF failover rediscovery.
19993  *
19994  * Return 0 if the mailbox command is submitted successfully, none 0
19995  * otherwise.
19996  **/
19997 int
19998 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19999 {
20000 	int rc = 0, error;
20001 	LPFC_MBOXQ_t *mboxq;
20002 
20003 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
20004 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
20005 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20006 	if (!mboxq) {
20007 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20008 				"2000 Failed to allocate mbox for "
20009 				"READ_FCF cmd\n");
20010 		error = -ENOMEM;
20011 		goto fail_fcf_scan;
20012 	}
20013 	/* Construct the read FCF record mailbox command */
20014 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20015 	if (rc) {
20016 		error = -EINVAL;
20017 		goto fail_fcf_scan;
20018 	}
20019 	/* Issue the mailbox command asynchronously */
20020 	mboxq->vport = phba->pport;
20021 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
20022 
20023 	spin_lock_irq(&phba->hbalock);
20024 	phba->hba_flag |= FCF_TS_INPROG;
20025 	spin_unlock_irq(&phba->hbalock);
20026 
20027 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20028 	if (rc == MBX_NOT_FINISHED)
20029 		error = -EIO;
20030 	else {
20031 		/* Reset eligible FCF count for new scan */
20032 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
20033 			phba->fcf.eligible_fcf_cnt = 0;
20034 		error = 0;
20035 	}
20036 fail_fcf_scan:
20037 	if (error) {
20038 		if (mboxq)
20039 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
20040 		/* FCF scan failed, clear FCF_TS_INPROG flag */
20041 		spin_lock_irq(&phba->hbalock);
20042 		phba->hba_flag &= ~FCF_TS_INPROG;
20043 		spin_unlock_irq(&phba->hbalock);
20044 	}
20045 	return error;
20046 }
20047 
20048 /**
20049  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
20050  * @phba: pointer to lpfc hba data structure.
20051  * @fcf_index: FCF table entry offset.
20052  *
20053  * This routine is invoked to read an FCF record indicated by @fcf_index
20054  * and to use it for FLOGI roundrobin FCF failover.
20055  *
20056  * Return 0 if the mailbox command is submitted successfully, none 0
20057  * otherwise.
20058  **/
20059 int
20060 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20061 {
20062 	int rc = 0, error;
20063 	LPFC_MBOXQ_t *mboxq;
20064 
20065 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20066 	if (!mboxq) {
20067 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20068 				"2763 Failed to allocate mbox for "
20069 				"READ_FCF cmd\n");
20070 		error = -ENOMEM;
20071 		goto fail_fcf_read;
20072 	}
20073 	/* Construct the read FCF record mailbox command */
20074 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20075 	if (rc) {
20076 		error = -EINVAL;
20077 		goto fail_fcf_read;
20078 	}
20079 	/* Issue the mailbox command asynchronously */
20080 	mboxq->vport = phba->pport;
20081 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
20082 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20083 	if (rc == MBX_NOT_FINISHED)
20084 		error = -EIO;
20085 	else
20086 		error = 0;
20087 
20088 fail_fcf_read:
20089 	if (error && mboxq)
20090 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20091 	return error;
20092 }
20093 
20094 /**
20095  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
20096  * @phba: pointer to lpfc hba data structure.
20097  * @fcf_index: FCF table entry offset.
20098  *
20099  * This routine is invoked to read an FCF record indicated by @fcf_index to
20100  * determine whether it's eligible for FLOGI roundrobin failover list.
20101  *
20102  * Return 0 if the mailbox command is submitted successfully, none 0
20103  * otherwise.
20104  **/
20105 int
20106 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20107 {
20108 	int rc = 0, error;
20109 	LPFC_MBOXQ_t *mboxq;
20110 
20111 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20112 	if (!mboxq) {
20113 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20114 				"2758 Failed to allocate mbox for "
20115 				"READ_FCF cmd\n");
20116 				error = -ENOMEM;
20117 				goto fail_fcf_read;
20118 	}
20119 	/* Construct the read FCF record mailbox command */
20120 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20121 	if (rc) {
20122 		error = -EINVAL;
20123 		goto fail_fcf_read;
20124 	}
20125 	/* Issue the mailbox command asynchronously */
20126 	mboxq->vport = phba->pport;
20127 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
20128 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20129 	if (rc == MBX_NOT_FINISHED)
20130 		error = -EIO;
20131 	else
20132 		error = 0;
20133 
20134 fail_fcf_read:
20135 	if (error && mboxq)
20136 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20137 	return error;
20138 }
20139 
20140 /**
20141  * lpfc_check_next_fcf_pri_level
20142  * @phba: pointer to the lpfc_hba struct for this port.
20143  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
20144  * routine when the rr_bmask is empty. The FCF indecies are put into the
20145  * rr_bmask based on their priority level. Starting from the highest priority
20146  * to the lowest. The most likely FCF candidate will be in the highest
20147  * priority group. When this routine is called it searches the fcf_pri list for
20148  * next lowest priority group and repopulates the rr_bmask with only those
20149  * fcf_indexes.
20150  * returns:
20151  * 1=success 0=failure
20152  **/
20153 static int
20154 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
20155 {
20156 	uint16_t next_fcf_pri;
20157 	uint16_t last_index;
20158 	struct lpfc_fcf_pri *fcf_pri;
20159 	int rc;
20160 	int ret = 0;
20161 
20162 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20163 			LPFC_SLI4_FCF_TBL_INDX_MAX);
20164 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20165 			"3060 Last IDX %d\n", last_index);
20166 
20167 	/* Verify the priority list has 2 or more entries */
20168 	spin_lock_irq(&phba->hbalock);
20169 	if (list_empty(&phba->fcf.fcf_pri_list) ||
20170 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
20171 		spin_unlock_irq(&phba->hbalock);
20172 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20173 			"3061 Last IDX %d\n", last_index);
20174 		return 0; /* Empty rr list */
20175 	}
20176 	spin_unlock_irq(&phba->hbalock);
20177 
20178 	next_fcf_pri = 0;
20179 	/*
20180 	 * Clear the rr_bmask and set all of the bits that are at this
20181 	 * priority.
20182 	 */
20183 	memset(phba->fcf.fcf_rr_bmask, 0,
20184 			sizeof(*phba->fcf.fcf_rr_bmask));
20185 	spin_lock_irq(&phba->hbalock);
20186 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20187 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
20188 			continue;
20189 		/*
20190 		 * the 1st priority that has not FLOGI failed
20191 		 * will be the highest.
20192 		 */
20193 		if (!next_fcf_pri)
20194 			next_fcf_pri = fcf_pri->fcf_rec.priority;
20195 		spin_unlock_irq(&phba->hbalock);
20196 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20197 			rc = lpfc_sli4_fcf_rr_index_set(phba,
20198 						fcf_pri->fcf_rec.fcf_index);
20199 			if (rc)
20200 				return 0;
20201 		}
20202 		spin_lock_irq(&phba->hbalock);
20203 	}
20204 	/*
20205 	 * if next_fcf_pri was not set above and the list is not empty then
20206 	 * we have failed flogis on all of them. So reset flogi failed
20207 	 * and start at the beginning.
20208 	 */
20209 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
20210 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20211 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
20212 			/*
20213 			 * the 1st priority that has not FLOGI failed
20214 			 * will be the highest.
20215 			 */
20216 			if (!next_fcf_pri)
20217 				next_fcf_pri = fcf_pri->fcf_rec.priority;
20218 			spin_unlock_irq(&phba->hbalock);
20219 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20220 				rc = lpfc_sli4_fcf_rr_index_set(phba,
20221 						fcf_pri->fcf_rec.fcf_index);
20222 				if (rc)
20223 					return 0;
20224 			}
20225 			spin_lock_irq(&phba->hbalock);
20226 		}
20227 	} else
20228 		ret = 1;
20229 	spin_unlock_irq(&phba->hbalock);
20230 
20231 	return ret;
20232 }
20233 /**
20234  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
20235  * @phba: pointer to lpfc hba data structure.
20236  *
20237  * This routine is to get the next eligible FCF record index in a round
20238  * robin fashion. If the next eligible FCF record index equals to the
20239  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
20240  * shall be returned, otherwise, the next eligible FCF record's index
20241  * shall be returned.
20242  **/
20243 uint16_t
20244 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
20245 {
20246 	uint16_t next_fcf_index;
20247 
20248 initial_priority:
20249 	/* Search start from next bit of currently registered FCF index */
20250 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
20251 
20252 next_priority:
20253 	/* Determine the next fcf index to check */
20254 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
20255 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
20256 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
20257 				       next_fcf_index);
20258 
20259 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
20260 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20261 		/*
20262 		 * If we have wrapped then we need to clear the bits that
20263 		 * have been tested so that we can detect when we should
20264 		 * change the priority level.
20265 		 */
20266 		next_fcf_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20267 					       LPFC_SLI4_FCF_TBL_INDX_MAX);
20268 	}
20269 
20270 
20271 	/* Check roundrobin failover list empty condition */
20272 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
20273 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
20274 		/*
20275 		 * If next fcf index is not found check if there are lower
20276 		 * Priority level fcf's in the fcf_priority list.
20277 		 * Set up the rr_bmask with all of the avaiable fcf bits
20278 		 * at that level and continue the selection process.
20279 		 */
20280 		if (lpfc_check_next_fcf_pri_level(phba))
20281 			goto initial_priority;
20282 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
20283 				"2844 No roundrobin failover FCF available\n");
20284 
20285 		return LPFC_FCOE_FCF_NEXT_NONE;
20286 	}
20287 
20288 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
20289 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
20290 		LPFC_FCF_FLOGI_FAILED) {
20291 		if (list_is_singular(&phba->fcf.fcf_pri_list))
20292 			return LPFC_FCOE_FCF_NEXT_NONE;
20293 
20294 		goto next_priority;
20295 	}
20296 
20297 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20298 			"2845 Get next roundrobin failover FCF (x%x)\n",
20299 			next_fcf_index);
20300 
20301 	return next_fcf_index;
20302 }
20303 
20304 /**
20305  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
20306  * @phba: pointer to lpfc hba data structure.
20307  * @fcf_index: index into the FCF table to 'set'
20308  *
20309  * This routine sets the FCF record index in to the eligible bmask for
20310  * roundrobin failover search. It checks to make sure that the index
20311  * does not go beyond the range of the driver allocated bmask dimension
20312  * before setting the bit.
20313  *
20314  * Returns 0 if the index bit successfully set, otherwise, it returns
20315  * -EINVAL.
20316  **/
20317 int
20318 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
20319 {
20320 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20321 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20322 				"2610 FCF (x%x) reached driver's book "
20323 				"keeping dimension:x%x\n",
20324 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20325 		return -EINVAL;
20326 	}
20327 	/* Set the eligible FCF record index bmask */
20328 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20329 
20330 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20331 			"2790 Set FCF (x%x) to roundrobin FCF failover "
20332 			"bmask\n", fcf_index);
20333 
20334 	return 0;
20335 }
20336 
20337 /**
20338  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
20339  * @phba: pointer to lpfc hba data structure.
20340  * @fcf_index: index into the FCF table to 'clear'
20341  *
20342  * This routine clears the FCF record index from the eligible bmask for
20343  * roundrobin failover search. It checks to make sure that the index
20344  * does not go beyond the range of the driver allocated bmask dimension
20345  * before clearing the bit.
20346  **/
20347 void
20348 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
20349 {
20350 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
20351 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20352 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20353 				"2762 FCF (x%x) reached driver's book "
20354 				"keeping dimension:x%x\n",
20355 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20356 		return;
20357 	}
20358 	/* Clear the eligible FCF record index bmask */
20359 	spin_lock_irq(&phba->hbalock);
20360 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
20361 				 list) {
20362 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
20363 			list_del_init(&fcf_pri->list);
20364 			break;
20365 		}
20366 	}
20367 	spin_unlock_irq(&phba->hbalock);
20368 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20369 
20370 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20371 			"2791 Clear FCF (x%x) from roundrobin failover "
20372 			"bmask\n", fcf_index);
20373 }
20374 
20375 /**
20376  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
20377  * @phba: pointer to lpfc hba data structure.
20378  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
20379  *
20380  * This routine is the completion routine for the rediscover FCF table mailbox
20381  * command. If the mailbox command returned failure, it will try to stop the
20382  * FCF rediscover wait timer.
20383  **/
20384 static void
20385 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
20386 {
20387 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20388 	uint32_t shdr_status, shdr_add_status;
20389 
20390 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20391 
20392 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20393 			     &redisc_fcf->header.cfg_shdr.response);
20394 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20395 			     &redisc_fcf->header.cfg_shdr.response);
20396 	if (shdr_status || shdr_add_status) {
20397 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20398 				"2746 Requesting for FCF rediscovery failed "
20399 				"status x%x add_status x%x\n",
20400 				shdr_status, shdr_add_status);
20401 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
20402 			spin_lock_irq(&phba->hbalock);
20403 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
20404 			spin_unlock_irq(&phba->hbalock);
20405 			/*
20406 			 * CVL event triggered FCF rediscover request failed,
20407 			 * last resort to re-try current registered FCF entry.
20408 			 */
20409 			lpfc_retry_pport_discovery(phba);
20410 		} else {
20411 			spin_lock_irq(&phba->hbalock);
20412 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
20413 			spin_unlock_irq(&phba->hbalock);
20414 			/*
20415 			 * DEAD FCF event triggered FCF rediscover request
20416 			 * failed, last resort to fail over as a link down
20417 			 * to FCF registration.
20418 			 */
20419 			lpfc_sli4_fcf_dead_failthrough(phba);
20420 		}
20421 	} else {
20422 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20423 				"2775 Start FCF rediscover quiescent timer\n");
20424 		/*
20425 		 * Start FCF rediscovery wait timer for pending FCF
20426 		 * before rescan FCF record table.
20427 		 */
20428 		lpfc_fcf_redisc_wait_start_timer(phba);
20429 	}
20430 
20431 	mempool_free(mbox, phba->mbox_mem_pool);
20432 }
20433 
20434 /**
20435  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
20436  * @phba: pointer to lpfc hba data structure.
20437  *
20438  * This routine is invoked to request for rediscovery of the entire FCF table
20439  * by the port.
20440  **/
20441 int
20442 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
20443 {
20444 	LPFC_MBOXQ_t *mbox;
20445 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20446 	int rc, length;
20447 
20448 	/* Cancel retry delay timers to all vports before FCF rediscover */
20449 	lpfc_cancel_all_vport_retry_delay_timer(phba);
20450 
20451 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20452 	if (!mbox) {
20453 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20454 				"2745 Failed to allocate mbox for "
20455 				"requesting FCF rediscover.\n");
20456 		return -ENOMEM;
20457 	}
20458 
20459 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
20460 		  sizeof(struct lpfc_sli4_cfg_mhdr));
20461 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
20462 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
20463 			 length, LPFC_SLI4_MBX_EMBED);
20464 
20465 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20466 	/* Set count to 0 for invalidating the entire FCF database */
20467 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
20468 
20469 	/* Issue the mailbox command asynchronously */
20470 	mbox->vport = phba->pport;
20471 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
20472 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
20473 
20474 	if (rc == MBX_NOT_FINISHED) {
20475 		mempool_free(mbox, phba->mbox_mem_pool);
20476 		return -EIO;
20477 	}
20478 	return 0;
20479 }
20480 
20481 /**
20482  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
20483  * @phba: pointer to lpfc hba data structure.
20484  *
20485  * This function is the failover routine as a last resort to the FCF DEAD
20486  * event when driver failed to perform fast FCF failover.
20487  **/
20488 void
20489 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
20490 {
20491 	uint32_t link_state;
20492 
20493 	/*
20494 	 * Last resort as FCF DEAD event failover will treat this as
20495 	 * a link down, but save the link state because we don't want
20496 	 * it to be changed to Link Down unless it is already down.
20497 	 */
20498 	link_state = phba->link_state;
20499 	lpfc_linkdown(phba);
20500 	phba->link_state = link_state;
20501 
20502 	/* Unregister FCF if no devices connected to it */
20503 	lpfc_unregister_unused_fcf(phba);
20504 }
20505 
20506 /**
20507  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
20508  * @phba: pointer to lpfc hba data structure.
20509  * @rgn23_data: pointer to configure region 23 data.
20510  *
20511  * This function gets SLI3 port configure region 23 data through memory dump
20512  * mailbox command. When it successfully retrieves data, the size of the data
20513  * will be returned, otherwise, 0 will be returned.
20514  **/
20515 static uint32_t
20516 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20517 {
20518 	LPFC_MBOXQ_t *pmb = NULL;
20519 	MAILBOX_t *mb;
20520 	uint32_t offset = 0;
20521 	int rc;
20522 
20523 	if (!rgn23_data)
20524 		return 0;
20525 
20526 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20527 	if (!pmb) {
20528 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20529 				"2600 failed to allocate mailbox memory\n");
20530 		return 0;
20531 	}
20532 	mb = &pmb->u.mb;
20533 
20534 	do {
20535 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
20536 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
20537 
20538 		if (rc != MBX_SUCCESS) {
20539 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20540 					"2601 failed to read config "
20541 					"region 23, rc 0x%x Status 0x%x\n",
20542 					rc, mb->mbxStatus);
20543 			mb->un.varDmp.word_cnt = 0;
20544 		}
20545 		/*
20546 		 * dump mem may return a zero when finished or we got a
20547 		 * mailbox error, either way we are done.
20548 		 */
20549 		if (mb->un.varDmp.word_cnt == 0)
20550 			break;
20551 
20552 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
20553 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
20554 
20555 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
20556 				       rgn23_data + offset,
20557 				       mb->un.varDmp.word_cnt);
20558 		offset += mb->un.varDmp.word_cnt;
20559 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
20560 
20561 	mempool_free(pmb, phba->mbox_mem_pool);
20562 	return offset;
20563 }
20564 
20565 /**
20566  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
20567  * @phba: pointer to lpfc hba data structure.
20568  * @rgn23_data: pointer to configure region 23 data.
20569  *
20570  * This function gets SLI4 port configure region 23 data through memory dump
20571  * mailbox command. When it successfully retrieves data, the size of the data
20572  * will be returned, otherwise, 0 will be returned.
20573  **/
20574 static uint32_t
20575 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20576 {
20577 	LPFC_MBOXQ_t *mboxq = NULL;
20578 	struct lpfc_dmabuf *mp = NULL;
20579 	struct lpfc_mqe *mqe;
20580 	uint32_t data_length = 0;
20581 	int rc;
20582 
20583 	if (!rgn23_data)
20584 		return 0;
20585 
20586 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20587 	if (!mboxq) {
20588 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20589 				"3105 failed to allocate mailbox memory\n");
20590 		return 0;
20591 	}
20592 
20593 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
20594 		goto out;
20595 	mqe = &mboxq->u.mqe;
20596 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
20597 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
20598 	if (rc)
20599 		goto out;
20600 	data_length = mqe->un.mb_words[5];
20601 	if (data_length == 0)
20602 		goto out;
20603 	if (data_length > DMP_RGN23_SIZE) {
20604 		data_length = 0;
20605 		goto out;
20606 	}
20607 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
20608 out:
20609 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
20610 	return data_length;
20611 }
20612 
20613 /**
20614  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
20615  * @phba: pointer to lpfc hba data structure.
20616  *
20617  * This function read region 23 and parse TLV for port status to
20618  * decide if the user disaled the port. If the TLV indicates the
20619  * port is disabled, the hba_flag is set accordingly.
20620  **/
20621 void
20622 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
20623 {
20624 	uint8_t *rgn23_data = NULL;
20625 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
20626 	uint32_t offset = 0;
20627 
20628 	/* Get adapter Region 23 data */
20629 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
20630 	if (!rgn23_data)
20631 		goto out;
20632 
20633 	if (phba->sli_rev < LPFC_SLI_REV4)
20634 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
20635 	else {
20636 		if_type = bf_get(lpfc_sli_intf_if_type,
20637 				 &phba->sli4_hba.sli_intf);
20638 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
20639 			goto out;
20640 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
20641 	}
20642 
20643 	if (!data_size)
20644 		goto out;
20645 
20646 	/* Check the region signature first */
20647 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
20648 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20649 			"2619 Config region 23 has bad signature\n");
20650 			goto out;
20651 	}
20652 	offset += 4;
20653 
20654 	/* Check the data structure version */
20655 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
20656 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20657 			"2620 Config region 23 has bad version\n");
20658 		goto out;
20659 	}
20660 	offset += 4;
20661 
20662 	/* Parse TLV entries in the region */
20663 	while (offset < data_size) {
20664 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
20665 			break;
20666 		/*
20667 		 * If the TLV is not driver specific TLV or driver id is
20668 		 * not linux driver id, skip the record.
20669 		 */
20670 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
20671 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
20672 		    (rgn23_data[offset + 3] != 0)) {
20673 			offset += rgn23_data[offset + 1] * 4 + 4;
20674 			continue;
20675 		}
20676 
20677 		/* Driver found a driver specific TLV in the config region */
20678 		sub_tlv_len = rgn23_data[offset + 1] * 4;
20679 		offset += 4;
20680 		tlv_offset = 0;
20681 
20682 		/*
20683 		 * Search for configured port state sub-TLV.
20684 		 */
20685 		while ((offset < data_size) &&
20686 			(tlv_offset < sub_tlv_len)) {
20687 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
20688 				offset += 4;
20689 				tlv_offset += 4;
20690 				break;
20691 			}
20692 			if (rgn23_data[offset] != PORT_STE_TYPE) {
20693 				offset += rgn23_data[offset + 1] * 4 + 4;
20694 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
20695 				continue;
20696 			}
20697 
20698 			/* This HBA contains PORT_STE configured */
20699 			if (!rgn23_data[offset + 2])
20700 				phba->hba_flag |= LINK_DISABLED;
20701 
20702 			goto out;
20703 		}
20704 	}
20705 
20706 out:
20707 	kfree(rgn23_data);
20708 	return;
20709 }
20710 
20711 /**
20712  * lpfc_log_fw_write_cmpl - logs firmware write completion status
20713  * @phba: pointer to lpfc hba data structure
20714  * @shdr_status: wr_object rsp's status field
20715  * @shdr_add_status: wr_object rsp's add_status field
20716  * @shdr_add_status_2: wr_object rsp's add_status_2 field
20717  * @shdr_change_status: wr_object rsp's change_status field
20718  * @shdr_csf: wr_object rsp's csf bit
20719  *
20720  * This routine is intended to be called after a firmware write completes.
20721  * It will log next action items to be performed by the user to instantiate
20722  * the newly downloaded firmware or reason for incompatibility.
20723  **/
20724 static void
20725 lpfc_log_fw_write_cmpl(struct lpfc_hba *phba, u32 shdr_status,
20726 		       u32 shdr_add_status, u32 shdr_add_status_2,
20727 		       u32 shdr_change_status, u32 shdr_csf)
20728 {
20729 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20730 			"4198 %s: flash_id x%02x, asic_rev x%02x, "
20731 			"status x%02x, add_status x%02x, add_status_2 x%02x, "
20732 			"change_status x%02x, csf %01x\n", __func__,
20733 			phba->sli4_hba.flash_id, phba->sli4_hba.asic_rev,
20734 			shdr_status, shdr_add_status, shdr_add_status_2,
20735 			shdr_change_status, shdr_csf);
20736 
20737 	if (shdr_add_status == LPFC_ADD_STATUS_INCOMPAT_OBJ) {
20738 		switch (shdr_add_status_2) {
20739 		case LPFC_ADD_STATUS_2_INCOMPAT_FLASH:
20740 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20741 					"4199 Firmware write failed: "
20742 					"image incompatible with flash x%02x\n",
20743 					phba->sli4_hba.flash_id);
20744 			break;
20745 		case LPFC_ADD_STATUS_2_INCORRECT_ASIC:
20746 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20747 					"4200 Firmware write failed: "
20748 					"image incompatible with ASIC "
20749 					"architecture x%02x\n",
20750 					phba->sli4_hba.asic_rev);
20751 			break;
20752 		default:
20753 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20754 					"4210 Firmware write failed: "
20755 					"add_status_2 x%02x\n",
20756 					shdr_add_status_2);
20757 			break;
20758 		}
20759 	} else if (!shdr_status && !shdr_add_status) {
20760 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20761 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20762 			if (shdr_csf)
20763 				shdr_change_status =
20764 						   LPFC_CHANGE_STATUS_PCI_RESET;
20765 		}
20766 
20767 		switch (shdr_change_status) {
20768 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20769 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20770 					"3198 Firmware write complete: System "
20771 					"reboot required to instantiate\n");
20772 			break;
20773 		case (LPFC_CHANGE_STATUS_FW_RESET):
20774 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20775 					"3199 Firmware write complete: "
20776 					"Firmware reset required to "
20777 					"instantiate\n");
20778 			break;
20779 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20780 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20781 					"3200 Firmware write complete: Port "
20782 					"Migration or PCI Reset required to "
20783 					"instantiate\n");
20784 			break;
20785 		case (LPFC_CHANGE_STATUS_PCI_RESET):
20786 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20787 					"3201 Firmware write complete: PCI "
20788 					"Reset required to instantiate\n");
20789 			break;
20790 		default:
20791 			break;
20792 		}
20793 	}
20794 }
20795 
20796 /**
20797  * lpfc_wr_object - write an object to the firmware
20798  * @phba: HBA structure that indicates port to create a queue on.
20799  * @dmabuf_list: list of dmabufs to write to the port.
20800  * @size: the total byte value of the objects to write to the port.
20801  * @offset: the current offset to be used to start the transfer.
20802  *
20803  * This routine will create a wr_object mailbox command to send to the port.
20804  * the mailbox command will be constructed using the dma buffers described in
20805  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
20806  * BDEs that the imbedded mailbox can support. The @offset variable will be
20807  * used to indicate the starting offset of the transfer and will also return
20808  * the offset after the write object mailbox has completed. @size is used to
20809  * determine the end of the object and whether the eof bit should be set.
20810  *
20811  * Return 0 is successful and offset will contain the the new offset to use
20812  * for the next write.
20813  * Return negative value for error cases.
20814  **/
20815 int
20816 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
20817 	       uint32_t size, uint32_t *offset)
20818 {
20819 	struct lpfc_mbx_wr_object *wr_object;
20820 	LPFC_MBOXQ_t *mbox;
20821 	int rc = 0, i = 0;
20822 	uint32_t shdr_status, shdr_add_status, shdr_add_status_2;
20823 	uint32_t shdr_change_status = 0, shdr_csf = 0;
20824 	uint32_t mbox_tmo;
20825 	struct lpfc_dmabuf *dmabuf;
20826 	uint32_t written = 0;
20827 	bool check_change_status = false;
20828 
20829 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20830 	if (!mbox)
20831 		return -ENOMEM;
20832 
20833 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
20834 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
20835 			sizeof(struct lpfc_mbx_wr_object) -
20836 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
20837 
20838 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
20839 	wr_object->u.request.write_offset = *offset;
20840 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
20841 	wr_object->u.request.object_name[0] =
20842 		cpu_to_le32(wr_object->u.request.object_name[0]);
20843 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
20844 	list_for_each_entry(dmabuf, dmabuf_list, list) {
20845 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
20846 			break;
20847 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
20848 		wr_object->u.request.bde[i].addrHigh =
20849 			putPaddrHigh(dmabuf->phys);
20850 		if (written + SLI4_PAGE_SIZE >= size) {
20851 			wr_object->u.request.bde[i].tus.f.bdeSize =
20852 				(size - written);
20853 			written += (size - written);
20854 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
20855 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
20856 			check_change_status = true;
20857 		} else {
20858 			wr_object->u.request.bde[i].tus.f.bdeSize =
20859 				SLI4_PAGE_SIZE;
20860 			written += SLI4_PAGE_SIZE;
20861 		}
20862 		i++;
20863 	}
20864 	wr_object->u.request.bde_count = i;
20865 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
20866 	if (!phba->sli4_hba.intr_enable)
20867 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
20868 	else {
20869 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
20870 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
20871 	}
20872 	/* The IOCTL status is embedded in the mailbox subheader. */
20873 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20874 			     &wr_object->header.cfg_shdr.response);
20875 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20876 				 &wr_object->header.cfg_shdr.response);
20877 	shdr_add_status_2 = bf_get(lpfc_mbox_hdr_add_status_2,
20878 				   &wr_object->header.cfg_shdr.response);
20879 	if (check_change_status) {
20880 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
20881 					    &wr_object->u.response);
20882 		shdr_csf = bf_get(lpfc_wr_object_csf,
20883 				  &wr_object->u.response);
20884 	}
20885 
20886 	if (!phba->sli4_hba.intr_enable)
20887 		mempool_free(mbox, phba->mbox_mem_pool);
20888 	else if (rc != MBX_TIMEOUT)
20889 		mempool_free(mbox, phba->mbox_mem_pool);
20890 	if (shdr_status || shdr_add_status || shdr_add_status_2 || rc) {
20891 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20892 				"3025 Write Object mailbox failed with "
20893 				"status x%x add_status x%x, add_status_2 x%x, "
20894 				"mbx status x%x\n",
20895 				shdr_status, shdr_add_status, shdr_add_status_2,
20896 				rc);
20897 		rc = -ENXIO;
20898 		*offset = shdr_add_status;
20899 	} else {
20900 		*offset += wr_object->u.response.actual_write_length;
20901 	}
20902 
20903 	if (rc || check_change_status)
20904 		lpfc_log_fw_write_cmpl(phba, shdr_status, shdr_add_status,
20905 				       shdr_add_status_2, shdr_change_status,
20906 				       shdr_csf);
20907 	return rc;
20908 }
20909 
20910 /**
20911  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
20912  * @vport: pointer to vport data structure.
20913  *
20914  * This function iterate through the mailboxq and clean up all REG_LOGIN
20915  * and REG_VPI mailbox commands associated with the vport. This function
20916  * is called when driver want to restart discovery of the vport due to
20917  * a Clear Virtual Link event.
20918  **/
20919 void
20920 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
20921 {
20922 	struct lpfc_hba *phba = vport->phba;
20923 	LPFC_MBOXQ_t *mb, *nextmb;
20924 	struct lpfc_nodelist *ndlp;
20925 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
20926 	LIST_HEAD(mbox_cmd_list);
20927 	uint8_t restart_loop;
20928 
20929 	/* Clean up internally queued mailbox commands with the vport */
20930 	spin_lock_irq(&phba->hbalock);
20931 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
20932 		if (mb->vport != vport)
20933 			continue;
20934 
20935 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
20936 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
20937 			continue;
20938 
20939 		list_move_tail(&mb->list, &mbox_cmd_list);
20940 	}
20941 	/* Clean up active mailbox command with the vport */
20942 	mb = phba->sli.mbox_active;
20943 	if (mb && (mb->vport == vport)) {
20944 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
20945 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
20946 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
20947 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20948 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20949 
20950 			/* This reference is local to this routine.  The
20951 			 * reference is removed at routine exit.
20952 			 */
20953 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
20954 
20955 			/* Unregister the RPI when mailbox complete */
20956 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
20957 		}
20958 	}
20959 	/* Cleanup any mailbox completions which are not yet processed */
20960 	do {
20961 		restart_loop = 0;
20962 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
20963 			/*
20964 			 * If this mailox is already processed or it is
20965 			 * for another vport ignore it.
20966 			 */
20967 			if ((mb->vport != vport) ||
20968 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
20969 				continue;
20970 
20971 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
20972 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
20973 				continue;
20974 
20975 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
20976 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20977 				ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20978 				/* Unregister the RPI when mailbox complete */
20979 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
20980 				restart_loop = 1;
20981 				spin_unlock_irq(&phba->hbalock);
20982 				spin_lock(&ndlp->lock);
20983 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20984 				spin_unlock(&ndlp->lock);
20985 				spin_lock_irq(&phba->hbalock);
20986 				break;
20987 			}
20988 		}
20989 	} while (restart_loop);
20990 
20991 	spin_unlock_irq(&phba->hbalock);
20992 
20993 	/* Release the cleaned-up mailbox commands */
20994 	while (!list_empty(&mbox_cmd_list)) {
20995 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
20996 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20997 			ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20998 			mb->ctx_ndlp = NULL;
20999 			if (ndlp) {
21000 				spin_lock(&ndlp->lock);
21001 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21002 				spin_unlock(&ndlp->lock);
21003 				lpfc_nlp_put(ndlp);
21004 			}
21005 		}
21006 		lpfc_mbox_rsrc_cleanup(phba, mb, MBOX_THD_UNLOCKED);
21007 	}
21008 
21009 	/* Release the ndlp with the cleaned-up active mailbox command */
21010 	if (act_mbx_ndlp) {
21011 		spin_lock(&act_mbx_ndlp->lock);
21012 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21013 		spin_unlock(&act_mbx_ndlp->lock);
21014 		lpfc_nlp_put(act_mbx_ndlp);
21015 	}
21016 }
21017 
21018 /**
21019  * lpfc_drain_txq - Drain the txq
21020  * @phba: Pointer to HBA context object.
21021  *
21022  * This function attempt to submit IOCBs on the txq
21023  * to the adapter.  For SLI4 adapters, the txq contains
21024  * ELS IOCBs that have been deferred because the there
21025  * are no SGLs.  This congestion can occur with large
21026  * vport counts during node discovery.
21027  **/
21028 
21029 uint32_t
21030 lpfc_drain_txq(struct lpfc_hba *phba)
21031 {
21032 	LIST_HEAD(completions);
21033 	struct lpfc_sli_ring *pring;
21034 	struct lpfc_iocbq *piocbq = NULL;
21035 	unsigned long iflags = 0;
21036 	char *fail_msg = NULL;
21037 	uint32_t txq_cnt = 0;
21038 	struct lpfc_queue *wq;
21039 	int ret = 0;
21040 
21041 	if (phba->link_flag & LS_MDS_LOOPBACK) {
21042 		/* MDS WQE are posted only to first WQ*/
21043 		wq = phba->sli4_hba.hdwq[0].io_wq;
21044 		if (unlikely(!wq))
21045 			return 0;
21046 		pring = wq->pring;
21047 	} else {
21048 		wq = phba->sli4_hba.els_wq;
21049 		if (unlikely(!wq))
21050 			return 0;
21051 		pring = lpfc_phba_elsring(phba);
21052 	}
21053 
21054 	if (unlikely(!pring) || list_empty(&pring->txq))
21055 		return 0;
21056 
21057 	spin_lock_irqsave(&pring->ring_lock, iflags);
21058 	list_for_each_entry(piocbq, &pring->txq, list) {
21059 		txq_cnt++;
21060 	}
21061 
21062 	if (txq_cnt > pring->txq_max)
21063 		pring->txq_max = txq_cnt;
21064 
21065 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
21066 
21067 	while (!list_empty(&pring->txq)) {
21068 		spin_lock_irqsave(&pring->ring_lock, iflags);
21069 
21070 		piocbq = lpfc_sli_ringtx_get(phba, pring);
21071 		if (!piocbq) {
21072 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21073 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21074 				"2823 txq empty and txq_cnt is %d\n ",
21075 				txq_cnt);
21076 			break;
21077 		}
21078 		txq_cnt--;
21079 
21080 		ret = __lpfc_sli_issue_iocb(phba, pring->ringno, piocbq, 0);
21081 
21082 		if (ret && ret != IOCB_BUSY) {
21083 			fail_msg = " - Cannot send IO ";
21084 			piocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21085 		}
21086 		if (fail_msg) {
21087 			piocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
21088 			/* Failed means we can't issue and need to cancel */
21089 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21090 					"2822 IOCB failed %s iotag 0x%x "
21091 					"xri 0x%x %d flg x%x\n",
21092 					fail_msg, piocbq->iotag,
21093 					piocbq->sli4_xritag, ret,
21094 					piocbq->cmd_flag);
21095 			list_add_tail(&piocbq->list, &completions);
21096 			fail_msg = NULL;
21097 		}
21098 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21099 		if (txq_cnt == 0 || ret == IOCB_BUSY)
21100 			break;
21101 	}
21102 	/* Cancel all the IOCBs that cannot be issued */
21103 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
21104 			      IOERR_SLI_ABORTED);
21105 
21106 	return txq_cnt;
21107 }
21108 
21109 /**
21110  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
21111  * @phba: Pointer to HBA context object.
21112  * @pwqeq: Pointer to command WQE.
21113  * @sglq: Pointer to the scatter gather queue object.
21114  *
21115  * This routine converts the bpl or bde that is in the WQE
21116  * to a sgl list for the sli4 hardware. The physical address
21117  * of the bpl/bde is converted back to a virtual address.
21118  * If the WQE contains a BPL then the list of BDE's is
21119  * converted to sli4_sge's. If the WQE contains a single
21120  * BDE then it is converted to a single sli_sge.
21121  * The WQE is still in cpu endianness so the contents of
21122  * the bpl can be used without byte swapping.
21123  *
21124  * Returns valid XRI = Success, NO_XRI = Failure.
21125  */
21126 static uint16_t
21127 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
21128 		 struct lpfc_sglq *sglq)
21129 {
21130 	uint16_t xritag = NO_XRI;
21131 	struct ulp_bde64 *bpl = NULL;
21132 	struct ulp_bde64 bde;
21133 	struct sli4_sge *sgl  = NULL;
21134 	struct lpfc_dmabuf *dmabuf;
21135 	union lpfc_wqe128 *wqe;
21136 	int numBdes = 0;
21137 	int i = 0;
21138 	uint32_t offset = 0; /* accumulated offset in the sg request list */
21139 	int inbound = 0; /* number of sg reply entries inbound from firmware */
21140 	uint32_t cmd;
21141 
21142 	if (!pwqeq || !sglq)
21143 		return xritag;
21144 
21145 	sgl  = (struct sli4_sge *)sglq->sgl;
21146 	wqe = &pwqeq->wqe;
21147 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
21148 
21149 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
21150 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
21151 		return sglq->sli4_xritag;
21152 	numBdes = pwqeq->num_bdes;
21153 	if (numBdes) {
21154 		/* The addrHigh and addrLow fields within the WQE
21155 		 * have not been byteswapped yet so there is no
21156 		 * need to swap them back.
21157 		 */
21158 		if (pwqeq->bpl_dmabuf)
21159 			dmabuf = pwqeq->bpl_dmabuf;
21160 		else
21161 			return xritag;
21162 
21163 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
21164 		if (!bpl)
21165 			return xritag;
21166 
21167 		for (i = 0; i < numBdes; i++) {
21168 			/* Should already be byte swapped. */
21169 			sgl->addr_hi = bpl->addrHigh;
21170 			sgl->addr_lo = bpl->addrLow;
21171 
21172 			sgl->word2 = le32_to_cpu(sgl->word2);
21173 			if ((i+1) == numBdes)
21174 				bf_set(lpfc_sli4_sge_last, sgl, 1);
21175 			else
21176 				bf_set(lpfc_sli4_sge_last, sgl, 0);
21177 			/* swap the size field back to the cpu so we
21178 			 * can assign it to the sgl.
21179 			 */
21180 			bde.tus.w = le32_to_cpu(bpl->tus.w);
21181 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
21182 			/* The offsets in the sgl need to be accumulated
21183 			 * separately for the request and reply lists.
21184 			 * The request is always first, the reply follows.
21185 			 */
21186 			switch (cmd) {
21187 			case CMD_GEN_REQUEST64_WQE:
21188 				/* add up the reply sg entries */
21189 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
21190 					inbound++;
21191 				/* first inbound? reset the offset */
21192 				if (inbound == 1)
21193 					offset = 0;
21194 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21195 				bf_set(lpfc_sli4_sge_type, sgl,
21196 					LPFC_SGE_TYPE_DATA);
21197 				offset += bde.tus.f.bdeSize;
21198 				break;
21199 			case CMD_FCP_TRSP64_WQE:
21200 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
21201 				bf_set(lpfc_sli4_sge_type, sgl,
21202 					LPFC_SGE_TYPE_DATA);
21203 				break;
21204 			case CMD_FCP_TSEND64_WQE:
21205 			case CMD_FCP_TRECEIVE64_WQE:
21206 				bf_set(lpfc_sli4_sge_type, sgl,
21207 					bpl->tus.f.bdeFlags);
21208 				if (i < 3)
21209 					offset = 0;
21210 				else
21211 					offset += bde.tus.f.bdeSize;
21212 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21213 				break;
21214 			}
21215 			sgl->word2 = cpu_to_le32(sgl->word2);
21216 			bpl++;
21217 			sgl++;
21218 		}
21219 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
21220 		/* The addrHigh and addrLow fields of the BDE have not
21221 		 * been byteswapped yet so they need to be swapped
21222 		 * before putting them in the sgl.
21223 		 */
21224 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
21225 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
21226 		sgl->word2 = le32_to_cpu(sgl->word2);
21227 		bf_set(lpfc_sli4_sge_last, sgl, 1);
21228 		sgl->word2 = cpu_to_le32(sgl->word2);
21229 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
21230 	}
21231 	return sglq->sli4_xritag;
21232 }
21233 
21234 /**
21235  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
21236  * @phba: Pointer to HBA context object.
21237  * @qp: Pointer to HDW queue.
21238  * @pwqe: Pointer to command WQE.
21239  **/
21240 int
21241 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21242 		    struct lpfc_iocbq *pwqe)
21243 {
21244 	union lpfc_wqe128 *wqe = &pwqe->wqe;
21245 	struct lpfc_async_xchg_ctx *ctxp;
21246 	struct lpfc_queue *wq;
21247 	struct lpfc_sglq *sglq;
21248 	struct lpfc_sli_ring *pring;
21249 	unsigned long iflags;
21250 	uint32_t ret = 0;
21251 
21252 	/* NVME_LS and NVME_LS ABTS requests. */
21253 	if (pwqe->cmd_flag & LPFC_IO_NVME_LS) {
21254 		pring =  phba->sli4_hba.nvmels_wq->pring;
21255 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21256 					  qp, wq_access);
21257 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
21258 		if (!sglq) {
21259 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21260 			return WQE_BUSY;
21261 		}
21262 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
21263 		pwqe->sli4_xritag = sglq->sli4_xritag;
21264 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
21265 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21266 			return WQE_ERROR;
21267 		}
21268 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21269 		       pwqe->sli4_xritag);
21270 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
21271 		if (ret) {
21272 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21273 			return ret;
21274 		}
21275 
21276 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21277 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21278 
21279 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
21280 		return 0;
21281 	}
21282 
21283 	/* NVME_FCREQ and NVME_ABTS requests */
21284 	if (pwqe->cmd_flag & (LPFC_IO_NVME | LPFC_IO_FCP | LPFC_IO_CMF)) {
21285 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21286 		wq = qp->io_wq;
21287 		pring = wq->pring;
21288 
21289 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21290 
21291 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21292 					  qp, wq_access);
21293 		ret = lpfc_sli4_wq_put(wq, wqe);
21294 		if (ret) {
21295 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21296 			return ret;
21297 		}
21298 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21299 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21300 
21301 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
21302 		return 0;
21303 	}
21304 
21305 	/* NVMET requests */
21306 	if (pwqe->cmd_flag & LPFC_IO_NVMET) {
21307 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21308 		wq = qp->io_wq;
21309 		pring = wq->pring;
21310 
21311 		ctxp = pwqe->context_un.axchg;
21312 		sglq = ctxp->ctxbuf->sglq;
21313 		if (pwqe->sli4_xritag ==  NO_XRI) {
21314 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
21315 			pwqe->sli4_xritag = sglq->sli4_xritag;
21316 		}
21317 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21318 		       pwqe->sli4_xritag);
21319 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21320 
21321 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21322 					  qp, wq_access);
21323 		ret = lpfc_sli4_wq_put(wq, wqe);
21324 		if (ret) {
21325 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21326 			return ret;
21327 		}
21328 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21329 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21330 
21331 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
21332 		return 0;
21333 	}
21334 	return WQE_ERROR;
21335 }
21336 
21337 /**
21338  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
21339  * @phba: Pointer to HBA context object.
21340  * @cmdiocb: Pointer to driver command iocb object.
21341  * @cmpl: completion function.
21342  *
21343  * Fill the appropriate fields for the abort WQE and call
21344  * internal routine lpfc_sli4_issue_wqe to send the WQE
21345  * This function is called with hbalock held and no ring_lock held.
21346  *
21347  * RETURNS 0 - SUCCESS
21348  **/
21349 
21350 int
21351 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
21352 			    void *cmpl)
21353 {
21354 	struct lpfc_vport *vport = cmdiocb->vport;
21355 	struct lpfc_iocbq *abtsiocb = NULL;
21356 	union lpfc_wqe128 *abtswqe;
21357 	struct lpfc_io_buf *lpfc_cmd;
21358 	int retval = IOCB_ERROR;
21359 	u16 xritag = cmdiocb->sli4_xritag;
21360 
21361 	/*
21362 	 * The scsi command can not be in txq and it is in flight because the
21363 	 * pCmd is still pointing at the SCSI command we have to abort. There
21364 	 * is no need to search the txcmplq. Just send an abort to the FW.
21365 	 */
21366 
21367 	abtsiocb = __lpfc_sli_get_iocbq(phba);
21368 	if (!abtsiocb)
21369 		return WQE_NORESOURCE;
21370 
21371 	/* Indicate the IO is being aborted by the driver. */
21372 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
21373 
21374 	abtswqe = &abtsiocb->wqe;
21375 	memset(abtswqe, 0, sizeof(*abtswqe));
21376 
21377 	if (!lpfc_is_link_up(phba) || (phba->link_flag & LS_EXTERNAL_LOOPBACK))
21378 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
21379 	bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
21380 	abtswqe->abort_cmd.rsrvd5 = 0;
21381 	abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
21382 	bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
21383 	bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
21384 	bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
21385 	bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
21386 	bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
21387 	bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
21388 
21389 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
21390 	abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
21391 	abtsiocb->cmd_flag |= LPFC_USE_FCPWQIDX;
21392 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
21393 		abtsiocb->cmd_flag |= LPFC_IO_FCP;
21394 	if (cmdiocb->cmd_flag & LPFC_IO_NVME)
21395 		abtsiocb->cmd_flag |= LPFC_IO_NVME;
21396 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
21397 		abtsiocb->cmd_flag |= LPFC_IO_FOF;
21398 	abtsiocb->vport = vport;
21399 	abtsiocb->cmd_cmpl = cmpl;
21400 
21401 	lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
21402 	retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
21403 
21404 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21405 			 "0359 Abort xri x%x, original iotag x%x, "
21406 			 "abort cmd iotag x%x retval x%x\n",
21407 			 xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
21408 
21409 	if (retval) {
21410 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21411 		__lpfc_sli_release_iocbq(phba, abtsiocb);
21412 	}
21413 
21414 	return retval;
21415 }
21416 
21417 #ifdef LPFC_MXP_STAT
21418 /**
21419  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
21420  * @phba: pointer to lpfc hba data structure.
21421  * @hwqid: belong to which HWQ.
21422  *
21423  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
21424  * 15 seconds after a test case is running.
21425  *
21426  * The user should call lpfc_debugfs_multixripools_write before running a test
21427  * case to clear stat_snapshot_taken. Then the user starts a test case. During
21428  * test case is running, stat_snapshot_taken is incremented by 1 every time when
21429  * this routine is called from heartbeat timer. When stat_snapshot_taken is
21430  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
21431  **/
21432 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
21433 {
21434 	struct lpfc_sli4_hdw_queue *qp;
21435 	struct lpfc_multixri_pool *multixri_pool;
21436 	struct lpfc_pvt_pool *pvt_pool;
21437 	struct lpfc_pbl_pool *pbl_pool;
21438 	u32 txcmplq_cnt;
21439 
21440 	qp = &phba->sli4_hba.hdwq[hwqid];
21441 	multixri_pool = qp->p_multixri_pool;
21442 	if (!multixri_pool)
21443 		return;
21444 
21445 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
21446 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21447 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21448 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21449 
21450 		multixri_pool->stat_pbl_count = pbl_pool->count;
21451 		multixri_pool->stat_pvt_count = pvt_pool->count;
21452 		multixri_pool->stat_busy_count = txcmplq_cnt;
21453 	}
21454 
21455 	multixri_pool->stat_snapshot_taken++;
21456 }
21457 #endif
21458 
21459 /**
21460  * lpfc_adjust_pvt_pool_count - Adjust private pool count
21461  * @phba: pointer to lpfc hba data structure.
21462  * @hwqid: belong to which HWQ.
21463  *
21464  * This routine moves some XRIs from private to public pool when private pool
21465  * is not busy.
21466  **/
21467 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
21468 {
21469 	struct lpfc_multixri_pool *multixri_pool;
21470 	u32 io_req_count;
21471 	u32 prev_io_req_count;
21472 
21473 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21474 	if (!multixri_pool)
21475 		return;
21476 	io_req_count = multixri_pool->io_req_count;
21477 	prev_io_req_count = multixri_pool->prev_io_req_count;
21478 
21479 	if (prev_io_req_count != io_req_count) {
21480 		/* Private pool is busy */
21481 		multixri_pool->prev_io_req_count = io_req_count;
21482 	} else {
21483 		/* Private pool is not busy.
21484 		 * Move XRIs from private to public pool.
21485 		 */
21486 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
21487 	}
21488 }
21489 
21490 /**
21491  * lpfc_adjust_high_watermark - Adjust high watermark
21492  * @phba: pointer to lpfc hba data structure.
21493  * @hwqid: belong to which HWQ.
21494  *
21495  * This routine sets high watermark as number of outstanding XRIs,
21496  * but make sure the new value is between xri_limit/2 and xri_limit.
21497  **/
21498 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
21499 {
21500 	u32 new_watermark;
21501 	u32 watermark_max;
21502 	u32 watermark_min;
21503 	u32 xri_limit;
21504 	u32 txcmplq_cnt;
21505 	u32 abts_io_bufs;
21506 	struct lpfc_multixri_pool *multixri_pool;
21507 	struct lpfc_sli4_hdw_queue *qp;
21508 
21509 	qp = &phba->sli4_hba.hdwq[hwqid];
21510 	multixri_pool = qp->p_multixri_pool;
21511 	if (!multixri_pool)
21512 		return;
21513 	xri_limit = multixri_pool->xri_limit;
21514 
21515 	watermark_max = xri_limit;
21516 	watermark_min = xri_limit / 2;
21517 
21518 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21519 	abts_io_bufs = qp->abts_scsi_io_bufs;
21520 	abts_io_bufs += qp->abts_nvme_io_bufs;
21521 
21522 	new_watermark = txcmplq_cnt + abts_io_bufs;
21523 	new_watermark = min(watermark_max, new_watermark);
21524 	new_watermark = max(watermark_min, new_watermark);
21525 	multixri_pool->pvt_pool.high_watermark = new_watermark;
21526 
21527 #ifdef LPFC_MXP_STAT
21528 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
21529 					  new_watermark);
21530 #endif
21531 }
21532 
21533 /**
21534  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
21535  * @phba: pointer to lpfc hba data structure.
21536  * @hwqid: belong to which HWQ.
21537  *
21538  * This routine is called from hearbeat timer when pvt_pool is idle.
21539  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
21540  * The first step moves (all - low_watermark) amount of XRIs.
21541  * The second step moves the rest of XRIs.
21542  **/
21543 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
21544 {
21545 	struct lpfc_pbl_pool *pbl_pool;
21546 	struct lpfc_pvt_pool *pvt_pool;
21547 	struct lpfc_sli4_hdw_queue *qp;
21548 	struct lpfc_io_buf *lpfc_ncmd;
21549 	struct lpfc_io_buf *lpfc_ncmd_next;
21550 	unsigned long iflag;
21551 	struct list_head tmp_list;
21552 	u32 tmp_count;
21553 
21554 	qp = &phba->sli4_hba.hdwq[hwqid];
21555 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
21556 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
21557 	tmp_count = 0;
21558 
21559 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
21560 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
21561 
21562 	if (pvt_pool->count > pvt_pool->low_watermark) {
21563 		/* Step 1: move (all - low_watermark) from pvt_pool
21564 		 * to pbl_pool
21565 		 */
21566 
21567 		/* Move low watermark of bufs from pvt_pool to tmp_list */
21568 		INIT_LIST_HEAD(&tmp_list);
21569 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21570 					 &pvt_pool->list, list) {
21571 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
21572 			tmp_count++;
21573 			if (tmp_count >= pvt_pool->low_watermark)
21574 				break;
21575 		}
21576 
21577 		/* Move all bufs from pvt_pool to pbl_pool */
21578 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21579 
21580 		/* Move all bufs from tmp_list to pvt_pool */
21581 		list_splice(&tmp_list, &pvt_pool->list);
21582 
21583 		pbl_pool->count += (pvt_pool->count - tmp_count);
21584 		pvt_pool->count = tmp_count;
21585 	} else {
21586 		/* Step 2: move the rest from pvt_pool to pbl_pool */
21587 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21588 		pbl_pool->count += pvt_pool->count;
21589 		pvt_pool->count = 0;
21590 	}
21591 
21592 	spin_unlock(&pvt_pool->lock);
21593 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21594 }
21595 
21596 /**
21597  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21598  * @phba: pointer to lpfc hba data structure
21599  * @qp: pointer to HDW queue
21600  * @pbl_pool: specified public free XRI pool
21601  * @pvt_pool: specified private free XRI pool
21602  * @count: number of XRIs to move
21603  *
21604  * This routine tries to move some free common bufs from the specified pbl_pool
21605  * to the specified pvt_pool. It might move less than count XRIs if there's not
21606  * enough in public pool.
21607  *
21608  * Return:
21609  *   true - if XRIs are successfully moved from the specified pbl_pool to the
21610  *          specified pvt_pool
21611  *   false - if the specified pbl_pool is empty or locked by someone else
21612  **/
21613 static bool
21614 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21615 			  struct lpfc_pbl_pool *pbl_pool,
21616 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
21617 {
21618 	struct lpfc_io_buf *lpfc_ncmd;
21619 	struct lpfc_io_buf *lpfc_ncmd_next;
21620 	unsigned long iflag;
21621 	int ret;
21622 
21623 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
21624 	if (ret) {
21625 		if (pbl_pool->count) {
21626 			/* Move a batch of XRIs from public to private pool */
21627 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
21628 			list_for_each_entry_safe(lpfc_ncmd,
21629 						 lpfc_ncmd_next,
21630 						 &pbl_pool->list,
21631 						 list) {
21632 				list_move_tail(&lpfc_ncmd->list,
21633 					       &pvt_pool->list);
21634 				pvt_pool->count++;
21635 				pbl_pool->count--;
21636 				count--;
21637 				if (count == 0)
21638 					break;
21639 			}
21640 
21641 			spin_unlock(&pvt_pool->lock);
21642 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21643 			return true;
21644 		}
21645 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21646 	}
21647 
21648 	return false;
21649 }
21650 
21651 /**
21652  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21653  * @phba: pointer to lpfc hba data structure.
21654  * @hwqid: belong to which HWQ.
21655  * @count: number of XRIs to move
21656  *
21657  * This routine tries to find some free common bufs in one of public pools with
21658  * Round Robin method. The search always starts from local hwqid, then the next
21659  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
21660  * a batch of free common bufs are moved to private pool on hwqid.
21661  * It might move less than count XRIs if there's not enough in public pool.
21662  **/
21663 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
21664 {
21665 	struct lpfc_multixri_pool *multixri_pool;
21666 	struct lpfc_multixri_pool *next_multixri_pool;
21667 	struct lpfc_pvt_pool *pvt_pool;
21668 	struct lpfc_pbl_pool *pbl_pool;
21669 	struct lpfc_sli4_hdw_queue *qp;
21670 	u32 next_hwqid;
21671 	u32 hwq_count;
21672 	int ret;
21673 
21674 	qp = &phba->sli4_hba.hdwq[hwqid];
21675 	multixri_pool = qp->p_multixri_pool;
21676 	pvt_pool = &multixri_pool->pvt_pool;
21677 	pbl_pool = &multixri_pool->pbl_pool;
21678 
21679 	/* Check if local pbl_pool is available */
21680 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
21681 	if (ret) {
21682 #ifdef LPFC_MXP_STAT
21683 		multixri_pool->local_pbl_hit_count++;
21684 #endif
21685 		return;
21686 	}
21687 
21688 	hwq_count = phba->cfg_hdw_queue;
21689 
21690 	/* Get the next hwqid which was found last time */
21691 	next_hwqid = multixri_pool->rrb_next_hwqid;
21692 
21693 	do {
21694 		/* Go to next hwq */
21695 		next_hwqid = (next_hwqid + 1) % hwq_count;
21696 
21697 		next_multixri_pool =
21698 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
21699 		pbl_pool = &next_multixri_pool->pbl_pool;
21700 
21701 		/* Check if the public free xri pool is available */
21702 		ret = _lpfc_move_xri_pbl_to_pvt(
21703 			phba, qp, pbl_pool, pvt_pool, count);
21704 
21705 		/* Exit while-loop if success or all hwqid are checked */
21706 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
21707 
21708 	/* Starting point for the next time */
21709 	multixri_pool->rrb_next_hwqid = next_hwqid;
21710 
21711 	if (!ret) {
21712 		/* stats: all public pools are empty*/
21713 		multixri_pool->pbl_empty_count++;
21714 	}
21715 
21716 #ifdef LPFC_MXP_STAT
21717 	if (ret) {
21718 		if (next_hwqid == hwqid)
21719 			multixri_pool->local_pbl_hit_count++;
21720 		else
21721 			multixri_pool->other_pbl_hit_count++;
21722 	}
21723 #endif
21724 }
21725 
21726 /**
21727  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
21728  * @phba: pointer to lpfc hba data structure.
21729  * @hwqid: belong to which HWQ.
21730  *
21731  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
21732  * low watermark.
21733  **/
21734 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
21735 {
21736 	struct lpfc_multixri_pool *multixri_pool;
21737 	struct lpfc_pvt_pool *pvt_pool;
21738 
21739 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21740 	pvt_pool = &multixri_pool->pvt_pool;
21741 
21742 	if (pvt_pool->count < pvt_pool->low_watermark)
21743 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21744 }
21745 
21746 /**
21747  * lpfc_release_io_buf - Return one IO buf back to free pool
21748  * @phba: pointer to lpfc hba data structure.
21749  * @lpfc_ncmd: IO buf to be returned.
21750  * @qp: belong to which HWQ.
21751  *
21752  * This routine returns one IO buf back to free pool. If this is an urgent IO,
21753  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
21754  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
21755  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
21756  * lpfc_io_buf_list_put.
21757  **/
21758 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
21759 			 struct lpfc_sli4_hdw_queue *qp)
21760 {
21761 	unsigned long iflag;
21762 	struct lpfc_pbl_pool *pbl_pool;
21763 	struct lpfc_pvt_pool *pvt_pool;
21764 	struct lpfc_epd_pool *epd_pool;
21765 	u32 txcmplq_cnt;
21766 	u32 xri_owned;
21767 	u32 xri_limit;
21768 	u32 abts_io_bufs;
21769 
21770 	/* MUST zero fields if buffer is reused by another protocol */
21771 	lpfc_ncmd->nvmeCmd = NULL;
21772 	lpfc_ncmd->cur_iocbq.cmd_cmpl = NULL;
21773 
21774 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
21775 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
21776 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
21777 
21778 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
21779 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
21780 
21781 	if (phba->cfg_xri_rebalancing) {
21782 		if (lpfc_ncmd->expedite) {
21783 			/* Return to expedite pool */
21784 			epd_pool = &phba->epd_pool;
21785 			spin_lock_irqsave(&epd_pool->lock, iflag);
21786 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21787 			epd_pool->count++;
21788 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
21789 			return;
21790 		}
21791 
21792 		/* Avoid invalid access if an IO sneaks in and is being rejected
21793 		 * just _after_ xri pools are destroyed in lpfc_offline.
21794 		 * Nothing much can be done at this point.
21795 		 */
21796 		if (!qp->p_multixri_pool)
21797 			return;
21798 
21799 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21800 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21801 
21802 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21803 		abts_io_bufs = qp->abts_scsi_io_bufs;
21804 		abts_io_bufs += qp->abts_nvme_io_bufs;
21805 
21806 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21807 		xri_limit = qp->p_multixri_pool->xri_limit;
21808 
21809 #ifdef LPFC_MXP_STAT
21810 		if (xri_owned <= xri_limit)
21811 			qp->p_multixri_pool->below_limit_count++;
21812 		else
21813 			qp->p_multixri_pool->above_limit_count++;
21814 #endif
21815 
21816 		/* XRI goes to either public or private free xri pool
21817 		 *     based on watermark and xri_limit
21818 		 */
21819 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
21820 		    (xri_owned < xri_limit &&
21821 		     pvt_pool->count < pvt_pool->high_watermark)) {
21822 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
21823 						  qp, free_pvt_pool);
21824 			list_add_tail(&lpfc_ncmd->list,
21825 				      &pvt_pool->list);
21826 			pvt_pool->count++;
21827 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21828 		} else {
21829 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
21830 						  qp, free_pub_pool);
21831 			list_add_tail(&lpfc_ncmd->list,
21832 				      &pbl_pool->list);
21833 			pbl_pool->count++;
21834 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21835 		}
21836 	} else {
21837 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
21838 					  qp, free_xri);
21839 		list_add_tail(&lpfc_ncmd->list,
21840 			      &qp->lpfc_io_buf_list_put);
21841 		qp->put_io_bufs++;
21842 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
21843 				       iflag);
21844 	}
21845 }
21846 
21847 /**
21848  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
21849  * @phba: pointer to lpfc hba data structure.
21850  * @qp: pointer to HDW queue
21851  * @pvt_pool: pointer to private pool data structure.
21852  * @ndlp: pointer to lpfc nodelist data structure.
21853  *
21854  * This routine tries to get one free IO buf from private pool.
21855  *
21856  * Return:
21857  *   pointer to one free IO buf - if private pool is not empty
21858  *   NULL - if private pool is empty
21859  **/
21860 static struct lpfc_io_buf *
21861 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
21862 				  struct lpfc_sli4_hdw_queue *qp,
21863 				  struct lpfc_pvt_pool *pvt_pool,
21864 				  struct lpfc_nodelist *ndlp)
21865 {
21866 	struct lpfc_io_buf *lpfc_ncmd;
21867 	struct lpfc_io_buf *lpfc_ncmd_next;
21868 	unsigned long iflag;
21869 
21870 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
21871 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21872 				 &pvt_pool->list, list) {
21873 		if (lpfc_test_rrq_active(
21874 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
21875 			continue;
21876 		list_del(&lpfc_ncmd->list);
21877 		pvt_pool->count--;
21878 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21879 		return lpfc_ncmd;
21880 	}
21881 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21882 
21883 	return NULL;
21884 }
21885 
21886 /**
21887  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
21888  * @phba: pointer to lpfc hba data structure.
21889  *
21890  * This routine tries to get one free IO buf from expedite pool.
21891  *
21892  * Return:
21893  *   pointer to one free IO buf - if expedite pool is not empty
21894  *   NULL - if expedite pool is empty
21895  **/
21896 static struct lpfc_io_buf *
21897 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
21898 {
21899 	struct lpfc_io_buf *lpfc_ncmd;
21900 	struct lpfc_io_buf *lpfc_ncmd_next;
21901 	unsigned long iflag;
21902 	struct lpfc_epd_pool *epd_pool;
21903 
21904 	epd_pool = &phba->epd_pool;
21905 	lpfc_ncmd = NULL;
21906 
21907 	spin_lock_irqsave(&epd_pool->lock, iflag);
21908 	if (epd_pool->count > 0) {
21909 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21910 					 &epd_pool->list, list) {
21911 			list_del(&lpfc_ncmd->list);
21912 			epd_pool->count--;
21913 			break;
21914 		}
21915 	}
21916 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
21917 
21918 	return lpfc_ncmd;
21919 }
21920 
21921 /**
21922  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
21923  * @phba: pointer to lpfc hba data structure.
21924  * @ndlp: pointer to lpfc nodelist data structure.
21925  * @hwqid: belong to which HWQ
21926  * @expedite: 1 means this request is urgent.
21927  *
21928  * This routine will do the following actions and then return a pointer to
21929  * one free IO buf.
21930  *
21931  * 1. If private free xri count is empty, move some XRIs from public to
21932  *    private pool.
21933  * 2. Get one XRI from private free xri pool.
21934  * 3. If we fail to get one from pvt_pool and this is an expedite request,
21935  *    get one free xri from expedite pool.
21936  *
21937  * Note: ndlp is only used on SCSI side for RRQ testing.
21938  *       The caller should pass NULL for ndlp on NVME side.
21939  *
21940  * Return:
21941  *   pointer to one free IO buf - if private pool is not empty
21942  *   NULL - if private pool is empty
21943  **/
21944 static struct lpfc_io_buf *
21945 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
21946 				    struct lpfc_nodelist *ndlp,
21947 				    int hwqid, int expedite)
21948 {
21949 	struct lpfc_sli4_hdw_queue *qp;
21950 	struct lpfc_multixri_pool *multixri_pool;
21951 	struct lpfc_pvt_pool *pvt_pool;
21952 	struct lpfc_io_buf *lpfc_ncmd;
21953 
21954 	qp = &phba->sli4_hba.hdwq[hwqid];
21955 	lpfc_ncmd = NULL;
21956 	if (!qp) {
21957 		lpfc_printf_log(phba, KERN_INFO,
21958 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21959 				"5556 NULL qp for hwqid  x%x\n", hwqid);
21960 		return lpfc_ncmd;
21961 	}
21962 	multixri_pool = qp->p_multixri_pool;
21963 	if (!multixri_pool) {
21964 		lpfc_printf_log(phba, KERN_INFO,
21965 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21966 				"5557 NULL multixri for hwqid  x%x\n", hwqid);
21967 		return lpfc_ncmd;
21968 	}
21969 	pvt_pool = &multixri_pool->pvt_pool;
21970 	if (!pvt_pool) {
21971 		lpfc_printf_log(phba, KERN_INFO,
21972 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21973 				"5558 NULL pvt_pool for hwqid  x%x\n", hwqid);
21974 		return lpfc_ncmd;
21975 	}
21976 	multixri_pool->io_req_count++;
21977 
21978 	/* If pvt_pool is empty, move some XRIs from public to private pool */
21979 	if (pvt_pool->count == 0)
21980 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21981 
21982 	/* Get one XRI from private free xri pool */
21983 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
21984 
21985 	if (lpfc_ncmd) {
21986 		lpfc_ncmd->hdwq = qp;
21987 		lpfc_ncmd->hdwq_no = hwqid;
21988 	} else if (expedite) {
21989 		/* If we fail to get one from pvt_pool and this is an expedite
21990 		 * request, get one free xri from expedite pool.
21991 		 */
21992 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
21993 	}
21994 
21995 	return lpfc_ncmd;
21996 }
21997 
21998 static inline struct lpfc_io_buf *
21999 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
22000 {
22001 	struct lpfc_sli4_hdw_queue *qp;
22002 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
22003 
22004 	qp = &phba->sli4_hba.hdwq[idx];
22005 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
22006 				 &qp->lpfc_io_buf_list_get, list) {
22007 		if (lpfc_test_rrq_active(phba, ndlp,
22008 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
22009 			continue;
22010 
22011 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
22012 			continue;
22013 
22014 		list_del_init(&lpfc_cmd->list);
22015 		qp->get_io_bufs--;
22016 		lpfc_cmd->hdwq = qp;
22017 		lpfc_cmd->hdwq_no = idx;
22018 		return lpfc_cmd;
22019 	}
22020 	return NULL;
22021 }
22022 
22023 /**
22024  * lpfc_get_io_buf - Get one IO buffer from free pool
22025  * @phba: The HBA for which this call is being executed.
22026  * @ndlp: pointer to lpfc nodelist data structure.
22027  * @hwqid: belong to which HWQ
22028  * @expedite: 1 means this request is urgent.
22029  *
22030  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
22031  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
22032  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
22033  *
22034  * Note: ndlp is only used on SCSI side for RRQ testing.
22035  *       The caller should pass NULL for ndlp on NVME side.
22036  *
22037  * Return codes:
22038  *   NULL - Error
22039  *   Pointer to lpfc_io_buf - Success
22040  **/
22041 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
22042 				    struct lpfc_nodelist *ndlp,
22043 				    u32 hwqid, int expedite)
22044 {
22045 	struct lpfc_sli4_hdw_queue *qp;
22046 	unsigned long iflag;
22047 	struct lpfc_io_buf *lpfc_cmd;
22048 
22049 	qp = &phba->sli4_hba.hdwq[hwqid];
22050 	lpfc_cmd = NULL;
22051 	if (!qp) {
22052 		lpfc_printf_log(phba, KERN_WARNING,
22053 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22054 				"5555 NULL qp for hwqid  x%x\n", hwqid);
22055 		return lpfc_cmd;
22056 	}
22057 
22058 	if (phba->cfg_xri_rebalancing)
22059 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
22060 			phba, ndlp, hwqid, expedite);
22061 	else {
22062 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
22063 					  qp, alloc_xri_get);
22064 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
22065 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22066 		if (!lpfc_cmd) {
22067 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
22068 					  qp, alloc_xri_put);
22069 			list_splice(&qp->lpfc_io_buf_list_put,
22070 				    &qp->lpfc_io_buf_list_get);
22071 			qp->get_io_bufs += qp->put_io_bufs;
22072 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
22073 			qp->put_io_bufs = 0;
22074 			spin_unlock(&qp->io_buf_list_put_lock);
22075 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
22076 			    expedite)
22077 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22078 		}
22079 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
22080 	}
22081 
22082 	return lpfc_cmd;
22083 }
22084 
22085 /**
22086  * lpfc_read_object - Retrieve object data from HBA
22087  * @phba: The HBA for which this call is being executed.
22088  * @rdobject: Pathname of object data we want to read.
22089  * @datap: Pointer to where data will be copied to.
22090  * @datasz: size of data area
22091  *
22092  * This routine is limited to object sizes of LPFC_BPL_SIZE (1024) or less.
22093  * The data will be truncated if datasz is not large enough.
22094  * Version 1 is not supported with Embedded mbox cmd, so we must use version 0.
22095  * Returns the actual bytes read from the object.
22096  */
22097 int
22098 lpfc_read_object(struct lpfc_hba *phba, char *rdobject, uint32_t *datap,
22099 		 uint32_t datasz)
22100 {
22101 	struct lpfc_mbx_read_object *read_object;
22102 	LPFC_MBOXQ_t *mbox;
22103 	int rc, length, eof, j, byte_cnt = 0;
22104 	uint32_t shdr_status, shdr_add_status;
22105 	union lpfc_sli4_cfg_shdr *shdr;
22106 	struct lpfc_dmabuf *pcmd;
22107 	u32 rd_object_name[LPFC_MBX_OBJECT_NAME_LEN_DW] = {0};
22108 
22109 	/* sanity check on queue memory */
22110 	if (!datap)
22111 		return -ENODEV;
22112 
22113 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
22114 	if (!mbox)
22115 		return -ENOMEM;
22116 	length = (sizeof(struct lpfc_mbx_read_object) -
22117 		  sizeof(struct lpfc_sli4_cfg_mhdr));
22118 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
22119 			 LPFC_MBOX_OPCODE_READ_OBJECT,
22120 			 length, LPFC_SLI4_MBX_EMBED);
22121 	read_object = &mbox->u.mqe.un.read_object;
22122 	shdr = (union lpfc_sli4_cfg_shdr *)&read_object->header.cfg_shdr;
22123 
22124 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_0);
22125 	bf_set(lpfc_mbx_rd_object_rlen, &read_object->u.request, datasz);
22126 	read_object->u.request.rd_object_offset = 0;
22127 	read_object->u.request.rd_object_cnt = 1;
22128 
22129 	memset((void *)read_object->u.request.rd_object_name, 0,
22130 	       LPFC_OBJ_NAME_SZ);
22131 	scnprintf((char *)rd_object_name, sizeof(rd_object_name), rdobject);
22132 	for (j = 0; j < strlen(rdobject); j++)
22133 		read_object->u.request.rd_object_name[j] =
22134 			cpu_to_le32(rd_object_name[j]);
22135 
22136 	pcmd = kmalloc(sizeof(*pcmd), GFP_KERNEL);
22137 	if (pcmd)
22138 		pcmd->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &pcmd->phys);
22139 	if (!pcmd || !pcmd->virt) {
22140 		kfree(pcmd);
22141 		mempool_free(mbox, phba->mbox_mem_pool);
22142 		return -ENOMEM;
22143 	}
22144 	memset((void *)pcmd->virt, 0, LPFC_BPL_SIZE);
22145 	read_object->u.request.rd_object_hbuf[0].pa_lo =
22146 		putPaddrLow(pcmd->phys);
22147 	read_object->u.request.rd_object_hbuf[0].pa_hi =
22148 		putPaddrHigh(pcmd->phys);
22149 	read_object->u.request.rd_object_hbuf[0].length = LPFC_BPL_SIZE;
22150 
22151 	mbox->vport = phba->pport;
22152 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
22153 	mbox->ctx_ndlp = NULL;
22154 
22155 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
22156 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
22157 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
22158 
22159 	if (shdr_status == STATUS_FAILED &&
22160 	    shdr_add_status == ADD_STATUS_INVALID_OBJECT_NAME) {
22161 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22162 				"4674 No port cfg file in FW.\n");
22163 		byte_cnt = -ENOENT;
22164 	} else if (shdr_status || shdr_add_status || rc) {
22165 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22166 				"2625 READ_OBJECT mailbox failed with "
22167 				"status x%x add_status x%x, mbx status x%x\n",
22168 				shdr_status, shdr_add_status, rc);
22169 		byte_cnt = -ENXIO;
22170 	} else {
22171 		/* Success */
22172 		length = read_object->u.response.rd_object_actual_rlen;
22173 		eof = bf_get(lpfc_mbx_rd_object_eof, &read_object->u.response);
22174 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_CGN_MGMT,
22175 				"2626 READ_OBJECT Success len %d:%d, EOF %d\n",
22176 				length, datasz, eof);
22177 
22178 		/* Detect the port config file exists but is empty */
22179 		if (!length && eof) {
22180 			byte_cnt = 0;
22181 			goto exit;
22182 		}
22183 
22184 		byte_cnt = length;
22185 		lpfc_sli_pcimem_bcopy(pcmd->virt, datap, byte_cnt);
22186 	}
22187 
22188  exit:
22189 	/* This is an embedded SLI4 mailbox with an external buffer allocated.
22190 	 * Free the pcmd and then cleanup with the correct routine.
22191 	 */
22192 	lpfc_mbuf_free(phba, pcmd->virt, pcmd->phys);
22193 	kfree(pcmd);
22194 	lpfc_sli4_mbox_cmd_free(phba, mbox);
22195 	return byte_cnt;
22196 }
22197 
22198 /**
22199  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
22200  * @phba: The HBA for which this call is being executed.
22201  * @lpfc_buf: IO buf structure to append the SGL chunk
22202  *
22203  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
22204  * and will allocate an SGL chunk if the pool is empty.
22205  *
22206  * Return codes:
22207  *   NULL - Error
22208  *   Pointer to sli4_hybrid_sgl - Success
22209  **/
22210 struct sli4_hybrid_sgl *
22211 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22212 {
22213 	struct sli4_hybrid_sgl *list_entry = NULL;
22214 	struct sli4_hybrid_sgl *tmp = NULL;
22215 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
22216 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22217 	struct list_head *buf_list = &hdwq->sgl_list;
22218 	unsigned long iflags;
22219 
22220 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22221 
22222 	if (likely(!list_empty(buf_list))) {
22223 		/* break off 1 chunk from the sgl_list */
22224 		list_for_each_entry_safe(list_entry, tmp,
22225 					 buf_list, list_node) {
22226 			list_move_tail(&list_entry->list_node,
22227 				       &lpfc_buf->dma_sgl_xtra_list);
22228 			break;
22229 		}
22230 	} else {
22231 		/* allocate more */
22232 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22233 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22234 				   cpu_to_node(hdwq->io_wq->chann));
22235 		if (!tmp) {
22236 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22237 					"8353 error kmalloc memory for HDWQ "
22238 					"%d %s\n",
22239 					lpfc_buf->hdwq_no, __func__);
22240 			return NULL;
22241 		}
22242 
22243 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
22244 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
22245 		if (!tmp->dma_sgl) {
22246 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22247 					"8354 error pool_alloc memory for HDWQ "
22248 					"%d %s\n",
22249 					lpfc_buf->hdwq_no, __func__);
22250 			kfree(tmp);
22251 			return NULL;
22252 		}
22253 
22254 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22255 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
22256 	}
22257 
22258 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
22259 					struct sli4_hybrid_sgl,
22260 					list_node);
22261 
22262 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22263 
22264 	return allocated_sgl;
22265 }
22266 
22267 /**
22268  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
22269  * @phba: The HBA for which this call is being executed.
22270  * @lpfc_buf: IO buf structure with the SGL chunk
22271  *
22272  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
22273  *
22274  * Return codes:
22275  *   0 - Success
22276  *   -EINVAL - Error
22277  **/
22278 int
22279 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22280 {
22281 	int rc = 0;
22282 	struct sli4_hybrid_sgl *list_entry = NULL;
22283 	struct sli4_hybrid_sgl *tmp = NULL;
22284 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22285 	struct list_head *buf_list = &hdwq->sgl_list;
22286 	unsigned long iflags;
22287 
22288 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22289 
22290 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
22291 		list_for_each_entry_safe(list_entry, tmp,
22292 					 &lpfc_buf->dma_sgl_xtra_list,
22293 					 list_node) {
22294 			list_move_tail(&list_entry->list_node,
22295 				       buf_list);
22296 		}
22297 	} else {
22298 		rc = -EINVAL;
22299 	}
22300 
22301 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22302 	return rc;
22303 }
22304 
22305 /**
22306  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
22307  * @phba: phba object
22308  * @hdwq: hdwq to cleanup sgl buff resources on
22309  *
22310  * This routine frees all SGL chunks of hdwq SGL chunk pool.
22311  *
22312  * Return codes:
22313  *   None
22314  **/
22315 void
22316 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
22317 		       struct lpfc_sli4_hdw_queue *hdwq)
22318 {
22319 	struct list_head *buf_list = &hdwq->sgl_list;
22320 	struct sli4_hybrid_sgl *list_entry = NULL;
22321 	struct sli4_hybrid_sgl *tmp = NULL;
22322 	unsigned long iflags;
22323 
22324 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22325 
22326 	/* Free sgl pool */
22327 	list_for_each_entry_safe(list_entry, tmp,
22328 				 buf_list, list_node) {
22329 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
22330 			      list_entry->dma_sgl,
22331 			      list_entry->dma_phys_sgl);
22332 		list_del(&list_entry->list_node);
22333 		kfree(list_entry);
22334 	}
22335 
22336 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22337 }
22338 
22339 /**
22340  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
22341  * @phba: The HBA for which this call is being executed.
22342  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
22343  *
22344  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
22345  * and will allocate an CMD/RSP buffer if the pool is empty.
22346  *
22347  * Return codes:
22348  *   NULL - Error
22349  *   Pointer to fcp_cmd_rsp_buf - Success
22350  **/
22351 struct fcp_cmd_rsp_buf *
22352 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22353 			      struct lpfc_io_buf *lpfc_buf)
22354 {
22355 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22356 	struct fcp_cmd_rsp_buf *tmp = NULL;
22357 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
22358 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22359 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22360 	unsigned long iflags;
22361 
22362 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22363 
22364 	if (likely(!list_empty(buf_list))) {
22365 		/* break off 1 chunk from the list */
22366 		list_for_each_entry_safe(list_entry, tmp,
22367 					 buf_list,
22368 					 list_node) {
22369 			list_move_tail(&list_entry->list_node,
22370 				       &lpfc_buf->dma_cmd_rsp_list);
22371 			break;
22372 		}
22373 	} else {
22374 		/* allocate more */
22375 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22376 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22377 				   cpu_to_node(hdwq->io_wq->chann));
22378 		if (!tmp) {
22379 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22380 					"8355 error kmalloc memory for HDWQ "
22381 					"%d %s\n",
22382 					lpfc_buf->hdwq_no, __func__);
22383 			return NULL;
22384 		}
22385 
22386 		tmp->fcp_cmnd = dma_pool_zalloc(phba->lpfc_cmd_rsp_buf_pool,
22387 						GFP_ATOMIC,
22388 						&tmp->fcp_cmd_rsp_dma_handle);
22389 
22390 		if (!tmp->fcp_cmnd) {
22391 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22392 					"8356 error pool_alloc memory for HDWQ "
22393 					"%d %s\n",
22394 					lpfc_buf->hdwq_no, __func__);
22395 			kfree(tmp);
22396 			return NULL;
22397 		}
22398 
22399 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
22400 				sizeof(struct fcp_cmnd));
22401 
22402 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22403 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
22404 	}
22405 
22406 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
22407 					struct fcp_cmd_rsp_buf,
22408 					list_node);
22409 
22410 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22411 
22412 	return allocated_buf;
22413 }
22414 
22415 /**
22416  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
22417  * @phba: The HBA for which this call is being executed.
22418  * @lpfc_buf: IO buf structure with the CMD/RSP buf
22419  *
22420  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
22421  *
22422  * Return codes:
22423  *   0 - Success
22424  *   -EINVAL - Error
22425  **/
22426 int
22427 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22428 			      struct lpfc_io_buf *lpfc_buf)
22429 {
22430 	int rc = 0;
22431 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22432 	struct fcp_cmd_rsp_buf *tmp = NULL;
22433 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22434 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22435 	unsigned long iflags;
22436 
22437 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22438 
22439 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
22440 		list_for_each_entry_safe(list_entry, tmp,
22441 					 &lpfc_buf->dma_cmd_rsp_list,
22442 					 list_node) {
22443 			list_move_tail(&list_entry->list_node,
22444 				       buf_list);
22445 		}
22446 	} else {
22447 		rc = -EINVAL;
22448 	}
22449 
22450 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22451 	return rc;
22452 }
22453 
22454 /**
22455  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
22456  * @phba: phba object
22457  * @hdwq: hdwq to cleanup cmd rsp buff resources on
22458  *
22459  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
22460  *
22461  * Return codes:
22462  *   None
22463  **/
22464 void
22465 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22466 			       struct lpfc_sli4_hdw_queue *hdwq)
22467 {
22468 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22469 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22470 	struct fcp_cmd_rsp_buf *tmp = NULL;
22471 	unsigned long iflags;
22472 
22473 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22474 
22475 	/* Free cmd_rsp buf pool */
22476 	list_for_each_entry_safe(list_entry, tmp,
22477 				 buf_list,
22478 				 list_node) {
22479 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
22480 			      list_entry->fcp_cmnd,
22481 			      list_entry->fcp_cmd_rsp_dma_handle);
22482 		list_del(&list_entry->list_node);
22483 		kfree(list_entry);
22484 	}
22485 
22486 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22487 }
22488 
22489 /**
22490  * lpfc_sli_prep_wqe - Prepare WQE for the command to be posted
22491  * @phba: phba object
22492  * @job: job entry of the command to be posted.
22493  *
22494  * Fill the common fields of the wqe for each of the command.
22495  *
22496  * Return codes:
22497  *	None
22498  **/
22499 void
22500 lpfc_sli_prep_wqe(struct lpfc_hba *phba, struct lpfc_iocbq *job)
22501 {
22502 	u8 cmnd;
22503 	u32 *pcmd;
22504 	u32 if_type = 0;
22505 	u32 fip, abort_tag;
22506 	struct lpfc_nodelist *ndlp = NULL;
22507 	union lpfc_wqe128 *wqe = &job->wqe;
22508 	u8 command_type = ELS_COMMAND_NON_FIP;
22509 
22510 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
22511 	/* The fcp commands will set command type */
22512 	if (job->cmd_flag &  LPFC_IO_FCP)
22513 		command_type = FCP_COMMAND;
22514 	else if (fip && (job->cmd_flag & LPFC_FIP_ELS_ID_MASK))
22515 		command_type = ELS_COMMAND_FIP;
22516 	else
22517 		command_type = ELS_COMMAND_NON_FIP;
22518 
22519 	abort_tag = job->iotag;
22520 	cmnd = bf_get(wqe_cmnd, &wqe->els_req.wqe_com);
22521 
22522 	switch (cmnd) {
22523 	case CMD_ELS_REQUEST64_WQE:
22524 		ndlp = job->ndlp;
22525 
22526 		if_type = bf_get(lpfc_sli_intf_if_type,
22527 				 &phba->sli4_hba.sli_intf);
22528 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22529 			pcmd = (u32 *)job->cmd_dmabuf->virt;
22530 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
22531 				     *pcmd == ELS_CMD_SCR ||
22532 				     *pcmd == ELS_CMD_RDF ||
22533 				     *pcmd == ELS_CMD_EDC ||
22534 				     *pcmd == ELS_CMD_RSCN_XMT ||
22535 				     *pcmd == ELS_CMD_FDISC ||
22536 				     *pcmd == ELS_CMD_LOGO ||
22537 				     *pcmd == ELS_CMD_QFPA ||
22538 				     *pcmd == ELS_CMD_UVEM ||
22539 				     *pcmd == ELS_CMD_PLOGI)) {
22540 				bf_set(els_req64_sp, &wqe->els_req, 1);
22541 				bf_set(els_req64_sid, &wqe->els_req,
22542 				       job->vport->fc_myDID);
22543 
22544 				if ((*pcmd == ELS_CMD_FLOGI) &&
22545 				    !(phba->fc_topology ==
22546 				      LPFC_TOPOLOGY_LOOP))
22547 					bf_set(els_req64_sid, &wqe->els_req, 0);
22548 
22549 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
22550 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22551 				       phba->vpi_ids[job->vport->vpi]);
22552 			} else if (pcmd) {
22553 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
22554 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22555 				       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22556 			}
22557 		}
22558 
22559 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
22560 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22561 
22562 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
22563 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
22564 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
22565 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22566 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
22567 		break;
22568 	case CMD_XMIT_ELS_RSP64_WQE:
22569 		ndlp = job->ndlp;
22570 
22571 		/* word4 */
22572 		wqe->xmit_els_rsp.word4 = 0;
22573 
22574 		if_type = bf_get(lpfc_sli_intf_if_type,
22575 				 &phba->sli4_hba.sli_intf);
22576 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22577 			if (job->vport->fc_flag & FC_PT2PT) {
22578 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22579 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22580 				       job->vport->fc_myDID);
22581 				if (job->vport->fc_myDID == Fabric_DID) {
22582 					bf_set(wqe_els_did,
22583 					       &wqe->xmit_els_rsp.wqe_dest, 0);
22584 				}
22585 			}
22586 		}
22587 
22588 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
22589 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
22590 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
22591 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
22592 		       LPFC_WQE_LENLOC_WORD3);
22593 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
22594 
22595 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
22596 			bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22597 			bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22598 			       job->vport->fc_myDID);
22599 			bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
22600 		}
22601 
22602 		if (phba->sli_rev == LPFC_SLI_REV4) {
22603 			bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
22604 			       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22605 
22606 			if (bf_get(wqe_ct, &wqe->xmit_els_rsp.wqe_com))
22607 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
22608 				       phba->vpi_ids[job->vport->vpi]);
22609 		}
22610 		command_type = OTHER_COMMAND;
22611 		break;
22612 	case CMD_GEN_REQUEST64_WQE:
22613 		/* Word 10 */
22614 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
22615 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
22616 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
22617 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22618 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
22619 		command_type = OTHER_COMMAND;
22620 		break;
22621 	case CMD_XMIT_SEQUENCE64_WQE:
22622 		if (phba->link_flag & LS_LOOPBACK_MODE)
22623 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
22624 
22625 		wqe->xmit_sequence.rsvd3 = 0;
22626 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
22627 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
22628 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
22629 		       LPFC_WQE_IOD_WRITE);
22630 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
22631 		       LPFC_WQE_LENLOC_WORD12);
22632 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
22633 		command_type = OTHER_COMMAND;
22634 		break;
22635 	case CMD_XMIT_BLS_RSP64_WQE:
22636 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
22637 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
22638 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
22639 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
22640 		       phba->vpi_ids[phba->pport->vpi]);
22641 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
22642 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
22643 		       LPFC_WQE_LENLOC_NONE);
22644 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
22645 		command_type = OTHER_COMMAND;
22646 		break;
22647 	case CMD_FCP_ICMND64_WQE:	/* task mgmt commands */
22648 	case CMD_ABORT_XRI_WQE:		/* abort iotag */
22649 	case CMD_SEND_FRAME:		/* mds loopback */
22650 		/* cases already formatted for sli4 wqe - no chgs necessary */
22651 		return;
22652 	default:
22653 		dump_stack();
22654 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
22655 				"6207 Invalid command 0x%x\n",
22656 				cmnd);
22657 		break;
22658 	}
22659 
22660 	wqe->generic.wqe_com.abort_tag = abort_tag;
22661 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, job->iotag);
22662 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
22663 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
22664 }
22665