xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision cdcc26d714c96e9de75c549f05d770b3ddaf2d21)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2023 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/crash_dump.h>
38 #ifdef CONFIG_X86
39 #include <asm/set_memory.h>
40 #endif
41 
42 #include "lpfc_hw4.h"
43 #include "lpfc_hw.h"
44 #include "lpfc_sli.h"
45 #include "lpfc_sli4.h"
46 #include "lpfc_nl.h"
47 #include "lpfc_disc.h"
48 #include "lpfc.h"
49 #include "lpfc_scsi.h"
50 #include "lpfc_nvme.h"
51 #include "lpfc_crtn.h"
52 #include "lpfc_logmsg.h"
53 #include "lpfc_compat.h"
54 #include "lpfc_debugfs.h"
55 #include "lpfc_vport.h"
56 #include "lpfc_version.h"
57 
58 /* There are only four IOCB completion types. */
59 typedef enum _lpfc_iocb_type {
60 	LPFC_UNKNOWN_IOCB,
61 	LPFC_UNSOL_IOCB,
62 	LPFC_SOL_IOCB,
63 	LPFC_ABORT_IOCB
64 } lpfc_iocb_type;
65 
66 
67 /* Provide function prototypes local to this module. */
68 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
69 				  uint32_t);
70 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
71 			      uint8_t *, uint32_t *);
72 static struct lpfc_iocbq *
73 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
74 				  struct lpfc_iocbq *rspiocbq);
75 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
76 				      struct hbq_dmabuf *);
77 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
78 					  struct hbq_dmabuf *dmabuf);
79 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
80 				   struct lpfc_queue *cq, struct lpfc_cqe *cqe);
81 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
82 				       int);
83 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
84 				     struct lpfc_queue *eq,
85 				     struct lpfc_eqe *eqe,
86 				     enum lpfc_poll_mode poll_mode);
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 		     u8 rearm, enum lpfc_poll_mode poll_mode)
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, poll_mode);
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 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1221 	if (empty)
1222 		lpfc_worker_wake_up(phba);
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 	u8 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 	if (!(phba->hba_flag & HBA_SETUP))
3939 		return;
3940 
3941 	/* Here we will also keep track of interrupts per sec of the hba */
3942 	sli_intr = phba->sli.slistat.sli_intr;
3943 
3944 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3945 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3946 			sli_intr);
3947 	else
3948 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3949 
3950 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3951 	do_div(cnt, phba->eratt_poll_interval);
3952 	phba->sli.slistat.sli_ips = cnt;
3953 
3954 	phba->sli.slistat.sli_prev_intr = sli_intr;
3955 
3956 	/* Check chip HA register for error event */
3957 	eratt = lpfc_sli_check_eratt(phba);
3958 
3959 	if (eratt)
3960 		/* Tell the worker thread there is work to do */
3961 		lpfc_worker_wake_up(phba);
3962 	else
3963 		/* Restart the timer for next eratt poll */
3964 		mod_timer(&phba->eratt_poll,
3965 			  jiffies +
3966 			  msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3967 	return;
3968 }
3969 
3970 
3971 /**
3972  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3973  * @phba: Pointer to HBA context object.
3974  * @pring: Pointer to driver SLI ring object.
3975  * @mask: Host attention register mask for this ring.
3976  *
3977  * This function is called from the interrupt context when there is a ring
3978  * event for the fcp ring. The caller does not hold any lock.
3979  * The function processes each response iocb in the response ring until it
3980  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3981  * LE bit set. The function will call the completion handler of the command iocb
3982  * if the response iocb indicates a completion for a command iocb or it is
3983  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3984  * function if this is an unsolicited iocb.
3985  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3986  * to check it explicitly.
3987  */
3988 int
3989 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3990 				struct lpfc_sli_ring *pring, uint32_t mask)
3991 {
3992 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3993 	IOCB_t *irsp = NULL;
3994 	IOCB_t *entry = NULL;
3995 	struct lpfc_iocbq *cmdiocbq = NULL;
3996 	struct lpfc_iocbq rspiocbq;
3997 	uint32_t status;
3998 	uint32_t portRspPut, portRspMax;
3999 	int rc = 1;
4000 	lpfc_iocb_type type;
4001 	unsigned long iflag;
4002 	uint32_t rsp_cmpl = 0;
4003 
4004 	spin_lock_irqsave(&phba->hbalock, iflag);
4005 	pring->stats.iocb_event++;
4006 
4007 	/*
4008 	 * The next available response entry should never exceed the maximum
4009 	 * entries.  If it does, treat it as an adapter hardware error.
4010 	 */
4011 	portRspMax = pring->sli.sli3.numRiocb;
4012 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4013 	if (unlikely(portRspPut >= portRspMax)) {
4014 		lpfc_sli_rsp_pointers_error(phba, pring);
4015 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4016 		return 1;
4017 	}
4018 	if (phba->fcp_ring_in_use) {
4019 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4020 		return 1;
4021 	} else
4022 		phba->fcp_ring_in_use = 1;
4023 
4024 	rmb();
4025 	while (pring->sli.sli3.rspidx != portRspPut) {
4026 		/*
4027 		 * Fetch an entry off the ring and copy it into a local data
4028 		 * structure.  The copy involves a byte-swap since the
4029 		 * network byte order and pci byte orders are different.
4030 		 */
4031 		entry = lpfc_resp_iocb(phba, pring);
4032 		phba->last_completion_time = jiffies;
4033 
4034 		if (++pring->sli.sli3.rspidx >= portRspMax)
4035 			pring->sli.sli3.rspidx = 0;
4036 
4037 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
4038 				      (uint32_t *) &rspiocbq.iocb,
4039 				      phba->iocb_rsp_size);
4040 		INIT_LIST_HEAD(&(rspiocbq.list));
4041 		irsp = &rspiocbq.iocb;
4042 
4043 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
4044 		pring->stats.iocb_rsp++;
4045 		rsp_cmpl++;
4046 
4047 		if (unlikely(irsp->ulpStatus)) {
4048 			/*
4049 			 * If resource errors reported from HBA, reduce
4050 			 * queuedepths of the SCSI device.
4051 			 */
4052 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
4053 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
4054 			     IOERR_NO_RESOURCES)) {
4055 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4056 				phba->lpfc_rampdown_queue_depth(phba);
4057 				spin_lock_irqsave(&phba->hbalock, iflag);
4058 			}
4059 
4060 			/* Rsp ring <ringno> error: IOCB */
4061 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4062 					"0336 Rsp Ring %d error: IOCB Data: "
4063 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
4064 					pring->ringno,
4065 					irsp->un.ulpWord[0],
4066 					irsp->un.ulpWord[1],
4067 					irsp->un.ulpWord[2],
4068 					irsp->un.ulpWord[3],
4069 					irsp->un.ulpWord[4],
4070 					irsp->un.ulpWord[5],
4071 					*(uint32_t *)&irsp->un1,
4072 					*((uint32_t *)&irsp->un1 + 1));
4073 		}
4074 
4075 		switch (type) {
4076 		case LPFC_ABORT_IOCB:
4077 		case LPFC_SOL_IOCB:
4078 			/*
4079 			 * Idle exchange closed via ABTS from port.  No iocb
4080 			 * resources need to be recovered.
4081 			 */
4082 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
4083 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4084 						"0333 IOCB cmd 0x%x"
4085 						" processed. Skipping"
4086 						" completion\n",
4087 						irsp->ulpCommand);
4088 				break;
4089 			}
4090 
4091 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
4092 							 &rspiocbq);
4093 			if (unlikely(!cmdiocbq))
4094 				break;
4095 			if (cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED)
4096 				cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
4097 			if (cmdiocbq->cmd_cmpl) {
4098 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4099 				cmdiocbq->cmd_cmpl(phba, cmdiocbq, &rspiocbq);
4100 				spin_lock_irqsave(&phba->hbalock, iflag);
4101 			}
4102 			break;
4103 		case LPFC_UNSOL_IOCB:
4104 			spin_unlock_irqrestore(&phba->hbalock, iflag);
4105 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
4106 			spin_lock_irqsave(&phba->hbalock, iflag);
4107 			break;
4108 		default:
4109 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
4110 				char adaptermsg[LPFC_MAX_ADPTMSG];
4111 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4112 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
4113 				       MAX_MSG_DATA);
4114 				dev_warn(&((phba->pcidev)->dev),
4115 					 "lpfc%d: %s\n",
4116 					 phba->brd_no, adaptermsg);
4117 			} else {
4118 				/* Unknown IOCB command */
4119 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4120 						"0334 Unknown IOCB command "
4121 						"Data: x%x, x%x x%x x%x x%x\n",
4122 						type, irsp->ulpCommand,
4123 						irsp->ulpStatus,
4124 						irsp->ulpIoTag,
4125 						irsp->ulpContext);
4126 			}
4127 			break;
4128 		}
4129 
4130 		/*
4131 		 * The response IOCB has been processed.  Update the ring
4132 		 * pointer in SLIM.  If the port response put pointer has not
4133 		 * been updated, sync the pgp->rspPutInx and fetch the new port
4134 		 * response put pointer.
4135 		 */
4136 		writel(pring->sli.sli3.rspidx,
4137 			&phba->host_gp[pring->ringno].rspGetInx);
4138 
4139 		if (pring->sli.sli3.rspidx == portRspPut)
4140 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4141 	}
4142 
4143 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
4144 		pring->stats.iocb_rsp_full++;
4145 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4146 		writel(status, phba->CAregaddr);
4147 		readl(phba->CAregaddr);
4148 	}
4149 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4150 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4151 		pring->stats.iocb_cmd_empty++;
4152 
4153 		/* Force update of the local copy of cmdGetInx */
4154 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4155 		lpfc_sli_resume_iocb(phba, pring);
4156 
4157 		if ((pring->lpfc_sli_cmd_available))
4158 			(pring->lpfc_sli_cmd_available) (phba, pring);
4159 
4160 	}
4161 
4162 	phba->fcp_ring_in_use = 0;
4163 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4164 	return rc;
4165 }
4166 
4167 /**
4168  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
4169  * @phba: Pointer to HBA context object.
4170  * @pring: Pointer to driver SLI ring object.
4171  * @rspiocbp: Pointer to driver response IOCB object.
4172  *
4173  * This function is called from the worker thread when there is a slow-path
4174  * response IOCB to process. This function chains all the response iocbs until
4175  * seeing the iocb with the LE bit set. The function will call
4176  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
4177  * completion of a command iocb. The function will call the
4178  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
4179  * The function frees the resources or calls the completion handler if this
4180  * iocb is an abort completion. The function returns NULL when the response
4181  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
4182  * this function shall chain the iocb on to the iocb_continueq and return the
4183  * response iocb passed in.
4184  **/
4185 static struct lpfc_iocbq *
4186 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
4187 			struct lpfc_iocbq *rspiocbp)
4188 {
4189 	struct lpfc_iocbq *saveq;
4190 	struct lpfc_iocbq *cmdiocb;
4191 	struct lpfc_iocbq *next_iocb;
4192 	IOCB_t *irsp;
4193 	uint32_t free_saveq;
4194 	u8 cmd_type;
4195 	lpfc_iocb_type type;
4196 	unsigned long iflag;
4197 	u32 ulp_status = get_job_ulpstatus(phba, rspiocbp);
4198 	u32 ulp_word4 = get_job_word4(phba, rspiocbp);
4199 	u32 ulp_command = get_job_cmnd(phba, rspiocbp);
4200 	int rc;
4201 
4202 	spin_lock_irqsave(&phba->hbalock, iflag);
4203 	/* First add the response iocb to the countinueq list */
4204 	list_add_tail(&rspiocbp->list, &pring->iocb_continueq);
4205 	pring->iocb_continueq_cnt++;
4206 
4207 	/*
4208 	 * By default, the driver expects to free all resources
4209 	 * associated with this iocb completion.
4210 	 */
4211 	free_saveq = 1;
4212 	saveq = list_get_first(&pring->iocb_continueq,
4213 			       struct lpfc_iocbq, list);
4214 	list_del_init(&pring->iocb_continueq);
4215 	pring->iocb_continueq_cnt = 0;
4216 
4217 	pring->stats.iocb_rsp++;
4218 
4219 	/*
4220 	 * If resource errors reported from HBA, reduce
4221 	 * queuedepths of the SCSI device.
4222 	 */
4223 	if (ulp_status == IOSTAT_LOCAL_REJECT &&
4224 	    ((ulp_word4 & IOERR_PARAM_MASK) ==
4225 	     IOERR_NO_RESOURCES)) {
4226 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4227 		phba->lpfc_rampdown_queue_depth(phba);
4228 		spin_lock_irqsave(&phba->hbalock, iflag);
4229 	}
4230 
4231 	if (ulp_status) {
4232 		/* Rsp ring <ringno> error: IOCB */
4233 		if (phba->sli_rev < LPFC_SLI_REV4) {
4234 			irsp = &rspiocbp->iocb;
4235 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4236 					"0328 Rsp Ring %d error: ulp_status x%x "
4237 					"IOCB Data: "
4238 					"x%08x x%08x x%08x x%08x "
4239 					"x%08x x%08x x%08x x%08x "
4240 					"x%08x x%08x x%08x x%08x "
4241 					"x%08x x%08x x%08x x%08x\n",
4242 					pring->ringno, ulp_status,
4243 					get_job_ulpword(rspiocbp, 0),
4244 					get_job_ulpword(rspiocbp, 1),
4245 					get_job_ulpword(rspiocbp, 2),
4246 					get_job_ulpword(rspiocbp, 3),
4247 					get_job_ulpword(rspiocbp, 4),
4248 					get_job_ulpword(rspiocbp, 5),
4249 					*(((uint32_t *)irsp) + 6),
4250 					*(((uint32_t *)irsp) + 7),
4251 					*(((uint32_t *)irsp) + 8),
4252 					*(((uint32_t *)irsp) + 9),
4253 					*(((uint32_t *)irsp) + 10),
4254 					*(((uint32_t *)irsp) + 11),
4255 					*(((uint32_t *)irsp) + 12),
4256 					*(((uint32_t *)irsp) + 13),
4257 					*(((uint32_t *)irsp) + 14),
4258 					*(((uint32_t *)irsp) + 15));
4259 		} else {
4260 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4261 					"0321 Rsp Ring %d error: "
4262 					"IOCB Data: "
4263 					"x%x x%x x%x x%x\n",
4264 					pring->ringno,
4265 					rspiocbp->wcqe_cmpl.word0,
4266 					rspiocbp->wcqe_cmpl.total_data_placed,
4267 					rspiocbp->wcqe_cmpl.parameter,
4268 					rspiocbp->wcqe_cmpl.word3);
4269 		}
4270 	}
4271 
4272 
4273 	/*
4274 	 * Fetch the iocb command type and call the correct completion
4275 	 * routine. Solicited and Unsolicited IOCBs on the ELS ring
4276 	 * get freed back to the lpfc_iocb_list by the discovery
4277 	 * kernel thread.
4278 	 */
4279 	cmd_type = ulp_command & CMD_IOCB_MASK;
4280 	type = lpfc_sli_iocb_cmd_type(cmd_type);
4281 	switch (type) {
4282 	case LPFC_SOL_IOCB:
4283 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4284 		rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
4285 		spin_lock_irqsave(&phba->hbalock, iflag);
4286 		break;
4287 	case LPFC_UNSOL_IOCB:
4288 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4289 		rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
4290 		spin_lock_irqsave(&phba->hbalock, iflag);
4291 		if (!rc)
4292 			free_saveq = 0;
4293 		break;
4294 	case LPFC_ABORT_IOCB:
4295 		cmdiocb = NULL;
4296 		if (ulp_command != CMD_XRI_ABORTED_CX)
4297 			cmdiocb = lpfc_sli_iocbq_lookup(phba, pring,
4298 							saveq);
4299 		if (cmdiocb) {
4300 			/* Call the specified completion routine */
4301 			if (cmdiocb->cmd_cmpl) {
4302 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4303 				cmdiocb->cmd_cmpl(phba, cmdiocb, saveq);
4304 				spin_lock_irqsave(&phba->hbalock, iflag);
4305 			} else {
4306 				__lpfc_sli_release_iocbq(phba, cmdiocb);
4307 			}
4308 		}
4309 		break;
4310 	case LPFC_UNKNOWN_IOCB:
4311 		if (ulp_command == CMD_ADAPTER_MSG) {
4312 			char adaptermsg[LPFC_MAX_ADPTMSG];
4313 
4314 			memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4315 			memcpy(&adaptermsg[0], (uint8_t *)&rspiocbp->wqe,
4316 			       MAX_MSG_DATA);
4317 			dev_warn(&((phba->pcidev)->dev),
4318 				 "lpfc%d: %s\n",
4319 				 phba->brd_no, adaptermsg);
4320 		} else {
4321 			/* Unknown command */
4322 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4323 					"0335 Unknown IOCB "
4324 					"command Data: x%x "
4325 					"x%x x%x x%x\n",
4326 					ulp_command,
4327 					ulp_status,
4328 					get_wqe_reqtag(rspiocbp),
4329 					get_job_ulpcontext(phba, rspiocbp));
4330 		}
4331 		break;
4332 	}
4333 
4334 	if (free_saveq) {
4335 		list_for_each_entry_safe(rspiocbp, next_iocb,
4336 					 &saveq->list, list) {
4337 			list_del_init(&rspiocbp->list);
4338 			__lpfc_sli_release_iocbq(phba, rspiocbp);
4339 		}
4340 		__lpfc_sli_release_iocbq(phba, saveq);
4341 	}
4342 	rspiocbp = NULL;
4343 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4344 	return rspiocbp;
4345 }
4346 
4347 /**
4348  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
4349  * @phba: Pointer to HBA context object.
4350  * @pring: Pointer to driver SLI ring object.
4351  * @mask: Host attention register mask for this ring.
4352  *
4353  * This routine wraps the actual slow_ring event process routine from the
4354  * API jump table function pointer from the lpfc_hba struct.
4355  **/
4356 void
4357 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
4358 				struct lpfc_sli_ring *pring, uint32_t mask)
4359 {
4360 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
4361 }
4362 
4363 /**
4364  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
4365  * @phba: Pointer to HBA context object.
4366  * @pring: Pointer to driver SLI ring object.
4367  * @mask: Host attention register mask for this ring.
4368  *
4369  * This function is called from the worker thread when there is a ring event
4370  * for non-fcp rings. The caller does not hold any lock. The function will
4371  * remove each response iocb in the response ring and calls the handle
4372  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4373  **/
4374 static void
4375 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
4376 				   struct lpfc_sli_ring *pring, uint32_t mask)
4377 {
4378 	struct lpfc_pgp *pgp;
4379 	IOCB_t *entry;
4380 	IOCB_t *irsp = NULL;
4381 	struct lpfc_iocbq *rspiocbp = NULL;
4382 	uint32_t portRspPut, portRspMax;
4383 	unsigned long iflag;
4384 	uint32_t status;
4385 
4386 	pgp = &phba->port_gp[pring->ringno];
4387 	spin_lock_irqsave(&phba->hbalock, iflag);
4388 	pring->stats.iocb_event++;
4389 
4390 	/*
4391 	 * The next available response entry should never exceed the maximum
4392 	 * entries.  If it does, treat it as an adapter hardware error.
4393 	 */
4394 	portRspMax = pring->sli.sli3.numRiocb;
4395 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4396 	if (portRspPut >= portRspMax) {
4397 		/*
4398 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
4399 		 * rsp ring <portRspMax>
4400 		 */
4401 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4402 				"0303 Ring %d handler: portRspPut %d "
4403 				"is bigger than rsp ring %d\n",
4404 				pring->ringno, portRspPut, portRspMax);
4405 
4406 		phba->link_state = LPFC_HBA_ERROR;
4407 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4408 
4409 		phba->work_hs = HS_FFER3;
4410 		lpfc_handle_eratt(phba);
4411 
4412 		return;
4413 	}
4414 
4415 	rmb();
4416 	while (pring->sli.sli3.rspidx != portRspPut) {
4417 		/*
4418 		 * Build a completion list and call the appropriate handler.
4419 		 * The process is to get the next available response iocb, get
4420 		 * a free iocb from the list, copy the response data into the
4421 		 * free iocb, insert to the continuation list, and update the
4422 		 * next response index to slim.  This process makes response
4423 		 * iocb's in the ring available to DMA as fast as possible but
4424 		 * pays a penalty for a copy operation.  Since the iocb is
4425 		 * only 32 bytes, this penalty is considered small relative to
4426 		 * the PCI reads for register values and a slim write.  When
4427 		 * the ulpLe field is set, the entire Command has been
4428 		 * received.
4429 		 */
4430 		entry = lpfc_resp_iocb(phba, pring);
4431 
4432 		phba->last_completion_time = jiffies;
4433 		rspiocbp = __lpfc_sli_get_iocbq(phba);
4434 		if (rspiocbp == NULL) {
4435 			printk(KERN_ERR "%s: out of buffers! Failing "
4436 			       "completion.\n", __func__);
4437 			break;
4438 		}
4439 
4440 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
4441 				      phba->iocb_rsp_size);
4442 		irsp = &rspiocbp->iocb;
4443 
4444 		if (++pring->sli.sli3.rspidx >= portRspMax)
4445 			pring->sli.sli3.rspidx = 0;
4446 
4447 		if (pring->ringno == LPFC_ELS_RING) {
4448 			lpfc_debugfs_slow_ring_trc(phba,
4449 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
4450 				*(((uint32_t *) irsp) + 4),
4451 				*(((uint32_t *) irsp) + 6),
4452 				*(((uint32_t *) irsp) + 7));
4453 		}
4454 
4455 		writel(pring->sli.sli3.rspidx,
4456 			&phba->host_gp[pring->ringno].rspGetInx);
4457 
4458 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4459 		/* Handle the response IOCB */
4460 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
4461 		spin_lock_irqsave(&phba->hbalock, iflag);
4462 
4463 		/*
4464 		 * If the port response put pointer has not been updated, sync
4465 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
4466 		 * response put pointer.
4467 		 */
4468 		if (pring->sli.sli3.rspidx == portRspPut) {
4469 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4470 		}
4471 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
4472 
4473 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
4474 		/* At least one response entry has been freed */
4475 		pring->stats.iocb_rsp_full++;
4476 		/* SET RxRE_RSP in Chip Att register */
4477 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4478 		writel(status, phba->CAregaddr);
4479 		readl(phba->CAregaddr); /* flush */
4480 	}
4481 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4482 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4483 		pring->stats.iocb_cmd_empty++;
4484 
4485 		/* Force update of the local copy of cmdGetInx */
4486 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4487 		lpfc_sli_resume_iocb(phba, pring);
4488 
4489 		if ((pring->lpfc_sli_cmd_available))
4490 			(pring->lpfc_sli_cmd_available) (phba, pring);
4491 
4492 	}
4493 
4494 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4495 	return;
4496 }
4497 
4498 /**
4499  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
4500  * @phba: Pointer to HBA context object.
4501  * @pring: Pointer to driver SLI ring object.
4502  * @mask: Host attention register mask for this ring.
4503  *
4504  * This function is called from the worker thread when there is a pending
4505  * ELS response iocb on the driver internal slow-path response iocb worker
4506  * queue. The caller does not hold any lock. The function will remove each
4507  * response iocb from the response worker queue and calls the handle
4508  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4509  **/
4510 static void
4511 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4512 				   struct lpfc_sli_ring *pring, uint32_t mask)
4513 {
4514 	struct lpfc_iocbq *irspiocbq;
4515 	struct hbq_dmabuf *dmabuf;
4516 	struct lpfc_cq_event *cq_event;
4517 	unsigned long iflag;
4518 	int count = 0;
4519 
4520 	spin_lock_irqsave(&phba->hbalock, iflag);
4521 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
4522 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4523 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4524 		/* Get the response iocb from the head of work queue */
4525 		spin_lock_irqsave(&phba->hbalock, iflag);
4526 		list_remove_head(&phba->sli4_hba.sp_queue_event,
4527 				 cq_event, struct lpfc_cq_event, list);
4528 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4529 
4530 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4531 		case CQE_CODE_COMPL_WQE:
4532 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4533 						 cq_event);
4534 			/* Translate ELS WCQE to response IOCBQ */
4535 			irspiocbq = lpfc_sli4_els_preprocess_rspiocbq(phba,
4536 								      irspiocbq);
4537 			if (irspiocbq)
4538 				lpfc_sli_sp_handle_rspiocb(phba, pring,
4539 							   irspiocbq);
4540 			count++;
4541 			break;
4542 		case CQE_CODE_RECEIVE:
4543 		case CQE_CODE_RECEIVE_V1:
4544 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
4545 					      cq_event);
4546 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
4547 			count++;
4548 			break;
4549 		default:
4550 			break;
4551 		}
4552 
4553 		/* Limit the number of events to 64 to avoid soft lockups */
4554 		if (count == 64)
4555 			break;
4556 	}
4557 }
4558 
4559 /**
4560  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4561  * @phba: Pointer to HBA context object.
4562  * @pring: Pointer to driver SLI ring object.
4563  *
4564  * This function aborts all iocbs in the given ring and frees all the iocb
4565  * objects in txq. This function issues an abort iocb for all the iocb commands
4566  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4567  * the return of this function. The caller is not required to hold any locks.
4568  **/
4569 void
4570 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4571 {
4572 	LIST_HEAD(tx_completions);
4573 	LIST_HEAD(txcmplq_completions);
4574 	struct lpfc_iocbq *iocb, *next_iocb;
4575 	int offline;
4576 
4577 	if (pring->ringno == LPFC_ELS_RING) {
4578 		lpfc_fabric_abort_hba(phba);
4579 	}
4580 	offline = pci_channel_offline(phba->pcidev);
4581 
4582 	/* Error everything on txq and txcmplq
4583 	 * First do the txq.
4584 	 */
4585 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4586 		spin_lock_irq(&pring->ring_lock);
4587 		list_splice_init(&pring->txq, &tx_completions);
4588 		pring->txq_cnt = 0;
4589 
4590 		if (offline) {
4591 			list_splice_init(&pring->txcmplq,
4592 					 &txcmplq_completions);
4593 		} else {
4594 			/* Next issue ABTS for everything on the txcmplq */
4595 			list_for_each_entry_safe(iocb, next_iocb,
4596 						 &pring->txcmplq, list)
4597 				lpfc_sli_issue_abort_iotag(phba, pring,
4598 							   iocb, NULL);
4599 		}
4600 		spin_unlock_irq(&pring->ring_lock);
4601 	} else {
4602 		spin_lock_irq(&phba->hbalock);
4603 		list_splice_init(&pring->txq, &tx_completions);
4604 		pring->txq_cnt = 0;
4605 
4606 		if (offline) {
4607 			list_splice_init(&pring->txcmplq, &txcmplq_completions);
4608 		} else {
4609 			/* Next issue ABTS for everything on the txcmplq */
4610 			list_for_each_entry_safe(iocb, next_iocb,
4611 						 &pring->txcmplq, list)
4612 				lpfc_sli_issue_abort_iotag(phba, pring,
4613 							   iocb, NULL);
4614 		}
4615 		spin_unlock_irq(&phba->hbalock);
4616 	}
4617 
4618 	if (offline) {
4619 		/* Cancel all the IOCBs from the completions list */
4620 		lpfc_sli_cancel_iocbs(phba, &txcmplq_completions,
4621 				      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
4622 	} else {
4623 		/* Make sure HBA is alive */
4624 		lpfc_issue_hb_tmo(phba);
4625 	}
4626 	/* Cancel all the IOCBs from the completions list */
4627 	lpfc_sli_cancel_iocbs(phba, &tx_completions, IOSTAT_LOCAL_REJECT,
4628 			      IOERR_SLI_ABORTED);
4629 }
4630 
4631 /**
4632  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4633  * @phba: Pointer to HBA context object.
4634  *
4635  * This function aborts all iocbs in FCP rings and frees all the iocb
4636  * objects in txq. This function issues an abort iocb for all the iocb commands
4637  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4638  * the return of this function. The caller is not required to hold any locks.
4639  **/
4640 void
4641 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4642 {
4643 	struct lpfc_sli *psli = &phba->sli;
4644 	struct lpfc_sli_ring  *pring;
4645 	uint32_t i;
4646 
4647 	/* Look on all the FCP Rings for the iotag */
4648 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4649 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4650 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4651 			lpfc_sli_abort_iocb_ring(phba, pring);
4652 		}
4653 	} else {
4654 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4655 		lpfc_sli_abort_iocb_ring(phba, pring);
4656 	}
4657 }
4658 
4659 /**
4660  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4661  * @phba: Pointer to HBA context object.
4662  *
4663  * This function flushes all iocbs in the IO ring and frees all the iocb
4664  * objects in txq and txcmplq. This function will not issue abort iocbs
4665  * for all the iocb commands in txcmplq, they will just be returned with
4666  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4667  * slot has been permanently disabled.
4668  **/
4669 void
4670 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4671 {
4672 	LIST_HEAD(txq);
4673 	LIST_HEAD(txcmplq);
4674 	struct lpfc_sli *psli = &phba->sli;
4675 	struct lpfc_sli_ring  *pring;
4676 	uint32_t i;
4677 	struct lpfc_iocbq *piocb, *next_iocb;
4678 
4679 	spin_lock_irq(&phba->hbalock);
4680 	/* Indicate the I/O queues are flushed */
4681 	phba->hba_flag |= HBA_IOQ_FLUSH;
4682 	spin_unlock_irq(&phba->hbalock);
4683 
4684 	/* Look on all the FCP Rings for the iotag */
4685 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4686 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4687 			if (!phba->sli4_hba.hdwq ||
4688 			    !phba->sli4_hba.hdwq[i].io_wq) {
4689 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4690 						"7777 hdwq's deleted %lx "
4691 						"%lx %x %x\n",
4692 						(unsigned long)phba->pport->load_flag,
4693 						(unsigned long)phba->hba_flag,
4694 						phba->link_state,
4695 						phba->sli.sli_flag);
4696 				return;
4697 			}
4698 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4699 
4700 			spin_lock_irq(&pring->ring_lock);
4701 			/* Retrieve everything on txq */
4702 			list_splice_init(&pring->txq, &txq);
4703 			list_for_each_entry_safe(piocb, next_iocb,
4704 						 &pring->txcmplq, list)
4705 				piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4706 			/* Retrieve everything on the txcmplq */
4707 			list_splice_init(&pring->txcmplq, &txcmplq);
4708 			pring->txq_cnt = 0;
4709 			pring->txcmplq_cnt = 0;
4710 			spin_unlock_irq(&pring->ring_lock);
4711 
4712 			/* Flush the txq */
4713 			lpfc_sli_cancel_iocbs(phba, &txq,
4714 					      IOSTAT_LOCAL_REJECT,
4715 					      IOERR_SLI_DOWN);
4716 			/* Flush the txcmplq */
4717 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4718 					      IOSTAT_LOCAL_REJECT,
4719 					      IOERR_SLI_DOWN);
4720 			if (unlikely(pci_channel_offline(phba->pcidev)))
4721 				lpfc_sli4_io_xri_aborted(phba, NULL, 0);
4722 		}
4723 	} else {
4724 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4725 
4726 		spin_lock_irq(&phba->hbalock);
4727 		/* Retrieve everything on txq */
4728 		list_splice_init(&pring->txq, &txq);
4729 		list_for_each_entry_safe(piocb, next_iocb,
4730 					 &pring->txcmplq, list)
4731 			piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4732 		/* Retrieve everything on the txcmplq */
4733 		list_splice_init(&pring->txcmplq, &txcmplq);
4734 		pring->txq_cnt = 0;
4735 		pring->txcmplq_cnt = 0;
4736 		spin_unlock_irq(&phba->hbalock);
4737 
4738 		/* Flush the txq */
4739 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4740 				      IOERR_SLI_DOWN);
4741 		/* Flush the txcmpq */
4742 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4743 				      IOERR_SLI_DOWN);
4744 	}
4745 }
4746 
4747 /**
4748  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4749  * @phba: Pointer to HBA context object.
4750  * @mask: Bit mask to be checked.
4751  *
4752  * This function reads the host status register and compares
4753  * with the provided bit mask to check if HBA completed
4754  * the restart. This function will wait in a loop for the
4755  * HBA to complete restart. If the HBA does not restart within
4756  * 15 iterations, the function will reset the HBA again. The
4757  * function returns 1 when HBA fail to restart otherwise returns
4758  * zero.
4759  **/
4760 static int
4761 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4762 {
4763 	uint32_t status;
4764 	int i = 0;
4765 	int retval = 0;
4766 
4767 	/* Read the HBA Host Status Register */
4768 	if (lpfc_readl(phba->HSregaddr, &status))
4769 		return 1;
4770 
4771 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4772 
4773 	/*
4774 	 * Check status register every 100ms for 5 retries, then every
4775 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4776 	 * every 2.5 sec for 4.
4777 	 * Break our of the loop if errors occurred during init.
4778 	 */
4779 	while (((status & mask) != mask) &&
4780 	       !(status & HS_FFERM) &&
4781 	       i++ < 20) {
4782 
4783 		if (i <= 5)
4784 			msleep(10);
4785 		else if (i <= 10)
4786 			msleep(500);
4787 		else
4788 			msleep(2500);
4789 
4790 		if (i == 15) {
4791 				/* Do post */
4792 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4793 			lpfc_sli_brdrestart(phba);
4794 		}
4795 		/* Read the HBA Host Status Register */
4796 		if (lpfc_readl(phba->HSregaddr, &status)) {
4797 			retval = 1;
4798 			break;
4799 		}
4800 	}
4801 
4802 	/* Check to see if any errors occurred during init */
4803 	if ((status & HS_FFERM) || (i >= 20)) {
4804 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4805 				"2751 Adapter failed to restart, "
4806 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4807 				status,
4808 				readl(phba->MBslimaddr + 0xa8),
4809 				readl(phba->MBslimaddr + 0xac));
4810 		phba->link_state = LPFC_HBA_ERROR;
4811 		retval = 1;
4812 	}
4813 
4814 	return retval;
4815 }
4816 
4817 /**
4818  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4819  * @phba: Pointer to HBA context object.
4820  * @mask: Bit mask to be checked.
4821  *
4822  * This function checks the host status register to check if HBA is
4823  * ready. This function will wait in a loop for the HBA to be ready
4824  * If the HBA is not ready , the function will will reset the HBA PCI
4825  * function again. The function returns 1 when HBA fail to be ready
4826  * otherwise returns zero.
4827  **/
4828 static int
4829 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4830 {
4831 	uint32_t status;
4832 	int retval = 0;
4833 
4834 	/* Read the HBA Host Status Register */
4835 	status = lpfc_sli4_post_status_check(phba);
4836 
4837 	if (status) {
4838 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4839 		lpfc_sli_brdrestart(phba);
4840 		status = lpfc_sli4_post_status_check(phba);
4841 	}
4842 
4843 	/* Check to see if any errors occurred during init */
4844 	if (status) {
4845 		phba->link_state = LPFC_HBA_ERROR;
4846 		retval = 1;
4847 	} else
4848 		phba->sli4_hba.intr_enable = 0;
4849 
4850 	phba->hba_flag &= ~HBA_SETUP;
4851 	return retval;
4852 }
4853 
4854 /**
4855  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4856  * @phba: Pointer to HBA context object.
4857  * @mask: Bit mask to be checked.
4858  *
4859  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4860  * from the API jump table function pointer from the lpfc_hba struct.
4861  **/
4862 int
4863 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4864 {
4865 	return phba->lpfc_sli_brdready(phba, mask);
4866 }
4867 
4868 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4869 
4870 /**
4871  * lpfc_reset_barrier - Make HBA ready for HBA reset
4872  * @phba: Pointer to HBA context object.
4873  *
4874  * This function is called before resetting an HBA. This function is called
4875  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4876  **/
4877 void lpfc_reset_barrier(struct lpfc_hba *phba)
4878 {
4879 	uint32_t __iomem *resp_buf;
4880 	uint32_t __iomem *mbox_buf;
4881 	volatile struct MAILBOX_word0 mbox;
4882 	uint32_t hc_copy, ha_copy, resp_data;
4883 	int  i;
4884 	uint8_t hdrtype;
4885 
4886 	lockdep_assert_held(&phba->hbalock);
4887 
4888 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4889 	if (hdrtype != 0x80 ||
4890 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4891 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4892 		return;
4893 
4894 	/*
4895 	 * Tell the other part of the chip to suspend temporarily all
4896 	 * its DMA activity.
4897 	 */
4898 	resp_buf = phba->MBslimaddr;
4899 
4900 	/* Disable the error attention */
4901 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4902 		return;
4903 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4904 	readl(phba->HCregaddr); /* flush */
4905 	phba->link_flag |= LS_IGNORE_ERATT;
4906 
4907 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4908 		return;
4909 	if (ha_copy & HA_ERATT) {
4910 		/* Clear Chip error bit */
4911 		writel(HA_ERATT, phba->HAregaddr);
4912 		phba->pport->stopped = 1;
4913 	}
4914 
4915 	mbox.word0 = 0;
4916 	mbox.mbxCommand = MBX_KILL_BOARD;
4917 	mbox.mbxOwner = OWN_CHIP;
4918 
4919 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4920 	mbox_buf = phba->MBslimaddr;
4921 	writel(mbox.word0, mbox_buf);
4922 
4923 	for (i = 0; i < 50; i++) {
4924 		if (lpfc_readl((resp_buf + 1), &resp_data))
4925 			return;
4926 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4927 			mdelay(1);
4928 		else
4929 			break;
4930 	}
4931 	resp_data = 0;
4932 	if (lpfc_readl((resp_buf + 1), &resp_data))
4933 		return;
4934 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4935 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4936 		    phba->pport->stopped)
4937 			goto restore_hc;
4938 		else
4939 			goto clear_errat;
4940 	}
4941 
4942 	mbox.mbxOwner = OWN_HOST;
4943 	resp_data = 0;
4944 	for (i = 0; i < 500; i++) {
4945 		if (lpfc_readl(resp_buf, &resp_data))
4946 			return;
4947 		if (resp_data != mbox.word0)
4948 			mdelay(1);
4949 		else
4950 			break;
4951 	}
4952 
4953 clear_errat:
4954 
4955 	while (++i < 500) {
4956 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4957 			return;
4958 		if (!(ha_copy & HA_ERATT))
4959 			mdelay(1);
4960 		else
4961 			break;
4962 	}
4963 
4964 	if (readl(phba->HAregaddr) & HA_ERATT) {
4965 		writel(HA_ERATT, phba->HAregaddr);
4966 		phba->pport->stopped = 1;
4967 	}
4968 
4969 restore_hc:
4970 	phba->link_flag &= ~LS_IGNORE_ERATT;
4971 	writel(hc_copy, phba->HCregaddr);
4972 	readl(phba->HCregaddr); /* flush */
4973 }
4974 
4975 /**
4976  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4977  * @phba: Pointer to HBA context object.
4978  *
4979  * This function issues a kill_board mailbox command and waits for
4980  * the error attention interrupt. This function is called for stopping
4981  * the firmware processing. The caller is not required to hold any
4982  * locks. This function calls lpfc_hba_down_post function to free
4983  * any pending commands after the kill. The function will return 1 when it
4984  * fails to kill the board else will return 0.
4985  **/
4986 int
4987 lpfc_sli_brdkill(struct lpfc_hba *phba)
4988 {
4989 	struct lpfc_sli *psli;
4990 	LPFC_MBOXQ_t *pmb;
4991 	uint32_t status;
4992 	uint32_t ha_copy;
4993 	int retval;
4994 	int i = 0;
4995 
4996 	psli = &phba->sli;
4997 
4998 	/* Kill HBA */
4999 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5000 			"0329 Kill HBA Data: x%x x%x\n",
5001 			phba->pport->port_state, psli->sli_flag);
5002 
5003 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5004 	if (!pmb)
5005 		return 1;
5006 
5007 	/* Disable the error attention */
5008 	spin_lock_irq(&phba->hbalock);
5009 	if (lpfc_readl(phba->HCregaddr, &status)) {
5010 		spin_unlock_irq(&phba->hbalock);
5011 		mempool_free(pmb, phba->mbox_mem_pool);
5012 		return 1;
5013 	}
5014 	status &= ~HC_ERINT_ENA;
5015 	writel(status, phba->HCregaddr);
5016 	readl(phba->HCregaddr); /* flush */
5017 	phba->link_flag |= LS_IGNORE_ERATT;
5018 	spin_unlock_irq(&phba->hbalock);
5019 
5020 	lpfc_kill_board(phba, pmb);
5021 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
5022 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5023 
5024 	if (retval != MBX_SUCCESS) {
5025 		if (retval != MBX_BUSY)
5026 			mempool_free(pmb, phba->mbox_mem_pool);
5027 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5028 				"2752 KILL_BOARD command failed retval %d\n",
5029 				retval);
5030 		spin_lock_irq(&phba->hbalock);
5031 		phba->link_flag &= ~LS_IGNORE_ERATT;
5032 		spin_unlock_irq(&phba->hbalock);
5033 		return 1;
5034 	}
5035 
5036 	spin_lock_irq(&phba->hbalock);
5037 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
5038 	spin_unlock_irq(&phba->hbalock);
5039 
5040 	mempool_free(pmb, phba->mbox_mem_pool);
5041 
5042 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
5043 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
5044 	 * 3 seconds we still set HBA_ERROR state because the status of the
5045 	 * board is now undefined.
5046 	 */
5047 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
5048 		return 1;
5049 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
5050 		mdelay(100);
5051 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
5052 			return 1;
5053 	}
5054 
5055 	del_timer_sync(&psli->mbox_tmo);
5056 	if (ha_copy & HA_ERATT) {
5057 		writel(HA_ERATT, phba->HAregaddr);
5058 		phba->pport->stopped = 1;
5059 	}
5060 	spin_lock_irq(&phba->hbalock);
5061 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5062 	psli->mbox_active = NULL;
5063 	phba->link_flag &= ~LS_IGNORE_ERATT;
5064 	spin_unlock_irq(&phba->hbalock);
5065 
5066 	lpfc_hba_down_post(phba);
5067 	phba->link_state = LPFC_HBA_ERROR;
5068 
5069 	return ha_copy & HA_ERATT ? 0 : 1;
5070 }
5071 
5072 /**
5073  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
5074  * @phba: Pointer to HBA context object.
5075  *
5076  * This function resets the HBA by writing HC_INITFF to the control
5077  * register. After the HBA resets, this function resets all the iocb ring
5078  * indices. This function disables PCI layer parity checking during
5079  * the reset.
5080  * This function returns 0 always.
5081  * The caller is not required to hold any locks.
5082  **/
5083 int
5084 lpfc_sli_brdreset(struct lpfc_hba *phba)
5085 {
5086 	struct lpfc_sli *psli;
5087 	struct lpfc_sli_ring *pring;
5088 	uint16_t cfg_value;
5089 	int i;
5090 
5091 	psli = &phba->sli;
5092 
5093 	/* Reset HBA */
5094 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5095 			"0325 Reset HBA Data: x%x x%x\n",
5096 			(phba->pport) ? phba->pport->port_state : 0,
5097 			psli->sli_flag);
5098 
5099 	/* perform board reset */
5100 	phba->fc_eventTag = 0;
5101 	phba->link_events = 0;
5102 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5103 	if (phba->pport) {
5104 		phba->pport->fc_myDID = 0;
5105 		phba->pport->fc_prevDID = 0;
5106 	}
5107 
5108 	/* Turn off parity checking and serr during the physical reset */
5109 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
5110 		return -EIO;
5111 
5112 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
5113 			      (cfg_value &
5114 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5115 
5116 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
5117 
5118 	/* Now toggle INITFF bit in the Host Control Register */
5119 	writel(HC_INITFF, phba->HCregaddr);
5120 	mdelay(1);
5121 	readl(phba->HCregaddr); /* flush */
5122 	writel(0, phba->HCregaddr);
5123 	readl(phba->HCregaddr); /* flush */
5124 
5125 	/* Restore PCI cmd register */
5126 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5127 
5128 	/* Initialize relevant SLI info */
5129 	for (i = 0; i < psli->num_rings; i++) {
5130 		pring = &psli->sli3_ring[i];
5131 		pring->flag = 0;
5132 		pring->sli.sli3.rspidx = 0;
5133 		pring->sli.sli3.next_cmdidx  = 0;
5134 		pring->sli.sli3.local_getidx = 0;
5135 		pring->sli.sli3.cmdidx = 0;
5136 		pring->missbufcnt = 0;
5137 	}
5138 
5139 	phba->link_state = LPFC_WARM_START;
5140 	return 0;
5141 }
5142 
5143 /**
5144  * lpfc_sli4_brdreset - Reset a sli-4 HBA
5145  * @phba: Pointer to HBA context object.
5146  *
5147  * This function resets a SLI4 HBA. This function disables PCI layer parity
5148  * checking during resets the device. The caller is not required to hold
5149  * any locks.
5150  *
5151  * This function returns 0 on success else returns negative error code.
5152  **/
5153 int
5154 lpfc_sli4_brdreset(struct lpfc_hba *phba)
5155 {
5156 	struct lpfc_sli *psli = &phba->sli;
5157 	uint16_t cfg_value;
5158 	int rc = 0;
5159 
5160 	/* Reset HBA */
5161 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5162 			"0295 Reset HBA Data: x%x x%x x%x\n",
5163 			phba->pport->port_state, psli->sli_flag,
5164 			phba->hba_flag);
5165 
5166 	/* perform board reset */
5167 	phba->fc_eventTag = 0;
5168 	phba->link_events = 0;
5169 	phba->pport->fc_myDID = 0;
5170 	phba->pport->fc_prevDID = 0;
5171 	phba->hba_flag &= ~HBA_SETUP;
5172 
5173 	spin_lock_irq(&phba->hbalock);
5174 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
5175 	phba->fcf.fcf_flag = 0;
5176 	spin_unlock_irq(&phba->hbalock);
5177 
5178 	/* Now physically reset the device */
5179 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5180 			"0389 Performing PCI function reset!\n");
5181 
5182 	/* Turn off parity checking and serr during the physical reset */
5183 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
5184 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5185 				"3205 PCI read Config failed\n");
5186 		return -EIO;
5187 	}
5188 
5189 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
5190 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5191 
5192 	/* Perform FCoE PCI function reset before freeing queue memory */
5193 	rc = lpfc_pci_function_reset(phba);
5194 
5195 	/* Restore PCI cmd register */
5196 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5197 
5198 	return rc;
5199 }
5200 
5201 /**
5202  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
5203  * @phba: Pointer to HBA context object.
5204  *
5205  * This function is called in the SLI initialization code path to
5206  * restart the HBA. The caller is not required to hold any lock.
5207  * This function writes MBX_RESTART mailbox command to the SLIM and
5208  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
5209  * function to free any pending commands. The function enables
5210  * POST only during the first initialization. The function returns zero.
5211  * The function does not guarantee completion of MBX_RESTART mailbox
5212  * command before the return of this function.
5213  **/
5214 static int
5215 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
5216 {
5217 	volatile struct MAILBOX_word0 mb;
5218 	struct lpfc_sli *psli;
5219 	void __iomem *to_slim;
5220 
5221 	spin_lock_irq(&phba->hbalock);
5222 
5223 	psli = &phba->sli;
5224 
5225 	/* Restart HBA */
5226 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5227 			"0337 Restart HBA Data: x%x x%x\n",
5228 			(phba->pport) ? phba->pport->port_state : 0,
5229 			psli->sli_flag);
5230 
5231 	mb.word0 = 0;
5232 	mb.mbxCommand = MBX_RESTART;
5233 	mb.mbxHc = 1;
5234 
5235 	lpfc_reset_barrier(phba);
5236 
5237 	to_slim = phba->MBslimaddr;
5238 	writel(mb.word0, to_slim);
5239 	readl(to_slim); /* flush */
5240 
5241 	/* Only skip post after fc_ffinit is completed */
5242 	if (phba->pport && phba->pport->port_state)
5243 		mb.word0 = 1;	/* This is really setting up word1 */
5244 	else
5245 		mb.word0 = 0;	/* This is really setting up word1 */
5246 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
5247 	writel(mb.word0, to_slim);
5248 	readl(to_slim); /* flush */
5249 
5250 	lpfc_sli_brdreset(phba);
5251 	if (phba->pport)
5252 		phba->pport->stopped = 0;
5253 	phba->link_state = LPFC_INIT_START;
5254 	phba->hba_flag = 0;
5255 	spin_unlock_irq(&phba->hbalock);
5256 
5257 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5258 	psli->stats_start = ktime_get_seconds();
5259 
5260 	/* Give the INITFF and Post time to settle. */
5261 	mdelay(100);
5262 
5263 	lpfc_hba_down_post(phba);
5264 
5265 	return 0;
5266 }
5267 
5268 /**
5269  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
5270  * @phba: Pointer to HBA context object.
5271  *
5272  * This function is called in the SLI initialization code path to restart
5273  * a SLI4 HBA. The caller is not required to hold any lock.
5274  * At the end of the function, it calls lpfc_hba_down_post function to
5275  * free any pending commands.
5276  **/
5277 static int
5278 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
5279 {
5280 	struct lpfc_sli *psli = &phba->sli;
5281 	int rc;
5282 
5283 	/* Restart HBA */
5284 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5285 			"0296 Restart HBA Data: x%x x%x\n",
5286 			phba->pport->port_state, psli->sli_flag);
5287 
5288 	rc = lpfc_sli4_brdreset(phba);
5289 	if (rc) {
5290 		phba->link_state = LPFC_HBA_ERROR;
5291 		goto hba_down_queue;
5292 	}
5293 
5294 	spin_lock_irq(&phba->hbalock);
5295 	phba->pport->stopped = 0;
5296 	phba->link_state = LPFC_INIT_START;
5297 	phba->hba_flag = 0;
5298 	/* Preserve FA-PWWN expectation */
5299 	phba->sli4_hba.fawwpn_flag &= LPFC_FAWWPN_FABRIC;
5300 	spin_unlock_irq(&phba->hbalock);
5301 
5302 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5303 	psli->stats_start = ktime_get_seconds();
5304 
5305 hba_down_queue:
5306 	lpfc_hba_down_post(phba);
5307 	lpfc_sli4_queue_destroy(phba);
5308 
5309 	return rc;
5310 }
5311 
5312 /**
5313  * lpfc_sli_brdrestart - Wrapper func for restarting hba
5314  * @phba: Pointer to HBA context object.
5315  *
5316  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
5317  * API jump table function pointer from the lpfc_hba struct.
5318 **/
5319 int
5320 lpfc_sli_brdrestart(struct lpfc_hba *phba)
5321 {
5322 	return phba->lpfc_sli_brdrestart(phba);
5323 }
5324 
5325 /**
5326  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
5327  * @phba: Pointer to HBA context object.
5328  *
5329  * This function is called after a HBA restart to wait for successful
5330  * restart of the HBA. Successful restart of the HBA is indicated by
5331  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
5332  * iteration, the function will restart the HBA again. The function returns
5333  * zero if HBA successfully restarted else returns negative error code.
5334  **/
5335 int
5336 lpfc_sli_chipset_init(struct lpfc_hba *phba)
5337 {
5338 	uint32_t status, i = 0;
5339 
5340 	/* Read the HBA Host Status Register */
5341 	if (lpfc_readl(phba->HSregaddr, &status))
5342 		return -EIO;
5343 
5344 	/* Check status register to see what current state is */
5345 	i = 0;
5346 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
5347 
5348 		/* Check every 10ms for 10 retries, then every 100ms for 90
5349 		 * retries, then every 1 sec for 50 retires for a total of
5350 		 * ~60 seconds before reset the board again and check every
5351 		 * 1 sec for 50 retries. The up to 60 seconds before the
5352 		 * board ready is required by the Falcon FIPS zeroization
5353 		 * complete, and any reset the board in between shall cause
5354 		 * restart of zeroization, further delay the board ready.
5355 		 */
5356 		if (i++ >= 200) {
5357 			/* Adapter failed to init, timeout, status reg
5358 			   <status> */
5359 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5360 					"0436 Adapter failed to init, "
5361 					"timeout, status reg x%x, "
5362 					"FW Data: A8 x%x AC x%x\n", status,
5363 					readl(phba->MBslimaddr + 0xa8),
5364 					readl(phba->MBslimaddr + 0xac));
5365 			phba->link_state = LPFC_HBA_ERROR;
5366 			return -ETIMEDOUT;
5367 		}
5368 
5369 		/* Check to see if any errors occurred during init */
5370 		if (status & HS_FFERM) {
5371 			/* ERROR: During chipset initialization */
5372 			/* Adapter failed to init, chipset, status reg
5373 			   <status> */
5374 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5375 					"0437 Adapter failed to init, "
5376 					"chipset, status reg x%x, "
5377 					"FW Data: A8 x%x AC x%x\n", status,
5378 					readl(phba->MBslimaddr + 0xa8),
5379 					readl(phba->MBslimaddr + 0xac));
5380 			phba->link_state = LPFC_HBA_ERROR;
5381 			return -EIO;
5382 		}
5383 
5384 		if (i <= 10)
5385 			msleep(10);
5386 		else if (i <= 100)
5387 			msleep(100);
5388 		else
5389 			msleep(1000);
5390 
5391 		if (i == 150) {
5392 			/* Do post */
5393 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5394 			lpfc_sli_brdrestart(phba);
5395 		}
5396 		/* Read the HBA Host Status Register */
5397 		if (lpfc_readl(phba->HSregaddr, &status))
5398 			return -EIO;
5399 	}
5400 
5401 	/* Check to see if any errors occurred during init */
5402 	if (status & HS_FFERM) {
5403 		/* ERROR: During chipset initialization */
5404 		/* Adapter failed to init, chipset, status reg <status> */
5405 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5406 				"0438 Adapter failed to init, chipset, "
5407 				"status reg x%x, "
5408 				"FW Data: A8 x%x AC x%x\n", status,
5409 				readl(phba->MBslimaddr + 0xa8),
5410 				readl(phba->MBslimaddr + 0xac));
5411 		phba->link_state = LPFC_HBA_ERROR;
5412 		return -EIO;
5413 	}
5414 
5415 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5416 
5417 	/* Clear all interrupt enable conditions */
5418 	writel(0, phba->HCregaddr);
5419 	readl(phba->HCregaddr); /* flush */
5420 
5421 	/* setup host attn register */
5422 	writel(0xffffffff, phba->HAregaddr);
5423 	readl(phba->HAregaddr); /* flush */
5424 	return 0;
5425 }
5426 
5427 /**
5428  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5429  *
5430  * This function calculates and returns the number of HBQs required to be
5431  * configured.
5432  **/
5433 int
5434 lpfc_sli_hbq_count(void)
5435 {
5436 	return ARRAY_SIZE(lpfc_hbq_defs);
5437 }
5438 
5439 /**
5440  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5441  *
5442  * This function adds the number of hbq entries in every HBQ to get
5443  * the total number of hbq entries required for the HBA and returns
5444  * the total count.
5445  **/
5446 static int
5447 lpfc_sli_hbq_entry_count(void)
5448 {
5449 	int  hbq_count = lpfc_sli_hbq_count();
5450 	int  count = 0;
5451 	int  i;
5452 
5453 	for (i = 0; i < hbq_count; ++i)
5454 		count += lpfc_hbq_defs[i]->entry_count;
5455 	return count;
5456 }
5457 
5458 /**
5459  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5460  *
5461  * This function calculates amount of memory required for all hbq entries
5462  * to be configured and returns the total memory required.
5463  **/
5464 int
5465 lpfc_sli_hbq_size(void)
5466 {
5467 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5468 }
5469 
5470 /**
5471  * lpfc_sli_hbq_setup - configure and initialize HBQs
5472  * @phba: Pointer to HBA context object.
5473  *
5474  * This function is called during the SLI initialization to configure
5475  * all the HBQs and post buffers to the HBQ. The caller is not
5476  * required to hold any locks. This function will return zero if successful
5477  * else it will return negative error code.
5478  **/
5479 static int
5480 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5481 {
5482 	int  hbq_count = lpfc_sli_hbq_count();
5483 	LPFC_MBOXQ_t *pmb;
5484 	MAILBOX_t *pmbox;
5485 	uint32_t hbqno;
5486 	uint32_t hbq_entry_index;
5487 
5488 				/* Get a Mailbox buffer to setup mailbox
5489 				 * commands for HBA initialization
5490 				 */
5491 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5492 
5493 	if (!pmb)
5494 		return -ENOMEM;
5495 
5496 	pmbox = &pmb->u.mb;
5497 
5498 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
5499 	phba->link_state = LPFC_INIT_MBX_CMDS;
5500 	phba->hbq_in_use = 1;
5501 
5502 	hbq_entry_index = 0;
5503 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5504 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
5505 		phba->hbqs[hbqno].hbqPutIdx      = 0;
5506 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5507 		phba->hbqs[hbqno].entry_count =
5508 			lpfc_hbq_defs[hbqno]->entry_count;
5509 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5510 			hbq_entry_index, pmb);
5511 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
5512 
5513 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5514 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5515 			   mbxStatus <status>, ring <num> */
5516 
5517 			lpfc_printf_log(phba, KERN_ERR,
5518 					LOG_SLI | LOG_VPORT,
5519 					"1805 Adapter failed to init. "
5520 					"Data: x%x x%x x%x\n",
5521 					pmbox->mbxCommand,
5522 					pmbox->mbxStatus, hbqno);
5523 
5524 			phba->link_state = LPFC_HBA_ERROR;
5525 			mempool_free(pmb, phba->mbox_mem_pool);
5526 			return -ENXIO;
5527 		}
5528 	}
5529 	phba->hbq_count = hbq_count;
5530 
5531 	mempool_free(pmb, phba->mbox_mem_pool);
5532 
5533 	/* Initially populate or replenish the HBQs */
5534 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5535 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5536 	return 0;
5537 }
5538 
5539 /**
5540  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5541  * @phba: Pointer to HBA context object.
5542  *
5543  * This function is called during the SLI initialization to configure
5544  * all the HBQs and post buffers to the HBQ. The caller is not
5545  * required to hold any locks. This function will return zero if successful
5546  * else it will return negative error code.
5547  **/
5548 static int
5549 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5550 {
5551 	phba->hbq_in_use = 1;
5552 	/**
5553 	 * Specific case when the MDS diagnostics is enabled and supported.
5554 	 * The receive buffer count is truncated to manage the incoming
5555 	 * traffic.
5556 	 **/
5557 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5558 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5559 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5560 	else
5561 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5562 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5563 	phba->hbq_count = 1;
5564 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5565 	/* Initially populate or replenish the HBQs */
5566 	return 0;
5567 }
5568 
5569 /**
5570  * lpfc_sli_config_port - Issue config port mailbox command
5571  * @phba: Pointer to HBA context object.
5572  * @sli_mode: sli mode - 2/3
5573  *
5574  * This function is called by the sli initialization code path
5575  * to issue config_port mailbox command. This function restarts the
5576  * HBA firmware and issues a config_port mailbox command to configure
5577  * the SLI interface in the sli mode specified by sli_mode
5578  * variable. The caller is not required to hold any locks.
5579  * The function returns 0 if successful, else returns negative error
5580  * code.
5581  **/
5582 int
5583 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5584 {
5585 	LPFC_MBOXQ_t *pmb;
5586 	uint32_t resetcount = 0, rc = 0, done = 0;
5587 
5588 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5589 	if (!pmb) {
5590 		phba->link_state = LPFC_HBA_ERROR;
5591 		return -ENOMEM;
5592 	}
5593 
5594 	phba->sli_rev = sli_mode;
5595 	while (resetcount < 2 && !done) {
5596 		spin_lock_irq(&phba->hbalock);
5597 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5598 		spin_unlock_irq(&phba->hbalock);
5599 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5600 		lpfc_sli_brdrestart(phba);
5601 		rc = lpfc_sli_chipset_init(phba);
5602 		if (rc)
5603 			break;
5604 
5605 		spin_lock_irq(&phba->hbalock);
5606 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5607 		spin_unlock_irq(&phba->hbalock);
5608 		resetcount++;
5609 
5610 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5611 		 * value of 0 means the call was successful.  Any other
5612 		 * nonzero value is a failure, but if ERESTART is returned,
5613 		 * the driver may reset the HBA and try again.
5614 		 */
5615 		rc = lpfc_config_port_prep(phba);
5616 		if (rc == -ERESTART) {
5617 			phba->link_state = LPFC_LINK_UNKNOWN;
5618 			continue;
5619 		} else if (rc)
5620 			break;
5621 
5622 		phba->link_state = LPFC_INIT_MBX_CMDS;
5623 		lpfc_config_port(phba, pmb);
5624 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5625 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5626 					LPFC_SLI3_HBQ_ENABLED |
5627 					LPFC_SLI3_CRP_ENABLED |
5628 					LPFC_SLI3_DSS_ENABLED);
5629 		if (rc != MBX_SUCCESS) {
5630 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5631 				"0442 Adapter failed to init, mbxCmd x%x "
5632 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5633 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5634 			spin_lock_irq(&phba->hbalock);
5635 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5636 			spin_unlock_irq(&phba->hbalock);
5637 			rc = -ENXIO;
5638 		} else {
5639 			/* Allow asynchronous mailbox command to go through */
5640 			spin_lock_irq(&phba->hbalock);
5641 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5642 			spin_unlock_irq(&phba->hbalock);
5643 			done = 1;
5644 
5645 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5646 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5647 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5648 					"3110 Port did not grant ASABT\n");
5649 		}
5650 	}
5651 	if (!done) {
5652 		rc = -EINVAL;
5653 		goto do_prep_failed;
5654 	}
5655 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5656 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5657 			rc = -ENXIO;
5658 			goto do_prep_failed;
5659 		}
5660 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5661 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5662 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5663 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5664 				phba->max_vpi : phba->max_vports;
5665 
5666 		} else
5667 			phba->max_vpi = 0;
5668 		if (pmb->u.mb.un.varCfgPort.gerbm)
5669 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5670 		if (pmb->u.mb.un.varCfgPort.gcrp)
5671 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5672 
5673 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5674 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5675 
5676 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5677 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5678 				phba->cfg_enable_bg = 0;
5679 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5680 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5681 						"0443 Adapter did not grant "
5682 						"BlockGuard\n");
5683 			}
5684 		}
5685 	} else {
5686 		phba->hbq_get = NULL;
5687 		phba->port_gp = phba->mbox->us.s2.port;
5688 		phba->max_vpi = 0;
5689 	}
5690 do_prep_failed:
5691 	mempool_free(pmb, phba->mbox_mem_pool);
5692 	return rc;
5693 }
5694 
5695 
5696 /**
5697  * lpfc_sli_hba_setup - SLI initialization function
5698  * @phba: Pointer to HBA context object.
5699  *
5700  * This function is the main SLI initialization function. This function
5701  * is called by the HBA initialization code, HBA reset code and HBA
5702  * error attention handler code. Caller is not required to hold any
5703  * locks. This function issues config_port mailbox command to configure
5704  * the SLI, setup iocb rings and HBQ rings. In the end the function
5705  * calls the config_port_post function to issue init_link mailbox
5706  * command and to start the discovery. The function will return zero
5707  * if successful, else it will return negative error code.
5708  **/
5709 int
5710 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5711 {
5712 	uint32_t rc;
5713 	int  i;
5714 	int longs;
5715 
5716 	/* Enable ISR already does config_port because of config_msi mbx */
5717 	if (phba->hba_flag & HBA_NEEDS_CFG_PORT) {
5718 		rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5719 		if (rc)
5720 			return -EIO;
5721 		phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
5722 	}
5723 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5724 
5725 	if (phba->sli_rev == 3) {
5726 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5727 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5728 	} else {
5729 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5730 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5731 		phba->sli3_options = 0;
5732 	}
5733 
5734 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5735 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5736 			phba->sli_rev, phba->max_vpi);
5737 	rc = lpfc_sli_ring_map(phba);
5738 
5739 	if (rc)
5740 		goto lpfc_sli_hba_setup_error;
5741 
5742 	/* Initialize VPIs. */
5743 	if (phba->sli_rev == LPFC_SLI_REV3) {
5744 		/*
5745 		 * The VPI bitmask and physical ID array are allocated
5746 		 * and initialized once only - at driver load.  A port
5747 		 * reset doesn't need to reinitialize this memory.
5748 		 */
5749 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5750 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5751 			phba->vpi_bmask = kcalloc(longs,
5752 						  sizeof(unsigned long),
5753 						  GFP_KERNEL);
5754 			if (!phba->vpi_bmask) {
5755 				rc = -ENOMEM;
5756 				goto lpfc_sli_hba_setup_error;
5757 			}
5758 
5759 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5760 						sizeof(uint16_t),
5761 						GFP_KERNEL);
5762 			if (!phba->vpi_ids) {
5763 				kfree(phba->vpi_bmask);
5764 				rc = -ENOMEM;
5765 				goto lpfc_sli_hba_setup_error;
5766 			}
5767 			for (i = 0; i < phba->max_vpi; i++)
5768 				phba->vpi_ids[i] = i;
5769 		}
5770 	}
5771 
5772 	/* Init HBQs */
5773 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5774 		rc = lpfc_sli_hbq_setup(phba);
5775 		if (rc)
5776 			goto lpfc_sli_hba_setup_error;
5777 	}
5778 	spin_lock_irq(&phba->hbalock);
5779 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5780 	spin_unlock_irq(&phba->hbalock);
5781 
5782 	rc = lpfc_config_port_post(phba);
5783 	if (rc)
5784 		goto lpfc_sli_hba_setup_error;
5785 
5786 	return rc;
5787 
5788 lpfc_sli_hba_setup_error:
5789 	phba->link_state = LPFC_HBA_ERROR;
5790 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5791 			"0445 Firmware initialization failed\n");
5792 	return rc;
5793 }
5794 
5795 /**
5796  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5797  * @phba: Pointer to HBA context object.
5798  *
5799  * This function issue a dump mailbox command to read config region
5800  * 23 and parse the records in the region and populate driver
5801  * data structure.
5802  **/
5803 static int
5804 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5805 {
5806 	LPFC_MBOXQ_t *mboxq;
5807 	struct lpfc_dmabuf *mp;
5808 	struct lpfc_mqe *mqe;
5809 	uint32_t data_length;
5810 	int rc;
5811 
5812 	/* Program the default value of vlan_id and fc_map */
5813 	phba->valid_vlan = 0;
5814 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5815 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5816 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5817 
5818 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5819 	if (!mboxq)
5820 		return -ENOMEM;
5821 
5822 	mqe = &mboxq->u.mqe;
5823 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5824 		rc = -ENOMEM;
5825 		goto out_free_mboxq;
5826 	}
5827 
5828 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5829 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5830 
5831 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5832 			"(%d):2571 Mailbox cmd x%x Status x%x "
5833 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5834 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5835 			"CQ: x%x x%x x%x x%x\n",
5836 			mboxq->vport ? mboxq->vport->vpi : 0,
5837 			bf_get(lpfc_mqe_command, mqe),
5838 			bf_get(lpfc_mqe_status, mqe),
5839 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5840 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5841 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5842 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5843 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5844 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5845 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5846 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5847 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5848 			mboxq->mcqe.word0,
5849 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5850 			mboxq->mcqe.trailer);
5851 
5852 	if (rc) {
5853 		rc = -EIO;
5854 		goto out_free_mboxq;
5855 	}
5856 	data_length = mqe->un.mb_words[5];
5857 	if (data_length > DMP_RGN23_SIZE) {
5858 		rc = -EIO;
5859 		goto out_free_mboxq;
5860 	}
5861 
5862 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5863 	rc = 0;
5864 
5865 out_free_mboxq:
5866 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
5867 	return rc;
5868 }
5869 
5870 /**
5871  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5872  * @phba: pointer to lpfc hba data structure.
5873  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5874  * @vpd: pointer to the memory to hold resulting port vpd data.
5875  * @vpd_size: On input, the number of bytes allocated to @vpd.
5876  *	      On output, the number of data bytes in @vpd.
5877  *
5878  * This routine executes a READ_REV SLI4 mailbox command.  In
5879  * addition, this routine gets the port vpd data.
5880  *
5881  * Return codes
5882  * 	0 - successful
5883  * 	-ENOMEM - could not allocated memory.
5884  **/
5885 static int
5886 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5887 		    uint8_t *vpd, uint32_t *vpd_size)
5888 {
5889 	int rc = 0;
5890 	uint32_t dma_size;
5891 	struct lpfc_dmabuf *dmabuf;
5892 	struct lpfc_mqe *mqe;
5893 
5894 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5895 	if (!dmabuf)
5896 		return -ENOMEM;
5897 
5898 	/*
5899 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5900 	 * mailbox command.
5901 	 */
5902 	dma_size = *vpd_size;
5903 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5904 					  &dmabuf->phys, GFP_KERNEL);
5905 	if (!dmabuf->virt) {
5906 		kfree(dmabuf);
5907 		return -ENOMEM;
5908 	}
5909 
5910 	/*
5911 	 * The SLI4 implementation of READ_REV conflicts at word1,
5912 	 * bits 31:16 and SLI4 adds vpd functionality not present
5913 	 * in SLI3.  This code corrects the conflicts.
5914 	 */
5915 	lpfc_read_rev(phba, mboxq);
5916 	mqe = &mboxq->u.mqe;
5917 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5918 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5919 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5920 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5921 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5922 
5923 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5924 	if (rc) {
5925 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5926 				  dmabuf->virt, dmabuf->phys);
5927 		kfree(dmabuf);
5928 		return -EIO;
5929 	}
5930 
5931 	/*
5932 	 * The available vpd length cannot be bigger than the
5933 	 * DMA buffer passed to the port.  Catch the less than
5934 	 * case and update the caller's size.
5935 	 */
5936 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5937 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5938 
5939 	memcpy(vpd, dmabuf->virt, *vpd_size);
5940 
5941 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5942 			  dmabuf->virt, dmabuf->phys);
5943 	kfree(dmabuf);
5944 	return 0;
5945 }
5946 
5947 /**
5948  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5949  * @phba: pointer to lpfc hba data structure.
5950  *
5951  * This routine retrieves SLI4 device physical port name this PCI function
5952  * is attached to.
5953  *
5954  * Return codes
5955  *      0 - successful
5956  *      otherwise - failed to retrieve controller attributes
5957  **/
5958 static int
5959 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5960 {
5961 	LPFC_MBOXQ_t *mboxq;
5962 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5963 	struct lpfc_controller_attribute *cntl_attr;
5964 	void *virtaddr = NULL;
5965 	uint32_t alloclen, reqlen;
5966 	uint32_t shdr_status, shdr_add_status;
5967 	union lpfc_sli4_cfg_shdr *shdr;
5968 	int rc;
5969 
5970 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5971 	if (!mboxq)
5972 		return -ENOMEM;
5973 
5974 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5975 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5976 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5977 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5978 			LPFC_SLI4_MBX_NEMBED);
5979 
5980 	if (alloclen < reqlen) {
5981 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5982 				"3084 Allocated DMA memory size (%d) is "
5983 				"less than the requested DMA memory size "
5984 				"(%d)\n", alloclen, reqlen);
5985 		rc = -ENOMEM;
5986 		goto out_free_mboxq;
5987 	}
5988 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5989 	virtaddr = mboxq->sge_array->addr[0];
5990 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5991 	shdr = &mbx_cntl_attr->cfg_shdr;
5992 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5993 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5994 	if (shdr_status || shdr_add_status || rc) {
5995 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5996 				"3085 Mailbox x%x (x%x/x%x) failed, "
5997 				"rc:x%x, status:x%x, add_status:x%x\n",
5998 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5999 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6000 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6001 				rc, shdr_status, shdr_add_status);
6002 		rc = -ENXIO;
6003 		goto out_free_mboxq;
6004 	}
6005 
6006 	cntl_attr = &mbx_cntl_attr->cntl_attr;
6007 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
6008 	phba->sli4_hba.lnk_info.lnk_tp =
6009 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
6010 	phba->sli4_hba.lnk_info.lnk_no =
6011 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
6012 	phba->sli4_hba.flash_id = bf_get(lpfc_cntl_attr_flash_id, cntl_attr);
6013 	phba->sli4_hba.asic_rev = bf_get(lpfc_cntl_attr_asic_rev, cntl_attr);
6014 
6015 	memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
6016 	strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
6017 		sizeof(phba->BIOSVersion));
6018 
6019 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6020 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s, "
6021 			"flash_id: x%02x, asic_rev: x%02x\n",
6022 			phba->sli4_hba.lnk_info.lnk_tp,
6023 			phba->sli4_hba.lnk_info.lnk_no,
6024 			phba->BIOSVersion, phba->sli4_hba.flash_id,
6025 			phba->sli4_hba.asic_rev);
6026 out_free_mboxq:
6027 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6028 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6029 	else
6030 		mempool_free(mboxq, phba->mbox_mem_pool);
6031 	return rc;
6032 }
6033 
6034 /**
6035  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
6036  * @phba: pointer to lpfc hba data structure.
6037  *
6038  * This routine retrieves SLI4 device physical port name this PCI function
6039  * is attached to.
6040  *
6041  * Return codes
6042  *      0 - successful
6043  *      otherwise - failed to retrieve physical port name
6044  **/
6045 static int
6046 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
6047 {
6048 	LPFC_MBOXQ_t *mboxq;
6049 	struct lpfc_mbx_get_port_name *get_port_name;
6050 	uint32_t shdr_status, shdr_add_status;
6051 	union lpfc_sli4_cfg_shdr *shdr;
6052 	char cport_name = 0;
6053 	int rc;
6054 
6055 	/* We assume nothing at this point */
6056 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6057 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
6058 
6059 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6060 	if (!mboxq)
6061 		return -ENOMEM;
6062 	/* obtain link type and link number via READ_CONFIG */
6063 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6064 	lpfc_sli4_read_config(phba);
6065 
6066 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG)
6067 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
6068 
6069 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
6070 		goto retrieve_ppname;
6071 
6072 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
6073 	rc = lpfc_sli4_get_ctl_attr(phba);
6074 	if (rc)
6075 		goto out_free_mboxq;
6076 
6077 retrieve_ppname:
6078 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
6079 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
6080 		sizeof(struct lpfc_mbx_get_port_name) -
6081 		sizeof(struct lpfc_sli4_cfg_mhdr),
6082 		LPFC_SLI4_MBX_EMBED);
6083 	get_port_name = &mboxq->u.mqe.un.get_port_name;
6084 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
6085 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
6086 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
6087 		phba->sli4_hba.lnk_info.lnk_tp);
6088 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6089 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6090 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6091 	if (shdr_status || shdr_add_status || rc) {
6092 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6093 				"3087 Mailbox x%x (x%x/x%x) failed: "
6094 				"rc:x%x, status:x%x, add_status:x%x\n",
6095 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6096 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6097 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6098 				rc, shdr_status, shdr_add_status);
6099 		rc = -ENXIO;
6100 		goto out_free_mboxq;
6101 	}
6102 	switch (phba->sli4_hba.lnk_info.lnk_no) {
6103 	case LPFC_LINK_NUMBER_0:
6104 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
6105 				&get_port_name->u.response);
6106 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6107 		break;
6108 	case LPFC_LINK_NUMBER_1:
6109 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
6110 				&get_port_name->u.response);
6111 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6112 		break;
6113 	case LPFC_LINK_NUMBER_2:
6114 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
6115 				&get_port_name->u.response);
6116 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6117 		break;
6118 	case LPFC_LINK_NUMBER_3:
6119 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
6120 				&get_port_name->u.response);
6121 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6122 		break;
6123 	default:
6124 		break;
6125 	}
6126 
6127 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
6128 		phba->Port[0] = cport_name;
6129 		phba->Port[1] = '\0';
6130 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6131 				"3091 SLI get port name: %s\n", phba->Port);
6132 	}
6133 
6134 out_free_mboxq:
6135 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6136 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6137 	else
6138 		mempool_free(mboxq, phba->mbox_mem_pool);
6139 	return rc;
6140 }
6141 
6142 /**
6143  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
6144  * @phba: pointer to lpfc hba data structure.
6145  *
6146  * This routine is called to explicitly arm the SLI4 device's completion and
6147  * event queues
6148  **/
6149 static void
6150 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
6151 {
6152 	int qidx;
6153 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
6154 	struct lpfc_sli4_hdw_queue *qp;
6155 	struct lpfc_queue *eq;
6156 
6157 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
6158 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
6159 	if (sli4_hba->nvmels_cq)
6160 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
6161 					   LPFC_QUEUE_REARM);
6162 
6163 	if (sli4_hba->hdwq) {
6164 		/* Loop thru all Hardware Queues */
6165 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
6166 			qp = &sli4_hba->hdwq[qidx];
6167 			/* ARM the corresponding CQ */
6168 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
6169 						LPFC_QUEUE_REARM);
6170 		}
6171 
6172 		/* Loop thru all IRQ vectors */
6173 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
6174 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
6175 			/* ARM the corresponding EQ */
6176 			sli4_hba->sli4_write_eq_db(phba, eq,
6177 						   0, LPFC_QUEUE_REARM);
6178 		}
6179 	}
6180 
6181 	if (phba->nvmet_support) {
6182 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
6183 			sli4_hba->sli4_write_cq_db(phba,
6184 				sli4_hba->nvmet_cqset[qidx], 0,
6185 				LPFC_QUEUE_REARM);
6186 		}
6187 	}
6188 }
6189 
6190 /**
6191  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
6192  * @phba: Pointer to HBA context object.
6193  * @type: The resource extent type.
6194  * @extnt_count: buffer to hold port available extent count.
6195  * @extnt_size: buffer to hold element count per extent.
6196  *
6197  * This function calls the port and retrievs the number of available
6198  * extents and their size for a particular extent type.
6199  *
6200  * Returns: 0 if successful.  Nonzero otherwise.
6201  **/
6202 int
6203 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
6204 			       uint16_t *extnt_count, uint16_t *extnt_size)
6205 {
6206 	int rc = 0;
6207 	uint32_t length;
6208 	uint32_t mbox_tmo;
6209 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
6210 	LPFC_MBOXQ_t *mbox;
6211 
6212 	*extnt_count = 0;
6213 	*extnt_size = 0;
6214 
6215 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6216 	if (!mbox)
6217 		return -ENOMEM;
6218 
6219 	/* Find out how many extents are available for this resource type */
6220 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
6221 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6222 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6223 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
6224 			 length, LPFC_SLI4_MBX_EMBED);
6225 
6226 	/* Send an extents count of 0 - the GET doesn't use it. */
6227 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6228 					LPFC_SLI4_MBX_EMBED);
6229 	if (unlikely(rc)) {
6230 		rc = -EIO;
6231 		goto err_exit;
6232 	}
6233 
6234 	if (!phba->sli4_hba.intr_enable)
6235 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6236 	else {
6237 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6238 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6239 	}
6240 	if (unlikely(rc)) {
6241 		rc = -EIO;
6242 		goto err_exit;
6243 	}
6244 
6245 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
6246 	if (bf_get(lpfc_mbox_hdr_status,
6247 		   &rsrc_info->header.cfg_shdr.response)) {
6248 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6249 				"2930 Failed to get resource extents "
6250 				"Status 0x%x Add'l Status 0x%x\n",
6251 				bf_get(lpfc_mbox_hdr_status,
6252 				       &rsrc_info->header.cfg_shdr.response),
6253 				bf_get(lpfc_mbox_hdr_add_status,
6254 				       &rsrc_info->header.cfg_shdr.response));
6255 		rc = -EIO;
6256 		goto err_exit;
6257 	}
6258 
6259 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
6260 			      &rsrc_info->u.rsp);
6261 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
6262 			     &rsrc_info->u.rsp);
6263 
6264 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6265 			"3162 Retrieved extents type-%d from port: count:%d, "
6266 			"size:%d\n", type, *extnt_count, *extnt_size);
6267 
6268 err_exit:
6269 	mempool_free(mbox, phba->mbox_mem_pool);
6270 	return rc;
6271 }
6272 
6273 /**
6274  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
6275  * @phba: Pointer to HBA context object.
6276  * @type: The extent type to check.
6277  *
6278  * This function reads the current available extents from the port and checks
6279  * if the extent count or extent size has changed since the last access.
6280  * Callers use this routine post port reset to understand if there is a
6281  * extent reprovisioning requirement.
6282  *
6283  * Returns:
6284  *   -Error: error indicates problem.
6285  *   1: Extent count or size has changed.
6286  *   0: No changes.
6287  **/
6288 static int
6289 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
6290 {
6291 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
6292 	uint16_t size_diff, rsrc_ext_size;
6293 	int rc = 0;
6294 	struct lpfc_rsrc_blks *rsrc_entry;
6295 	struct list_head *rsrc_blk_list = NULL;
6296 
6297 	size_diff = 0;
6298 	curr_ext_cnt = 0;
6299 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6300 					    &rsrc_ext_cnt,
6301 					    &rsrc_ext_size);
6302 	if (unlikely(rc))
6303 		return -EIO;
6304 
6305 	switch (type) {
6306 	case LPFC_RSC_TYPE_FCOE_RPI:
6307 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6308 		break;
6309 	case LPFC_RSC_TYPE_FCOE_VPI:
6310 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
6311 		break;
6312 	case LPFC_RSC_TYPE_FCOE_XRI:
6313 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6314 		break;
6315 	case LPFC_RSC_TYPE_FCOE_VFI:
6316 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6317 		break;
6318 	default:
6319 		break;
6320 	}
6321 
6322 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
6323 		curr_ext_cnt++;
6324 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
6325 			size_diff++;
6326 	}
6327 
6328 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
6329 		rc = 1;
6330 
6331 	return rc;
6332 }
6333 
6334 /**
6335  * lpfc_sli4_cfg_post_extnts -
6336  * @phba: Pointer to HBA context object.
6337  * @extnt_cnt: number of available extents.
6338  * @type: the extent type (rpi, xri, vfi, vpi).
6339  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
6340  * @mbox: pointer to the caller's allocated mailbox structure.
6341  *
6342  * This function executes the extents allocation request.  It also
6343  * takes care of the amount of memory needed to allocate or get the
6344  * allocated extents. It is the caller's responsibility to evaluate
6345  * the response.
6346  *
6347  * Returns:
6348  *   -Error:  Error value describes the condition found.
6349  *   0: if successful
6350  **/
6351 static int
6352 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6353 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6354 {
6355 	int rc = 0;
6356 	uint32_t req_len;
6357 	uint32_t emb_len;
6358 	uint32_t alloc_len, mbox_tmo;
6359 
6360 	/* Calculate the total requested length of the dma memory */
6361 	req_len = extnt_cnt * sizeof(uint16_t);
6362 
6363 	/*
6364 	 * Calculate the size of an embedded mailbox.  The uint32_t
6365 	 * accounts for extents-specific word.
6366 	 */
6367 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6368 		sizeof(uint32_t);
6369 
6370 	/*
6371 	 * Presume the allocation and response will fit into an embedded
6372 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6373 	 */
6374 	*emb = LPFC_SLI4_MBX_EMBED;
6375 	if (req_len > emb_len) {
6376 		req_len = extnt_cnt * sizeof(uint16_t) +
6377 			sizeof(union lpfc_sli4_cfg_shdr) +
6378 			sizeof(uint32_t);
6379 		*emb = LPFC_SLI4_MBX_NEMBED;
6380 	}
6381 
6382 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6383 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6384 				     req_len, *emb);
6385 	if (alloc_len < req_len) {
6386 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6387 			"2982 Allocated DMA memory size (x%x) is "
6388 			"less than the requested DMA memory "
6389 			"size (x%x)\n", alloc_len, req_len);
6390 		return -ENOMEM;
6391 	}
6392 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6393 	if (unlikely(rc))
6394 		return -EIO;
6395 
6396 	if (!phba->sli4_hba.intr_enable)
6397 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6398 	else {
6399 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6400 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6401 	}
6402 
6403 	if (unlikely(rc))
6404 		rc = -EIO;
6405 	return rc;
6406 }
6407 
6408 /**
6409  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6410  * @phba: Pointer to HBA context object.
6411  * @type:  The resource extent type to allocate.
6412  *
6413  * This function allocates the number of elements for the specified
6414  * resource type.
6415  **/
6416 static int
6417 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6418 {
6419 	bool emb = false;
6420 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6421 	uint16_t rsrc_id, rsrc_start, j, k;
6422 	uint16_t *ids;
6423 	int i, rc;
6424 	unsigned long longs;
6425 	unsigned long *bmask;
6426 	struct lpfc_rsrc_blks *rsrc_blks;
6427 	LPFC_MBOXQ_t *mbox;
6428 	uint32_t length;
6429 	struct lpfc_id_range *id_array = NULL;
6430 	void *virtaddr = NULL;
6431 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6432 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6433 	struct list_head *ext_blk_list;
6434 
6435 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6436 					    &rsrc_cnt,
6437 					    &rsrc_size);
6438 	if (unlikely(rc))
6439 		return -EIO;
6440 
6441 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6442 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6443 			"3009 No available Resource Extents "
6444 			"for resource type 0x%x: Count: 0x%x, "
6445 			"Size 0x%x\n", type, rsrc_cnt,
6446 			rsrc_size);
6447 		return -ENOMEM;
6448 	}
6449 
6450 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6451 			"2903 Post resource extents type-0x%x: "
6452 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6453 
6454 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6455 	if (!mbox)
6456 		return -ENOMEM;
6457 
6458 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6459 	if (unlikely(rc)) {
6460 		rc = -EIO;
6461 		goto err_exit;
6462 	}
6463 
6464 	/*
6465 	 * Figure out where the response is located.  Then get local pointers
6466 	 * to the response data.  The port does not guarantee to respond to
6467 	 * all extents counts request so update the local variable with the
6468 	 * allocated count from the port.
6469 	 */
6470 	if (emb == LPFC_SLI4_MBX_EMBED) {
6471 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6472 		id_array = &rsrc_ext->u.rsp.id[0];
6473 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6474 	} else {
6475 		virtaddr = mbox->sge_array->addr[0];
6476 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6477 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6478 		id_array = &n_rsrc->id;
6479 	}
6480 
6481 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6482 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6483 
6484 	/*
6485 	 * Based on the resource size and count, correct the base and max
6486 	 * resource values.
6487 	 */
6488 	length = sizeof(struct lpfc_rsrc_blks);
6489 	switch (type) {
6490 	case LPFC_RSC_TYPE_FCOE_RPI:
6491 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6492 						   sizeof(unsigned long),
6493 						   GFP_KERNEL);
6494 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6495 			rc = -ENOMEM;
6496 			goto err_exit;
6497 		}
6498 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6499 						 sizeof(uint16_t),
6500 						 GFP_KERNEL);
6501 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6502 			kfree(phba->sli4_hba.rpi_bmask);
6503 			rc = -ENOMEM;
6504 			goto err_exit;
6505 		}
6506 
6507 		/*
6508 		 * The next_rpi was initialized with the maximum available
6509 		 * count but the port may allocate a smaller number.  Catch
6510 		 * that case and update the next_rpi.
6511 		 */
6512 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6513 
6514 		/* Initialize local ptrs for common extent processing later. */
6515 		bmask = phba->sli4_hba.rpi_bmask;
6516 		ids = phba->sli4_hba.rpi_ids;
6517 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6518 		break;
6519 	case LPFC_RSC_TYPE_FCOE_VPI:
6520 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6521 					  GFP_KERNEL);
6522 		if (unlikely(!phba->vpi_bmask)) {
6523 			rc = -ENOMEM;
6524 			goto err_exit;
6525 		}
6526 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6527 					 GFP_KERNEL);
6528 		if (unlikely(!phba->vpi_ids)) {
6529 			kfree(phba->vpi_bmask);
6530 			rc = -ENOMEM;
6531 			goto err_exit;
6532 		}
6533 
6534 		/* Initialize local ptrs for common extent processing later. */
6535 		bmask = phba->vpi_bmask;
6536 		ids = phba->vpi_ids;
6537 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6538 		break;
6539 	case LPFC_RSC_TYPE_FCOE_XRI:
6540 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6541 						   sizeof(unsigned long),
6542 						   GFP_KERNEL);
6543 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6544 			rc = -ENOMEM;
6545 			goto err_exit;
6546 		}
6547 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6548 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6549 						 sizeof(uint16_t),
6550 						 GFP_KERNEL);
6551 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6552 			kfree(phba->sli4_hba.xri_bmask);
6553 			rc = -ENOMEM;
6554 			goto err_exit;
6555 		}
6556 
6557 		/* Initialize local ptrs for common extent processing later. */
6558 		bmask = phba->sli4_hba.xri_bmask;
6559 		ids = phba->sli4_hba.xri_ids;
6560 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6561 		break;
6562 	case LPFC_RSC_TYPE_FCOE_VFI:
6563 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6564 						   sizeof(unsigned long),
6565 						   GFP_KERNEL);
6566 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6567 			rc = -ENOMEM;
6568 			goto err_exit;
6569 		}
6570 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6571 						 sizeof(uint16_t),
6572 						 GFP_KERNEL);
6573 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6574 			kfree(phba->sli4_hba.vfi_bmask);
6575 			rc = -ENOMEM;
6576 			goto err_exit;
6577 		}
6578 
6579 		/* Initialize local ptrs for common extent processing later. */
6580 		bmask = phba->sli4_hba.vfi_bmask;
6581 		ids = phba->sli4_hba.vfi_ids;
6582 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6583 		break;
6584 	default:
6585 		/* Unsupported Opcode.  Fail call. */
6586 		id_array = NULL;
6587 		bmask = NULL;
6588 		ids = NULL;
6589 		ext_blk_list = NULL;
6590 		goto err_exit;
6591 	}
6592 
6593 	/*
6594 	 * Complete initializing the extent configuration with the
6595 	 * allocated ids assigned to this function.  The bitmask serves
6596 	 * as an index into the array and manages the available ids.  The
6597 	 * array just stores the ids communicated to the port via the wqes.
6598 	 */
6599 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6600 		if ((i % 2) == 0)
6601 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6602 					 &id_array[k]);
6603 		else
6604 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6605 					 &id_array[k]);
6606 
6607 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6608 		if (unlikely(!rsrc_blks)) {
6609 			rc = -ENOMEM;
6610 			kfree(bmask);
6611 			kfree(ids);
6612 			goto err_exit;
6613 		}
6614 		rsrc_blks->rsrc_start = rsrc_id;
6615 		rsrc_blks->rsrc_size = rsrc_size;
6616 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6617 		rsrc_start = rsrc_id;
6618 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6619 			phba->sli4_hba.io_xri_start = rsrc_start +
6620 				lpfc_sli4_get_iocb_cnt(phba);
6621 		}
6622 
6623 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6624 			ids[j] = rsrc_id;
6625 			rsrc_id++;
6626 			j++;
6627 		}
6628 		/* Entire word processed.  Get next word.*/
6629 		if ((i % 2) == 1)
6630 			k++;
6631 	}
6632  err_exit:
6633 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6634 	return rc;
6635 }
6636 
6637 
6638 
6639 /**
6640  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6641  * @phba: Pointer to HBA context object.
6642  * @type: the extent's type.
6643  *
6644  * This function deallocates all extents of a particular resource type.
6645  * SLI4 does not allow for deallocating a particular extent range.  It
6646  * is the caller's responsibility to release all kernel memory resources.
6647  **/
6648 static int
6649 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6650 {
6651 	int rc;
6652 	uint32_t length, mbox_tmo = 0;
6653 	LPFC_MBOXQ_t *mbox;
6654 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6655 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6656 
6657 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6658 	if (!mbox)
6659 		return -ENOMEM;
6660 
6661 	/*
6662 	 * This function sends an embedded mailbox because it only sends the
6663 	 * the resource type.  All extents of this type are released by the
6664 	 * port.
6665 	 */
6666 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6667 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6668 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6669 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6670 			 length, LPFC_SLI4_MBX_EMBED);
6671 
6672 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6673 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6674 					LPFC_SLI4_MBX_EMBED);
6675 	if (unlikely(rc)) {
6676 		rc = -EIO;
6677 		goto out_free_mbox;
6678 	}
6679 	if (!phba->sli4_hba.intr_enable)
6680 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6681 	else {
6682 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6683 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6684 	}
6685 	if (unlikely(rc)) {
6686 		rc = -EIO;
6687 		goto out_free_mbox;
6688 	}
6689 
6690 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6691 	if (bf_get(lpfc_mbox_hdr_status,
6692 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6693 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6694 				"2919 Failed to release resource extents "
6695 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6696 				"Resource memory not released.\n",
6697 				type,
6698 				bf_get(lpfc_mbox_hdr_status,
6699 				    &dealloc_rsrc->header.cfg_shdr.response),
6700 				bf_get(lpfc_mbox_hdr_add_status,
6701 				    &dealloc_rsrc->header.cfg_shdr.response));
6702 		rc = -EIO;
6703 		goto out_free_mbox;
6704 	}
6705 
6706 	/* Release kernel memory resources for the specific type. */
6707 	switch (type) {
6708 	case LPFC_RSC_TYPE_FCOE_VPI:
6709 		kfree(phba->vpi_bmask);
6710 		kfree(phba->vpi_ids);
6711 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6712 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6713 				    &phba->lpfc_vpi_blk_list, list) {
6714 			list_del_init(&rsrc_blk->list);
6715 			kfree(rsrc_blk);
6716 		}
6717 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6718 		break;
6719 	case LPFC_RSC_TYPE_FCOE_XRI:
6720 		kfree(phba->sli4_hba.xri_bmask);
6721 		kfree(phba->sli4_hba.xri_ids);
6722 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6723 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6724 			list_del_init(&rsrc_blk->list);
6725 			kfree(rsrc_blk);
6726 		}
6727 		break;
6728 	case LPFC_RSC_TYPE_FCOE_VFI:
6729 		kfree(phba->sli4_hba.vfi_bmask);
6730 		kfree(phba->sli4_hba.vfi_ids);
6731 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6732 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6733 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6734 			list_del_init(&rsrc_blk->list);
6735 			kfree(rsrc_blk);
6736 		}
6737 		break;
6738 	case LPFC_RSC_TYPE_FCOE_RPI:
6739 		/* RPI bitmask and physical id array are cleaned up earlier. */
6740 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6741 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6742 			list_del_init(&rsrc_blk->list);
6743 			kfree(rsrc_blk);
6744 		}
6745 		break;
6746 	default:
6747 		break;
6748 	}
6749 
6750 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6751 
6752  out_free_mbox:
6753 	mempool_free(mbox, phba->mbox_mem_pool);
6754 	return rc;
6755 }
6756 
6757 static void
6758 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6759 		  uint32_t feature)
6760 {
6761 	uint32_t len;
6762 	u32 sig_freq = 0;
6763 
6764 	len = sizeof(struct lpfc_mbx_set_feature) -
6765 		sizeof(struct lpfc_sli4_cfg_mhdr);
6766 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6767 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6768 			 LPFC_SLI4_MBX_EMBED);
6769 
6770 	switch (feature) {
6771 	case LPFC_SET_UE_RECOVERY:
6772 		bf_set(lpfc_mbx_set_feature_UER,
6773 		       &mbox->u.mqe.un.set_feature, 1);
6774 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6775 		mbox->u.mqe.un.set_feature.param_len = 8;
6776 		break;
6777 	case LPFC_SET_MDS_DIAGS:
6778 		bf_set(lpfc_mbx_set_feature_mds,
6779 		       &mbox->u.mqe.un.set_feature, 1);
6780 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6781 		       &mbox->u.mqe.un.set_feature, 1);
6782 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6783 		mbox->u.mqe.un.set_feature.param_len = 8;
6784 		break;
6785 	case LPFC_SET_CGN_SIGNAL:
6786 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6787 			sig_freq = 0;
6788 		else
6789 			sig_freq = phba->cgn_sig_freq;
6790 
6791 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6792 			bf_set(lpfc_mbx_set_feature_CGN_alarm_freq,
6793 			       &mbox->u.mqe.un.set_feature, sig_freq);
6794 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6795 			       &mbox->u.mqe.un.set_feature, sig_freq);
6796 		}
6797 
6798 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY)
6799 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6800 			       &mbox->u.mqe.un.set_feature, sig_freq);
6801 
6802 		if (phba->cmf_active_mode == LPFC_CFG_OFF ||
6803 		    phba->cgn_reg_signal == EDC_CG_SIG_NOTSUPPORTED)
6804 			sig_freq = 0;
6805 		else
6806 			sig_freq = lpfc_acqe_cgn_frequency;
6807 
6808 		bf_set(lpfc_mbx_set_feature_CGN_acqe_freq,
6809 		       &mbox->u.mqe.un.set_feature, sig_freq);
6810 
6811 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_CGN_SIGNAL;
6812 		mbox->u.mqe.un.set_feature.param_len = 12;
6813 		break;
6814 	case LPFC_SET_DUAL_DUMP:
6815 		bf_set(lpfc_mbx_set_feature_dd,
6816 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6817 		bf_set(lpfc_mbx_set_feature_ddquery,
6818 		       &mbox->u.mqe.un.set_feature, 0);
6819 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6820 		mbox->u.mqe.un.set_feature.param_len = 4;
6821 		break;
6822 	case LPFC_SET_ENABLE_MI:
6823 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_MI;
6824 		mbox->u.mqe.un.set_feature.param_len = 4;
6825 		bf_set(lpfc_mbx_set_feature_milunq, &mbox->u.mqe.un.set_feature,
6826 		       phba->pport->cfg_lun_queue_depth);
6827 		bf_set(lpfc_mbx_set_feature_mi, &mbox->u.mqe.un.set_feature,
6828 		       phba->sli4_hba.pc_sli4_params.mi_ver);
6829 		break;
6830 	case LPFC_SET_LD_SIGNAL:
6831 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_LD_SIGNAL;
6832 		mbox->u.mqe.un.set_feature.param_len = 16;
6833 		bf_set(lpfc_mbx_set_feature_lds_qry,
6834 		       &mbox->u.mqe.un.set_feature, LPFC_QUERY_LDS_OP);
6835 		break;
6836 	case LPFC_SET_ENABLE_CMF:
6837 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_CMF;
6838 		mbox->u.mqe.un.set_feature.param_len = 4;
6839 		bf_set(lpfc_mbx_set_feature_cmf,
6840 		       &mbox->u.mqe.un.set_feature, 1);
6841 		break;
6842 	}
6843 	return;
6844 }
6845 
6846 /**
6847  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6848  * @phba: Pointer to HBA context object.
6849  *
6850  * Disable FW logging into host memory on the adapter. To
6851  * be done before reading logs from the host memory.
6852  **/
6853 void
6854 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6855 {
6856 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6857 
6858 	spin_lock_irq(&phba->ras_fwlog_lock);
6859 	ras_fwlog->state = INACTIVE;
6860 	spin_unlock_irq(&phba->ras_fwlog_lock);
6861 
6862 	/* Disable FW logging to host memory */
6863 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6864 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6865 
6866 	/* Wait 10ms for firmware to stop using DMA buffer */
6867 	usleep_range(10 * 1000, 20 * 1000);
6868 }
6869 
6870 /**
6871  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6872  * @phba: Pointer to HBA context object.
6873  *
6874  * This function is called to free memory allocated for RAS FW logging
6875  * support in the driver.
6876  **/
6877 void
6878 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6879 {
6880 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6881 	struct lpfc_dmabuf *dmabuf, *next;
6882 
6883 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6884 		list_for_each_entry_safe(dmabuf, next,
6885 				    &ras_fwlog->fwlog_buff_list,
6886 				    list) {
6887 			list_del(&dmabuf->list);
6888 			dma_free_coherent(&phba->pcidev->dev,
6889 					  LPFC_RAS_MAX_ENTRY_SIZE,
6890 					  dmabuf->virt, dmabuf->phys);
6891 			kfree(dmabuf);
6892 		}
6893 	}
6894 
6895 	if (ras_fwlog->lwpd.virt) {
6896 		dma_free_coherent(&phba->pcidev->dev,
6897 				  sizeof(uint32_t) * 2,
6898 				  ras_fwlog->lwpd.virt,
6899 				  ras_fwlog->lwpd.phys);
6900 		ras_fwlog->lwpd.virt = NULL;
6901 	}
6902 
6903 	spin_lock_irq(&phba->ras_fwlog_lock);
6904 	ras_fwlog->state = INACTIVE;
6905 	spin_unlock_irq(&phba->ras_fwlog_lock);
6906 }
6907 
6908 /**
6909  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6910  * @phba: Pointer to HBA context object.
6911  * @fwlog_buff_count: Count of buffers to be created.
6912  *
6913  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6914  * to update FW log is posted to the adapter.
6915  * Buffer count is calculated based on module param ras_fwlog_buffsize
6916  * Size of each buffer posted to FW is 64K.
6917  **/
6918 
6919 static int
6920 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6921 			uint32_t fwlog_buff_count)
6922 {
6923 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6924 	struct lpfc_dmabuf *dmabuf;
6925 	int rc = 0, i = 0;
6926 
6927 	/* Initialize List */
6928 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6929 
6930 	/* Allocate memory for the LWPD */
6931 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6932 					    sizeof(uint32_t) * 2,
6933 					    &ras_fwlog->lwpd.phys,
6934 					    GFP_KERNEL);
6935 	if (!ras_fwlog->lwpd.virt) {
6936 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6937 				"6185 LWPD Memory Alloc Failed\n");
6938 
6939 		return -ENOMEM;
6940 	}
6941 
6942 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6943 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6944 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6945 				 GFP_KERNEL);
6946 		if (!dmabuf) {
6947 			rc = -ENOMEM;
6948 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6949 					"6186 Memory Alloc failed FW logging");
6950 			goto free_mem;
6951 		}
6952 
6953 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6954 						  LPFC_RAS_MAX_ENTRY_SIZE,
6955 						  &dmabuf->phys, GFP_KERNEL);
6956 		if (!dmabuf->virt) {
6957 			kfree(dmabuf);
6958 			rc = -ENOMEM;
6959 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6960 					"6187 DMA Alloc Failed FW logging");
6961 			goto free_mem;
6962 		}
6963 		dmabuf->buffer_tag = i;
6964 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6965 	}
6966 
6967 free_mem:
6968 	if (rc)
6969 		lpfc_sli4_ras_dma_free(phba);
6970 
6971 	return rc;
6972 }
6973 
6974 /**
6975  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6976  * @phba: pointer to lpfc hba data structure.
6977  * @pmb: pointer to the driver internal queue element for mailbox command.
6978  *
6979  * Completion handler for driver's RAS MBX command to the device.
6980  **/
6981 static void
6982 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6983 {
6984 	MAILBOX_t *mb;
6985 	union lpfc_sli4_cfg_shdr *shdr;
6986 	uint32_t shdr_status, shdr_add_status;
6987 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6988 
6989 	mb = &pmb->u.mb;
6990 
6991 	shdr = (union lpfc_sli4_cfg_shdr *)
6992 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6993 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6994 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6995 
6996 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6997 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6998 				"6188 FW LOG mailbox "
6999 				"completed with status x%x add_status x%x,"
7000 				" mbx status x%x\n",
7001 				shdr_status, shdr_add_status, mb->mbxStatus);
7002 
7003 		ras_fwlog->ras_hwsupport = false;
7004 		goto disable_ras;
7005 	}
7006 
7007 	spin_lock_irq(&phba->ras_fwlog_lock);
7008 	ras_fwlog->state = ACTIVE;
7009 	spin_unlock_irq(&phba->ras_fwlog_lock);
7010 	mempool_free(pmb, phba->mbox_mem_pool);
7011 
7012 	return;
7013 
7014 disable_ras:
7015 	/* Free RAS DMA memory */
7016 	lpfc_sli4_ras_dma_free(phba);
7017 	mempool_free(pmb, phba->mbox_mem_pool);
7018 }
7019 
7020 /**
7021  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
7022  * @phba: pointer to lpfc hba data structure.
7023  * @fwlog_level: Logging verbosity level.
7024  * @fwlog_enable: Enable/Disable logging.
7025  *
7026  * Initialize memory and post mailbox command to enable FW logging in host
7027  * memory.
7028  **/
7029 int
7030 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
7031 			 uint32_t fwlog_level,
7032 			 uint32_t fwlog_enable)
7033 {
7034 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
7035 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
7036 	struct lpfc_dmabuf *dmabuf;
7037 	LPFC_MBOXQ_t *mbox;
7038 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
7039 	int rc = 0;
7040 
7041 	spin_lock_irq(&phba->ras_fwlog_lock);
7042 	ras_fwlog->state = INACTIVE;
7043 	spin_unlock_irq(&phba->ras_fwlog_lock);
7044 
7045 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
7046 			  phba->cfg_ras_fwlog_buffsize);
7047 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
7048 
7049 	/*
7050 	 * If re-enabling FW logging support use earlier allocated
7051 	 * DMA buffers while posting MBX command.
7052 	 **/
7053 	if (!ras_fwlog->lwpd.virt) {
7054 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
7055 		if (rc) {
7056 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7057 					"6189 FW Log Memory Allocation Failed");
7058 			return rc;
7059 		}
7060 	}
7061 
7062 	/* Setup Mailbox command */
7063 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7064 	if (!mbox) {
7065 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7066 				"6190 RAS MBX Alloc Failed");
7067 		rc = -ENOMEM;
7068 		goto mem_free;
7069 	}
7070 
7071 	ras_fwlog->fw_loglevel = fwlog_level;
7072 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
7073 		sizeof(struct lpfc_sli4_cfg_mhdr));
7074 
7075 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
7076 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
7077 			 len, LPFC_SLI4_MBX_EMBED);
7078 
7079 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
7080 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
7081 	       fwlog_enable);
7082 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
7083 	       ras_fwlog->fw_loglevel);
7084 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
7085 	       ras_fwlog->fw_buffcount);
7086 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
7087 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
7088 
7089 	/* Update DMA buffer address */
7090 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
7091 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
7092 
7093 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
7094 			putPaddrLow(dmabuf->phys);
7095 
7096 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
7097 			putPaddrHigh(dmabuf->phys);
7098 	}
7099 
7100 	/* Update LPWD address */
7101 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
7102 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
7103 
7104 	spin_lock_irq(&phba->ras_fwlog_lock);
7105 	ras_fwlog->state = REG_INPROGRESS;
7106 	spin_unlock_irq(&phba->ras_fwlog_lock);
7107 	mbox->vport = phba->pport;
7108 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
7109 
7110 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
7111 
7112 	if (rc == MBX_NOT_FINISHED) {
7113 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7114 				"6191 FW-Log Mailbox failed. "
7115 				"status %d mbxStatus : x%x", rc,
7116 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
7117 		mempool_free(mbox, phba->mbox_mem_pool);
7118 		rc = -EIO;
7119 		goto mem_free;
7120 	} else
7121 		rc = 0;
7122 mem_free:
7123 	if (rc)
7124 		lpfc_sli4_ras_dma_free(phba);
7125 
7126 	return rc;
7127 }
7128 
7129 /**
7130  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
7131  * @phba: Pointer to HBA context object.
7132  *
7133  * Check if RAS is supported on the adapter and initialize it.
7134  **/
7135 void
7136 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
7137 {
7138 	/* Check RAS FW Log needs to be enabled or not */
7139 	if (lpfc_check_fwlog_support(phba))
7140 		return;
7141 
7142 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
7143 				 LPFC_RAS_ENABLE_LOGGING);
7144 }
7145 
7146 /**
7147  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
7148  * @phba: Pointer to HBA context object.
7149  *
7150  * This function allocates all SLI4 resource identifiers.
7151  **/
7152 int
7153 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
7154 {
7155 	int i, rc, error = 0;
7156 	uint16_t count, base;
7157 	unsigned long longs;
7158 
7159 	if (!phba->sli4_hba.rpi_hdrs_in_use)
7160 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
7161 	if (phba->sli4_hba.extents_in_use) {
7162 		/*
7163 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
7164 		 * resource extent count must be read and allocated before
7165 		 * provisioning the resource id arrays.
7166 		 */
7167 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7168 		    LPFC_IDX_RSRC_RDY) {
7169 			/*
7170 			 * Extent-based resources are set - the driver could
7171 			 * be in a port reset. Figure out if any corrective
7172 			 * actions need to be taken.
7173 			 */
7174 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7175 						 LPFC_RSC_TYPE_FCOE_VFI);
7176 			if (rc != 0)
7177 				error++;
7178 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7179 						 LPFC_RSC_TYPE_FCOE_VPI);
7180 			if (rc != 0)
7181 				error++;
7182 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7183 						 LPFC_RSC_TYPE_FCOE_XRI);
7184 			if (rc != 0)
7185 				error++;
7186 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7187 						 LPFC_RSC_TYPE_FCOE_RPI);
7188 			if (rc != 0)
7189 				error++;
7190 
7191 			/*
7192 			 * It's possible that the number of resources
7193 			 * provided to this port instance changed between
7194 			 * resets.  Detect this condition and reallocate
7195 			 * resources.  Otherwise, there is no action.
7196 			 */
7197 			if (error) {
7198 				lpfc_printf_log(phba, KERN_INFO,
7199 						LOG_MBOX | LOG_INIT,
7200 						"2931 Detected extent resource "
7201 						"change.  Reallocating all "
7202 						"extents.\n");
7203 				rc = lpfc_sli4_dealloc_extent(phba,
7204 						 LPFC_RSC_TYPE_FCOE_VFI);
7205 				rc = lpfc_sli4_dealloc_extent(phba,
7206 						 LPFC_RSC_TYPE_FCOE_VPI);
7207 				rc = lpfc_sli4_dealloc_extent(phba,
7208 						 LPFC_RSC_TYPE_FCOE_XRI);
7209 				rc = lpfc_sli4_dealloc_extent(phba,
7210 						 LPFC_RSC_TYPE_FCOE_RPI);
7211 			} else
7212 				return 0;
7213 		}
7214 
7215 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7216 		if (unlikely(rc))
7217 			goto err_exit;
7218 
7219 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7220 		if (unlikely(rc))
7221 			goto err_exit;
7222 
7223 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7224 		if (unlikely(rc))
7225 			goto err_exit;
7226 
7227 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7228 		if (unlikely(rc))
7229 			goto err_exit;
7230 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7231 		       LPFC_IDX_RSRC_RDY);
7232 		return rc;
7233 	} else {
7234 		/*
7235 		 * The port does not support resource extents.  The XRI, VPI,
7236 		 * VFI, RPI resource ids were determined from READ_CONFIG.
7237 		 * Just allocate the bitmasks and provision the resource id
7238 		 * arrays.  If a port reset is active, the resources don't
7239 		 * need any action - just exit.
7240 		 */
7241 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7242 		    LPFC_IDX_RSRC_RDY) {
7243 			lpfc_sli4_dealloc_resource_identifiers(phba);
7244 			lpfc_sli4_remove_rpis(phba);
7245 		}
7246 		/* RPIs. */
7247 		count = phba->sli4_hba.max_cfg_param.max_rpi;
7248 		if (count <= 0) {
7249 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7250 					"3279 Invalid provisioning of "
7251 					"rpi:%d\n", count);
7252 			rc = -EINVAL;
7253 			goto err_exit;
7254 		}
7255 		base = phba->sli4_hba.max_cfg_param.rpi_base;
7256 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7257 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
7258 						   sizeof(unsigned long),
7259 						   GFP_KERNEL);
7260 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
7261 			rc = -ENOMEM;
7262 			goto err_exit;
7263 		}
7264 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
7265 						 GFP_KERNEL);
7266 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
7267 			rc = -ENOMEM;
7268 			goto free_rpi_bmask;
7269 		}
7270 
7271 		for (i = 0; i < count; i++)
7272 			phba->sli4_hba.rpi_ids[i] = base + i;
7273 
7274 		/* VPIs. */
7275 		count = phba->sli4_hba.max_cfg_param.max_vpi;
7276 		if (count <= 0) {
7277 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7278 					"3280 Invalid provisioning of "
7279 					"vpi:%d\n", count);
7280 			rc = -EINVAL;
7281 			goto free_rpi_ids;
7282 		}
7283 		base = phba->sli4_hba.max_cfg_param.vpi_base;
7284 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7285 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
7286 					  GFP_KERNEL);
7287 		if (unlikely(!phba->vpi_bmask)) {
7288 			rc = -ENOMEM;
7289 			goto free_rpi_ids;
7290 		}
7291 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
7292 					GFP_KERNEL);
7293 		if (unlikely(!phba->vpi_ids)) {
7294 			rc = -ENOMEM;
7295 			goto free_vpi_bmask;
7296 		}
7297 
7298 		for (i = 0; i < count; i++)
7299 			phba->vpi_ids[i] = base + i;
7300 
7301 		/* XRIs. */
7302 		count = phba->sli4_hba.max_cfg_param.max_xri;
7303 		if (count <= 0) {
7304 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7305 					"3281 Invalid provisioning of "
7306 					"xri:%d\n", count);
7307 			rc = -EINVAL;
7308 			goto free_vpi_ids;
7309 		}
7310 		base = phba->sli4_hba.max_cfg_param.xri_base;
7311 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7312 		phba->sli4_hba.xri_bmask = kcalloc(longs,
7313 						   sizeof(unsigned long),
7314 						   GFP_KERNEL);
7315 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
7316 			rc = -ENOMEM;
7317 			goto free_vpi_ids;
7318 		}
7319 		phba->sli4_hba.max_cfg_param.xri_used = 0;
7320 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
7321 						 GFP_KERNEL);
7322 		if (unlikely(!phba->sli4_hba.xri_ids)) {
7323 			rc = -ENOMEM;
7324 			goto free_xri_bmask;
7325 		}
7326 
7327 		for (i = 0; i < count; i++)
7328 			phba->sli4_hba.xri_ids[i] = base + i;
7329 
7330 		/* VFIs. */
7331 		count = phba->sli4_hba.max_cfg_param.max_vfi;
7332 		if (count <= 0) {
7333 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7334 					"3282 Invalid provisioning of "
7335 					"vfi:%d\n", count);
7336 			rc = -EINVAL;
7337 			goto free_xri_ids;
7338 		}
7339 		base = phba->sli4_hba.max_cfg_param.vfi_base;
7340 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7341 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
7342 						   sizeof(unsigned long),
7343 						   GFP_KERNEL);
7344 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
7345 			rc = -ENOMEM;
7346 			goto free_xri_ids;
7347 		}
7348 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
7349 						 GFP_KERNEL);
7350 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
7351 			rc = -ENOMEM;
7352 			goto free_vfi_bmask;
7353 		}
7354 
7355 		for (i = 0; i < count; i++)
7356 			phba->sli4_hba.vfi_ids[i] = base + i;
7357 
7358 		/*
7359 		 * Mark all resources ready.  An HBA reset doesn't need
7360 		 * to reset the initialization.
7361 		 */
7362 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7363 		       LPFC_IDX_RSRC_RDY);
7364 		return 0;
7365 	}
7366 
7367  free_vfi_bmask:
7368 	kfree(phba->sli4_hba.vfi_bmask);
7369 	phba->sli4_hba.vfi_bmask = NULL;
7370  free_xri_ids:
7371 	kfree(phba->sli4_hba.xri_ids);
7372 	phba->sli4_hba.xri_ids = NULL;
7373  free_xri_bmask:
7374 	kfree(phba->sli4_hba.xri_bmask);
7375 	phba->sli4_hba.xri_bmask = NULL;
7376  free_vpi_ids:
7377 	kfree(phba->vpi_ids);
7378 	phba->vpi_ids = NULL;
7379  free_vpi_bmask:
7380 	kfree(phba->vpi_bmask);
7381 	phba->vpi_bmask = NULL;
7382  free_rpi_ids:
7383 	kfree(phba->sli4_hba.rpi_ids);
7384 	phba->sli4_hba.rpi_ids = NULL;
7385  free_rpi_bmask:
7386 	kfree(phba->sli4_hba.rpi_bmask);
7387 	phba->sli4_hba.rpi_bmask = NULL;
7388  err_exit:
7389 	return rc;
7390 }
7391 
7392 /**
7393  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
7394  * @phba: Pointer to HBA context object.
7395  *
7396  * This function allocates the number of elements for the specified
7397  * resource type.
7398  **/
7399 int
7400 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7401 {
7402 	if (phba->sli4_hba.extents_in_use) {
7403 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7404 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7405 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7406 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7407 	} else {
7408 		kfree(phba->vpi_bmask);
7409 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
7410 		kfree(phba->vpi_ids);
7411 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7412 		kfree(phba->sli4_hba.xri_bmask);
7413 		kfree(phba->sli4_hba.xri_ids);
7414 		kfree(phba->sli4_hba.vfi_bmask);
7415 		kfree(phba->sli4_hba.vfi_ids);
7416 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7417 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7418 	}
7419 
7420 	return 0;
7421 }
7422 
7423 /**
7424  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7425  * @phba: Pointer to HBA context object.
7426  * @type: The resource extent type.
7427  * @extnt_cnt: buffer to hold port extent count response
7428  * @extnt_size: buffer to hold port extent size response.
7429  *
7430  * This function calls the port to read the host allocated extents
7431  * for a particular type.
7432  **/
7433 int
7434 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7435 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
7436 {
7437 	bool emb;
7438 	int rc = 0;
7439 	uint16_t curr_blks = 0;
7440 	uint32_t req_len, emb_len;
7441 	uint32_t alloc_len, mbox_tmo;
7442 	struct list_head *blk_list_head;
7443 	struct lpfc_rsrc_blks *rsrc_blk;
7444 	LPFC_MBOXQ_t *mbox;
7445 	void *virtaddr = NULL;
7446 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7447 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7448 	union  lpfc_sli4_cfg_shdr *shdr;
7449 
7450 	switch (type) {
7451 	case LPFC_RSC_TYPE_FCOE_VPI:
7452 		blk_list_head = &phba->lpfc_vpi_blk_list;
7453 		break;
7454 	case LPFC_RSC_TYPE_FCOE_XRI:
7455 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7456 		break;
7457 	case LPFC_RSC_TYPE_FCOE_VFI:
7458 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7459 		break;
7460 	case LPFC_RSC_TYPE_FCOE_RPI:
7461 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7462 		break;
7463 	default:
7464 		return -EIO;
7465 	}
7466 
7467 	/* Count the number of extents currently allocatd for this type. */
7468 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
7469 		if (curr_blks == 0) {
7470 			/*
7471 			 * The GET_ALLOCATED mailbox does not return the size,
7472 			 * just the count.  The size should be just the size
7473 			 * stored in the current allocated block and all sizes
7474 			 * for an extent type are the same so set the return
7475 			 * value now.
7476 			 */
7477 			*extnt_size = rsrc_blk->rsrc_size;
7478 		}
7479 		curr_blks++;
7480 	}
7481 
7482 	/*
7483 	 * Calculate the size of an embedded mailbox.  The uint32_t
7484 	 * accounts for extents-specific word.
7485 	 */
7486 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7487 		sizeof(uint32_t);
7488 
7489 	/*
7490 	 * Presume the allocation and response will fit into an embedded
7491 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7492 	 */
7493 	emb = LPFC_SLI4_MBX_EMBED;
7494 	req_len = emb_len;
7495 	if (req_len > emb_len) {
7496 		req_len = curr_blks * sizeof(uint16_t) +
7497 			sizeof(union lpfc_sli4_cfg_shdr) +
7498 			sizeof(uint32_t);
7499 		emb = LPFC_SLI4_MBX_NEMBED;
7500 	}
7501 
7502 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7503 	if (!mbox)
7504 		return -ENOMEM;
7505 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7506 
7507 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7508 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7509 				     req_len, emb);
7510 	if (alloc_len < req_len) {
7511 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7512 			"2983 Allocated DMA memory size (x%x) is "
7513 			"less than the requested DMA memory "
7514 			"size (x%x)\n", alloc_len, req_len);
7515 		rc = -ENOMEM;
7516 		goto err_exit;
7517 	}
7518 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7519 	if (unlikely(rc)) {
7520 		rc = -EIO;
7521 		goto err_exit;
7522 	}
7523 
7524 	if (!phba->sli4_hba.intr_enable)
7525 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7526 	else {
7527 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7528 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7529 	}
7530 
7531 	if (unlikely(rc)) {
7532 		rc = -EIO;
7533 		goto err_exit;
7534 	}
7535 
7536 	/*
7537 	 * Figure out where the response is located.  Then get local pointers
7538 	 * to the response data.  The port does not guarantee to respond to
7539 	 * all extents counts request so update the local variable with the
7540 	 * allocated count from the port.
7541 	 */
7542 	if (emb == LPFC_SLI4_MBX_EMBED) {
7543 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7544 		shdr = &rsrc_ext->header.cfg_shdr;
7545 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7546 	} else {
7547 		virtaddr = mbox->sge_array->addr[0];
7548 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7549 		shdr = &n_rsrc->cfg_shdr;
7550 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7551 	}
7552 
7553 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7554 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7555 			"2984 Failed to read allocated resources "
7556 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7557 			type,
7558 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7559 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7560 		rc = -EIO;
7561 		goto err_exit;
7562 	}
7563  err_exit:
7564 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7565 	return rc;
7566 }
7567 
7568 /**
7569  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7570  * @phba: pointer to lpfc hba data structure.
7571  * @sgl_list: linked link of sgl buffers to post
7572  * @cnt: number of linked list buffers
7573  *
7574  * This routine walks the list of buffers that have been allocated and
7575  * repost them to the port by using SGL block post. This is needed after a
7576  * pci_function_reset/warm_start or start. It attempts to construct blocks
7577  * of buffer sgls which contains contiguous xris and uses the non-embedded
7578  * SGL block post mailbox commands to post them to the port. For single
7579  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7580  * mailbox command for posting.
7581  *
7582  * Returns: 0 = success, non-zero failure.
7583  **/
7584 static int
7585 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7586 			  struct list_head *sgl_list, int cnt)
7587 {
7588 	struct lpfc_sglq *sglq_entry = NULL;
7589 	struct lpfc_sglq *sglq_entry_next = NULL;
7590 	struct lpfc_sglq *sglq_entry_first = NULL;
7591 	int status = 0, total_cnt;
7592 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7593 	int last_xritag = NO_XRI;
7594 	LIST_HEAD(prep_sgl_list);
7595 	LIST_HEAD(blck_sgl_list);
7596 	LIST_HEAD(allc_sgl_list);
7597 	LIST_HEAD(post_sgl_list);
7598 	LIST_HEAD(free_sgl_list);
7599 
7600 	spin_lock_irq(&phba->hbalock);
7601 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7602 	list_splice_init(sgl_list, &allc_sgl_list);
7603 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7604 	spin_unlock_irq(&phba->hbalock);
7605 
7606 	total_cnt = cnt;
7607 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7608 				 &allc_sgl_list, list) {
7609 		list_del_init(&sglq_entry->list);
7610 		block_cnt++;
7611 		if ((last_xritag != NO_XRI) &&
7612 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7613 			/* a hole in xri block, form a sgl posting block */
7614 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7615 			post_cnt = block_cnt - 1;
7616 			/* prepare list for next posting block */
7617 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7618 			block_cnt = 1;
7619 		} else {
7620 			/* prepare list for next posting block */
7621 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7622 			/* enough sgls for non-embed sgl mbox command */
7623 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7624 				list_splice_init(&prep_sgl_list,
7625 						 &blck_sgl_list);
7626 				post_cnt = block_cnt;
7627 				block_cnt = 0;
7628 			}
7629 		}
7630 		num_posted++;
7631 
7632 		/* keep track of last sgl's xritag */
7633 		last_xritag = sglq_entry->sli4_xritag;
7634 
7635 		/* end of repost sgl list condition for buffers */
7636 		if (num_posted == total_cnt) {
7637 			if (post_cnt == 0) {
7638 				list_splice_init(&prep_sgl_list,
7639 						 &blck_sgl_list);
7640 				post_cnt = block_cnt;
7641 			} else if (block_cnt == 1) {
7642 				status = lpfc_sli4_post_sgl(phba,
7643 						sglq_entry->phys, 0,
7644 						sglq_entry->sli4_xritag);
7645 				if (!status) {
7646 					/* successful, put sgl to posted list */
7647 					list_add_tail(&sglq_entry->list,
7648 						      &post_sgl_list);
7649 				} else {
7650 					/* Failure, put sgl to free list */
7651 					lpfc_printf_log(phba, KERN_WARNING,
7652 						LOG_SLI,
7653 						"3159 Failed to post "
7654 						"sgl, xritag:x%x\n",
7655 						sglq_entry->sli4_xritag);
7656 					list_add_tail(&sglq_entry->list,
7657 						      &free_sgl_list);
7658 					total_cnt--;
7659 				}
7660 			}
7661 		}
7662 
7663 		/* continue until a nembed page worth of sgls */
7664 		if (post_cnt == 0)
7665 			continue;
7666 
7667 		/* post the buffer list sgls as a block */
7668 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7669 						 post_cnt);
7670 
7671 		if (!status) {
7672 			/* success, put sgl list to posted sgl list */
7673 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7674 		} else {
7675 			/* Failure, put sgl list to free sgl list */
7676 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7677 							    struct lpfc_sglq,
7678 							    list);
7679 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7680 					"3160 Failed to post sgl-list, "
7681 					"xritag:x%x-x%x\n",
7682 					sglq_entry_first->sli4_xritag,
7683 					(sglq_entry_first->sli4_xritag +
7684 					 post_cnt - 1));
7685 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7686 			total_cnt -= post_cnt;
7687 		}
7688 
7689 		/* don't reset xirtag due to hole in xri block */
7690 		if (block_cnt == 0)
7691 			last_xritag = NO_XRI;
7692 
7693 		/* reset sgl post count for next round of posting */
7694 		post_cnt = 0;
7695 	}
7696 
7697 	/* free the sgls failed to post */
7698 	lpfc_free_sgl_list(phba, &free_sgl_list);
7699 
7700 	/* push sgls posted to the available list */
7701 	if (!list_empty(&post_sgl_list)) {
7702 		spin_lock_irq(&phba->hbalock);
7703 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7704 		list_splice_init(&post_sgl_list, sgl_list);
7705 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7706 		spin_unlock_irq(&phba->hbalock);
7707 	} else {
7708 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7709 				"3161 Failure to post sgl to port,status %x "
7710 				"blkcnt %d totalcnt %d postcnt %d\n",
7711 				status, block_cnt, total_cnt, post_cnt);
7712 		return -EIO;
7713 	}
7714 
7715 	/* return the number of XRIs actually posted */
7716 	return total_cnt;
7717 }
7718 
7719 /**
7720  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7721  * @phba: pointer to lpfc hba data structure.
7722  *
7723  * This routine walks the list of nvme buffers that have been allocated and
7724  * repost them to the port by using SGL block post. This is needed after a
7725  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7726  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7727  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7728  *
7729  * Returns: 0 = success, non-zero failure.
7730  **/
7731 static int
7732 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7733 {
7734 	LIST_HEAD(post_nblist);
7735 	int num_posted, rc = 0;
7736 
7737 	/* get all NVME buffers need to repost to a local list */
7738 	lpfc_io_buf_flush(phba, &post_nblist);
7739 
7740 	/* post the list of nvme buffer sgls to port if available */
7741 	if (!list_empty(&post_nblist)) {
7742 		num_posted = lpfc_sli4_post_io_sgl_list(
7743 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7744 		/* failed to post any nvme buffer, return error */
7745 		if (num_posted == 0)
7746 			rc = -EIO;
7747 	}
7748 	return rc;
7749 }
7750 
7751 static void
7752 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7753 {
7754 	uint32_t len;
7755 
7756 	len = sizeof(struct lpfc_mbx_set_host_data) -
7757 		sizeof(struct lpfc_sli4_cfg_mhdr);
7758 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7759 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7760 			 LPFC_SLI4_MBX_EMBED);
7761 
7762 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7763 	mbox->u.mqe.un.set_host_data.param_len =
7764 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7765 	snprintf(mbox->u.mqe.un.set_host_data.un.data,
7766 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7767 		 "Linux %s v"LPFC_DRIVER_VERSION,
7768 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7769 }
7770 
7771 int
7772 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7773 		    struct lpfc_queue *drq, int count, int idx)
7774 {
7775 	int rc, i;
7776 	struct lpfc_rqe hrqe;
7777 	struct lpfc_rqe drqe;
7778 	struct lpfc_rqb *rqbp;
7779 	unsigned long flags;
7780 	struct rqb_dmabuf *rqb_buffer;
7781 	LIST_HEAD(rqb_buf_list);
7782 
7783 	rqbp = hrq->rqbp;
7784 	for (i = 0; i < count; i++) {
7785 		spin_lock_irqsave(&phba->hbalock, flags);
7786 		/* IF RQ is already full, don't bother */
7787 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7788 			spin_unlock_irqrestore(&phba->hbalock, flags);
7789 			break;
7790 		}
7791 		spin_unlock_irqrestore(&phba->hbalock, flags);
7792 
7793 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7794 		if (!rqb_buffer)
7795 			break;
7796 		rqb_buffer->hrq = hrq;
7797 		rqb_buffer->drq = drq;
7798 		rqb_buffer->idx = idx;
7799 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7800 	}
7801 
7802 	spin_lock_irqsave(&phba->hbalock, flags);
7803 	while (!list_empty(&rqb_buf_list)) {
7804 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7805 				 hbuf.list);
7806 
7807 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7808 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7809 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7810 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7811 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7812 		if (rc < 0) {
7813 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7814 					"6421 Cannot post to HRQ %d: %x %x %x "
7815 					"DRQ %x %x\n",
7816 					hrq->queue_id,
7817 					hrq->host_index,
7818 					hrq->hba_index,
7819 					hrq->entry_count,
7820 					drq->host_index,
7821 					drq->hba_index);
7822 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7823 		} else {
7824 			list_add_tail(&rqb_buffer->hbuf.list,
7825 				      &rqbp->rqb_buffer_list);
7826 			rqbp->buffer_count++;
7827 		}
7828 	}
7829 	spin_unlock_irqrestore(&phba->hbalock, flags);
7830 	return 1;
7831 }
7832 
7833 static void
7834 lpfc_mbx_cmpl_read_lds_params(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7835 {
7836 	union lpfc_sli4_cfg_shdr *shdr;
7837 	u32 shdr_status, shdr_add_status;
7838 
7839 	shdr = (union lpfc_sli4_cfg_shdr *)
7840 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7841 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7842 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7843 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7844 		lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT | LOG_MBOX,
7845 				"4622 SET_FEATURE (x%x) mbox failed, "
7846 				"status x%x add_status x%x, mbx status x%x\n",
7847 				LPFC_SET_LD_SIGNAL, shdr_status,
7848 				shdr_add_status, pmb->u.mb.mbxStatus);
7849 		phba->degrade_activate_threshold = 0;
7850 		phba->degrade_deactivate_threshold = 0;
7851 		phba->fec_degrade_interval = 0;
7852 		goto out;
7853 	}
7854 
7855 	phba->degrade_activate_threshold = pmb->u.mqe.un.set_feature.word7;
7856 	phba->degrade_deactivate_threshold = pmb->u.mqe.un.set_feature.word8;
7857 	phba->fec_degrade_interval = pmb->u.mqe.un.set_feature.word10;
7858 
7859 	lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT,
7860 			"4624 Success: da x%x dd x%x interval x%x\n",
7861 			phba->degrade_activate_threshold,
7862 			phba->degrade_deactivate_threshold,
7863 			phba->fec_degrade_interval);
7864 out:
7865 	mempool_free(pmb, phba->mbox_mem_pool);
7866 }
7867 
7868 int
7869 lpfc_read_lds_params(struct lpfc_hba *phba)
7870 {
7871 	LPFC_MBOXQ_t *mboxq;
7872 	int rc;
7873 
7874 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7875 	if (!mboxq)
7876 		return -ENOMEM;
7877 
7878 	lpfc_set_features(phba, mboxq, LPFC_SET_LD_SIGNAL);
7879 	mboxq->vport = phba->pport;
7880 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_lds_params;
7881 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7882 	if (rc == MBX_NOT_FINISHED) {
7883 		mempool_free(mboxq, phba->mbox_mem_pool);
7884 		return -EIO;
7885 	}
7886 	return 0;
7887 }
7888 
7889 static void
7890 lpfc_mbx_cmpl_cgn_set_ftrs(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7891 {
7892 	struct lpfc_vport *vport = pmb->vport;
7893 	union lpfc_sli4_cfg_shdr *shdr;
7894 	u32 shdr_status, shdr_add_status;
7895 	u32 sig, acqe;
7896 
7897 	/* Two outcomes. (1) Set featurs was successul and EDC negotiation
7898 	 * is done. (2) Mailbox failed and send FPIN support only.
7899 	 */
7900 	shdr = (union lpfc_sli4_cfg_shdr *)
7901 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7902 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7903 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7904 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7905 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
7906 				"2516 CGN SET_FEATURE mbox failed with "
7907 				"status x%x add_status x%x, mbx status x%x "
7908 				"Reset Congestion to FPINs only\n",
7909 				shdr_status, shdr_add_status,
7910 				pmb->u.mb.mbxStatus);
7911 		/* If there is a mbox error, move on to RDF */
7912 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7913 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7914 		goto out;
7915 	}
7916 
7917 	/* Zero out Congestion Signal ACQE counter */
7918 	phba->cgn_acqe_cnt = 0;
7919 
7920 	acqe = bf_get(lpfc_mbx_set_feature_CGN_acqe_freq,
7921 		      &pmb->u.mqe.un.set_feature);
7922 	sig = bf_get(lpfc_mbx_set_feature_CGN_warn_freq,
7923 		     &pmb->u.mqe.un.set_feature);
7924 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7925 			"4620 SET_FEATURES Success: Freq: %ds %dms "
7926 			" Reg: x%x x%x\n", acqe, sig,
7927 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7928 out:
7929 	mempool_free(pmb, phba->mbox_mem_pool);
7930 
7931 	/* Register for FPIN events from the fabric now that the
7932 	 * EDC common_set_features has completed.
7933 	 */
7934 	lpfc_issue_els_rdf(vport, 0);
7935 }
7936 
7937 int
7938 lpfc_config_cgn_signal(struct lpfc_hba *phba)
7939 {
7940 	LPFC_MBOXQ_t *mboxq;
7941 	u32 rc;
7942 
7943 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7944 	if (!mboxq)
7945 		goto out_rdf;
7946 
7947 	lpfc_set_features(phba, mboxq, LPFC_SET_CGN_SIGNAL);
7948 	mboxq->vport = phba->pport;
7949 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_cgn_set_ftrs;
7950 
7951 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7952 			"4621 SET_FEATURES: FREQ sig x%x acqe x%x: "
7953 			"Reg: x%x x%x\n",
7954 			phba->cgn_sig_freq, lpfc_acqe_cgn_frequency,
7955 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7956 
7957 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7958 	if (rc == MBX_NOT_FINISHED)
7959 		goto out;
7960 	return 0;
7961 
7962 out:
7963 	mempool_free(mboxq, phba->mbox_mem_pool);
7964 out_rdf:
7965 	/* If there is a mbox error, move on to RDF */
7966 	phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7967 	phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7968 	lpfc_issue_els_rdf(phba->pport, 0);
7969 	return -EIO;
7970 }
7971 
7972 /**
7973  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7974  * @phba: pointer to lpfc hba data structure.
7975  *
7976  * This routine initializes the per-eq idle_stat to dynamically dictate
7977  * polling decisions.
7978  *
7979  * Return codes:
7980  *   None
7981  **/
7982 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
7983 {
7984 	int i;
7985 	struct lpfc_sli4_hdw_queue *hdwq;
7986 	struct lpfc_queue *eq;
7987 	struct lpfc_idle_stat *idle_stat;
7988 	u64 wall;
7989 
7990 	for_each_present_cpu(i) {
7991 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
7992 		eq = hdwq->hba_eq;
7993 
7994 		/* Skip if we've already handled this eq's primary CPU */
7995 		if (eq->chann != i)
7996 			continue;
7997 
7998 		idle_stat = &phba->sli4_hba.idle_stat[i];
7999 
8000 		idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
8001 		idle_stat->prev_wall = wall;
8002 
8003 		if (phba->nvmet_support ||
8004 		    phba->cmf_active_mode != LPFC_CFG_OFF ||
8005 		    phba->intr_type != MSIX)
8006 			eq->poll_mode = LPFC_QUEUE_WORK;
8007 		else
8008 			eq->poll_mode = LPFC_THREADED_IRQ;
8009 	}
8010 
8011 	if (!phba->nvmet_support && phba->intr_type == MSIX)
8012 		schedule_delayed_work(&phba->idle_stat_delay_work,
8013 				      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
8014 }
8015 
8016 static void lpfc_sli4_dip(struct lpfc_hba *phba)
8017 {
8018 	uint32_t if_type;
8019 
8020 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
8021 	if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
8022 	    if_type == LPFC_SLI_INTF_IF_TYPE_6) {
8023 		struct lpfc_register reg_data;
8024 
8025 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
8026 			       &reg_data.word0))
8027 			return;
8028 
8029 		if (bf_get(lpfc_sliport_status_dip, &reg_data))
8030 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8031 					"2904 Firmware Dump Image Present"
8032 					" on Adapter");
8033 	}
8034 }
8035 
8036 /**
8037  * lpfc_rx_monitor_create_ring - Initialize ring buffer for rx_monitor
8038  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8039  * @entries: Number of rx_info_entry objects to allocate in ring
8040  *
8041  * Return:
8042  * 0 - Success
8043  * ENOMEM - Failure to kmalloc
8044  **/
8045 int lpfc_rx_monitor_create_ring(struct lpfc_rx_info_monitor *rx_monitor,
8046 				u32 entries)
8047 {
8048 	rx_monitor->ring = kmalloc_array(entries, sizeof(struct rx_info_entry),
8049 					 GFP_KERNEL);
8050 	if (!rx_monitor->ring)
8051 		return -ENOMEM;
8052 
8053 	rx_monitor->head_idx = 0;
8054 	rx_monitor->tail_idx = 0;
8055 	spin_lock_init(&rx_monitor->lock);
8056 	rx_monitor->entries = entries;
8057 
8058 	return 0;
8059 }
8060 
8061 /**
8062  * lpfc_rx_monitor_destroy_ring - Free ring buffer for rx_monitor
8063  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8064  *
8065  * Called after cancellation of cmf_timer.
8066  **/
8067 void lpfc_rx_monitor_destroy_ring(struct lpfc_rx_info_monitor *rx_monitor)
8068 {
8069 	kfree(rx_monitor->ring);
8070 	rx_monitor->ring = NULL;
8071 	rx_monitor->entries = 0;
8072 	rx_monitor->head_idx = 0;
8073 	rx_monitor->tail_idx = 0;
8074 }
8075 
8076 /**
8077  * lpfc_rx_monitor_record - Insert an entry into rx_monitor's ring
8078  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8079  * @entry: Pointer to rx_info_entry
8080  *
8081  * Used to insert an rx_info_entry into rx_monitor's ring.  Note that this is a
8082  * deep copy of rx_info_entry not a shallow copy of the rx_info_entry ptr.
8083  *
8084  * This is called from lpfc_cmf_timer, which is in timer/softirq context.
8085  *
8086  * In cases of old data overflow, we do a best effort of FIFO order.
8087  **/
8088 void lpfc_rx_monitor_record(struct lpfc_rx_info_monitor *rx_monitor,
8089 			    struct rx_info_entry *entry)
8090 {
8091 	struct rx_info_entry *ring = rx_monitor->ring;
8092 	u32 *head_idx = &rx_monitor->head_idx;
8093 	u32 *tail_idx = &rx_monitor->tail_idx;
8094 	spinlock_t *ring_lock = &rx_monitor->lock;
8095 	u32 ring_size = rx_monitor->entries;
8096 
8097 	spin_lock(ring_lock);
8098 	memcpy(&ring[*tail_idx], entry, sizeof(*entry));
8099 	*tail_idx = (*tail_idx + 1) % ring_size;
8100 
8101 	/* Best effort of FIFO saved data */
8102 	if (*tail_idx == *head_idx)
8103 		*head_idx = (*head_idx + 1) % ring_size;
8104 
8105 	spin_unlock(ring_lock);
8106 }
8107 
8108 /**
8109  * lpfc_rx_monitor_report - Read out rx_monitor's ring
8110  * @phba: Pointer to lpfc_hba object
8111  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8112  * @buf: Pointer to char buffer that will contain rx monitor info data
8113  * @buf_len: Length buf including null char
8114  * @max_read_entries: Maximum number of entries to read out of ring
8115  *
8116  * Used to dump/read what's in rx_monitor's ring buffer.
8117  *
8118  * If buf is NULL || buf_len == 0, then it is implied that we want to log the
8119  * information to kmsg instead of filling out buf.
8120  *
8121  * Return:
8122  * Number of entries read out of the ring
8123  **/
8124 u32 lpfc_rx_monitor_report(struct lpfc_hba *phba,
8125 			   struct lpfc_rx_info_monitor *rx_monitor, char *buf,
8126 			   u32 buf_len, u32 max_read_entries)
8127 {
8128 	struct rx_info_entry *ring = rx_monitor->ring;
8129 	struct rx_info_entry *entry;
8130 	u32 *head_idx = &rx_monitor->head_idx;
8131 	u32 *tail_idx = &rx_monitor->tail_idx;
8132 	spinlock_t *ring_lock = &rx_monitor->lock;
8133 	u32 ring_size = rx_monitor->entries;
8134 	u32 cnt = 0;
8135 	char tmp[DBG_LOG_STR_SZ] = {0};
8136 	bool log_to_kmsg = (!buf || !buf_len) ? true : false;
8137 
8138 	if (!log_to_kmsg) {
8139 		/* clear the buffer to be sure */
8140 		memset(buf, 0, buf_len);
8141 
8142 		scnprintf(buf, buf_len, "\t%-16s%-16s%-16s%-16s%-8s%-8s%-8s"
8143 					"%-8s%-8s%-8s%-16s\n",
8144 					"MaxBPI", "Tot_Data_CMF",
8145 					"Tot_Data_Cmd", "Tot_Data_Cmpl",
8146 					"Lat(us)", "Avg_IO", "Max_IO", "Bsy",
8147 					"IO_cnt", "Info", "BWutil(ms)");
8148 	}
8149 
8150 	/* Needs to be _irq because record is called from timer interrupt
8151 	 * context
8152 	 */
8153 	spin_lock_irq(ring_lock);
8154 	while (*head_idx != *tail_idx) {
8155 		entry = &ring[*head_idx];
8156 
8157 		/* Read out this entry's data. */
8158 		if (!log_to_kmsg) {
8159 			/* If !log_to_kmsg, then store to buf. */
8160 			scnprintf(tmp, sizeof(tmp),
8161 				  "%03d:\t%-16llu%-16llu%-16llu%-16llu%-8llu"
8162 				  "%-8llu%-8llu%-8u%-8u%-8u%u(%u)\n",
8163 				  *head_idx, entry->max_bytes_per_interval,
8164 				  entry->cmf_bytes, entry->total_bytes,
8165 				  entry->rcv_bytes, entry->avg_io_latency,
8166 				  entry->avg_io_size, entry->max_read_cnt,
8167 				  entry->cmf_busy, entry->io_cnt,
8168 				  entry->cmf_info, entry->timer_utilization,
8169 				  entry->timer_interval);
8170 
8171 			/* Check for buffer overflow */
8172 			if ((strlen(buf) + strlen(tmp)) >= buf_len)
8173 				break;
8174 
8175 			/* Append entry's data to buffer */
8176 			strlcat(buf, tmp, buf_len);
8177 		} else {
8178 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
8179 					"4410 %02u: MBPI %llu Xmit %llu "
8180 					"Cmpl %llu Lat %llu ASz %llu Info %02u "
8181 					"BWUtil %u Int %u slot %u\n",
8182 					cnt, entry->max_bytes_per_interval,
8183 					entry->total_bytes, entry->rcv_bytes,
8184 					entry->avg_io_latency,
8185 					entry->avg_io_size, entry->cmf_info,
8186 					entry->timer_utilization,
8187 					entry->timer_interval, *head_idx);
8188 		}
8189 
8190 		*head_idx = (*head_idx + 1) % ring_size;
8191 
8192 		/* Don't feed more than max_read_entries */
8193 		cnt++;
8194 		if (cnt >= max_read_entries)
8195 			break;
8196 	}
8197 	spin_unlock_irq(ring_lock);
8198 
8199 	return cnt;
8200 }
8201 
8202 /**
8203  * lpfc_cmf_setup - Initialize idle_stat tracking
8204  * @phba: Pointer to HBA context object.
8205  *
8206  * This is called from HBA setup during driver load or when the HBA
8207  * comes online. this does all the initialization to support CMF and MI.
8208  **/
8209 static int
8210 lpfc_cmf_setup(struct lpfc_hba *phba)
8211 {
8212 	LPFC_MBOXQ_t *mboxq;
8213 	struct lpfc_dmabuf *mp;
8214 	struct lpfc_pc_sli4_params *sli4_params;
8215 	int rc, cmf, mi_ver;
8216 
8217 	rc = lpfc_sli4_refresh_params(phba);
8218 	if (unlikely(rc))
8219 		return rc;
8220 
8221 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8222 	if (!mboxq)
8223 		return -ENOMEM;
8224 
8225 	sli4_params = &phba->sli4_hba.pc_sli4_params;
8226 
8227 	/* Always try to enable MI feature if we can */
8228 	if (sli4_params->mi_ver) {
8229 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_MI);
8230 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8231 		mi_ver = bf_get(lpfc_mbx_set_feature_mi,
8232 				 &mboxq->u.mqe.un.set_feature);
8233 
8234 		if (rc == MBX_SUCCESS) {
8235 			if (mi_ver) {
8236 				lpfc_printf_log(phba,
8237 						KERN_WARNING, LOG_CGN_MGMT,
8238 						"6215 MI is enabled\n");
8239 				sli4_params->mi_ver = mi_ver;
8240 			} else {
8241 				lpfc_printf_log(phba,
8242 						KERN_WARNING, LOG_CGN_MGMT,
8243 						"6338 MI is disabled\n");
8244 				sli4_params->mi_ver = 0;
8245 			}
8246 		} else {
8247 			/* mi_ver is already set from GET_SLI4_PARAMETERS */
8248 			lpfc_printf_log(phba, KERN_INFO,
8249 					LOG_CGN_MGMT | LOG_INIT,
8250 					"6245 Enable MI Mailbox x%x (x%x/x%x) "
8251 					"failed, rc:x%x mi:x%x\n",
8252 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8253 					lpfc_sli_config_mbox_subsys_get
8254 						(phba, mboxq),
8255 					lpfc_sli_config_mbox_opcode_get
8256 						(phba, mboxq),
8257 					rc, sli4_params->mi_ver);
8258 		}
8259 	} else {
8260 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8261 				"6217 MI is disabled\n");
8262 	}
8263 
8264 	/* Ensure FDMI is enabled for MI if enable_mi is set */
8265 	if (sli4_params->mi_ver)
8266 		phba->cfg_fdmi_on = LPFC_FDMI_SUPPORT;
8267 
8268 	/* Always try to enable CMF feature if we can */
8269 	if (sli4_params->cmf) {
8270 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_CMF);
8271 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8272 		cmf = bf_get(lpfc_mbx_set_feature_cmf,
8273 			     &mboxq->u.mqe.un.set_feature);
8274 		if (rc == MBX_SUCCESS && cmf) {
8275 			lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8276 					"6218 CMF is enabled: mode %d\n",
8277 					phba->cmf_active_mode);
8278 		} else {
8279 			lpfc_printf_log(phba, KERN_WARNING,
8280 					LOG_CGN_MGMT | LOG_INIT,
8281 					"6219 Enable CMF Mailbox x%x (x%x/x%x) "
8282 					"failed, rc:x%x dd:x%x\n",
8283 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8284 					lpfc_sli_config_mbox_subsys_get
8285 						(phba, mboxq),
8286 					lpfc_sli_config_mbox_opcode_get
8287 						(phba, mboxq),
8288 					rc, cmf);
8289 			sli4_params->cmf = 0;
8290 			phba->cmf_active_mode = LPFC_CFG_OFF;
8291 			goto no_cmf;
8292 		}
8293 
8294 		/* Allocate Congestion Information Buffer */
8295 		if (!phba->cgn_i) {
8296 			mp = kmalloc(sizeof(*mp), GFP_KERNEL);
8297 			if (mp)
8298 				mp->virt = dma_alloc_coherent
8299 						(&phba->pcidev->dev,
8300 						sizeof(struct lpfc_cgn_info),
8301 						&mp->phys, GFP_KERNEL);
8302 			if (!mp || !mp->virt) {
8303 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8304 						"2640 Failed to alloc memory "
8305 						"for Congestion Info\n");
8306 				kfree(mp);
8307 				sli4_params->cmf = 0;
8308 				phba->cmf_active_mode = LPFC_CFG_OFF;
8309 				goto no_cmf;
8310 			}
8311 			phba->cgn_i = mp;
8312 
8313 			/* initialize congestion buffer info */
8314 			lpfc_init_congestion_buf(phba);
8315 			lpfc_init_congestion_stat(phba);
8316 
8317 			/* Zero out Congestion Signal counters */
8318 			atomic64_set(&phba->cgn_acqe_stat.alarm, 0);
8319 			atomic64_set(&phba->cgn_acqe_stat.warn, 0);
8320 		}
8321 
8322 		rc = lpfc_sli4_cgn_params_read(phba);
8323 		if (rc < 0) {
8324 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8325 					"6242 Error reading Cgn Params (%d)\n",
8326 					rc);
8327 			/* Ensure CGN Mode is off */
8328 			sli4_params->cmf = 0;
8329 		} else if (!rc) {
8330 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8331 					"6243 CGN Event empty object.\n");
8332 			/* Ensure CGN Mode is off */
8333 			sli4_params->cmf = 0;
8334 		}
8335 	} else {
8336 no_cmf:
8337 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8338 				"6220 CMF is disabled\n");
8339 	}
8340 
8341 	/* Only register congestion buffer with firmware if BOTH
8342 	 * CMF and E2E are enabled.
8343 	 */
8344 	if (sli4_params->cmf && sli4_params->mi_ver) {
8345 		rc = lpfc_reg_congestion_buf(phba);
8346 		if (rc) {
8347 			dma_free_coherent(&phba->pcidev->dev,
8348 					  sizeof(struct lpfc_cgn_info),
8349 					  phba->cgn_i->virt, phba->cgn_i->phys);
8350 			kfree(phba->cgn_i);
8351 			phba->cgn_i = NULL;
8352 			/* Ensure CGN Mode is off */
8353 			phba->cmf_active_mode = LPFC_CFG_OFF;
8354 			sli4_params->cmf = 0;
8355 			return 0;
8356 		}
8357 	}
8358 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8359 			"6470 Setup MI version %d CMF %d mode %d\n",
8360 			sli4_params->mi_ver, sli4_params->cmf,
8361 			phba->cmf_active_mode);
8362 
8363 	mempool_free(mboxq, phba->mbox_mem_pool);
8364 
8365 	/* Initialize atomic counters */
8366 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
8367 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
8368 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
8369 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
8370 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
8371 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
8372 	atomic64_set(&phba->cgn_latency_evt, 0);
8373 
8374 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
8375 
8376 	/* Allocate RX Monitor Buffer */
8377 	if (!phba->rx_monitor) {
8378 		phba->rx_monitor = kzalloc(sizeof(*phba->rx_monitor),
8379 					   GFP_KERNEL);
8380 
8381 		if (!phba->rx_monitor) {
8382 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8383 					"2644 Failed to alloc memory "
8384 					"for RX Monitor Buffer\n");
8385 			return -ENOMEM;
8386 		}
8387 
8388 		/* Instruct the rx_monitor object to instantiate its ring */
8389 		if (lpfc_rx_monitor_create_ring(phba->rx_monitor,
8390 						LPFC_MAX_RXMONITOR_ENTRY)) {
8391 			kfree(phba->rx_monitor);
8392 			phba->rx_monitor = NULL;
8393 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8394 					"2645 Failed to alloc memory "
8395 					"for RX Monitor's Ring\n");
8396 			return -ENOMEM;
8397 		}
8398 	}
8399 
8400 	return 0;
8401 }
8402 
8403 static int
8404 lpfc_set_host_tm(struct lpfc_hba *phba)
8405 {
8406 	LPFC_MBOXQ_t *mboxq;
8407 	uint32_t len, rc;
8408 	struct timespec64 cur_time;
8409 	struct tm broken;
8410 	uint32_t month, day, year;
8411 	uint32_t hour, minute, second;
8412 	struct lpfc_mbx_set_host_date_time *tm;
8413 
8414 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8415 	if (!mboxq)
8416 		return -ENOMEM;
8417 
8418 	len = sizeof(struct lpfc_mbx_set_host_data) -
8419 		sizeof(struct lpfc_sli4_cfg_mhdr);
8420 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
8421 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
8422 			 LPFC_SLI4_MBX_EMBED);
8423 
8424 	mboxq->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_DATE_TIME;
8425 	mboxq->u.mqe.un.set_host_data.param_len =
8426 			sizeof(struct lpfc_mbx_set_host_date_time);
8427 	tm = &mboxq->u.mqe.un.set_host_data.un.tm;
8428 	ktime_get_real_ts64(&cur_time);
8429 	time64_to_tm(cur_time.tv_sec, 0, &broken);
8430 	month = broken.tm_mon + 1;
8431 	day = broken.tm_mday;
8432 	year = broken.tm_year - 100;
8433 	hour = broken.tm_hour;
8434 	minute = broken.tm_min;
8435 	second = broken.tm_sec;
8436 	bf_set(lpfc_mbx_set_host_month, tm, month);
8437 	bf_set(lpfc_mbx_set_host_day, tm, day);
8438 	bf_set(lpfc_mbx_set_host_year, tm, year);
8439 	bf_set(lpfc_mbx_set_host_hour, tm, hour);
8440 	bf_set(lpfc_mbx_set_host_min, tm, minute);
8441 	bf_set(lpfc_mbx_set_host_sec, tm, second);
8442 
8443 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8444 	mempool_free(mboxq, phba->mbox_mem_pool);
8445 	return rc;
8446 }
8447 
8448 /**
8449  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
8450  * @phba: Pointer to HBA context object.
8451  *
8452  * This function is the main SLI4 device initialization PCI function. This
8453  * function is called by the HBA initialization code, HBA reset code and
8454  * HBA error attention handler code. Caller is not required to hold any
8455  * locks.
8456  **/
8457 int
8458 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
8459 {
8460 	int rc, i, cnt, len, dd;
8461 	LPFC_MBOXQ_t *mboxq;
8462 	struct lpfc_mqe *mqe;
8463 	uint8_t *vpd;
8464 	uint32_t vpd_size;
8465 	uint32_t ftr_rsp = 0;
8466 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
8467 	struct lpfc_vport *vport = phba->pport;
8468 	struct lpfc_dmabuf *mp;
8469 	struct lpfc_rqb *rqbp;
8470 	u32 flg;
8471 
8472 	/* Perform a PCI function reset to start from clean */
8473 	rc = lpfc_pci_function_reset(phba);
8474 	if (unlikely(rc))
8475 		return -ENODEV;
8476 
8477 	/* Check the HBA Host Status Register for readyness */
8478 	rc = lpfc_sli4_post_status_check(phba);
8479 	if (unlikely(rc))
8480 		return -ENODEV;
8481 	else {
8482 		spin_lock_irq(&phba->hbalock);
8483 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
8484 		flg = phba->sli.sli_flag;
8485 		spin_unlock_irq(&phba->hbalock);
8486 		/* Allow a little time after setting SLI_ACTIVE for any polled
8487 		 * MBX commands to complete via BSG.
8488 		 */
8489 		for (i = 0; i < 50 && (flg & LPFC_SLI_MBOX_ACTIVE); i++) {
8490 			msleep(20);
8491 			spin_lock_irq(&phba->hbalock);
8492 			flg = phba->sli.sli_flag;
8493 			spin_unlock_irq(&phba->hbalock);
8494 		}
8495 	}
8496 	phba->hba_flag &= ~HBA_SETUP;
8497 
8498 	lpfc_sli4_dip(phba);
8499 
8500 	/*
8501 	 * Allocate a single mailbox container for initializing the
8502 	 * port.
8503 	 */
8504 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8505 	if (!mboxq)
8506 		return -ENOMEM;
8507 
8508 	/* Issue READ_REV to collect vpd and FW information. */
8509 	vpd_size = SLI4_PAGE_SIZE;
8510 	vpd = kzalloc(vpd_size, GFP_KERNEL);
8511 	if (!vpd) {
8512 		rc = -ENOMEM;
8513 		goto out_free_mbox;
8514 	}
8515 
8516 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
8517 	if (unlikely(rc)) {
8518 		kfree(vpd);
8519 		goto out_free_mbox;
8520 	}
8521 
8522 	mqe = &mboxq->u.mqe;
8523 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
8524 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
8525 		phba->hba_flag |= HBA_FCOE_MODE;
8526 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
8527 	} else {
8528 		phba->hba_flag &= ~HBA_FCOE_MODE;
8529 	}
8530 
8531 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
8532 		LPFC_DCBX_CEE_MODE)
8533 		phba->hba_flag |= HBA_FIP_SUPPORT;
8534 	else
8535 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
8536 
8537 	phba->hba_flag &= ~HBA_IOQ_FLUSH;
8538 
8539 	if (phba->sli_rev != LPFC_SLI_REV4) {
8540 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8541 			"0376 READ_REV Error. SLI Level %d "
8542 			"FCoE enabled %d\n",
8543 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
8544 		rc = -EIO;
8545 		kfree(vpd);
8546 		goto out_free_mbox;
8547 	}
8548 
8549 	rc = lpfc_set_host_tm(phba);
8550 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
8551 			"6468 Set host date / time: Status x%x:\n", rc);
8552 
8553 	/*
8554 	 * Continue initialization with default values even if driver failed
8555 	 * to read FCoE param config regions, only read parameters if the
8556 	 * board is FCoE
8557 	 */
8558 	if (phba->hba_flag & HBA_FCOE_MODE &&
8559 	    lpfc_sli4_read_fcoe_params(phba))
8560 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
8561 			"2570 Failed to read FCoE parameters\n");
8562 
8563 	/*
8564 	 * Retrieve sli4 device physical port name, failure of doing it
8565 	 * is considered as non-fatal.
8566 	 */
8567 	rc = lpfc_sli4_retrieve_pport_name(phba);
8568 	if (!rc)
8569 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8570 				"3080 Successful retrieving SLI4 device "
8571 				"physical port name: %s.\n", phba->Port);
8572 
8573 	rc = lpfc_sli4_get_ctl_attr(phba);
8574 	if (!rc)
8575 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8576 				"8351 Successful retrieving SLI4 device "
8577 				"CTL ATTR\n");
8578 
8579 	/*
8580 	 * Evaluate the read rev and vpd data. Populate the driver
8581 	 * state with the results. If this routine fails, the failure
8582 	 * is not fatal as the driver will use generic values.
8583 	 */
8584 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
8585 	if (unlikely(!rc)) {
8586 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8587 				"0377 Error %d parsing vpd. "
8588 				"Using defaults.\n", rc);
8589 		rc = 0;
8590 	}
8591 	kfree(vpd);
8592 
8593 	/* Save information as VPD data */
8594 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
8595 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
8596 
8597 	/*
8598 	 * This is because first G7 ASIC doesn't support the standard
8599 	 * 0x5a NVME cmd descriptor type/subtype
8600 	 */
8601 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8602 			LPFC_SLI_INTF_IF_TYPE_6) &&
8603 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
8604 	    (phba->vpd.rev.smRev == 0) &&
8605 	    (phba->cfg_nvme_embed_cmd == 1))
8606 		phba->cfg_nvme_embed_cmd = 0;
8607 
8608 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
8609 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
8610 					 &mqe->un.read_rev);
8611 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
8612 				       &mqe->un.read_rev);
8613 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
8614 					    &mqe->un.read_rev);
8615 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
8616 					   &mqe->un.read_rev);
8617 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
8618 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
8619 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
8620 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
8621 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
8622 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
8623 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8624 			"(%d):0380 READ_REV Status x%x "
8625 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
8626 			mboxq->vport ? mboxq->vport->vpi : 0,
8627 			bf_get(lpfc_mqe_status, mqe),
8628 			phba->vpd.rev.opFwName,
8629 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
8630 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
8631 
8632 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8633 	    LPFC_SLI_INTF_IF_TYPE_0) {
8634 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
8635 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8636 		if (rc == MBX_SUCCESS) {
8637 			phba->hba_flag |= HBA_RECOVERABLE_UE;
8638 			/* Set 1Sec interval to detect UE */
8639 			phba->eratt_poll_interval = 1;
8640 			phba->sli4_hba.ue_to_sr = bf_get(
8641 					lpfc_mbx_set_feature_UESR,
8642 					&mboxq->u.mqe.un.set_feature);
8643 			phba->sli4_hba.ue_to_rp = bf_get(
8644 					lpfc_mbx_set_feature_UERP,
8645 					&mboxq->u.mqe.un.set_feature);
8646 		}
8647 	}
8648 
8649 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
8650 		/* Enable MDS Diagnostics only if the SLI Port supports it */
8651 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
8652 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8653 		if (rc != MBX_SUCCESS)
8654 			phba->mds_diags_support = 0;
8655 	}
8656 
8657 	/*
8658 	 * Discover the port's supported feature set and match it against the
8659 	 * hosts requests.
8660 	 */
8661 	lpfc_request_features(phba, mboxq);
8662 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8663 	if (unlikely(rc)) {
8664 		rc = -EIO;
8665 		goto out_free_mbox;
8666 	}
8667 
8668 	/* Disable VMID if app header is not supported */
8669 	if (phba->cfg_vmid_app_header && !(bf_get(lpfc_mbx_rq_ftr_rsp_ashdr,
8670 						  &mqe->un.req_ftrs))) {
8671 		bf_set(lpfc_ftr_ashdr, &phba->sli4_hba.sli4_flags, 0);
8672 		phba->cfg_vmid_app_header = 0;
8673 		lpfc_printf_log(phba, KERN_DEBUG, LOG_SLI,
8674 				"1242 vmid feature not supported\n");
8675 	}
8676 
8677 	/*
8678 	 * The port must support FCP initiator mode as this is the
8679 	 * only mode running in the host.
8680 	 */
8681 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
8682 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8683 				"0378 No support for fcpi mode.\n");
8684 		ftr_rsp++;
8685 	}
8686 
8687 	/* Performance Hints are ONLY for FCoE */
8688 	if (phba->hba_flag & HBA_FCOE_MODE) {
8689 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
8690 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
8691 		else
8692 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
8693 	}
8694 
8695 	/*
8696 	 * If the port cannot support the host's requested features
8697 	 * then turn off the global config parameters to disable the
8698 	 * feature in the driver.  This is not a fatal error.
8699 	 */
8700 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8701 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
8702 			phba->cfg_enable_bg = 0;
8703 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
8704 			ftr_rsp++;
8705 		}
8706 	}
8707 
8708 	if (phba->max_vpi && phba->cfg_enable_npiv &&
8709 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8710 		ftr_rsp++;
8711 
8712 	if (ftr_rsp) {
8713 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8714 				"0379 Feature Mismatch Data: x%08x %08x "
8715 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
8716 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
8717 				phba->cfg_enable_npiv, phba->max_vpi);
8718 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
8719 			phba->cfg_enable_bg = 0;
8720 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8721 			phba->cfg_enable_npiv = 0;
8722 	}
8723 
8724 	/* These SLI3 features are assumed in SLI4 */
8725 	spin_lock_irq(&phba->hbalock);
8726 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
8727 	spin_unlock_irq(&phba->hbalock);
8728 
8729 	/* Always try to enable dual dump feature if we can */
8730 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
8731 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8732 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
8733 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
8734 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8735 				"6448 Dual Dump is enabled\n");
8736 	else
8737 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
8738 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
8739 				"rc:x%x dd:x%x\n",
8740 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8741 				lpfc_sli_config_mbox_subsys_get(
8742 					phba, mboxq),
8743 				lpfc_sli_config_mbox_opcode_get(
8744 					phba, mboxq),
8745 				rc, dd);
8746 	/*
8747 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
8748 	 * calls depends on these resources to complete port setup.
8749 	 */
8750 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
8751 	if (rc) {
8752 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8753 				"2920 Failed to alloc Resource IDs "
8754 				"rc = x%x\n", rc);
8755 		goto out_free_mbox;
8756 	}
8757 
8758 	lpfc_set_host_data(phba, mboxq);
8759 
8760 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8761 	if (rc) {
8762 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8763 				"2134 Failed to set host os driver version %x",
8764 				rc);
8765 	}
8766 
8767 	/* Read the port's service parameters. */
8768 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
8769 	if (rc) {
8770 		phba->link_state = LPFC_HBA_ERROR;
8771 		rc = -ENOMEM;
8772 		goto out_free_mbox;
8773 	}
8774 
8775 	mboxq->vport = vport;
8776 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8777 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
8778 	if (rc == MBX_SUCCESS) {
8779 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
8780 		rc = 0;
8781 	}
8782 
8783 	/*
8784 	 * This memory was allocated by the lpfc_read_sparam routine but is
8785 	 * no longer needed.  It is released and ctx_buf NULLed to prevent
8786 	 * unintended pointer access as the mbox is reused.
8787 	 */
8788 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
8789 	kfree(mp);
8790 	mboxq->ctx_buf = NULL;
8791 	if (unlikely(rc)) {
8792 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8793 				"0382 READ_SPARAM command failed "
8794 				"status %d, mbxStatus x%x\n",
8795 				rc, bf_get(lpfc_mqe_status, mqe));
8796 		phba->link_state = LPFC_HBA_ERROR;
8797 		rc = -EIO;
8798 		goto out_free_mbox;
8799 	}
8800 
8801 	lpfc_update_vport_wwn(vport);
8802 
8803 	/* Update the fc_host data structures with new wwn. */
8804 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
8805 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
8806 
8807 	/* Create all the SLI4 queues */
8808 	rc = lpfc_sli4_queue_create(phba);
8809 	if (rc) {
8810 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8811 				"3089 Failed to allocate queues\n");
8812 		rc = -ENODEV;
8813 		goto out_free_mbox;
8814 	}
8815 	/* Set up all the queues to the device */
8816 	rc = lpfc_sli4_queue_setup(phba);
8817 	if (unlikely(rc)) {
8818 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8819 				"0381 Error %d during queue setup.\n ", rc);
8820 		goto out_stop_timers;
8821 	}
8822 	/* Initialize the driver internal SLI layer lists. */
8823 	lpfc_sli4_setup(phba);
8824 	lpfc_sli4_queue_init(phba);
8825 
8826 	/* update host els xri-sgl sizes and mappings */
8827 	rc = lpfc_sli4_els_sgl_update(phba);
8828 	if (unlikely(rc)) {
8829 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8830 				"1400 Failed to update xri-sgl size and "
8831 				"mapping: %d\n", rc);
8832 		goto out_destroy_queue;
8833 	}
8834 
8835 	/* register the els sgl pool to the port */
8836 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
8837 				       phba->sli4_hba.els_xri_cnt);
8838 	if (unlikely(rc < 0)) {
8839 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8840 				"0582 Error %d during els sgl post "
8841 				"operation\n", rc);
8842 		rc = -ENODEV;
8843 		goto out_destroy_queue;
8844 	}
8845 	phba->sli4_hba.els_xri_cnt = rc;
8846 
8847 	if (phba->nvmet_support) {
8848 		/* update host nvmet xri-sgl sizes and mappings */
8849 		rc = lpfc_sli4_nvmet_sgl_update(phba);
8850 		if (unlikely(rc)) {
8851 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8852 					"6308 Failed to update nvmet-sgl size "
8853 					"and mapping: %d\n", rc);
8854 			goto out_destroy_queue;
8855 		}
8856 
8857 		/* register the nvmet sgl pool to the port */
8858 		rc = lpfc_sli4_repost_sgl_list(
8859 			phba,
8860 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
8861 			phba->sli4_hba.nvmet_xri_cnt);
8862 		if (unlikely(rc < 0)) {
8863 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8864 					"3117 Error %d during nvmet "
8865 					"sgl post\n", rc);
8866 			rc = -ENODEV;
8867 			goto out_destroy_queue;
8868 		}
8869 		phba->sli4_hba.nvmet_xri_cnt = rc;
8870 
8871 		/* We allocate an iocbq for every receive context SGL.
8872 		 * The additional allocation is for abort and ls handling.
8873 		 */
8874 		cnt = phba->sli4_hba.nvmet_xri_cnt +
8875 			phba->sli4_hba.max_cfg_param.max_xri;
8876 	} else {
8877 		/* update host common xri-sgl sizes and mappings */
8878 		rc = lpfc_sli4_io_sgl_update(phba);
8879 		if (unlikely(rc)) {
8880 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8881 					"6082 Failed to update nvme-sgl size "
8882 					"and mapping: %d\n", rc);
8883 			goto out_destroy_queue;
8884 		}
8885 
8886 		/* register the allocated common sgl pool to the port */
8887 		rc = lpfc_sli4_repost_io_sgl_list(phba);
8888 		if (unlikely(rc)) {
8889 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8890 					"6116 Error %d during nvme sgl post "
8891 					"operation\n", rc);
8892 			/* Some NVME buffers were moved to abort nvme list */
8893 			/* A pci function reset will repost them */
8894 			rc = -ENODEV;
8895 			goto out_destroy_queue;
8896 		}
8897 		/* Each lpfc_io_buf job structure has an iocbq element.
8898 		 * This cnt provides for abort, els, ct and ls requests.
8899 		 */
8900 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
8901 	}
8902 
8903 	if (!phba->sli.iocbq_lookup) {
8904 		/* Initialize and populate the iocb list per host */
8905 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8906 				"2821 initialize iocb list with %d entries\n",
8907 				cnt);
8908 		rc = lpfc_init_iocb_list(phba, cnt);
8909 		if (rc) {
8910 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8911 					"1413 Failed to init iocb list.\n");
8912 			goto out_destroy_queue;
8913 		}
8914 	}
8915 
8916 	if (phba->nvmet_support)
8917 		lpfc_nvmet_create_targetport(phba);
8918 
8919 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
8920 		/* Post initial buffers to all RQs created */
8921 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
8922 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
8923 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
8924 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
8925 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
8926 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
8927 			rqbp->buffer_count = 0;
8928 
8929 			lpfc_post_rq_buffer(
8930 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
8931 				phba->sli4_hba.nvmet_mrq_data[i],
8932 				phba->cfg_nvmet_mrq_post, i);
8933 		}
8934 	}
8935 
8936 	/* Post the rpi header region to the device. */
8937 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
8938 	if (unlikely(rc)) {
8939 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8940 				"0393 Error %d during rpi post operation\n",
8941 				rc);
8942 		rc = -ENODEV;
8943 		goto out_free_iocblist;
8944 	}
8945 	lpfc_sli4_node_prep(phba);
8946 
8947 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
8948 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
8949 			/*
8950 			 * The FC Port needs to register FCFI (index 0)
8951 			 */
8952 			lpfc_reg_fcfi(phba, mboxq);
8953 			mboxq->vport = phba->pport;
8954 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8955 			if (rc != MBX_SUCCESS)
8956 				goto out_unset_queue;
8957 			rc = 0;
8958 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
8959 						&mboxq->u.mqe.un.reg_fcfi);
8960 		} else {
8961 			/* We are a NVME Target mode with MRQ > 1 */
8962 
8963 			/* First register the FCFI */
8964 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
8965 			mboxq->vport = phba->pport;
8966 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8967 			if (rc != MBX_SUCCESS)
8968 				goto out_unset_queue;
8969 			rc = 0;
8970 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
8971 						&mboxq->u.mqe.un.reg_fcfi_mrq);
8972 
8973 			/* Next register the MRQs */
8974 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
8975 			mboxq->vport = phba->pport;
8976 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8977 			if (rc != MBX_SUCCESS)
8978 				goto out_unset_queue;
8979 			rc = 0;
8980 		}
8981 		/* Check if the port is configured to be disabled */
8982 		lpfc_sli_read_link_ste(phba);
8983 	}
8984 
8985 	/* Don't post more new bufs if repost already recovered
8986 	 * the nvme sgls.
8987 	 */
8988 	if (phba->nvmet_support == 0) {
8989 		if (phba->sli4_hba.io_xri_cnt == 0) {
8990 			len = lpfc_new_io_buf(
8991 					      phba, phba->sli4_hba.io_xri_max);
8992 			if (len == 0) {
8993 				rc = -ENOMEM;
8994 				goto out_unset_queue;
8995 			}
8996 
8997 			if (phba->cfg_xri_rebalancing)
8998 				lpfc_create_multixri_pools(phba);
8999 		}
9000 	} else {
9001 		phba->cfg_xri_rebalancing = 0;
9002 	}
9003 
9004 	/* Allow asynchronous mailbox command to go through */
9005 	spin_lock_irq(&phba->hbalock);
9006 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9007 	spin_unlock_irq(&phba->hbalock);
9008 
9009 	/* Post receive buffers to the device */
9010 	lpfc_sli4_rb_setup(phba);
9011 
9012 	/* Reset HBA FCF states after HBA reset */
9013 	phba->fcf.fcf_flag = 0;
9014 	phba->fcf.current_rec.flag = 0;
9015 
9016 	/* Start the ELS watchdog timer */
9017 	mod_timer(&vport->els_tmofunc,
9018 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
9019 
9020 	/* Start heart beat timer */
9021 	mod_timer(&phba->hb_tmofunc,
9022 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
9023 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
9024 	phba->last_completion_time = jiffies;
9025 
9026 	/* start eq_delay heartbeat */
9027 	if (phba->cfg_auto_imax)
9028 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
9029 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
9030 
9031 	/* start per phba idle_stat_delay heartbeat */
9032 	lpfc_init_idle_stat_hb(phba);
9033 
9034 	/* Start error attention (ERATT) polling timer */
9035 	mod_timer(&phba->eratt_poll,
9036 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
9037 
9038 	/*
9039 	 * The port is ready, set the host's link state to LINK_DOWN
9040 	 * in preparation for link interrupts.
9041 	 */
9042 	spin_lock_irq(&phba->hbalock);
9043 	phba->link_state = LPFC_LINK_DOWN;
9044 
9045 	/* Check if physical ports are trunked */
9046 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
9047 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
9048 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
9049 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
9050 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
9051 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
9052 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
9053 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
9054 	spin_unlock_irq(&phba->hbalock);
9055 
9056 	/* Arm the CQs and then EQs on device */
9057 	lpfc_sli4_arm_cqeq_intr(phba);
9058 
9059 	/* Indicate device interrupt mode */
9060 	phba->sli4_hba.intr_enable = 1;
9061 
9062 	/* Setup CMF after HBA is initialized */
9063 	lpfc_cmf_setup(phba);
9064 
9065 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
9066 	    (phba->hba_flag & LINK_DISABLED)) {
9067 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9068 				"3103 Adapter Link is disabled.\n");
9069 		lpfc_down_link(phba, mboxq);
9070 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9071 		if (rc != MBX_SUCCESS) {
9072 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9073 					"3104 Adapter failed to issue "
9074 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
9075 			goto out_io_buff_free;
9076 		}
9077 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
9078 		/* don't perform init_link on SLI4 FC port loopback test */
9079 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
9080 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
9081 			if (rc)
9082 				goto out_io_buff_free;
9083 		}
9084 	}
9085 	mempool_free(mboxq, phba->mbox_mem_pool);
9086 
9087 	/* Enable RAS FW log support */
9088 	lpfc_sli4_ras_setup(phba);
9089 
9090 	phba->hba_flag |= HBA_SETUP;
9091 	return rc;
9092 
9093 out_io_buff_free:
9094 	/* Free allocated IO Buffers */
9095 	lpfc_io_free(phba);
9096 out_unset_queue:
9097 	/* Unset all the queues set up in this routine when error out */
9098 	lpfc_sli4_queue_unset(phba);
9099 out_free_iocblist:
9100 	lpfc_free_iocb_list(phba);
9101 out_destroy_queue:
9102 	lpfc_sli4_queue_destroy(phba);
9103 out_stop_timers:
9104 	lpfc_stop_hba_timers(phba);
9105 out_free_mbox:
9106 	mempool_free(mboxq, phba->mbox_mem_pool);
9107 	return rc;
9108 }
9109 
9110 /**
9111  * lpfc_mbox_timeout - Timeout call back function for mbox timer
9112  * @t: Context to fetch pointer to hba structure from.
9113  *
9114  * This is the callback function for mailbox timer. The mailbox
9115  * timer is armed when a new mailbox command is issued and the timer
9116  * is deleted when the mailbox complete. The function is called by
9117  * the kernel timer code when a mailbox does not complete within
9118  * expected time. This function wakes up the worker thread to
9119  * process the mailbox timeout and returns. All the processing is
9120  * done by the worker thread function lpfc_mbox_timeout_handler.
9121  **/
9122 void
9123 lpfc_mbox_timeout(struct timer_list *t)
9124 {
9125 	struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
9126 	unsigned long iflag;
9127 	uint32_t tmo_posted;
9128 
9129 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
9130 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
9131 	if (!tmo_posted)
9132 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
9133 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
9134 
9135 	if (!tmo_posted)
9136 		lpfc_worker_wake_up(phba);
9137 	return;
9138 }
9139 
9140 /**
9141  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
9142  *                                    are pending
9143  * @phba: Pointer to HBA context object.
9144  *
9145  * This function checks if any mailbox completions are present on the mailbox
9146  * completion queue.
9147  **/
9148 static bool
9149 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
9150 {
9151 
9152 	uint32_t idx;
9153 	struct lpfc_queue *mcq;
9154 	struct lpfc_mcqe *mcqe;
9155 	bool pending_completions = false;
9156 	uint8_t	qe_valid;
9157 
9158 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9159 		return false;
9160 
9161 	/* Check for completions on mailbox completion queue */
9162 
9163 	mcq = phba->sli4_hba.mbx_cq;
9164 	idx = mcq->hba_index;
9165 	qe_valid = mcq->qe_valid;
9166 	while (bf_get_le32(lpfc_cqe_valid,
9167 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
9168 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
9169 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
9170 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
9171 			pending_completions = true;
9172 			break;
9173 		}
9174 		idx = (idx + 1) % mcq->entry_count;
9175 		if (mcq->hba_index == idx)
9176 			break;
9177 
9178 		/* if the index wrapped around, toggle the valid bit */
9179 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
9180 			qe_valid = (qe_valid) ? 0 : 1;
9181 	}
9182 	return pending_completions;
9183 
9184 }
9185 
9186 /**
9187  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
9188  *					      that were missed.
9189  * @phba: Pointer to HBA context object.
9190  *
9191  * For sli4, it is possible to miss an interrupt. As such mbox completions
9192  * maybe missed causing erroneous mailbox timeouts to occur. This function
9193  * checks to see if mbox completions are on the mailbox completion queue
9194  * and will process all the completions associated with the eq for the
9195  * mailbox completion queue.
9196  **/
9197 static bool
9198 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
9199 {
9200 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
9201 	uint32_t eqidx;
9202 	struct lpfc_queue *fpeq = NULL;
9203 	struct lpfc_queue *eq;
9204 	bool mbox_pending;
9205 
9206 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9207 		return false;
9208 
9209 	/* Find the EQ associated with the mbox CQ */
9210 	if (sli4_hba->hdwq) {
9211 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
9212 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
9213 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
9214 				fpeq = eq;
9215 				break;
9216 			}
9217 		}
9218 	}
9219 	if (!fpeq)
9220 		return false;
9221 
9222 	/* Turn off interrupts from this EQ */
9223 
9224 	sli4_hba->sli4_eq_clr_intr(fpeq);
9225 
9226 	/* Check to see if a mbox completion is pending */
9227 
9228 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
9229 
9230 	/*
9231 	 * If a mbox completion is pending, process all the events on EQ
9232 	 * associated with the mbox completion queue (this could include
9233 	 * mailbox commands, async events, els commands, receive queue data
9234 	 * and fcp commands)
9235 	 */
9236 
9237 	if (mbox_pending)
9238 		/* process and rearm the EQ */
9239 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
9240 				     LPFC_QUEUE_WORK);
9241 	else
9242 		/* Always clear and re-arm the EQ */
9243 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
9244 
9245 	return mbox_pending;
9246 
9247 }
9248 
9249 /**
9250  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
9251  * @phba: Pointer to HBA context object.
9252  *
9253  * This function is called from worker thread when a mailbox command times out.
9254  * The caller is not required to hold any locks. This function will reset the
9255  * HBA and recover all the pending commands.
9256  **/
9257 void
9258 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
9259 {
9260 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
9261 	MAILBOX_t *mb = NULL;
9262 
9263 	struct lpfc_sli *psli = &phba->sli;
9264 
9265 	/* If the mailbox completed, process the completion */
9266 	lpfc_sli4_process_missed_mbox_completions(phba);
9267 
9268 	if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
9269 		return;
9270 
9271 	if (pmbox != NULL)
9272 		mb = &pmbox->u.mb;
9273 	/* Check the pmbox pointer first.  There is a race condition
9274 	 * between the mbox timeout handler getting executed in the
9275 	 * worklist and the mailbox actually completing. When this
9276 	 * race condition occurs, the mbox_active will be NULL.
9277 	 */
9278 	spin_lock_irq(&phba->hbalock);
9279 	if (pmbox == NULL) {
9280 		lpfc_printf_log(phba, KERN_WARNING,
9281 				LOG_MBOX | LOG_SLI,
9282 				"0353 Active Mailbox cleared - mailbox timeout "
9283 				"exiting\n");
9284 		spin_unlock_irq(&phba->hbalock);
9285 		return;
9286 	}
9287 
9288 	/* Mbox cmd <mbxCommand> timeout */
9289 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9290 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
9291 			mb->mbxCommand,
9292 			phba->pport->port_state,
9293 			phba->sli.sli_flag,
9294 			phba->sli.mbox_active);
9295 	spin_unlock_irq(&phba->hbalock);
9296 
9297 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
9298 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
9299 	 * it to fail all outstanding SCSI IO.
9300 	 */
9301 	set_bit(MBX_TMO_ERR, &phba->bit_flags);
9302 	spin_lock_irq(&phba->pport->work_port_lock);
9303 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9304 	spin_unlock_irq(&phba->pport->work_port_lock);
9305 	spin_lock_irq(&phba->hbalock);
9306 	phba->link_state = LPFC_LINK_UNKNOWN;
9307 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
9308 	spin_unlock_irq(&phba->hbalock);
9309 
9310 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9311 			"0345 Resetting board due to mailbox timeout\n");
9312 
9313 	/* Reset the HBA device */
9314 	lpfc_reset_hba(phba);
9315 }
9316 
9317 /**
9318  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
9319  * @phba: Pointer to HBA context object.
9320  * @pmbox: Pointer to mailbox object.
9321  * @flag: Flag indicating how the mailbox need to be processed.
9322  *
9323  * This function is called by discovery code and HBA management code
9324  * to submit a mailbox command to firmware with SLI-3 interface spec. This
9325  * function gets the hbalock to protect the data structures.
9326  * The mailbox command can be submitted in polling mode, in which case
9327  * this function will wait in a polling loop for the completion of the
9328  * mailbox.
9329  * If the mailbox is submitted in no_wait mode (not polling) the
9330  * function will submit the command and returns immediately without waiting
9331  * for the mailbox completion. The no_wait is supported only when HBA
9332  * is in SLI2/SLI3 mode - interrupts are enabled.
9333  * The SLI interface allows only one mailbox pending at a time. If the
9334  * mailbox is issued in polling mode and there is already a mailbox
9335  * pending, then the function will return an error. If the mailbox is issued
9336  * in NO_WAIT mode and there is a mailbox pending already, the function
9337  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
9338  * The sli layer owns the mailbox object until the completion of mailbox
9339  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
9340  * return codes the caller owns the mailbox command after the return of
9341  * the function.
9342  **/
9343 static int
9344 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
9345 		       uint32_t flag)
9346 {
9347 	MAILBOX_t *mbx;
9348 	struct lpfc_sli *psli = &phba->sli;
9349 	uint32_t status, evtctr;
9350 	uint32_t ha_copy, hc_copy;
9351 	int i;
9352 	unsigned long timeout;
9353 	unsigned long drvr_flag = 0;
9354 	uint32_t word0, ldata;
9355 	void __iomem *to_slim;
9356 	int processing_queue = 0;
9357 
9358 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
9359 	if (!pmbox) {
9360 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9361 		/* processing mbox queue from intr_handler */
9362 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9363 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9364 			return MBX_SUCCESS;
9365 		}
9366 		processing_queue = 1;
9367 		pmbox = lpfc_mbox_get(phba);
9368 		if (!pmbox) {
9369 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9370 			return MBX_SUCCESS;
9371 		}
9372 	}
9373 
9374 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
9375 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
9376 		if(!pmbox->vport) {
9377 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9378 			lpfc_printf_log(phba, KERN_ERR,
9379 					LOG_MBOX | LOG_VPORT,
9380 					"1806 Mbox x%x failed. No vport\n",
9381 					pmbox->u.mb.mbxCommand);
9382 			dump_stack();
9383 			goto out_not_finished;
9384 		}
9385 	}
9386 
9387 	/* If the PCI channel is in offline state, do not post mbox. */
9388 	if (unlikely(pci_channel_offline(phba->pcidev))) {
9389 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9390 		goto out_not_finished;
9391 	}
9392 
9393 	/* If HBA has a deferred error attention, fail the iocb. */
9394 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
9395 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9396 		goto out_not_finished;
9397 	}
9398 
9399 	psli = &phba->sli;
9400 
9401 	mbx = &pmbox->u.mb;
9402 	status = MBX_SUCCESS;
9403 
9404 	if (phba->link_state == LPFC_HBA_ERROR) {
9405 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9406 
9407 		/* Mbox command <mbxCommand> cannot issue */
9408 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9409 				"(%d):0311 Mailbox command x%x cannot "
9410 				"issue Data: x%x x%x\n",
9411 				pmbox->vport ? pmbox->vport->vpi : 0,
9412 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9413 		goto out_not_finished;
9414 	}
9415 
9416 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
9417 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
9418 			!(hc_copy & HC_MBINT_ENA)) {
9419 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9420 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9421 				"(%d):2528 Mailbox command x%x cannot "
9422 				"issue Data: x%x x%x\n",
9423 				pmbox->vport ? pmbox->vport->vpi : 0,
9424 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9425 			goto out_not_finished;
9426 		}
9427 	}
9428 
9429 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9430 		/* Polling for a mbox command when another one is already active
9431 		 * is not allowed in SLI. Also, the driver must have established
9432 		 * SLI2 mode to queue and process multiple mbox commands.
9433 		 */
9434 
9435 		if (flag & MBX_POLL) {
9436 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9437 
9438 			/* Mbox command <mbxCommand> cannot issue */
9439 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9440 					"(%d):2529 Mailbox command x%x "
9441 					"cannot issue Data: x%x x%x\n",
9442 					pmbox->vport ? pmbox->vport->vpi : 0,
9443 					pmbox->u.mb.mbxCommand,
9444 					psli->sli_flag, flag);
9445 			goto out_not_finished;
9446 		}
9447 
9448 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
9449 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9450 			/* Mbox command <mbxCommand> cannot issue */
9451 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9452 					"(%d):2530 Mailbox command x%x "
9453 					"cannot issue Data: x%x x%x\n",
9454 					pmbox->vport ? pmbox->vport->vpi : 0,
9455 					pmbox->u.mb.mbxCommand,
9456 					psli->sli_flag, flag);
9457 			goto out_not_finished;
9458 		}
9459 
9460 		/* Another mailbox command is still being processed, queue this
9461 		 * command to be processed later.
9462 		 */
9463 		lpfc_mbox_put(phba, pmbox);
9464 
9465 		/* Mbox cmd issue - BUSY */
9466 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9467 				"(%d):0308 Mbox cmd issue - BUSY Data: "
9468 				"x%x x%x x%x x%x\n",
9469 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
9470 				mbx->mbxCommand,
9471 				phba->pport ? phba->pport->port_state : 0xff,
9472 				psli->sli_flag, flag);
9473 
9474 		psli->slistat.mbox_busy++;
9475 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9476 
9477 		if (pmbox->vport) {
9478 			lpfc_debugfs_disc_trc(pmbox->vport,
9479 				LPFC_DISC_TRC_MBOX_VPORT,
9480 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
9481 				(uint32_t)mbx->mbxCommand,
9482 				mbx->un.varWords[0], mbx->un.varWords[1]);
9483 		}
9484 		else {
9485 			lpfc_debugfs_disc_trc(phba->pport,
9486 				LPFC_DISC_TRC_MBOX,
9487 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
9488 				(uint32_t)mbx->mbxCommand,
9489 				mbx->un.varWords[0], mbx->un.varWords[1]);
9490 		}
9491 
9492 		return MBX_BUSY;
9493 	}
9494 
9495 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9496 
9497 	/* If we are not polling, we MUST be in SLI2 mode */
9498 	if (flag != MBX_POLL) {
9499 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
9500 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
9501 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9502 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9503 			/* Mbox command <mbxCommand> cannot issue */
9504 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9505 					"(%d):2531 Mailbox command x%x "
9506 					"cannot issue Data: x%x x%x\n",
9507 					pmbox->vport ? pmbox->vport->vpi : 0,
9508 					pmbox->u.mb.mbxCommand,
9509 					psli->sli_flag, flag);
9510 			goto out_not_finished;
9511 		}
9512 		/* timeout active mbox command */
9513 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9514 					   1000);
9515 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
9516 	}
9517 
9518 	/* Mailbox cmd <cmd> issue */
9519 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9520 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
9521 			"x%x\n",
9522 			pmbox->vport ? pmbox->vport->vpi : 0,
9523 			mbx->mbxCommand,
9524 			phba->pport ? phba->pport->port_state : 0xff,
9525 			psli->sli_flag, flag);
9526 
9527 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
9528 		if (pmbox->vport) {
9529 			lpfc_debugfs_disc_trc(pmbox->vport,
9530 				LPFC_DISC_TRC_MBOX_VPORT,
9531 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9532 				(uint32_t)mbx->mbxCommand,
9533 				mbx->un.varWords[0], mbx->un.varWords[1]);
9534 		}
9535 		else {
9536 			lpfc_debugfs_disc_trc(phba->pport,
9537 				LPFC_DISC_TRC_MBOX,
9538 				"MBOX Send:       cmd:x%x mb:x%x x%x",
9539 				(uint32_t)mbx->mbxCommand,
9540 				mbx->un.varWords[0], mbx->un.varWords[1]);
9541 		}
9542 	}
9543 
9544 	psli->slistat.mbox_cmd++;
9545 	evtctr = psli->slistat.mbox_event;
9546 
9547 	/* next set own bit for the adapter and copy over command word */
9548 	mbx->mbxOwner = OWN_CHIP;
9549 
9550 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9551 		/* Populate mbox extension offset word. */
9552 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
9553 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9554 				= (uint8_t *)phba->mbox_ext
9555 				  - (uint8_t *)phba->mbox;
9556 		}
9557 
9558 		/* Copy the mailbox extension data */
9559 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
9560 			lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
9561 					      (uint8_t *)phba->mbox_ext,
9562 					      pmbox->in_ext_byte_len);
9563 		}
9564 		/* Copy command data to host SLIM area */
9565 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
9566 	} else {
9567 		/* Populate mbox extension offset word. */
9568 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
9569 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9570 				= MAILBOX_HBA_EXT_OFFSET;
9571 
9572 		/* Copy the mailbox extension data */
9573 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
9574 			lpfc_memcpy_to_slim(phba->MBslimaddr +
9575 				MAILBOX_HBA_EXT_OFFSET,
9576 				pmbox->ctx_buf, pmbox->in_ext_byte_len);
9577 
9578 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9579 			/* copy command data into host mbox for cmpl */
9580 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
9581 					      MAILBOX_CMD_SIZE);
9582 
9583 		/* First copy mbox command data to HBA SLIM, skip past first
9584 		   word */
9585 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
9586 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
9587 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
9588 
9589 		/* Next copy over first word, with mbxOwner set */
9590 		ldata = *((uint32_t *)mbx);
9591 		to_slim = phba->MBslimaddr;
9592 		writel(ldata, to_slim);
9593 		readl(to_slim); /* flush */
9594 
9595 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9596 			/* switch over to host mailbox */
9597 			psli->sli_flag |= LPFC_SLI_ACTIVE;
9598 	}
9599 
9600 	wmb();
9601 
9602 	switch (flag) {
9603 	case MBX_NOWAIT:
9604 		/* Set up reference to mailbox command */
9605 		psli->mbox_active = pmbox;
9606 		/* Interrupt board to do it */
9607 		writel(CA_MBATT, phba->CAregaddr);
9608 		readl(phba->CAregaddr); /* flush */
9609 		/* Don't wait for it to finish, just return */
9610 		break;
9611 
9612 	case MBX_POLL:
9613 		/* Set up null reference to mailbox command */
9614 		psli->mbox_active = NULL;
9615 		/* Interrupt board to do it */
9616 		writel(CA_MBATT, phba->CAregaddr);
9617 		readl(phba->CAregaddr); /* flush */
9618 
9619 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9620 			/* First read mbox status word */
9621 			word0 = *((uint32_t *)phba->mbox);
9622 			word0 = le32_to_cpu(word0);
9623 		} else {
9624 			/* First read mbox status word */
9625 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
9626 				spin_unlock_irqrestore(&phba->hbalock,
9627 						       drvr_flag);
9628 				goto out_not_finished;
9629 			}
9630 		}
9631 
9632 		/* Read the HBA Host Attention Register */
9633 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9634 			spin_unlock_irqrestore(&phba->hbalock,
9635 						       drvr_flag);
9636 			goto out_not_finished;
9637 		}
9638 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9639 							1000) + jiffies;
9640 		i = 0;
9641 		/* Wait for command to complete */
9642 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
9643 		       (!(ha_copy & HA_MBATT) &&
9644 			(phba->link_state > LPFC_WARM_START))) {
9645 			if (time_after(jiffies, timeout)) {
9646 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9647 				spin_unlock_irqrestore(&phba->hbalock,
9648 						       drvr_flag);
9649 				goto out_not_finished;
9650 			}
9651 
9652 			/* Check if we took a mbox interrupt while we were
9653 			   polling */
9654 			if (((word0 & OWN_CHIP) != OWN_CHIP)
9655 			    && (evtctr != psli->slistat.mbox_event))
9656 				break;
9657 
9658 			if (i++ > 10) {
9659 				spin_unlock_irqrestore(&phba->hbalock,
9660 						       drvr_flag);
9661 				msleep(1);
9662 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
9663 			}
9664 
9665 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9666 				/* First copy command data */
9667 				word0 = *((uint32_t *)phba->mbox);
9668 				word0 = le32_to_cpu(word0);
9669 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
9670 					MAILBOX_t *slimmb;
9671 					uint32_t slimword0;
9672 					/* Check real SLIM for any errors */
9673 					slimword0 = readl(phba->MBslimaddr);
9674 					slimmb = (MAILBOX_t *) & slimword0;
9675 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
9676 					    && slimmb->mbxStatus) {
9677 						psli->sli_flag &=
9678 						    ~LPFC_SLI_ACTIVE;
9679 						word0 = slimword0;
9680 					}
9681 				}
9682 			} else {
9683 				/* First copy command data */
9684 				word0 = readl(phba->MBslimaddr);
9685 			}
9686 			/* Read the HBA Host Attention Register */
9687 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9688 				spin_unlock_irqrestore(&phba->hbalock,
9689 						       drvr_flag);
9690 				goto out_not_finished;
9691 			}
9692 		}
9693 
9694 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9695 			/* copy results back to user */
9696 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
9697 						MAILBOX_CMD_SIZE);
9698 			/* Copy the mailbox extension data */
9699 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9700 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
9701 						      pmbox->ctx_buf,
9702 						      pmbox->out_ext_byte_len);
9703 			}
9704 		} else {
9705 			/* First copy command data */
9706 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
9707 						MAILBOX_CMD_SIZE);
9708 			/* Copy the mailbox extension data */
9709 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9710 				lpfc_memcpy_from_slim(
9711 					pmbox->ctx_buf,
9712 					phba->MBslimaddr +
9713 					MAILBOX_HBA_EXT_OFFSET,
9714 					pmbox->out_ext_byte_len);
9715 			}
9716 		}
9717 
9718 		writel(HA_MBATT, phba->HAregaddr);
9719 		readl(phba->HAregaddr); /* flush */
9720 
9721 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9722 		status = mbx->mbxStatus;
9723 	}
9724 
9725 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9726 	return status;
9727 
9728 out_not_finished:
9729 	if (processing_queue) {
9730 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
9731 		lpfc_mbox_cmpl_put(phba, pmbox);
9732 	}
9733 	return MBX_NOT_FINISHED;
9734 }
9735 
9736 /**
9737  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
9738  * @phba: Pointer to HBA context object.
9739  *
9740  * The function blocks the posting of SLI4 asynchronous mailbox commands from
9741  * the driver internal pending mailbox queue. It will then try to wait out the
9742  * possible outstanding mailbox command before return.
9743  *
9744  * Returns:
9745  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
9746  * 	the outstanding mailbox command timed out.
9747  **/
9748 static int
9749 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
9750 {
9751 	struct lpfc_sli *psli = &phba->sli;
9752 	LPFC_MBOXQ_t *mboxq;
9753 	int rc = 0;
9754 	unsigned long timeout = 0;
9755 	u32 sli_flag;
9756 	u8 cmd, subsys, opcode;
9757 
9758 	/* Mark the asynchronous mailbox command posting as blocked */
9759 	spin_lock_irq(&phba->hbalock);
9760 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
9761 	/* Determine how long we might wait for the active mailbox
9762 	 * command to be gracefully completed by firmware.
9763 	 */
9764 	if (phba->sli.mbox_active)
9765 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
9766 						phba->sli.mbox_active) *
9767 						1000) + jiffies;
9768 	spin_unlock_irq(&phba->hbalock);
9769 
9770 	/* Make sure the mailbox is really active */
9771 	if (timeout)
9772 		lpfc_sli4_process_missed_mbox_completions(phba);
9773 
9774 	/* Wait for the outstanding mailbox command to complete */
9775 	while (phba->sli.mbox_active) {
9776 		/* Check active mailbox complete status every 2ms */
9777 		msleep(2);
9778 		if (time_after(jiffies, timeout)) {
9779 			/* Timeout, mark the outstanding cmd not complete */
9780 
9781 			/* Sanity check sli.mbox_active has not completed or
9782 			 * cancelled from another context during last 2ms sleep,
9783 			 * so take hbalock to be sure before logging.
9784 			 */
9785 			spin_lock_irq(&phba->hbalock);
9786 			if (phba->sli.mbox_active) {
9787 				mboxq = phba->sli.mbox_active;
9788 				cmd = mboxq->u.mb.mbxCommand;
9789 				subsys = lpfc_sli_config_mbox_subsys_get(phba,
9790 									 mboxq);
9791 				opcode = lpfc_sli_config_mbox_opcode_get(phba,
9792 									 mboxq);
9793 				sli_flag = psli->sli_flag;
9794 				spin_unlock_irq(&phba->hbalock);
9795 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9796 						"2352 Mailbox command x%x "
9797 						"(x%x/x%x) sli_flag x%x could "
9798 						"not complete\n",
9799 						cmd, subsys, opcode,
9800 						sli_flag);
9801 			} else {
9802 				spin_unlock_irq(&phba->hbalock);
9803 			}
9804 
9805 			rc = 1;
9806 			break;
9807 		}
9808 	}
9809 
9810 	/* Can not cleanly block async mailbox command, fails it */
9811 	if (rc) {
9812 		spin_lock_irq(&phba->hbalock);
9813 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9814 		spin_unlock_irq(&phba->hbalock);
9815 	}
9816 	return rc;
9817 }
9818 
9819 /**
9820  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
9821  * @phba: Pointer to HBA context object.
9822  *
9823  * The function unblocks and resume posting of SLI4 asynchronous mailbox
9824  * commands from the driver internal pending mailbox queue. It makes sure
9825  * that there is no outstanding mailbox command before resuming posting
9826  * asynchronous mailbox commands. If, for any reason, there is outstanding
9827  * mailbox command, it will try to wait it out before resuming asynchronous
9828  * mailbox command posting.
9829  **/
9830 static void
9831 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
9832 {
9833 	struct lpfc_sli *psli = &phba->sli;
9834 
9835 	spin_lock_irq(&phba->hbalock);
9836 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9837 		/* Asynchronous mailbox posting is not blocked, do nothing */
9838 		spin_unlock_irq(&phba->hbalock);
9839 		return;
9840 	}
9841 
9842 	/* Outstanding synchronous mailbox command is guaranteed to be done,
9843 	 * successful or timeout, after timing-out the outstanding mailbox
9844 	 * command shall always be removed, so just unblock posting async
9845 	 * mailbox command and resume
9846 	 */
9847 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9848 	spin_unlock_irq(&phba->hbalock);
9849 
9850 	/* wake up worker thread to post asynchronous mailbox command */
9851 	lpfc_worker_wake_up(phba);
9852 }
9853 
9854 /**
9855  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
9856  * @phba: Pointer to HBA context object.
9857  * @mboxq: Pointer to mailbox object.
9858  *
9859  * The function waits for the bootstrap mailbox register ready bit from
9860  * port for twice the regular mailbox command timeout value.
9861  *
9862  *      0 - no timeout on waiting for bootstrap mailbox register ready.
9863  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out or port
9864  *                     is in an unrecoverable state.
9865  **/
9866 static int
9867 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9868 {
9869 	uint32_t db_ready;
9870 	unsigned long timeout;
9871 	struct lpfc_register bmbx_reg;
9872 	struct lpfc_register portstat_reg = {-1};
9873 
9874 	/* Sanity check - there is no point to wait if the port is in an
9875 	 * unrecoverable state.
9876 	 */
9877 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
9878 	    LPFC_SLI_INTF_IF_TYPE_2) {
9879 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9880 			       &portstat_reg.word0) ||
9881 		    lpfc_sli4_unrecoverable_port(&portstat_reg)) {
9882 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9883 					"3858 Skipping bmbx ready because "
9884 					"Port Status x%x\n",
9885 					portstat_reg.word0);
9886 			return MBXERR_ERROR;
9887 		}
9888 	}
9889 
9890 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
9891 				   * 1000) + jiffies;
9892 
9893 	do {
9894 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
9895 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
9896 		if (!db_ready)
9897 			mdelay(2);
9898 
9899 		if (time_after(jiffies, timeout))
9900 			return MBXERR_ERROR;
9901 	} while (!db_ready);
9902 
9903 	return 0;
9904 }
9905 
9906 /**
9907  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
9908  * @phba: Pointer to HBA context object.
9909  * @mboxq: Pointer to mailbox object.
9910  *
9911  * The function posts a mailbox to the port.  The mailbox is expected
9912  * to be comletely filled in and ready for the port to operate on it.
9913  * This routine executes a synchronous completion operation on the
9914  * mailbox by polling for its completion.
9915  *
9916  * The caller must not be holding any locks when calling this routine.
9917  *
9918  * Returns:
9919  *	MBX_SUCCESS - mailbox posted successfully
9920  *	Any of the MBX error values.
9921  **/
9922 static int
9923 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9924 {
9925 	int rc = MBX_SUCCESS;
9926 	unsigned long iflag;
9927 	uint32_t mcqe_status;
9928 	uint32_t mbx_cmnd;
9929 	struct lpfc_sli *psli = &phba->sli;
9930 	struct lpfc_mqe *mb = &mboxq->u.mqe;
9931 	struct lpfc_bmbx_create *mbox_rgn;
9932 	struct dma_address *dma_address;
9933 
9934 	/*
9935 	 * Only one mailbox can be active to the bootstrap mailbox region
9936 	 * at a time and there is no queueing provided.
9937 	 */
9938 	spin_lock_irqsave(&phba->hbalock, iflag);
9939 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9940 		spin_unlock_irqrestore(&phba->hbalock, iflag);
9941 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9942 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
9943 				"cannot issue Data: x%x x%x\n",
9944 				mboxq->vport ? mboxq->vport->vpi : 0,
9945 				mboxq->u.mb.mbxCommand,
9946 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9947 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9948 				psli->sli_flag, MBX_POLL);
9949 		return MBXERR_ERROR;
9950 	}
9951 	/* The server grabs the token and owns it until release */
9952 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9953 	phba->sli.mbox_active = mboxq;
9954 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9955 
9956 	/* wait for bootstrap mbox register for readyness */
9957 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9958 	if (rc)
9959 		goto exit;
9960 	/*
9961 	 * Initialize the bootstrap memory region to avoid stale data areas
9962 	 * in the mailbox post.  Then copy the caller's mailbox contents to
9963 	 * the bmbx mailbox region.
9964 	 */
9965 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
9966 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
9967 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
9968 			       sizeof(struct lpfc_mqe));
9969 
9970 	/* Post the high mailbox dma address to the port and wait for ready. */
9971 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9972 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
9973 
9974 	/* wait for bootstrap mbox register for hi-address write done */
9975 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9976 	if (rc)
9977 		goto exit;
9978 
9979 	/* Post the low mailbox dma address to the port. */
9980 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
9981 
9982 	/* wait for bootstrap mbox register for low address write done */
9983 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9984 	if (rc)
9985 		goto exit;
9986 
9987 	/*
9988 	 * Read the CQ to ensure the mailbox has completed.
9989 	 * If so, update the mailbox status so that the upper layers
9990 	 * can complete the request normally.
9991 	 */
9992 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
9993 			       sizeof(struct lpfc_mqe));
9994 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
9995 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
9996 			       sizeof(struct lpfc_mcqe));
9997 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
9998 	/*
9999 	 * When the CQE status indicates a failure and the mailbox status
10000 	 * indicates success then copy the CQE status into the mailbox status
10001 	 * (and prefix it with x4000).
10002 	 */
10003 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
10004 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
10005 			bf_set(lpfc_mqe_status, mb,
10006 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
10007 		rc = MBXERR_ERROR;
10008 	} else
10009 		lpfc_sli4_swap_str(phba, mboxq);
10010 
10011 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10012 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
10013 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
10014 			" x%x x%x CQ: x%x x%x x%x x%x\n",
10015 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10016 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10017 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10018 			bf_get(lpfc_mqe_status, mb),
10019 			mb->un.mb_words[0], mb->un.mb_words[1],
10020 			mb->un.mb_words[2], mb->un.mb_words[3],
10021 			mb->un.mb_words[4], mb->un.mb_words[5],
10022 			mb->un.mb_words[6], mb->un.mb_words[7],
10023 			mb->un.mb_words[8], mb->un.mb_words[9],
10024 			mb->un.mb_words[10], mb->un.mb_words[11],
10025 			mb->un.mb_words[12], mboxq->mcqe.word0,
10026 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
10027 			mboxq->mcqe.trailer);
10028 exit:
10029 	/* We are holding the token, no needed for lock when release */
10030 	spin_lock_irqsave(&phba->hbalock, iflag);
10031 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10032 	phba->sli.mbox_active = NULL;
10033 	spin_unlock_irqrestore(&phba->hbalock, iflag);
10034 	return rc;
10035 }
10036 
10037 /**
10038  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
10039  * @phba: Pointer to HBA context object.
10040  * @mboxq: Pointer to mailbox object.
10041  * @flag: Flag indicating how the mailbox need to be processed.
10042  *
10043  * This function is called by discovery code and HBA management code to submit
10044  * a mailbox command to firmware with SLI-4 interface spec.
10045  *
10046  * Return codes the caller owns the mailbox command after the return of the
10047  * function.
10048  **/
10049 static int
10050 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
10051 		       uint32_t flag)
10052 {
10053 	struct lpfc_sli *psli = &phba->sli;
10054 	unsigned long iflags;
10055 	int rc;
10056 
10057 	/* dump from issue mailbox command if setup */
10058 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
10059 
10060 	rc = lpfc_mbox_dev_check(phba);
10061 	if (unlikely(rc)) {
10062 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10063 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
10064 				"cannot issue Data: x%x x%x\n",
10065 				mboxq->vport ? mboxq->vport->vpi : 0,
10066 				mboxq->u.mb.mbxCommand,
10067 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10068 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10069 				psli->sli_flag, flag);
10070 		goto out_not_finished;
10071 	}
10072 
10073 	/* Detect polling mode and jump to a handler */
10074 	if (!phba->sli4_hba.intr_enable) {
10075 		if (flag == MBX_POLL)
10076 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10077 		else
10078 			rc = -EIO;
10079 		if (rc != MBX_SUCCESS)
10080 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10081 					"(%d):2541 Mailbox command x%x "
10082 					"(x%x/x%x) failure: "
10083 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
10084 					"Data: x%x x%x\n",
10085 					mboxq->vport ? mboxq->vport->vpi : 0,
10086 					mboxq->u.mb.mbxCommand,
10087 					lpfc_sli_config_mbox_subsys_get(phba,
10088 									mboxq),
10089 					lpfc_sli_config_mbox_opcode_get(phba,
10090 									mboxq),
10091 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10092 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10093 					bf_get(lpfc_mcqe_ext_status,
10094 					       &mboxq->mcqe),
10095 					psli->sli_flag, flag);
10096 		return rc;
10097 	} else if (flag == MBX_POLL) {
10098 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10099 				"(%d):2542 Try to issue mailbox command "
10100 				"x%x (x%x/x%x) synchronously ahead of async "
10101 				"mailbox command queue: 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, mboxq),
10105 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10106 				psli->sli_flag, flag);
10107 		/* Try to block the asynchronous mailbox posting */
10108 		rc = lpfc_sli4_async_mbox_block(phba);
10109 		if (!rc) {
10110 			/* Successfully blocked, now issue sync mbox cmd */
10111 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10112 			if (rc != MBX_SUCCESS)
10113 				lpfc_printf_log(phba, KERN_WARNING,
10114 					LOG_MBOX | LOG_SLI,
10115 					"(%d):2597 Sync Mailbox command "
10116 					"x%x (x%x/x%x) failure: "
10117 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
10118 					"Data: 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,
10122 									mboxq),
10123 					lpfc_sli_config_mbox_opcode_get(phba,
10124 									mboxq),
10125 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10126 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10127 					bf_get(lpfc_mcqe_ext_status,
10128 					       &mboxq->mcqe),
10129 					psli->sli_flag, flag);
10130 			/* Unblock the async mailbox posting afterward */
10131 			lpfc_sli4_async_mbox_unblock(phba);
10132 		}
10133 		return rc;
10134 	}
10135 
10136 	/* Now, interrupt mode asynchronous mailbox command */
10137 	rc = lpfc_mbox_cmd_check(phba, mboxq);
10138 	if (rc) {
10139 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10140 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
10141 				"cannot issue Data: x%x x%x\n",
10142 				mboxq->vport ? mboxq->vport->vpi : 0,
10143 				mboxq->u.mb.mbxCommand,
10144 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10145 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10146 				psli->sli_flag, flag);
10147 		goto out_not_finished;
10148 	}
10149 
10150 	/* Put the mailbox command to the driver internal FIFO */
10151 	psli->slistat.mbox_busy++;
10152 	spin_lock_irqsave(&phba->hbalock, iflags);
10153 	lpfc_mbox_put(phba, mboxq);
10154 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10155 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10156 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
10157 			"x%x (x%x/x%x) x%x x%x x%x\n",
10158 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
10159 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
10160 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10161 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10162 			phba->pport->port_state,
10163 			psli->sli_flag, MBX_NOWAIT);
10164 	/* Wake up worker thread to transport mailbox command from head */
10165 	lpfc_worker_wake_up(phba);
10166 
10167 	return MBX_BUSY;
10168 
10169 out_not_finished:
10170 	return MBX_NOT_FINISHED;
10171 }
10172 
10173 /**
10174  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
10175  * @phba: Pointer to HBA context object.
10176  *
10177  * This function is called by worker thread to send a mailbox command to
10178  * SLI4 HBA firmware.
10179  *
10180  **/
10181 int
10182 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
10183 {
10184 	struct lpfc_sli *psli = &phba->sli;
10185 	LPFC_MBOXQ_t *mboxq;
10186 	int rc = MBX_SUCCESS;
10187 	unsigned long iflags;
10188 	struct lpfc_mqe *mqe;
10189 	uint32_t mbx_cmnd;
10190 
10191 	/* Check interrupt mode before post async mailbox command */
10192 	if (unlikely(!phba->sli4_hba.intr_enable))
10193 		return MBX_NOT_FINISHED;
10194 
10195 	/* Check for mailbox command service token */
10196 	spin_lock_irqsave(&phba->hbalock, iflags);
10197 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
10198 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10199 		return MBX_NOT_FINISHED;
10200 	}
10201 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
10202 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10203 		return MBX_NOT_FINISHED;
10204 	}
10205 	if (unlikely(phba->sli.mbox_active)) {
10206 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10207 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10208 				"0384 There is pending active mailbox cmd\n");
10209 		return MBX_NOT_FINISHED;
10210 	}
10211 	/* Take the mailbox command service token */
10212 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
10213 
10214 	/* Get the next mailbox command from head of queue */
10215 	mboxq = lpfc_mbox_get(phba);
10216 
10217 	/* If no more mailbox command waiting for post, we're done */
10218 	if (!mboxq) {
10219 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10220 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10221 		return MBX_SUCCESS;
10222 	}
10223 	phba->sli.mbox_active = mboxq;
10224 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10225 
10226 	/* Check device readiness for posting mailbox command */
10227 	rc = lpfc_mbox_dev_check(phba);
10228 	if (unlikely(rc))
10229 		/* Driver clean routine will clean up pending mailbox */
10230 		goto out_not_finished;
10231 
10232 	/* Prepare the mbox command to be posted */
10233 	mqe = &mboxq->u.mqe;
10234 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
10235 
10236 	/* Start timer for the mbox_tmo and log some mailbox post messages */
10237 	mod_timer(&psli->mbox_tmo, (jiffies +
10238 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
10239 
10240 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10241 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
10242 			"x%x x%x\n",
10243 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10244 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10245 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10246 			phba->pport->port_state, psli->sli_flag);
10247 
10248 	if (mbx_cmnd != MBX_HEARTBEAT) {
10249 		if (mboxq->vport) {
10250 			lpfc_debugfs_disc_trc(mboxq->vport,
10251 				LPFC_DISC_TRC_MBOX_VPORT,
10252 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
10253 				mbx_cmnd, mqe->un.mb_words[0],
10254 				mqe->un.mb_words[1]);
10255 		} else {
10256 			lpfc_debugfs_disc_trc(phba->pport,
10257 				LPFC_DISC_TRC_MBOX,
10258 				"MBOX Send: cmd:x%x mb:x%x x%x",
10259 				mbx_cmnd, mqe->un.mb_words[0],
10260 				mqe->un.mb_words[1]);
10261 		}
10262 	}
10263 	psli->slistat.mbox_cmd++;
10264 
10265 	/* Post the mailbox command to the port */
10266 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
10267 	if (rc != MBX_SUCCESS) {
10268 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10269 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
10270 				"cannot issue Data: x%x x%x\n",
10271 				mboxq->vport ? mboxq->vport->vpi : 0,
10272 				mboxq->u.mb.mbxCommand,
10273 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10274 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10275 				psli->sli_flag, MBX_NOWAIT);
10276 		goto out_not_finished;
10277 	}
10278 
10279 	return rc;
10280 
10281 out_not_finished:
10282 	spin_lock_irqsave(&phba->hbalock, iflags);
10283 	if (phba->sli.mbox_active) {
10284 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
10285 		__lpfc_mbox_cmpl_put(phba, mboxq);
10286 		/* Release the token */
10287 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10288 		phba->sli.mbox_active = NULL;
10289 	}
10290 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10291 
10292 	return MBX_NOT_FINISHED;
10293 }
10294 
10295 /**
10296  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
10297  * @phba: Pointer to HBA context object.
10298  * @pmbox: Pointer to mailbox object.
10299  * @flag: Flag indicating how the mailbox need to be processed.
10300  *
10301  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
10302  * the API jump table function pointer from the lpfc_hba struct.
10303  *
10304  * Return codes the caller owns the mailbox command after the return of the
10305  * function.
10306  **/
10307 int
10308 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
10309 {
10310 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
10311 }
10312 
10313 /**
10314  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
10315  * @phba: The hba struct for which this call is being executed.
10316  * @dev_grp: The HBA PCI-Device group number.
10317  *
10318  * This routine sets up the mbox interface API function jump table in @phba
10319  * struct.
10320  * Returns: 0 - success, -ENODEV - failure.
10321  **/
10322 int
10323 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10324 {
10325 
10326 	switch (dev_grp) {
10327 	case LPFC_PCI_DEV_LP:
10328 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
10329 		phba->lpfc_sli_handle_slow_ring_event =
10330 				lpfc_sli_handle_slow_ring_event_s3;
10331 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
10332 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
10333 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
10334 		break;
10335 	case LPFC_PCI_DEV_OC:
10336 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
10337 		phba->lpfc_sli_handle_slow_ring_event =
10338 				lpfc_sli_handle_slow_ring_event_s4;
10339 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
10340 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
10341 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
10342 		break;
10343 	default:
10344 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10345 				"1420 Invalid HBA PCI-device group: 0x%x\n",
10346 				dev_grp);
10347 		return -ENODEV;
10348 	}
10349 	return 0;
10350 }
10351 
10352 /**
10353  * __lpfc_sli_ringtx_put - Add an iocb to the txq
10354  * @phba: Pointer to HBA context object.
10355  * @pring: Pointer to driver SLI ring object.
10356  * @piocb: Pointer to address of newly added command iocb.
10357  *
10358  * This function is called with hbalock held for SLI3 ports or
10359  * the ring lock held for SLI4 ports to add a command
10360  * iocb to the txq when SLI layer cannot submit the command iocb
10361  * to the ring.
10362  **/
10363 void
10364 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10365 		    struct lpfc_iocbq *piocb)
10366 {
10367 	if (phba->sli_rev == LPFC_SLI_REV4)
10368 		lockdep_assert_held(&pring->ring_lock);
10369 	else
10370 		lockdep_assert_held(&phba->hbalock);
10371 	/* Insert the caller's iocb in the txq tail for later processing. */
10372 	list_add_tail(&piocb->list, &pring->txq);
10373 }
10374 
10375 /**
10376  * lpfc_sli_next_iocb - Get the next iocb in the txq
10377  * @phba: Pointer to HBA context object.
10378  * @pring: Pointer to driver SLI ring object.
10379  * @piocb: Pointer to address of newly added command iocb.
10380  *
10381  * This function is called with hbalock held before a new
10382  * iocb is submitted to the firmware. This function checks
10383  * txq to flush the iocbs in txq to Firmware before
10384  * submitting new iocbs to the Firmware.
10385  * If there are iocbs in the txq which need to be submitted
10386  * to firmware, lpfc_sli_next_iocb returns the first element
10387  * of the txq after dequeuing it from txq.
10388  * If there is no iocb in the txq then the function will return
10389  * *piocb and *piocb is set to NULL. Caller needs to check
10390  * *piocb to find if there are more commands in the txq.
10391  **/
10392 static struct lpfc_iocbq *
10393 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10394 		   struct lpfc_iocbq **piocb)
10395 {
10396 	struct lpfc_iocbq * nextiocb;
10397 
10398 	lockdep_assert_held(&phba->hbalock);
10399 
10400 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
10401 	if (!nextiocb) {
10402 		nextiocb = *piocb;
10403 		*piocb = NULL;
10404 	}
10405 
10406 	return nextiocb;
10407 }
10408 
10409 /**
10410  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
10411  * @phba: Pointer to HBA context object.
10412  * @ring_number: SLI ring number to issue iocb on.
10413  * @piocb: Pointer to command iocb.
10414  * @flag: Flag indicating if this command can be put into txq.
10415  *
10416  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
10417  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
10418  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
10419  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
10420  * this function allows only iocbs for posting buffers. This function finds
10421  * next available slot in the command ring and posts the command to the
10422  * available slot and writes the port attention register to request HBA start
10423  * processing new iocb. If there is no slot available in the ring and
10424  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
10425  * the function returns IOCB_BUSY.
10426  *
10427  * This function is called with hbalock held. The function will return success
10428  * after it successfully submit the iocb to firmware or after adding to the
10429  * txq.
10430  **/
10431 static int
10432 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
10433 		    struct lpfc_iocbq *piocb, uint32_t flag)
10434 {
10435 	struct lpfc_iocbq *nextiocb;
10436 	IOCB_t *iocb;
10437 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
10438 
10439 	lockdep_assert_held(&phba->hbalock);
10440 
10441 	if (piocb->cmd_cmpl && (!piocb->vport) &&
10442 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
10443 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
10444 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10445 				"1807 IOCB x%x failed. No vport\n",
10446 				piocb->iocb.ulpCommand);
10447 		dump_stack();
10448 		return IOCB_ERROR;
10449 	}
10450 
10451 
10452 	/* If the PCI channel is in offline state, do not post iocbs. */
10453 	if (unlikely(pci_channel_offline(phba->pcidev)))
10454 		return IOCB_ERROR;
10455 
10456 	/* If HBA has a deferred error attention, fail the iocb. */
10457 	if (unlikely(phba->hba_flag & DEFER_ERATT))
10458 		return IOCB_ERROR;
10459 
10460 	/*
10461 	 * We should never get an IOCB if we are in a < LINK_DOWN state
10462 	 */
10463 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
10464 		return IOCB_ERROR;
10465 
10466 	/*
10467 	 * Check to see if we are blocking IOCB processing because of a
10468 	 * outstanding event.
10469 	 */
10470 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
10471 		goto iocb_busy;
10472 
10473 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
10474 		/*
10475 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
10476 		 * can be issued if the link is not up.
10477 		 */
10478 		switch (piocb->iocb.ulpCommand) {
10479 		case CMD_QUE_RING_BUF_CN:
10480 		case CMD_QUE_RING_BUF64_CN:
10481 			/*
10482 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
10483 			 * completion, cmd_cmpl MUST be 0.
10484 			 */
10485 			if (piocb->cmd_cmpl)
10486 				piocb->cmd_cmpl = NULL;
10487 			fallthrough;
10488 		case CMD_CREATE_XRI_CR:
10489 		case CMD_CLOSE_XRI_CN:
10490 		case CMD_CLOSE_XRI_CX:
10491 			break;
10492 		default:
10493 			goto iocb_busy;
10494 		}
10495 
10496 	/*
10497 	 * For FCP commands, we must be in a state where we can process link
10498 	 * attention events.
10499 	 */
10500 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
10501 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
10502 		goto iocb_busy;
10503 	}
10504 
10505 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
10506 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
10507 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
10508 
10509 	if (iocb)
10510 		lpfc_sli_update_ring(phba, pring);
10511 	else
10512 		lpfc_sli_update_full_ring(phba, pring);
10513 
10514 	if (!piocb)
10515 		return IOCB_SUCCESS;
10516 
10517 	goto out_busy;
10518 
10519  iocb_busy:
10520 	pring->stats.iocb_cmd_delay++;
10521 
10522  out_busy:
10523 
10524 	if (!(flag & SLI_IOCB_RET_IOCB)) {
10525 		__lpfc_sli_ringtx_put(phba, pring, piocb);
10526 		return IOCB_SUCCESS;
10527 	}
10528 
10529 	return IOCB_BUSY;
10530 }
10531 
10532 /**
10533  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10534  * @phba: Pointer to HBA context object.
10535  * @ring_number: SLI ring number to issue wqe on.
10536  * @piocb: Pointer to command iocb.
10537  * @flag: Flag indicating if this command can be put into txq.
10538  *
10539  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10540  * send  an iocb command to an HBA with SLI-3 interface spec.
10541  *
10542  * This function takes the hbalock before invoking the lockless version.
10543  * The function will return success after it successfully submit the wqe to
10544  * firmware or after adding to the txq.
10545  **/
10546 static int
10547 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10548 			   struct lpfc_iocbq *piocb, uint32_t flag)
10549 {
10550 	unsigned long iflags;
10551 	int rc;
10552 
10553 	spin_lock_irqsave(&phba->hbalock, iflags);
10554 	rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10555 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10556 
10557 	return rc;
10558 }
10559 
10560 /**
10561  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10562  * @phba: Pointer to HBA context object.
10563  * @ring_number: SLI ring number to issue wqe on.
10564  * @piocb: Pointer to command iocb.
10565  * @flag: Flag indicating if this command can be put into txq.
10566  *
10567  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10568  * an wqe command to an HBA with SLI-4 interface spec.
10569  *
10570  * This function is a lockless version. The function will return success
10571  * after it successfully submit the wqe to firmware or after adding to the
10572  * txq.
10573  **/
10574 static int
10575 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10576 			   struct lpfc_iocbq *piocb, uint32_t flag)
10577 {
10578 	struct lpfc_io_buf *lpfc_cmd = piocb->io_buf;
10579 
10580 	lpfc_prep_embed_io(phba, lpfc_cmd);
10581 	return lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
10582 }
10583 
10584 void
10585 lpfc_prep_embed_io(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
10586 {
10587 	struct lpfc_iocbq *piocb = &lpfc_cmd->cur_iocbq;
10588 	union lpfc_wqe128 *wqe = &lpfc_cmd->cur_iocbq.wqe;
10589 	struct sli4_sge *sgl;
10590 
10591 	/* 128 byte wqe support here */
10592 	sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10593 
10594 	if (phba->fcp_embed_io) {
10595 		struct fcp_cmnd *fcp_cmnd;
10596 		u32 *ptr;
10597 
10598 		fcp_cmnd = lpfc_cmd->fcp_cmnd;
10599 
10600 		/* Word 0-2 - FCP_CMND */
10601 		wqe->generic.bde.tus.f.bdeFlags =
10602 			BUFF_TYPE_BDE_IMMED;
10603 		wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10604 		wqe->generic.bde.addrHigh = 0;
10605 		wqe->generic.bde.addrLow =  88;  /* Word 22 */
10606 
10607 		bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10608 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10609 
10610 		/* Word 22-29  FCP CMND Payload */
10611 		ptr = &wqe->words[22];
10612 		memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10613 	} else {
10614 		/* Word 0-2 - Inline BDE */
10615 		wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
10616 		wqe->generic.bde.tus.f.bdeSize = sizeof(struct fcp_cmnd);
10617 		wqe->generic.bde.addrHigh = sgl->addr_hi;
10618 		wqe->generic.bde.addrLow =  sgl->addr_lo;
10619 
10620 		/* Word 10 */
10621 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10622 		bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
10623 	}
10624 
10625 	/* add the VMID tags as per switch response */
10626 	if (unlikely(piocb->cmd_flag & LPFC_IO_VMID)) {
10627 		if (phba->pport->vmid_flag & LPFC_VMID_TYPE_PRIO) {
10628 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
10629 			bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10630 					(piocb->vmid_tag.cs_ctl_vmid));
10631 		} else if (phba->cfg_vmid_app_header) {
10632 			bf_set(wqe_appid, &wqe->fcp_iwrite.wqe_com, 1);
10633 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10634 			wqe->words[31] = piocb->vmid_tag.app_id;
10635 		}
10636 	}
10637 }
10638 
10639 /**
10640  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10641  * @phba: Pointer to HBA context object.
10642  * @ring_number: SLI ring number to issue iocb on.
10643  * @piocb: Pointer to command iocb.
10644  * @flag: Flag indicating if this command can be put into txq.
10645  *
10646  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10647  * an iocb command to an HBA with SLI-4 interface spec.
10648  *
10649  * This function is called with ringlock held. The function will return success
10650  * after it successfully submit the iocb to firmware or after adding to the
10651  * txq.
10652  **/
10653 static int
10654 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10655 			 struct lpfc_iocbq *piocb, uint32_t flag)
10656 {
10657 	struct lpfc_sglq *sglq;
10658 	union lpfc_wqe128 *wqe;
10659 	struct lpfc_queue *wq;
10660 	struct lpfc_sli_ring *pring;
10661 	u32 ulp_command = get_job_cmnd(phba, piocb);
10662 
10663 	/* Get the WQ */
10664 	if ((piocb->cmd_flag & LPFC_IO_FCP) ||
10665 	    (piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
10666 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10667 	} else {
10668 		wq = phba->sli4_hba.els_wq;
10669 	}
10670 
10671 	/* Get corresponding ring */
10672 	pring = wq->pring;
10673 
10674 	/*
10675 	 * The WQE can be either 64 or 128 bytes,
10676 	 */
10677 
10678 	lockdep_assert_held(&pring->ring_lock);
10679 	wqe = &piocb->wqe;
10680 	if (piocb->sli4_xritag == NO_XRI) {
10681 		if (ulp_command == CMD_ABORT_XRI_CX)
10682 			sglq = NULL;
10683 		else {
10684 			sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10685 			if (!sglq) {
10686 				if (!(flag & SLI_IOCB_RET_IOCB)) {
10687 					__lpfc_sli_ringtx_put(phba,
10688 							pring,
10689 							piocb);
10690 					return IOCB_SUCCESS;
10691 				} else {
10692 					return IOCB_BUSY;
10693 				}
10694 			}
10695 		}
10696 	} else if (piocb->cmd_flag &  LPFC_IO_FCP) {
10697 		/* These IO's already have an XRI and a mapped sgl. */
10698 		sglq = NULL;
10699 	}
10700 	else {
10701 		/*
10702 		 * This is a continuation of a commandi,(CX) so this
10703 		 * sglq is on the active list
10704 		 */
10705 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10706 		if (!sglq)
10707 			return IOCB_ERROR;
10708 	}
10709 
10710 	if (sglq) {
10711 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10712 		piocb->sli4_xritag = sglq->sli4_xritag;
10713 
10714 		/* ABTS sent by initiator to CT exchange, the
10715 		 * RX_ID field will be filled with the newly
10716 		 * allocated responder XRI.
10717 		 */
10718 		if (ulp_command == CMD_XMIT_BLS_RSP64_CX &&
10719 		    piocb->abort_bls == LPFC_ABTS_UNSOL_INT)
10720 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10721 			       piocb->sli4_xritag);
10722 
10723 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com,
10724 		       piocb->sli4_xritag);
10725 
10726 		if (lpfc_wqe_bpl2sgl(phba, piocb, sglq) == NO_XRI)
10727 			return IOCB_ERROR;
10728 	}
10729 
10730 	if (lpfc_sli4_wq_put(wq, wqe))
10731 		return IOCB_ERROR;
10732 
10733 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10734 
10735 	return 0;
10736 }
10737 
10738 /*
10739  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
10740  *
10741  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
10742  * or IOCB for sli-3  function.
10743  * pointer from the lpfc_hba struct.
10744  *
10745  * Return codes:
10746  * IOCB_ERROR - Error
10747  * IOCB_SUCCESS - Success
10748  * IOCB_BUSY - Busy
10749  **/
10750 int
10751 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
10752 		      struct lpfc_iocbq *piocb, uint32_t flag)
10753 {
10754 	return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
10755 }
10756 
10757 /*
10758  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10759  *
10760  * This routine wraps the actual lockless version for issusing IOCB function
10761  * pointer from the lpfc_hba struct.
10762  *
10763  * Return codes:
10764  * IOCB_ERROR - Error
10765  * IOCB_SUCCESS - Success
10766  * IOCB_BUSY - Busy
10767  **/
10768 int
10769 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10770 		struct lpfc_iocbq *piocb, uint32_t flag)
10771 {
10772 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10773 }
10774 
10775 static void
10776 __lpfc_sli_prep_els_req_rsp_s3(struct lpfc_iocbq *cmdiocbq,
10777 			       struct lpfc_vport *vport,
10778 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10779 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10780 {
10781 	struct lpfc_hba *phba = vport->phba;
10782 	IOCB_t *cmd;
10783 
10784 	cmd = &cmdiocbq->iocb;
10785 	memset(cmd, 0, sizeof(*cmd));
10786 
10787 	cmd->un.elsreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10788 	cmd->un.elsreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10789 	cmd->un.elsreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10790 
10791 	if (expect_rsp) {
10792 		cmd->un.elsreq64.bdl.bdeSize = (2 * sizeof(struct ulp_bde64));
10793 		cmd->un.elsreq64.remoteID = did; /* DID */
10794 		cmd->ulpCommand = CMD_ELS_REQUEST64_CR;
10795 		cmd->ulpTimeout = tmo;
10796 	} else {
10797 		cmd->un.elsreq64.bdl.bdeSize = sizeof(struct ulp_bde64);
10798 		cmd->un.genreq64.xmit_els_remoteID = did; /* DID */
10799 		cmd->ulpCommand = CMD_XMIT_ELS_RSP64_CX;
10800 		cmd->ulpPU = PARM_NPIV_DID;
10801 	}
10802 	cmd->ulpBdeCount = 1;
10803 	cmd->ulpLe = 1;
10804 	cmd->ulpClass = CLASS3;
10805 
10806 	/* If we have NPIV enabled, we want to send ELS traffic by VPI. */
10807 	if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) {
10808 		if (expect_rsp) {
10809 			cmd->un.elsreq64.myID = vport->fc_myDID;
10810 
10811 			/* For ELS_REQUEST64_CR, use the VPI by default */
10812 			cmd->ulpContext = phba->vpi_ids[vport->vpi];
10813 		}
10814 
10815 		cmd->ulpCt_h = 0;
10816 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10817 		if (elscmd == ELS_CMD_ECHO)
10818 			cmd->ulpCt_l = 0; /* context = invalid RPI */
10819 		else
10820 			cmd->ulpCt_l = 1; /* context = VPI */
10821 	}
10822 }
10823 
10824 static void
10825 __lpfc_sli_prep_els_req_rsp_s4(struct lpfc_iocbq *cmdiocbq,
10826 			       struct lpfc_vport *vport,
10827 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10828 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10829 {
10830 	struct lpfc_hba  *phba = vport->phba;
10831 	union lpfc_wqe128 *wqe;
10832 	struct ulp_bde64_le *bde;
10833 	u8 els_id;
10834 
10835 	wqe = &cmdiocbq->wqe;
10836 	memset(wqe, 0, sizeof(*wqe));
10837 
10838 	/* Word 0 - 2 BDE */
10839 	bde = (struct ulp_bde64_le *)&wqe->generic.bde;
10840 	bde->addr_low = cpu_to_le32(putPaddrLow(bmp->phys));
10841 	bde->addr_high = cpu_to_le32(putPaddrHigh(bmp->phys));
10842 	bde->type_size = cpu_to_le32(cmd_size);
10843 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10844 
10845 	if (expect_rsp) {
10846 		bf_set(wqe_cmnd, &wqe->els_req.wqe_com, CMD_ELS_REQUEST64_WQE);
10847 
10848 		/* Transfer length */
10849 		wqe->els_req.payload_len = cmd_size;
10850 		wqe->els_req.max_response_payload_len = FCELSSIZE;
10851 
10852 		/* DID */
10853 		bf_set(wqe_els_did, &wqe->els_req.wqe_dest, did);
10854 
10855 		/* Word 11 - ELS_ID */
10856 		switch (elscmd) {
10857 		case ELS_CMD_PLOGI:
10858 			els_id = LPFC_ELS_ID_PLOGI;
10859 			break;
10860 		case ELS_CMD_FLOGI:
10861 			els_id = LPFC_ELS_ID_FLOGI;
10862 			break;
10863 		case ELS_CMD_LOGO:
10864 			els_id = LPFC_ELS_ID_LOGO;
10865 			break;
10866 		case ELS_CMD_FDISC:
10867 			if (!vport->fc_myDID) {
10868 				els_id = LPFC_ELS_ID_FDISC;
10869 				break;
10870 			}
10871 			fallthrough;
10872 		default:
10873 			els_id = LPFC_ELS_ID_DEFAULT;
10874 			break;
10875 		}
10876 
10877 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
10878 	} else {
10879 		/* DID */
10880 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest, did);
10881 
10882 		/* Transfer length */
10883 		wqe->xmit_els_rsp.response_payload_len = cmd_size;
10884 
10885 		bf_set(wqe_cmnd, &wqe->xmit_els_rsp.wqe_com,
10886 		       CMD_XMIT_ELS_RSP64_WQE);
10887 	}
10888 
10889 	bf_set(wqe_tmo, &wqe->generic.wqe_com, tmo);
10890 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, cmdiocbq->iotag);
10891 	bf_set(wqe_class, &wqe->generic.wqe_com, CLASS3);
10892 
10893 	/* If we have NPIV enabled, we want to send ELS traffic by VPI.
10894 	 * For SLI4, since the driver controls VPIs we also want to include
10895 	 * all ELS pt2pt protocol traffic as well.
10896 	 */
10897 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) ||
10898 	    (vport->fc_flag & FC_PT2PT)) {
10899 		if (expect_rsp) {
10900 			bf_set(els_req64_sid, &wqe->els_req, vport->fc_myDID);
10901 
10902 			/* For ELS_REQUEST64_WQE, use the VPI by default */
10903 			bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10904 			       phba->vpi_ids[vport->vpi]);
10905 		}
10906 
10907 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10908 		if (elscmd == ELS_CMD_ECHO)
10909 			bf_set(wqe_ct, &wqe->generic.wqe_com, 0);
10910 		else
10911 			bf_set(wqe_ct, &wqe->generic.wqe_com, 1);
10912 	}
10913 }
10914 
10915 void
10916 lpfc_sli_prep_els_req_rsp(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
10917 			  struct lpfc_vport *vport, struct lpfc_dmabuf *bmp,
10918 			  u16 cmd_size, u32 did, u32 elscmd, u8 tmo,
10919 			  u8 expect_rsp)
10920 {
10921 	phba->__lpfc_sli_prep_els_req_rsp(cmdiocbq, vport, bmp, cmd_size, did,
10922 					  elscmd, tmo, expect_rsp);
10923 }
10924 
10925 static void
10926 __lpfc_sli_prep_gen_req_s3(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10927 			   u16 rpi, u32 num_entry, u8 tmo)
10928 {
10929 	IOCB_t *cmd;
10930 
10931 	cmd = &cmdiocbq->iocb;
10932 	memset(cmd, 0, sizeof(*cmd));
10933 
10934 	cmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10935 	cmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10936 	cmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10937 	cmd->un.genreq64.bdl.bdeSize = num_entry * sizeof(struct ulp_bde64);
10938 
10939 	cmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
10940 	cmd->un.genreq64.w5.hcsw.Type = FC_TYPE_CT;
10941 	cmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
10942 
10943 	cmd->ulpContext = rpi;
10944 	cmd->ulpClass = CLASS3;
10945 	cmd->ulpCommand = CMD_GEN_REQUEST64_CR;
10946 	cmd->ulpBdeCount = 1;
10947 	cmd->ulpLe = 1;
10948 	cmd->ulpOwner = OWN_CHIP;
10949 	cmd->ulpTimeout = tmo;
10950 }
10951 
10952 static void
10953 __lpfc_sli_prep_gen_req_s4(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10954 			   u16 rpi, u32 num_entry, u8 tmo)
10955 {
10956 	union lpfc_wqe128 *cmdwqe;
10957 	struct ulp_bde64_le *bde, *bpl;
10958 	u32 xmit_len = 0, total_len = 0, size, type, i;
10959 
10960 	cmdwqe = &cmdiocbq->wqe;
10961 	memset(cmdwqe, 0, sizeof(*cmdwqe));
10962 
10963 	/* Calculate total_len and xmit_len */
10964 	bpl = (struct ulp_bde64_le *)bmp->virt;
10965 	for (i = 0; i < num_entry; i++) {
10966 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10967 		total_len += size;
10968 	}
10969 	for (i = 0; i < num_entry; i++) {
10970 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10971 		type = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_TYPE_MASK;
10972 		if (type != ULP_BDE64_TYPE_BDE_64)
10973 			break;
10974 		xmit_len += size;
10975 	}
10976 
10977 	/* Words 0 - 2 */
10978 	bde = (struct ulp_bde64_le *)&cmdwqe->generic.bde;
10979 	bde->addr_low = bpl->addr_low;
10980 	bde->addr_high = bpl->addr_high;
10981 	bde->type_size = cpu_to_le32(xmit_len);
10982 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10983 
10984 	/* Word 3 */
10985 	cmdwqe->gen_req.request_payload_len = xmit_len;
10986 
10987 	/* Word 5 */
10988 	bf_set(wqe_type, &cmdwqe->gen_req.wge_ctl, FC_TYPE_CT);
10989 	bf_set(wqe_rctl, &cmdwqe->gen_req.wge_ctl, FC_RCTL_DD_UNSOL_CTL);
10990 	bf_set(wqe_si, &cmdwqe->gen_req.wge_ctl, 1);
10991 	bf_set(wqe_la, &cmdwqe->gen_req.wge_ctl, 1);
10992 
10993 	/* Word 6 */
10994 	bf_set(wqe_ctxt_tag, &cmdwqe->gen_req.wqe_com, rpi);
10995 
10996 	/* Word 7 */
10997 	bf_set(wqe_tmo, &cmdwqe->gen_req.wqe_com, tmo);
10998 	bf_set(wqe_class, &cmdwqe->gen_req.wqe_com, CLASS3);
10999 	bf_set(wqe_cmnd, &cmdwqe->gen_req.wqe_com, CMD_GEN_REQUEST64_CR);
11000 	bf_set(wqe_ct, &cmdwqe->gen_req.wqe_com, SLI4_CT_RPI);
11001 
11002 	/* Word 12 */
11003 	cmdwqe->gen_req.max_response_payload_len = total_len - xmit_len;
11004 }
11005 
11006 void
11007 lpfc_sli_prep_gen_req(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11008 		      struct lpfc_dmabuf *bmp, u16 rpi, u32 num_entry, u8 tmo)
11009 {
11010 	phba->__lpfc_sli_prep_gen_req(cmdiocbq, bmp, rpi, num_entry, tmo);
11011 }
11012 
11013 static void
11014 __lpfc_sli_prep_xmit_seq64_s3(struct lpfc_iocbq *cmdiocbq,
11015 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11016 			      u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11017 {
11018 	IOCB_t *icmd;
11019 
11020 	icmd = &cmdiocbq->iocb;
11021 	memset(icmd, 0, sizeof(*icmd));
11022 
11023 	icmd->un.xseq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
11024 	icmd->un.xseq64.bdl.addrLow = putPaddrLow(bmp->phys);
11025 	icmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
11026 	icmd->un.xseq64.bdl.bdeSize = (num_entry * sizeof(struct ulp_bde64));
11027 	icmd->un.xseq64.w5.hcsw.Fctl = LA;
11028 	if (last_seq)
11029 		icmd->un.xseq64.w5.hcsw.Fctl |= LS;
11030 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
11031 	icmd->un.xseq64.w5.hcsw.Rctl = rctl;
11032 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
11033 
11034 	icmd->ulpBdeCount = 1;
11035 	icmd->ulpLe = 1;
11036 	icmd->ulpClass = CLASS3;
11037 
11038 	switch (cr_cx_cmd) {
11039 	case CMD_XMIT_SEQUENCE64_CR:
11040 		icmd->ulpContext = rpi;
11041 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CR;
11042 		break;
11043 	case CMD_XMIT_SEQUENCE64_CX:
11044 		icmd->ulpContext = ox_id;
11045 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CX;
11046 		break;
11047 	default:
11048 		break;
11049 	}
11050 }
11051 
11052 static void
11053 __lpfc_sli_prep_xmit_seq64_s4(struct lpfc_iocbq *cmdiocbq,
11054 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11055 			      u32 full_size, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11056 {
11057 	union lpfc_wqe128 *wqe;
11058 	struct ulp_bde64 *bpl;
11059 
11060 	wqe = &cmdiocbq->wqe;
11061 	memset(wqe, 0, sizeof(*wqe));
11062 
11063 	/* Words 0 - 2 */
11064 	bpl = (struct ulp_bde64 *)bmp->virt;
11065 	wqe->xmit_sequence.bde.addrHigh = bpl->addrHigh;
11066 	wqe->xmit_sequence.bde.addrLow = bpl->addrLow;
11067 	wqe->xmit_sequence.bde.tus.w = bpl->tus.w;
11068 
11069 	/* Word 5 */
11070 	bf_set(wqe_ls, &wqe->xmit_sequence.wge_ctl, last_seq);
11071 	bf_set(wqe_la, &wqe->xmit_sequence.wge_ctl, 1);
11072 	bf_set(wqe_dfctl, &wqe->xmit_sequence.wge_ctl, 0);
11073 	bf_set(wqe_rctl, &wqe->xmit_sequence.wge_ctl, rctl);
11074 	bf_set(wqe_type, &wqe->xmit_sequence.wge_ctl, FC_TYPE_CT);
11075 
11076 	/* Word 6 */
11077 	bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com, rpi);
11078 
11079 	bf_set(wqe_cmnd, &wqe->xmit_sequence.wqe_com,
11080 	       CMD_XMIT_SEQUENCE64_WQE);
11081 
11082 	/* Word 7 */
11083 	bf_set(wqe_class, &wqe->xmit_sequence.wqe_com, CLASS3);
11084 
11085 	/* Word 9 */
11086 	bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com, ox_id);
11087 
11088 	/* Word 12 */
11089 	if (cmdiocbq->cmd_flag & (LPFC_IO_LIBDFC | LPFC_IO_LOOPBACK))
11090 		wqe->xmit_sequence.xmit_len = full_size;
11091 	else
11092 		wqe->xmit_sequence.xmit_len =
11093 			wqe->xmit_sequence.bde.tus.f.bdeSize;
11094 }
11095 
11096 void
11097 lpfc_sli_prep_xmit_seq64(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11098 			 struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11099 			 u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11100 {
11101 	phba->__lpfc_sli_prep_xmit_seq64(cmdiocbq, bmp, rpi, ox_id, num_entry,
11102 					 rctl, last_seq, cr_cx_cmd);
11103 }
11104 
11105 static void
11106 __lpfc_sli_prep_abort_xri_s3(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11107 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11108 			     bool wqec)
11109 {
11110 	IOCB_t *icmd = NULL;
11111 
11112 	icmd = &cmdiocbq->iocb;
11113 	memset(icmd, 0, sizeof(*icmd));
11114 
11115 	/* Word 5 */
11116 	icmd->un.acxri.abortContextTag = ulp_context;
11117 	icmd->un.acxri.abortIoTag = iotag;
11118 
11119 	if (ia) {
11120 		/* Word 7 */
11121 		icmd->ulpCommand = CMD_CLOSE_XRI_CN;
11122 	} else {
11123 		/* Word 3 */
11124 		icmd->un.acxri.abortType = ABORT_TYPE_ABTS;
11125 
11126 		/* Word 7 */
11127 		icmd->ulpClass = ulp_class;
11128 		icmd->ulpCommand = CMD_ABORT_XRI_CN;
11129 	}
11130 
11131 	/* Word 7 */
11132 	icmd->ulpLe = 1;
11133 }
11134 
11135 static void
11136 __lpfc_sli_prep_abort_xri_s4(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11137 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11138 			     bool wqec)
11139 {
11140 	union lpfc_wqe128 *wqe;
11141 
11142 	wqe = &cmdiocbq->wqe;
11143 	memset(wqe, 0, sizeof(*wqe));
11144 
11145 	/* Word 3 */
11146 	bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
11147 	if (ia)
11148 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
11149 	else
11150 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
11151 
11152 	/* Word 7 */
11153 	bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_WQE);
11154 
11155 	/* Word 8 */
11156 	wqe->abort_cmd.wqe_com.abort_tag = ulp_context;
11157 
11158 	/* Word 9 */
11159 	bf_set(wqe_reqtag, &wqe->abort_cmd.wqe_com, iotag);
11160 
11161 	/* Word 10 */
11162 	bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
11163 
11164 	/* Word 11 */
11165 	if (wqec)
11166 		bf_set(wqe_wqec, &wqe->abort_cmd.wqe_com, 1);
11167 	bf_set(wqe_cqid, &wqe->abort_cmd.wqe_com, cqid);
11168 	bf_set(wqe_cmd_type, &wqe->abort_cmd.wqe_com, OTHER_COMMAND);
11169 }
11170 
11171 void
11172 lpfc_sli_prep_abort_xri(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11173 			u16 ulp_context, u16 iotag, u8 ulp_class, u16 cqid,
11174 			bool ia, bool wqec)
11175 {
11176 	phba->__lpfc_sli_prep_abort_xri(cmdiocbq, ulp_context, iotag, ulp_class,
11177 					cqid, ia, wqec);
11178 }
11179 
11180 /**
11181  * lpfc_sli_api_table_setup - Set up sli api function jump table
11182  * @phba: The hba struct for which this call is being executed.
11183  * @dev_grp: The HBA PCI-Device group number.
11184  *
11185  * This routine sets up the SLI interface API function jump table in @phba
11186  * struct.
11187  * Returns: 0 - success, -ENODEV - failure.
11188  **/
11189 int
11190 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
11191 {
11192 
11193 	switch (dev_grp) {
11194 	case LPFC_PCI_DEV_LP:
11195 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
11196 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
11197 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
11198 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s3;
11199 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s3;
11200 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s3;
11201 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s3;
11202 		break;
11203 	case LPFC_PCI_DEV_OC:
11204 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
11205 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
11206 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
11207 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s4;
11208 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s4;
11209 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s4;
11210 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s4;
11211 		break;
11212 	default:
11213 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11214 				"1419 Invalid HBA PCI-device group: 0x%x\n",
11215 				dev_grp);
11216 		return -ENODEV;
11217 	}
11218 	return 0;
11219 }
11220 
11221 /**
11222  * lpfc_sli4_calc_ring - Calculates which ring to use
11223  * @phba: Pointer to HBA context object.
11224  * @piocb: Pointer to command iocb.
11225  *
11226  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
11227  * hba_wqidx, thus we need to calculate the corresponding ring.
11228  * Since ABORTS must go on the same WQ of the command they are
11229  * aborting, we use command's hba_wqidx.
11230  */
11231 struct lpfc_sli_ring *
11232 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
11233 {
11234 	struct lpfc_io_buf *lpfc_cmd;
11235 
11236 	if (piocb->cmd_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
11237 		if (unlikely(!phba->sli4_hba.hdwq))
11238 			return NULL;
11239 		/*
11240 		 * for abort iocb hba_wqidx should already
11241 		 * be setup based on what work queue we used.
11242 		 */
11243 		if (!(piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
11244 			lpfc_cmd = piocb->io_buf;
11245 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
11246 		}
11247 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
11248 	} else {
11249 		if (unlikely(!phba->sli4_hba.els_wq))
11250 			return NULL;
11251 		piocb->hba_wqidx = 0;
11252 		return phba->sli4_hba.els_wq->pring;
11253 	}
11254 }
11255 
11256 inline void lpfc_sli4_poll_eq(struct lpfc_queue *eq)
11257 {
11258 	struct lpfc_hba *phba = eq->phba;
11259 
11260 	/*
11261 	 * Unlocking an irq is one of the entry point to check
11262 	 * for re-schedule, but we are good for io submission
11263 	 * path as midlayer does a get_cpu to glue us in. Flush
11264 	 * out the invalidate queue so we can see the updated
11265 	 * value for flag.
11266 	 */
11267 	smp_rmb();
11268 
11269 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
11270 		/* We will not likely get the completion for the caller
11271 		 * during this iteration but i guess that's fine.
11272 		 * Future io's coming on this eq should be able to
11273 		 * pick it up.  As for the case of single io's, they
11274 		 * will be handled through a sched from polling timer
11275 		 * function which is currently triggered every 1msec.
11276 		 */
11277 		lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM,
11278 				     LPFC_QUEUE_WORK);
11279 }
11280 
11281 /**
11282  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
11283  * @phba: Pointer to HBA context object.
11284  * @ring_number: Ring number
11285  * @piocb: Pointer to command iocb.
11286  * @flag: Flag indicating if this command can be put into txq.
11287  *
11288  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
11289  * function. This function gets the hbalock and calls
11290  * __lpfc_sli_issue_iocb function and will return the error returned
11291  * by __lpfc_sli_issue_iocb function. This wrapper is used by
11292  * functions which do not hold hbalock.
11293  **/
11294 int
11295 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
11296 		    struct lpfc_iocbq *piocb, uint32_t flag)
11297 {
11298 	struct lpfc_sli_ring *pring;
11299 	struct lpfc_queue *eq;
11300 	unsigned long iflags;
11301 	int rc;
11302 
11303 	/* If the PCI channel is in offline state, do not post iocbs. */
11304 	if (unlikely(pci_channel_offline(phba->pcidev)))
11305 		return IOCB_ERROR;
11306 
11307 	if (phba->sli_rev == LPFC_SLI_REV4) {
11308 		lpfc_sli_prep_wqe(phba, piocb);
11309 
11310 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
11311 
11312 		pring = lpfc_sli4_calc_ring(phba, piocb);
11313 		if (unlikely(pring == NULL))
11314 			return IOCB_ERROR;
11315 
11316 		spin_lock_irqsave(&pring->ring_lock, iflags);
11317 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11318 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11319 
11320 		lpfc_sli4_poll_eq(eq);
11321 	} else {
11322 		/* For now, SLI2/3 will still use hbalock */
11323 		spin_lock_irqsave(&phba->hbalock, iflags);
11324 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11325 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11326 	}
11327 	return rc;
11328 }
11329 
11330 /**
11331  * lpfc_extra_ring_setup - Extra ring setup function
11332  * @phba: Pointer to HBA context object.
11333  *
11334  * This function is called while driver attaches with the
11335  * HBA to setup the extra ring. The extra ring is used
11336  * only when driver needs to support target mode functionality
11337  * or IP over FC functionalities.
11338  *
11339  * This function is called with no lock held. SLI3 only.
11340  **/
11341 static int
11342 lpfc_extra_ring_setup( struct lpfc_hba *phba)
11343 {
11344 	struct lpfc_sli *psli;
11345 	struct lpfc_sli_ring *pring;
11346 
11347 	psli = &phba->sli;
11348 
11349 	/* Adjust cmd/rsp ring iocb entries more evenly */
11350 
11351 	/* Take some away from the FCP ring */
11352 	pring = &psli->sli3_ring[LPFC_FCP_RING];
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 	/* and give them to the extra ring */
11359 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
11360 
11361 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11362 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11363 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11364 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11365 
11366 	/* Setup default profile for this ring */
11367 	pring->iotag_max = 4096;
11368 	pring->num_mask = 1;
11369 	pring->prt[0].profile = 0;      /* Mask 0 */
11370 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
11371 	pring->prt[0].type = phba->cfg_multi_ring_type;
11372 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
11373 	return 0;
11374 }
11375 
11376 static void
11377 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
11378 			     struct lpfc_nodelist *ndlp)
11379 {
11380 	unsigned long iflags;
11381 	struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
11382 
11383 	/* Hold a node reference for outstanding queued work */
11384 	if (!lpfc_nlp_get(ndlp))
11385 		return;
11386 
11387 	spin_lock_irqsave(&phba->hbalock, iflags);
11388 	if (!list_empty(&evtp->evt_listp)) {
11389 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11390 		lpfc_nlp_put(ndlp);
11391 		return;
11392 	}
11393 
11394 	evtp->evt_arg1 = ndlp;
11395 	evtp->evt = LPFC_EVT_RECOVER_PORT;
11396 	list_add_tail(&evtp->evt_listp, &phba->work_list);
11397 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11398 
11399 	lpfc_worker_wake_up(phba);
11400 }
11401 
11402 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
11403  * @phba: Pointer to HBA context object.
11404  * @iocbq: Pointer to iocb object.
11405  *
11406  * The async_event handler calls this routine when it receives
11407  * an ASYNC_STATUS_CN event from the port.  The port generates
11408  * this event when an Abort Sequence request to an rport fails
11409  * twice in succession.  The abort could be originated by the
11410  * driver or by the port.  The ABTS could have been for an ELS
11411  * or FCP IO.  The port only generates this event when an ABTS
11412  * fails to complete after one retry.
11413  */
11414 static void
11415 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
11416 			  struct lpfc_iocbq *iocbq)
11417 {
11418 	struct lpfc_nodelist *ndlp = NULL;
11419 	uint16_t rpi = 0, vpi = 0;
11420 	struct lpfc_vport *vport = NULL;
11421 
11422 	/* The rpi in the ulpContext is vport-sensitive. */
11423 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
11424 	rpi = iocbq->iocb.ulpContext;
11425 
11426 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11427 			"3092 Port generated ABTS async event "
11428 			"on vpi %d rpi %d status 0x%x\n",
11429 			vpi, rpi, iocbq->iocb.ulpStatus);
11430 
11431 	vport = lpfc_find_vport_by_vpid(phba, vpi);
11432 	if (!vport)
11433 		goto err_exit;
11434 	ndlp = lpfc_findnode_rpi(vport, rpi);
11435 	if (!ndlp)
11436 		goto err_exit;
11437 
11438 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
11439 		lpfc_sli_abts_recover_port(vport, ndlp);
11440 	return;
11441 
11442  err_exit:
11443 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11444 			"3095 Event Context not found, no "
11445 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
11446 			vpi, rpi, iocbq->iocb.ulpStatus,
11447 			iocbq->iocb.ulpContext);
11448 }
11449 
11450 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
11451  * @phba: pointer to HBA context object.
11452  * @ndlp: nodelist pointer for the impacted rport.
11453  * @axri: pointer to the wcqe containing the failed exchange.
11454  *
11455  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
11456  * port.  The port generates this event when an abort exchange request to an
11457  * rport fails twice in succession with no reply.  The abort could be originated
11458  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
11459  */
11460 void
11461 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
11462 			   struct lpfc_nodelist *ndlp,
11463 			   struct sli4_wcqe_xri_aborted *axri)
11464 {
11465 	uint32_t ext_status = 0;
11466 
11467 	if (!ndlp) {
11468 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11469 				"3115 Node Context not found, driver "
11470 				"ignoring abts err event\n");
11471 		return;
11472 	}
11473 
11474 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11475 			"3116 Port generated FCP XRI ABORT event on "
11476 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
11477 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
11478 			bf_get(lpfc_wcqe_xa_xri, axri),
11479 			bf_get(lpfc_wcqe_xa_status, axri),
11480 			axri->parameter);
11481 
11482 	/*
11483 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
11484 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
11485 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
11486 	 */
11487 	ext_status = axri->parameter & IOERR_PARAM_MASK;
11488 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
11489 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
11490 		lpfc_sli_post_recovery_event(phba, ndlp);
11491 }
11492 
11493 /**
11494  * lpfc_sli_async_event_handler - ASYNC iocb handler function
11495  * @phba: Pointer to HBA context object.
11496  * @pring: Pointer to driver SLI ring object.
11497  * @iocbq: Pointer to iocb object.
11498  *
11499  * This function is called by the slow ring event handler
11500  * function when there is an ASYNC event iocb in the ring.
11501  * This function is called with no lock held.
11502  * Currently this function handles only temperature related
11503  * ASYNC events. The function decodes the temperature sensor
11504  * event message and posts events for the management applications.
11505  **/
11506 static void
11507 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
11508 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
11509 {
11510 	IOCB_t *icmd;
11511 	uint16_t evt_code;
11512 	struct temp_event temp_event_data;
11513 	struct Scsi_Host *shost;
11514 	uint32_t *iocb_w;
11515 
11516 	icmd = &iocbq->iocb;
11517 	evt_code = icmd->un.asyncstat.evt_code;
11518 
11519 	switch (evt_code) {
11520 	case ASYNC_TEMP_WARN:
11521 	case ASYNC_TEMP_SAFE:
11522 		temp_event_data.data = (uint32_t) icmd->ulpContext;
11523 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
11524 		if (evt_code == ASYNC_TEMP_WARN) {
11525 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
11526 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11527 				"0347 Adapter is very hot, please take "
11528 				"corrective action. temperature : %d Celsius\n",
11529 				(uint32_t) icmd->ulpContext);
11530 		} else {
11531 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
11532 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11533 				"0340 Adapter temperature is OK now. "
11534 				"temperature : %d Celsius\n",
11535 				(uint32_t) icmd->ulpContext);
11536 		}
11537 
11538 		/* Send temperature change event to applications */
11539 		shost = lpfc_shost_from_vport(phba->pport);
11540 		fc_host_post_vendor_event(shost, fc_get_event_number(),
11541 			sizeof(temp_event_data), (char *) &temp_event_data,
11542 			LPFC_NL_VENDOR_ID);
11543 		break;
11544 	case ASYNC_STATUS_CN:
11545 		lpfc_sli_abts_err_handler(phba, iocbq);
11546 		break;
11547 	default:
11548 		iocb_w = (uint32_t *) icmd;
11549 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11550 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
11551 			" evt_code 0x%x\n"
11552 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
11553 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
11554 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
11555 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
11556 			pring->ringno, icmd->un.asyncstat.evt_code,
11557 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
11558 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
11559 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
11560 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
11561 
11562 		break;
11563 	}
11564 }
11565 
11566 
11567 /**
11568  * lpfc_sli4_setup - SLI ring setup function
11569  * @phba: Pointer to HBA context object.
11570  *
11571  * lpfc_sli_setup sets up rings of the SLI interface with
11572  * number of iocbs per ring and iotags. This function is
11573  * called while driver attach to the HBA and before the
11574  * interrupts are enabled. So there is no need for locking.
11575  *
11576  * This function always returns 0.
11577  **/
11578 int
11579 lpfc_sli4_setup(struct lpfc_hba *phba)
11580 {
11581 	struct lpfc_sli_ring *pring;
11582 
11583 	pring = phba->sli4_hba.els_wq->pring;
11584 	pring->num_mask = LPFC_MAX_RING_MASK;
11585 	pring->prt[0].profile = 0;	/* Mask 0 */
11586 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11587 	pring->prt[0].type = FC_TYPE_ELS;
11588 	pring->prt[0].lpfc_sli_rcv_unsol_event =
11589 	    lpfc_els_unsol_event;
11590 	pring->prt[1].profile = 0;	/* Mask 1 */
11591 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
11592 	pring->prt[1].type = FC_TYPE_ELS;
11593 	pring->prt[1].lpfc_sli_rcv_unsol_event =
11594 	    lpfc_els_unsol_event;
11595 	pring->prt[2].profile = 0;	/* Mask 2 */
11596 	/* NameServer Inquiry */
11597 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11598 	/* NameServer */
11599 	pring->prt[2].type = FC_TYPE_CT;
11600 	pring->prt[2].lpfc_sli_rcv_unsol_event =
11601 	    lpfc_ct_unsol_event;
11602 	pring->prt[3].profile = 0;	/* Mask 3 */
11603 	/* NameServer response */
11604 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11605 	/* NameServer */
11606 	pring->prt[3].type = FC_TYPE_CT;
11607 	pring->prt[3].lpfc_sli_rcv_unsol_event =
11608 	    lpfc_ct_unsol_event;
11609 	return 0;
11610 }
11611 
11612 /**
11613  * lpfc_sli_setup - SLI ring setup function
11614  * @phba: Pointer to HBA context object.
11615  *
11616  * lpfc_sli_setup sets up rings of the SLI interface with
11617  * number of iocbs per ring and iotags. This function is
11618  * called while driver attach to the HBA and before the
11619  * interrupts are enabled. So there is no need for locking.
11620  *
11621  * This function always returns 0. SLI3 only.
11622  **/
11623 int
11624 lpfc_sli_setup(struct lpfc_hba *phba)
11625 {
11626 	int i, totiocbsize = 0;
11627 	struct lpfc_sli *psli = &phba->sli;
11628 	struct lpfc_sli_ring *pring;
11629 
11630 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
11631 	psli->sli_flag = 0;
11632 
11633 	psli->iocbq_lookup = NULL;
11634 	psli->iocbq_lookup_len = 0;
11635 	psli->last_iotag = 0;
11636 
11637 	for (i = 0; i < psli->num_rings; i++) {
11638 		pring = &psli->sli3_ring[i];
11639 		switch (i) {
11640 		case LPFC_FCP_RING:	/* ring 0 - FCP */
11641 			/* numCiocb and numRiocb are used in config_port */
11642 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
11643 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
11644 			pring->sli.sli3.numCiocb +=
11645 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11646 			pring->sli.sli3.numRiocb +=
11647 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11648 			pring->sli.sli3.numCiocb +=
11649 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11650 			pring->sli.sli3.numRiocb +=
11651 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11652 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11653 							SLI3_IOCB_CMD_SIZE :
11654 							SLI2_IOCB_CMD_SIZE;
11655 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11656 							SLI3_IOCB_RSP_SIZE :
11657 							SLI2_IOCB_RSP_SIZE;
11658 			pring->iotag_ctr = 0;
11659 			pring->iotag_max =
11660 			    (phba->cfg_hba_queue_depth * 2);
11661 			pring->fast_iotag = pring->iotag_max;
11662 			pring->num_mask = 0;
11663 			break;
11664 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
11665 			/* numCiocb and numRiocb are used in config_port */
11666 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
11667 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
11668 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11669 							SLI3_IOCB_CMD_SIZE :
11670 							SLI2_IOCB_CMD_SIZE;
11671 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11672 							SLI3_IOCB_RSP_SIZE :
11673 							SLI2_IOCB_RSP_SIZE;
11674 			pring->iotag_max = phba->cfg_hba_queue_depth;
11675 			pring->num_mask = 0;
11676 			break;
11677 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
11678 			/* numCiocb and numRiocb are used in config_port */
11679 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
11680 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
11681 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11682 							SLI3_IOCB_CMD_SIZE :
11683 							SLI2_IOCB_CMD_SIZE;
11684 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11685 							SLI3_IOCB_RSP_SIZE :
11686 							SLI2_IOCB_RSP_SIZE;
11687 			pring->fast_iotag = 0;
11688 			pring->iotag_ctr = 0;
11689 			pring->iotag_max = 4096;
11690 			pring->lpfc_sli_rcv_async_status =
11691 				lpfc_sli_async_event_handler;
11692 			pring->num_mask = LPFC_MAX_RING_MASK;
11693 			pring->prt[0].profile = 0;	/* Mask 0 */
11694 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11695 			pring->prt[0].type = FC_TYPE_ELS;
11696 			pring->prt[0].lpfc_sli_rcv_unsol_event =
11697 			    lpfc_els_unsol_event;
11698 			pring->prt[1].profile = 0;	/* Mask 1 */
11699 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
11700 			pring->prt[1].type = FC_TYPE_ELS;
11701 			pring->prt[1].lpfc_sli_rcv_unsol_event =
11702 			    lpfc_els_unsol_event;
11703 			pring->prt[2].profile = 0;	/* Mask 2 */
11704 			/* NameServer Inquiry */
11705 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11706 			/* NameServer */
11707 			pring->prt[2].type = FC_TYPE_CT;
11708 			pring->prt[2].lpfc_sli_rcv_unsol_event =
11709 			    lpfc_ct_unsol_event;
11710 			pring->prt[3].profile = 0;	/* Mask 3 */
11711 			/* NameServer response */
11712 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11713 			/* NameServer */
11714 			pring->prt[3].type = FC_TYPE_CT;
11715 			pring->prt[3].lpfc_sli_rcv_unsol_event =
11716 			    lpfc_ct_unsol_event;
11717 			break;
11718 		}
11719 		totiocbsize += (pring->sli.sli3.numCiocb *
11720 			pring->sli.sli3.sizeCiocb) +
11721 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
11722 	}
11723 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
11724 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
11725 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
11726 		       "SLI2 SLIM Data: x%x x%lx\n",
11727 		       phba->brd_no, totiocbsize,
11728 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
11729 	}
11730 	if (phba->cfg_multi_ring_support == 2)
11731 		lpfc_extra_ring_setup(phba);
11732 
11733 	return 0;
11734 }
11735 
11736 /**
11737  * lpfc_sli4_queue_init - Queue initialization function
11738  * @phba: Pointer to HBA context object.
11739  *
11740  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
11741  * ring. This function also initializes ring indices of each ring.
11742  * This function is called during the initialization of the SLI
11743  * interface of an HBA.
11744  * This function is called with no lock held and always returns
11745  * 1.
11746  **/
11747 void
11748 lpfc_sli4_queue_init(struct lpfc_hba *phba)
11749 {
11750 	struct lpfc_sli *psli;
11751 	struct lpfc_sli_ring *pring;
11752 	int i;
11753 
11754 	psli = &phba->sli;
11755 	spin_lock_irq(&phba->hbalock);
11756 	INIT_LIST_HEAD(&psli->mboxq);
11757 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11758 	/* Initialize list headers for txq and txcmplq as double linked lists */
11759 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
11760 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
11761 		pring->flag = 0;
11762 		pring->ringno = LPFC_FCP_RING;
11763 		pring->txcmplq_cnt = 0;
11764 		INIT_LIST_HEAD(&pring->txq);
11765 		INIT_LIST_HEAD(&pring->txcmplq);
11766 		INIT_LIST_HEAD(&pring->iocb_continueq);
11767 		spin_lock_init(&pring->ring_lock);
11768 	}
11769 	pring = phba->sli4_hba.els_wq->pring;
11770 	pring->flag = 0;
11771 	pring->ringno = LPFC_ELS_RING;
11772 	pring->txcmplq_cnt = 0;
11773 	INIT_LIST_HEAD(&pring->txq);
11774 	INIT_LIST_HEAD(&pring->txcmplq);
11775 	INIT_LIST_HEAD(&pring->iocb_continueq);
11776 	spin_lock_init(&pring->ring_lock);
11777 
11778 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11779 		pring = phba->sli4_hba.nvmels_wq->pring;
11780 		pring->flag = 0;
11781 		pring->ringno = LPFC_ELS_RING;
11782 		pring->txcmplq_cnt = 0;
11783 		INIT_LIST_HEAD(&pring->txq);
11784 		INIT_LIST_HEAD(&pring->txcmplq);
11785 		INIT_LIST_HEAD(&pring->iocb_continueq);
11786 		spin_lock_init(&pring->ring_lock);
11787 	}
11788 
11789 	spin_unlock_irq(&phba->hbalock);
11790 }
11791 
11792 /**
11793  * lpfc_sli_queue_init - Queue initialization function
11794  * @phba: Pointer to HBA context object.
11795  *
11796  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11797  * ring. This function also initializes ring indices of each ring.
11798  * This function is called during the initialization of the SLI
11799  * interface of an HBA.
11800  * This function is called with no lock held and always returns
11801  * 1.
11802  **/
11803 void
11804 lpfc_sli_queue_init(struct lpfc_hba *phba)
11805 {
11806 	struct lpfc_sli *psli;
11807 	struct lpfc_sli_ring *pring;
11808 	int i;
11809 
11810 	psli = &phba->sli;
11811 	spin_lock_irq(&phba->hbalock);
11812 	INIT_LIST_HEAD(&psli->mboxq);
11813 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11814 	/* Initialize list headers for txq and txcmplq as double linked lists */
11815 	for (i = 0; i < psli->num_rings; i++) {
11816 		pring = &psli->sli3_ring[i];
11817 		pring->ringno = i;
11818 		pring->sli.sli3.next_cmdidx  = 0;
11819 		pring->sli.sli3.local_getidx = 0;
11820 		pring->sli.sli3.cmdidx = 0;
11821 		INIT_LIST_HEAD(&pring->iocb_continueq);
11822 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11823 		INIT_LIST_HEAD(&pring->postbufq);
11824 		pring->flag = 0;
11825 		INIT_LIST_HEAD(&pring->txq);
11826 		INIT_LIST_HEAD(&pring->txcmplq);
11827 		spin_lock_init(&pring->ring_lock);
11828 	}
11829 	spin_unlock_irq(&phba->hbalock);
11830 }
11831 
11832 /**
11833  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11834  * @phba: Pointer to HBA context object.
11835  *
11836  * This routine flushes the mailbox command subsystem. It will unconditionally
11837  * flush all the mailbox commands in the three possible stages in the mailbox
11838  * command sub-system: pending mailbox command queue; the outstanding mailbox
11839  * command; and completed mailbox command queue. It is caller's responsibility
11840  * to make sure that the driver is in the proper state to flush the mailbox
11841  * command sub-system. Namely, the posting of mailbox commands into the
11842  * pending mailbox command queue from the various clients must be stopped;
11843  * either the HBA is in a state that it will never works on the outstanding
11844  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11845  * mailbox command has been completed.
11846  **/
11847 static void
11848 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11849 {
11850 	LIST_HEAD(completions);
11851 	struct lpfc_sli *psli = &phba->sli;
11852 	LPFC_MBOXQ_t *pmb;
11853 	unsigned long iflag;
11854 
11855 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11856 	local_bh_disable();
11857 
11858 	/* Flush all the mailbox commands in the mbox system */
11859 	spin_lock_irqsave(&phba->hbalock, iflag);
11860 
11861 	/* The pending mailbox command queue */
11862 	list_splice_init(&phba->sli.mboxq, &completions);
11863 	/* The outstanding active mailbox command */
11864 	if (psli->mbox_active) {
11865 		list_add_tail(&psli->mbox_active->list, &completions);
11866 		psli->mbox_active = NULL;
11867 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11868 	}
11869 	/* The completed mailbox command queue */
11870 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11871 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11872 
11873 	/* Enable softirqs again, done with phba->hbalock */
11874 	local_bh_enable();
11875 
11876 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11877 	while (!list_empty(&completions)) {
11878 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11879 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11880 		if (pmb->mbox_cmpl)
11881 			pmb->mbox_cmpl(phba, pmb);
11882 	}
11883 }
11884 
11885 /**
11886  * lpfc_sli_host_down - Vport cleanup function
11887  * @vport: Pointer to virtual port object.
11888  *
11889  * lpfc_sli_host_down is called to clean up the resources
11890  * associated with a vport before destroying virtual
11891  * port data structures.
11892  * This function does following operations:
11893  * - Free discovery resources associated with this virtual
11894  *   port.
11895  * - Free iocbs associated with this virtual port in
11896  *   the txq.
11897  * - Send abort for all iocb commands associated with this
11898  *   vport in txcmplq.
11899  *
11900  * This function is called with no lock held and always returns 1.
11901  **/
11902 int
11903 lpfc_sli_host_down(struct lpfc_vport *vport)
11904 {
11905 	LIST_HEAD(completions);
11906 	struct lpfc_hba *phba = vport->phba;
11907 	struct lpfc_sli *psli = &phba->sli;
11908 	struct lpfc_queue *qp = NULL;
11909 	struct lpfc_sli_ring *pring;
11910 	struct lpfc_iocbq *iocb, *next_iocb;
11911 	int i;
11912 	unsigned long flags = 0;
11913 	uint16_t prev_pring_flag;
11914 
11915 	lpfc_cleanup_discovery_resources(vport);
11916 
11917 	spin_lock_irqsave(&phba->hbalock, flags);
11918 
11919 	/*
11920 	 * Error everything on the txq since these iocbs
11921 	 * have not been given to the FW yet.
11922 	 * Also issue ABTS for everything on the txcmplq
11923 	 */
11924 	if (phba->sli_rev != LPFC_SLI_REV4) {
11925 		for (i = 0; i < psli->num_rings; i++) {
11926 			pring = &psli->sli3_ring[i];
11927 			prev_pring_flag = pring->flag;
11928 			/* Only slow rings */
11929 			if (pring->ringno == LPFC_ELS_RING) {
11930 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11931 				/* Set the lpfc data pending flag */
11932 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11933 			}
11934 			list_for_each_entry_safe(iocb, next_iocb,
11935 						 &pring->txq, list) {
11936 				if (iocb->vport != vport)
11937 					continue;
11938 				list_move_tail(&iocb->list, &completions);
11939 			}
11940 			list_for_each_entry_safe(iocb, next_iocb,
11941 						 &pring->txcmplq, list) {
11942 				if (iocb->vport != vport)
11943 					continue;
11944 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11945 							   NULL);
11946 			}
11947 			pring->flag = prev_pring_flag;
11948 		}
11949 	} else {
11950 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11951 			pring = qp->pring;
11952 			if (!pring)
11953 				continue;
11954 			if (pring == phba->sli4_hba.els_wq->pring) {
11955 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11956 				/* Set the lpfc data pending flag */
11957 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11958 			}
11959 			prev_pring_flag = pring->flag;
11960 			spin_lock(&pring->ring_lock);
11961 			list_for_each_entry_safe(iocb, next_iocb,
11962 						 &pring->txq, list) {
11963 				if (iocb->vport != vport)
11964 					continue;
11965 				list_move_tail(&iocb->list, &completions);
11966 			}
11967 			spin_unlock(&pring->ring_lock);
11968 			list_for_each_entry_safe(iocb, next_iocb,
11969 						 &pring->txcmplq, list) {
11970 				if (iocb->vport != vport)
11971 					continue;
11972 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11973 							   NULL);
11974 			}
11975 			pring->flag = prev_pring_flag;
11976 		}
11977 	}
11978 	spin_unlock_irqrestore(&phba->hbalock, flags);
11979 
11980 	/* Make sure HBA is alive */
11981 	lpfc_issue_hb_tmo(phba);
11982 
11983 	/* Cancel all the IOCBs from the completions list */
11984 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11985 			      IOERR_SLI_DOWN);
11986 	return 1;
11987 }
11988 
11989 /**
11990  * lpfc_sli_hba_down - Resource cleanup function for the HBA
11991  * @phba: Pointer to HBA context object.
11992  *
11993  * This function cleans up all iocb, buffers, mailbox commands
11994  * while shutting down the HBA. This function is called with no
11995  * lock held and always returns 1.
11996  * This function does the following to cleanup driver resources:
11997  * - Free discovery resources for each virtual port
11998  * - Cleanup any pending fabric iocbs
11999  * - Iterate through the iocb txq and free each entry
12000  *   in the list.
12001  * - Free up any buffer posted to the HBA
12002  * - Free mailbox commands in the mailbox queue.
12003  **/
12004 int
12005 lpfc_sli_hba_down(struct lpfc_hba *phba)
12006 {
12007 	LIST_HEAD(completions);
12008 	struct lpfc_sli *psli = &phba->sli;
12009 	struct lpfc_queue *qp = NULL;
12010 	struct lpfc_sli_ring *pring;
12011 	struct lpfc_dmabuf *buf_ptr;
12012 	unsigned long flags = 0;
12013 	int i;
12014 
12015 	/* Shutdown the mailbox command sub-system */
12016 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
12017 
12018 	lpfc_hba_down_prep(phba);
12019 
12020 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12021 	local_bh_disable();
12022 
12023 	lpfc_fabric_abort_hba(phba);
12024 
12025 	spin_lock_irqsave(&phba->hbalock, flags);
12026 
12027 	/*
12028 	 * Error everything on the txq since these iocbs
12029 	 * have not been given to the FW yet.
12030 	 */
12031 	if (phba->sli_rev != LPFC_SLI_REV4) {
12032 		for (i = 0; i < psli->num_rings; i++) {
12033 			pring = &psli->sli3_ring[i];
12034 			/* Only slow rings */
12035 			if (pring->ringno == LPFC_ELS_RING) {
12036 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12037 				/* Set the lpfc data pending flag */
12038 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12039 			}
12040 			list_splice_init(&pring->txq, &completions);
12041 		}
12042 	} else {
12043 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12044 			pring = qp->pring;
12045 			if (!pring)
12046 				continue;
12047 			spin_lock(&pring->ring_lock);
12048 			list_splice_init(&pring->txq, &completions);
12049 			spin_unlock(&pring->ring_lock);
12050 			if (pring == phba->sli4_hba.els_wq->pring) {
12051 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12052 				/* Set the lpfc data pending flag */
12053 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12054 			}
12055 		}
12056 	}
12057 	spin_unlock_irqrestore(&phba->hbalock, flags);
12058 
12059 	/* Cancel all the IOCBs from the completions list */
12060 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
12061 			      IOERR_SLI_DOWN);
12062 
12063 	spin_lock_irqsave(&phba->hbalock, flags);
12064 	list_splice_init(&phba->elsbuf, &completions);
12065 	phba->elsbuf_cnt = 0;
12066 	phba->elsbuf_prev_cnt = 0;
12067 	spin_unlock_irqrestore(&phba->hbalock, flags);
12068 
12069 	while (!list_empty(&completions)) {
12070 		list_remove_head(&completions, buf_ptr,
12071 			struct lpfc_dmabuf, list);
12072 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
12073 		kfree(buf_ptr);
12074 	}
12075 
12076 	/* Enable softirqs again, done with phba->hbalock */
12077 	local_bh_enable();
12078 
12079 	/* Return any active mbox cmds */
12080 	del_timer_sync(&psli->mbox_tmo);
12081 
12082 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
12083 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
12084 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
12085 
12086 	return 1;
12087 }
12088 
12089 /**
12090  * lpfc_sli_pcimem_bcopy - SLI memory copy function
12091  * @srcp: Source memory pointer.
12092  * @destp: Destination memory pointer.
12093  * @cnt: Number of words required to be copied.
12094  *
12095  * This function is used for copying data between driver memory
12096  * and the SLI memory. This function also changes the endianness
12097  * of each word if native endianness is different from SLI
12098  * endianness. This function can be called with or without
12099  * lock.
12100  **/
12101 void
12102 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
12103 {
12104 	uint32_t *src = srcp;
12105 	uint32_t *dest = destp;
12106 	uint32_t ldata;
12107 	int i;
12108 
12109 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
12110 		ldata = *src;
12111 		ldata = le32_to_cpu(ldata);
12112 		*dest = ldata;
12113 		src++;
12114 		dest++;
12115 	}
12116 }
12117 
12118 
12119 /**
12120  * lpfc_sli_bemem_bcopy - SLI memory copy function
12121  * @srcp: Source memory pointer.
12122  * @destp: Destination memory pointer.
12123  * @cnt: Number of words required to be copied.
12124  *
12125  * This function is used for copying data between a data structure
12126  * with big endian representation to local endianness.
12127  * This function can be called with or without lock.
12128  **/
12129 void
12130 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
12131 {
12132 	uint32_t *src = srcp;
12133 	uint32_t *dest = destp;
12134 	uint32_t ldata;
12135 	int i;
12136 
12137 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
12138 		ldata = *src;
12139 		ldata = be32_to_cpu(ldata);
12140 		*dest = ldata;
12141 		src++;
12142 		dest++;
12143 	}
12144 }
12145 
12146 /**
12147  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
12148  * @phba: Pointer to HBA context object.
12149  * @pring: Pointer to driver SLI ring object.
12150  * @mp: Pointer to driver buffer object.
12151  *
12152  * This function is called with no lock held.
12153  * It always return zero after adding the buffer to the postbufq
12154  * buffer list.
12155  **/
12156 int
12157 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12158 			 struct lpfc_dmabuf *mp)
12159 {
12160 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
12161 	   later */
12162 	spin_lock_irq(&phba->hbalock);
12163 	list_add_tail(&mp->list, &pring->postbufq);
12164 	pring->postbufq_cnt++;
12165 	spin_unlock_irq(&phba->hbalock);
12166 	return 0;
12167 }
12168 
12169 /**
12170  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
12171  * @phba: Pointer to HBA context object.
12172  *
12173  * When HBQ is enabled, buffers are searched based on tags. This function
12174  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
12175  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
12176  * does not conflict with tags of buffer posted for unsolicited events.
12177  * The function returns the allocated tag. The function is called with
12178  * no locks held.
12179  **/
12180 uint32_t
12181 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
12182 {
12183 	spin_lock_irq(&phba->hbalock);
12184 	phba->buffer_tag_count++;
12185 	/*
12186 	 * Always set the QUE_BUFTAG_BIT to distiguish between
12187 	 * a tag assigned by HBQ.
12188 	 */
12189 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
12190 	spin_unlock_irq(&phba->hbalock);
12191 	return phba->buffer_tag_count;
12192 }
12193 
12194 /**
12195  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
12196  * @phba: Pointer to HBA context object.
12197  * @pring: Pointer to driver SLI ring object.
12198  * @tag: Buffer tag.
12199  *
12200  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
12201  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
12202  * iocb is posted to the response ring with the tag of the buffer.
12203  * This function searches the pring->postbufq list using the tag
12204  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
12205  * iocb. If the buffer is found then lpfc_dmabuf object of the
12206  * buffer is returned to the caller else NULL is returned.
12207  * This function is called with no lock held.
12208  **/
12209 struct lpfc_dmabuf *
12210 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12211 			uint32_t tag)
12212 {
12213 	struct lpfc_dmabuf *mp, *next_mp;
12214 	struct list_head *slp = &pring->postbufq;
12215 
12216 	/* Search postbufq, from the beginning, looking for a match on tag */
12217 	spin_lock_irq(&phba->hbalock);
12218 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12219 		if (mp->buffer_tag == tag) {
12220 			list_del_init(&mp->list);
12221 			pring->postbufq_cnt--;
12222 			spin_unlock_irq(&phba->hbalock);
12223 			return mp;
12224 		}
12225 	}
12226 
12227 	spin_unlock_irq(&phba->hbalock);
12228 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12229 			"0402 Cannot find virtual addr for buffer tag on "
12230 			"ring %d Data x%lx x%px x%px x%x\n",
12231 			pring->ringno, (unsigned long) tag,
12232 			slp->next, slp->prev, pring->postbufq_cnt);
12233 
12234 	return NULL;
12235 }
12236 
12237 /**
12238  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
12239  * @phba: Pointer to HBA context object.
12240  * @pring: Pointer to driver SLI ring object.
12241  * @phys: DMA address of the buffer.
12242  *
12243  * This function searches the buffer list using the dma_address
12244  * of unsolicited event to find the driver's lpfc_dmabuf object
12245  * corresponding to the dma_address. The function returns the
12246  * lpfc_dmabuf object if a buffer is found else it returns NULL.
12247  * This function is called by the ct and els unsolicited event
12248  * handlers to get the buffer associated with the unsolicited
12249  * event.
12250  *
12251  * This function is called with no lock held.
12252  **/
12253 struct lpfc_dmabuf *
12254 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12255 			 dma_addr_t phys)
12256 {
12257 	struct lpfc_dmabuf *mp, *next_mp;
12258 	struct list_head *slp = &pring->postbufq;
12259 
12260 	/* Search postbufq, from the beginning, looking for a match on phys */
12261 	spin_lock_irq(&phba->hbalock);
12262 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12263 		if (mp->phys == phys) {
12264 			list_del_init(&mp->list);
12265 			pring->postbufq_cnt--;
12266 			spin_unlock_irq(&phba->hbalock);
12267 			return mp;
12268 		}
12269 	}
12270 
12271 	spin_unlock_irq(&phba->hbalock);
12272 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12273 			"0410 Cannot find virtual addr for mapped buf on "
12274 			"ring %d Data x%llx x%px x%px x%x\n",
12275 			pring->ringno, (unsigned long long)phys,
12276 			slp->next, slp->prev, pring->postbufq_cnt);
12277 	return NULL;
12278 }
12279 
12280 /**
12281  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
12282  * @phba: Pointer to HBA context object.
12283  * @cmdiocb: Pointer to driver command iocb object.
12284  * @rspiocb: Pointer to driver response iocb object.
12285  *
12286  * This function is the completion handler for the abort iocbs for
12287  * ELS commands. This function is called from the ELS ring event
12288  * handler with no lock held. This function frees memory resources
12289  * associated with the abort iocb.
12290  **/
12291 static void
12292 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12293 			struct lpfc_iocbq *rspiocb)
12294 {
12295 	u32 ulp_status = get_job_ulpstatus(phba, rspiocb);
12296 	u32 ulp_word4 = get_job_word4(phba, rspiocb);
12297 	u8 cmnd = get_job_cmnd(phba, cmdiocb);
12298 
12299 	if (ulp_status) {
12300 		/*
12301 		 * Assume that the port already completed and returned, or
12302 		 * will return the iocb. Just Log the message.
12303 		 */
12304 		if (phba->sli_rev < LPFC_SLI_REV4) {
12305 			if (cmnd == CMD_ABORT_XRI_CX &&
12306 			    ulp_status == IOSTAT_LOCAL_REJECT &&
12307 			    ulp_word4 == IOERR_ABORT_REQUESTED) {
12308 				goto release_iocb;
12309 			}
12310 		}
12311 
12312 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
12313 				"0327 Cannot abort els iocb x%px "
12314 				"with io cmd xri %x abort tag : x%x, "
12315 				"abort status %x abort code %x\n",
12316 				cmdiocb, get_job_abtsiotag(phba, cmdiocb),
12317 				(phba->sli_rev == LPFC_SLI_REV4) ?
12318 				get_wqe_reqtag(cmdiocb) :
12319 				cmdiocb->iocb.un.acxri.abortContextTag,
12320 				ulp_status, ulp_word4);
12321 
12322 	}
12323 release_iocb:
12324 	lpfc_sli_release_iocbq(phba, cmdiocb);
12325 	return;
12326 }
12327 
12328 /**
12329  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
12330  * @phba: Pointer to HBA context object.
12331  * @cmdiocb: Pointer to driver command iocb object.
12332  * @rspiocb: Pointer to driver response iocb object.
12333  *
12334  * The function is called from SLI ring event handler with no
12335  * lock held. This function is the completion handler for ELS commands
12336  * which are aborted. The function frees memory resources used for
12337  * the aborted ELS commands.
12338  **/
12339 void
12340 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12341 		     struct lpfc_iocbq *rspiocb)
12342 {
12343 	struct lpfc_nodelist *ndlp = cmdiocb->ndlp;
12344 	IOCB_t *irsp;
12345 	LPFC_MBOXQ_t *mbox;
12346 	u32 ulp_command, ulp_status, ulp_word4, iotag;
12347 
12348 	ulp_command = get_job_cmnd(phba, cmdiocb);
12349 	ulp_status = get_job_ulpstatus(phba, rspiocb);
12350 	ulp_word4 = get_job_word4(phba, rspiocb);
12351 
12352 	if (phba->sli_rev == LPFC_SLI_REV4) {
12353 		iotag = get_wqe_reqtag(cmdiocb);
12354 	} else {
12355 		irsp = &rspiocb->iocb;
12356 		iotag = irsp->ulpIoTag;
12357 
12358 		/* It is possible a PLOGI_RJT for NPIV ports to get aborted.
12359 		 * The MBX_REG_LOGIN64 mbox command is freed back to the
12360 		 * mbox_mem_pool here.
12361 		 */
12362 		if (cmdiocb->context_un.mbox) {
12363 			mbox = cmdiocb->context_un.mbox;
12364 			lpfc_mbox_rsrc_cleanup(phba, mbox, MBOX_THD_UNLOCKED);
12365 			cmdiocb->context_un.mbox = NULL;
12366 		}
12367 	}
12368 
12369 	/* ELS cmd tag <ulpIoTag> completes */
12370 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
12371 			"0139 Ignoring ELS cmd code x%x completion Data: "
12372 			"x%x x%x x%x x%px\n",
12373 			ulp_command, ulp_status, ulp_word4, iotag,
12374 			cmdiocb->ndlp);
12375 	/*
12376 	 * Deref the ndlp after free_iocb. sli_release_iocb will access the ndlp
12377 	 * if exchange is busy.
12378 	 */
12379 	if (ulp_command == CMD_GEN_REQUEST64_CR)
12380 		lpfc_ct_free_iocb(phba, cmdiocb);
12381 	else
12382 		lpfc_els_free_iocb(phba, cmdiocb);
12383 
12384 	lpfc_nlp_put(ndlp);
12385 }
12386 
12387 /**
12388  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
12389  * @phba: Pointer to HBA context object.
12390  * @pring: Pointer to driver SLI ring object.
12391  * @cmdiocb: Pointer to driver command iocb object.
12392  * @cmpl: completion function.
12393  *
12394  * This function issues an abort iocb for the provided command iocb. In case
12395  * of unloading, the abort iocb will not be issued to commands on the ELS
12396  * ring. Instead, the callback function shall be changed to those commands
12397  * so that nothing happens when them finishes. This function is called with
12398  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
12399  * when the command iocb is an abort request.
12400  *
12401  **/
12402 int
12403 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12404 			   struct lpfc_iocbq *cmdiocb, void *cmpl)
12405 {
12406 	struct lpfc_vport *vport = cmdiocb->vport;
12407 	struct lpfc_iocbq *abtsiocbp;
12408 	int retval = IOCB_ERROR;
12409 	unsigned long iflags;
12410 	struct lpfc_nodelist *ndlp = NULL;
12411 	u32 ulp_command = get_job_cmnd(phba, cmdiocb);
12412 	u16 ulp_context, iotag;
12413 	bool ia;
12414 
12415 	/*
12416 	 * There are certain command types we don't want to abort.  And we
12417 	 * don't want to abort commands that are already in the process of
12418 	 * being aborted.
12419 	 */
12420 	if (ulp_command == CMD_ABORT_XRI_WQE ||
12421 	    ulp_command == CMD_ABORT_XRI_CN ||
12422 	    ulp_command == CMD_CLOSE_XRI_CN ||
12423 	    cmdiocb->cmd_flag & LPFC_DRIVER_ABORTED)
12424 		return IOCB_ABORTING;
12425 
12426 	if (!pring) {
12427 		if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12428 			cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12429 		else
12430 			cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12431 		return retval;
12432 	}
12433 
12434 	/*
12435 	 * If we're unloading, don't abort iocb on the ELS ring, but change
12436 	 * the callback so that nothing happens when it finishes.
12437 	 */
12438 	if ((vport->load_flag & FC_UNLOADING) &&
12439 	    pring->ringno == LPFC_ELS_RING) {
12440 		if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12441 			cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12442 		else
12443 			cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12444 		return retval;
12445 	}
12446 
12447 	/* issue ABTS for this IOCB based on iotag */
12448 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
12449 	if (abtsiocbp == NULL)
12450 		return IOCB_NORESOURCE;
12451 
12452 	/* This signals the response to set the correct status
12453 	 * before calling the completion handler
12454 	 */
12455 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
12456 
12457 	if (phba->sli_rev == LPFC_SLI_REV4) {
12458 		ulp_context = cmdiocb->sli4_xritag;
12459 		iotag = abtsiocbp->iotag;
12460 	} else {
12461 		iotag = cmdiocb->iocb.ulpIoTag;
12462 		if (pring->ringno == LPFC_ELS_RING) {
12463 			ndlp = cmdiocb->ndlp;
12464 			ulp_context = ndlp->nlp_rpi;
12465 		} else {
12466 			ulp_context = cmdiocb->iocb.ulpContext;
12467 		}
12468 	}
12469 
12470 	if (phba->link_state < LPFC_LINK_UP ||
12471 	    (phba->sli_rev == LPFC_SLI_REV4 &&
12472 	     phba->sli4_hba.link_state.status == LPFC_FC_LA_TYPE_LINK_DOWN) ||
12473 	    (phba->link_flag & LS_EXTERNAL_LOOPBACK))
12474 		ia = true;
12475 	else
12476 		ia = false;
12477 
12478 	lpfc_sli_prep_abort_xri(phba, abtsiocbp, ulp_context, iotag,
12479 				cmdiocb->iocb.ulpClass,
12480 				LPFC_WQE_CQ_ID_DEFAULT, ia, false);
12481 
12482 	abtsiocbp->vport = vport;
12483 
12484 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12485 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
12486 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
12487 		abtsiocbp->cmd_flag |= (LPFC_IO_FCP | LPFC_USE_FCPWQIDX);
12488 
12489 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
12490 		abtsiocbp->cmd_flag |= LPFC_IO_FOF;
12491 
12492 	if (cmpl)
12493 		abtsiocbp->cmd_cmpl = cmpl;
12494 	else
12495 		abtsiocbp->cmd_cmpl = lpfc_sli_abort_els_cmpl;
12496 	abtsiocbp->vport = vport;
12497 
12498 	if (phba->sli_rev == LPFC_SLI_REV4) {
12499 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
12500 		if (unlikely(pring == NULL))
12501 			goto abort_iotag_exit;
12502 		/* Note: both hbalock and ring_lock need to be set here */
12503 		spin_lock_irqsave(&pring->ring_lock, iflags);
12504 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12505 			abtsiocbp, 0);
12506 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
12507 	} else {
12508 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12509 			abtsiocbp, 0);
12510 	}
12511 
12512 abort_iotag_exit:
12513 
12514 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
12515 			 "0339 Abort IO XRI x%x, Original iotag x%x, "
12516 			 "abort tag x%x Cmdjob : x%px Abortjob : x%px "
12517 			 "retval x%x\n",
12518 			 ulp_context, (phba->sli_rev == LPFC_SLI_REV4) ?
12519 			 cmdiocb->iotag : iotag, iotag, cmdiocb, abtsiocbp,
12520 			 retval);
12521 	if (retval) {
12522 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
12523 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
12524 	}
12525 
12526 	/*
12527 	 * Caller to this routine should check for IOCB_ERROR
12528 	 * and handle it properly.  This routine no longer removes
12529 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
12530 	 */
12531 	return retval;
12532 }
12533 
12534 /**
12535  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
12536  * @phba: pointer to lpfc HBA data structure.
12537  *
12538  * This routine will abort all pending and outstanding iocbs to an HBA.
12539  **/
12540 void
12541 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
12542 {
12543 	struct lpfc_sli *psli = &phba->sli;
12544 	struct lpfc_sli_ring *pring;
12545 	struct lpfc_queue *qp = NULL;
12546 	int i;
12547 
12548 	if (phba->sli_rev != LPFC_SLI_REV4) {
12549 		for (i = 0; i < psli->num_rings; i++) {
12550 			pring = &psli->sli3_ring[i];
12551 			lpfc_sli_abort_iocb_ring(phba, pring);
12552 		}
12553 		return;
12554 	}
12555 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12556 		pring = qp->pring;
12557 		if (!pring)
12558 			continue;
12559 		lpfc_sli_abort_iocb_ring(phba, pring);
12560 	}
12561 }
12562 
12563 /**
12564  * lpfc_sli_validate_fcp_iocb_for_abort - filter iocbs appropriate for FCP aborts
12565  * @iocbq: Pointer to iocb object.
12566  * @vport: Pointer to driver virtual port object.
12567  *
12568  * This function acts as an iocb filter for functions which abort FCP iocbs.
12569  *
12570  * Return values
12571  * -ENODEV, if a null iocb or vport ptr is encountered
12572  * -EINVAL, if the iocb is not an FCP I/O, not on the TX cmpl queue, premarked as
12573  *          driver already started the abort process, or is an abort iocb itself
12574  * 0, passes criteria for aborting the FCP I/O iocb
12575  **/
12576 static int
12577 lpfc_sli_validate_fcp_iocb_for_abort(struct lpfc_iocbq *iocbq,
12578 				     struct lpfc_vport *vport)
12579 {
12580 	u8 ulp_command;
12581 
12582 	/* No null ptr vports */
12583 	if (!iocbq || iocbq->vport != vport)
12584 		return -ENODEV;
12585 
12586 	/* iocb must be for FCP IO, already exists on the TX cmpl queue,
12587 	 * can't be premarked as driver aborted, nor be an ABORT iocb itself
12588 	 */
12589 	ulp_command = get_job_cmnd(vport->phba, iocbq);
12590 	if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12591 	    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ) ||
12592 	    (iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12593 	    (ulp_command == CMD_ABORT_XRI_CN ||
12594 	     ulp_command == CMD_CLOSE_XRI_CN ||
12595 	     ulp_command == CMD_ABORT_XRI_WQE))
12596 		return -EINVAL;
12597 
12598 	return 0;
12599 }
12600 
12601 /**
12602  * lpfc_sli_validate_fcp_iocb - validate commands associated with a SCSI target
12603  * @iocbq: Pointer to driver iocb object.
12604  * @vport: Pointer to driver virtual port object.
12605  * @tgt_id: SCSI ID of the target.
12606  * @lun_id: LUN ID of the scsi device.
12607  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
12608  *
12609  * This function acts as an iocb filter for validating a lun/SCSI target/SCSI
12610  * host.
12611  *
12612  * It will return
12613  * 0 if the filtering criteria is met for the given iocb and will return
12614  * 1 if the filtering criteria is not met.
12615  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
12616  * given iocb is for the SCSI device specified by vport, tgt_id and
12617  * lun_id parameter.
12618  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
12619  * given iocb is for the SCSI target specified by vport and tgt_id
12620  * parameters.
12621  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
12622  * given iocb is for the SCSI host associated with the given vport.
12623  * This function is called with no locks held.
12624  **/
12625 static int
12626 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
12627 			   uint16_t tgt_id, uint64_t lun_id,
12628 			   lpfc_ctx_cmd ctx_cmd)
12629 {
12630 	struct lpfc_io_buf *lpfc_cmd;
12631 	int rc = 1;
12632 
12633 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12634 
12635 	if (lpfc_cmd->pCmd == NULL)
12636 		return rc;
12637 
12638 	switch (ctx_cmd) {
12639 	case LPFC_CTX_LUN:
12640 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12641 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
12642 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
12643 			rc = 0;
12644 		break;
12645 	case LPFC_CTX_TGT:
12646 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12647 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
12648 			rc = 0;
12649 		break;
12650 	case LPFC_CTX_HOST:
12651 		rc = 0;
12652 		break;
12653 	default:
12654 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
12655 			__func__, ctx_cmd);
12656 		break;
12657 	}
12658 
12659 	return rc;
12660 }
12661 
12662 /**
12663  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
12664  * @vport: Pointer to virtual port.
12665  * @tgt_id: SCSI ID of the target.
12666  * @lun_id: LUN ID of the scsi device.
12667  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12668  *
12669  * This function returns number of FCP commands pending for the vport.
12670  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
12671  * commands pending on the vport associated with SCSI device specified
12672  * by tgt_id and lun_id parameters.
12673  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
12674  * commands pending on the vport associated with SCSI target specified
12675  * by tgt_id parameter.
12676  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
12677  * commands pending on the vport.
12678  * This function returns the number of iocbs which satisfy the filter.
12679  * This function is called without any lock held.
12680  **/
12681 int
12682 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
12683 		  lpfc_ctx_cmd ctx_cmd)
12684 {
12685 	struct lpfc_hba *phba = vport->phba;
12686 	struct lpfc_iocbq *iocbq;
12687 	int sum, i;
12688 	unsigned long iflags;
12689 	u8 ulp_command;
12690 
12691 	spin_lock_irqsave(&phba->hbalock, iflags);
12692 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
12693 		iocbq = phba->sli.iocbq_lookup[i];
12694 
12695 		if (!iocbq || iocbq->vport != vport)
12696 			continue;
12697 		if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12698 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ))
12699 			continue;
12700 
12701 		/* Include counting outstanding aborts */
12702 		ulp_command = get_job_cmnd(phba, iocbq);
12703 		if (ulp_command == CMD_ABORT_XRI_CN ||
12704 		    ulp_command == CMD_CLOSE_XRI_CN ||
12705 		    ulp_command == CMD_ABORT_XRI_WQE) {
12706 			sum++;
12707 			continue;
12708 		}
12709 
12710 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12711 					       ctx_cmd) == 0)
12712 			sum++;
12713 	}
12714 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12715 
12716 	return sum;
12717 }
12718 
12719 /**
12720  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
12721  * @phba: Pointer to HBA context object
12722  * @cmdiocb: Pointer to command iocb object.
12723  * @rspiocb: Pointer to response iocb object.
12724  *
12725  * This function is called when an aborted FCP iocb completes. This
12726  * function is called by the ring event handler with no lock held.
12727  * This function frees the iocb.
12728  **/
12729 void
12730 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12731 			struct lpfc_iocbq *rspiocb)
12732 {
12733 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12734 			"3096 ABORT_XRI_CX completing on rpi x%x "
12735 			"original iotag x%x, abort cmd iotag x%x "
12736 			"status 0x%x, reason 0x%x\n",
12737 			(phba->sli_rev == LPFC_SLI_REV4) ?
12738 			cmdiocb->sli4_xritag :
12739 			cmdiocb->iocb.un.acxri.abortContextTag,
12740 			get_job_abtsiotag(phba, cmdiocb),
12741 			cmdiocb->iotag, get_job_ulpstatus(phba, rspiocb),
12742 			get_job_word4(phba, rspiocb));
12743 	lpfc_sli_release_iocbq(phba, cmdiocb);
12744 	return;
12745 }
12746 
12747 /**
12748  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
12749  * @vport: Pointer to virtual port.
12750  * @tgt_id: SCSI ID of the target.
12751  * @lun_id: LUN ID of the scsi device.
12752  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12753  *
12754  * This function sends an abort command for every SCSI command
12755  * associated with the given virtual port pending on the ring
12756  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12757  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12758  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12759  * followed by lpfc_sli_validate_fcp_iocb.
12760  *
12761  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
12762  * FCP iocbs associated with lun specified by tgt_id and lun_id
12763  * parameters
12764  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
12765  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12766  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
12767  * FCP iocbs associated with virtual port.
12768  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
12769  * lpfc_sli4_calc_ring is used.
12770  * This function returns number of iocbs it failed to abort.
12771  * This function is called with no locks held.
12772  **/
12773 int
12774 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
12775 		    lpfc_ctx_cmd abort_cmd)
12776 {
12777 	struct lpfc_hba *phba = vport->phba;
12778 	struct lpfc_sli_ring *pring = NULL;
12779 	struct lpfc_iocbq *iocbq;
12780 	int errcnt = 0, ret_val = 0;
12781 	unsigned long iflags;
12782 	int i;
12783 
12784 	/* all I/Os are in process of being flushed */
12785 	if (phba->hba_flag & HBA_IOQ_FLUSH)
12786 		return errcnt;
12787 
12788 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12789 		iocbq = phba->sli.iocbq_lookup[i];
12790 
12791 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12792 			continue;
12793 
12794 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12795 					       abort_cmd) != 0)
12796 			continue;
12797 
12798 		spin_lock_irqsave(&phba->hbalock, iflags);
12799 		if (phba->sli_rev == LPFC_SLI_REV3) {
12800 			pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12801 		} else if (phba->sli_rev == LPFC_SLI_REV4) {
12802 			pring = lpfc_sli4_calc_ring(phba, iocbq);
12803 		}
12804 		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
12805 						     lpfc_sli_abort_fcp_cmpl);
12806 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12807 		if (ret_val != IOCB_SUCCESS)
12808 			errcnt++;
12809 	}
12810 
12811 	return errcnt;
12812 }
12813 
12814 /**
12815  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12816  * @vport: Pointer to virtual port.
12817  * @pring: Pointer to driver SLI ring object.
12818  * @tgt_id: SCSI ID of the target.
12819  * @lun_id: LUN ID of the scsi device.
12820  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12821  *
12822  * This function sends an abort command for every SCSI command
12823  * associated with the given virtual port pending on the ring
12824  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12825  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12826  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12827  * followed by lpfc_sli_validate_fcp_iocb.
12828  *
12829  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12830  * FCP iocbs associated with lun specified by tgt_id and lun_id
12831  * parameters
12832  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12833  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12834  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12835  * FCP iocbs associated with virtual port.
12836  * This function returns number of iocbs it aborted .
12837  * This function is called with no locks held right after a taskmgmt
12838  * command is sent.
12839  **/
12840 int
12841 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12842 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12843 {
12844 	struct lpfc_hba *phba = vport->phba;
12845 	struct lpfc_io_buf *lpfc_cmd;
12846 	struct lpfc_iocbq *abtsiocbq;
12847 	struct lpfc_nodelist *ndlp = NULL;
12848 	struct lpfc_iocbq *iocbq;
12849 	int sum, i, ret_val;
12850 	unsigned long iflags;
12851 	struct lpfc_sli_ring *pring_s4 = NULL;
12852 	u16 ulp_context, iotag, cqid = LPFC_WQE_CQ_ID_DEFAULT;
12853 	bool ia;
12854 
12855 	spin_lock_irqsave(&phba->hbalock, iflags);
12856 
12857 	/* all I/Os are in process of being flushed */
12858 	if (phba->hba_flag & HBA_IOQ_FLUSH) {
12859 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12860 		return 0;
12861 	}
12862 	sum = 0;
12863 
12864 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12865 		iocbq = phba->sli.iocbq_lookup[i];
12866 
12867 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12868 			continue;
12869 
12870 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12871 					       cmd) != 0)
12872 			continue;
12873 
12874 		/* Guard against IO completion being called at same time */
12875 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12876 		spin_lock(&lpfc_cmd->buf_lock);
12877 
12878 		if (!lpfc_cmd->pCmd) {
12879 			spin_unlock(&lpfc_cmd->buf_lock);
12880 			continue;
12881 		}
12882 
12883 		if (phba->sli_rev == LPFC_SLI_REV4) {
12884 			pring_s4 =
12885 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12886 			if (!pring_s4) {
12887 				spin_unlock(&lpfc_cmd->buf_lock);
12888 				continue;
12889 			}
12890 			/* Note: both hbalock and ring_lock must be set here */
12891 			spin_lock(&pring_s4->ring_lock);
12892 		}
12893 
12894 		/*
12895 		 * If the iocbq is already being aborted, don't take a second
12896 		 * action, but do count it.
12897 		 */
12898 		if ((iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12899 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ)) {
12900 			if (phba->sli_rev == LPFC_SLI_REV4)
12901 				spin_unlock(&pring_s4->ring_lock);
12902 			spin_unlock(&lpfc_cmd->buf_lock);
12903 			continue;
12904 		}
12905 
12906 		/* issue ABTS for this IOCB based on iotag */
12907 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
12908 		if (!abtsiocbq) {
12909 			if (phba->sli_rev == LPFC_SLI_REV4)
12910 				spin_unlock(&pring_s4->ring_lock);
12911 			spin_unlock(&lpfc_cmd->buf_lock);
12912 			continue;
12913 		}
12914 
12915 		if (phba->sli_rev == LPFC_SLI_REV4) {
12916 			iotag = abtsiocbq->iotag;
12917 			ulp_context = iocbq->sli4_xritag;
12918 			cqid = lpfc_cmd->hdwq->io_cq_map;
12919 		} else {
12920 			iotag = iocbq->iocb.ulpIoTag;
12921 			if (pring->ringno == LPFC_ELS_RING) {
12922 				ndlp = iocbq->ndlp;
12923 				ulp_context = ndlp->nlp_rpi;
12924 			} else {
12925 				ulp_context = iocbq->iocb.ulpContext;
12926 			}
12927 		}
12928 
12929 		ndlp = lpfc_cmd->rdata->pnode;
12930 
12931 		if (lpfc_is_link_up(phba) &&
12932 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE) &&
12933 		    !(phba->link_flag & LS_EXTERNAL_LOOPBACK))
12934 			ia = false;
12935 		else
12936 			ia = true;
12937 
12938 		lpfc_sli_prep_abort_xri(phba, abtsiocbq, ulp_context, iotag,
12939 					iocbq->iocb.ulpClass, cqid,
12940 					ia, false);
12941 
12942 		abtsiocbq->vport = vport;
12943 
12944 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12945 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12946 		if (iocbq->cmd_flag & LPFC_IO_FCP)
12947 			abtsiocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
12948 		if (iocbq->cmd_flag & LPFC_IO_FOF)
12949 			abtsiocbq->cmd_flag |= LPFC_IO_FOF;
12950 
12951 		/* Setup callback routine and issue the command. */
12952 		abtsiocbq->cmd_cmpl = lpfc_sli_abort_fcp_cmpl;
12953 
12954 		/*
12955 		 * Indicate the IO is being aborted by the driver and set
12956 		 * the caller's flag into the aborted IO.
12957 		 */
12958 		iocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
12959 
12960 		if (phba->sli_rev == LPFC_SLI_REV4) {
12961 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
12962 							abtsiocbq, 0);
12963 			spin_unlock(&pring_s4->ring_lock);
12964 		} else {
12965 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
12966 							abtsiocbq, 0);
12967 		}
12968 
12969 		spin_unlock(&lpfc_cmd->buf_lock);
12970 
12971 		if (ret_val == IOCB_ERROR)
12972 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
12973 		else
12974 			sum++;
12975 	}
12976 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12977 	return sum;
12978 }
12979 
12980 /**
12981  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
12982  * @phba: Pointer to HBA context object.
12983  * @cmdiocbq: Pointer to command iocb.
12984  * @rspiocbq: Pointer to response iocb.
12985  *
12986  * This function is the completion handler for iocbs issued using
12987  * lpfc_sli_issue_iocb_wait function. This function is called by the
12988  * ring event handler function without any lock held. This function
12989  * can be called from both worker thread context and interrupt
12990  * context. This function also can be called from other thread which
12991  * cleans up the SLI layer objects.
12992  * This function copy the contents of the response iocb to the
12993  * response iocb memory object provided by the caller of
12994  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
12995  * sleeps for the iocb completion.
12996  **/
12997 static void
12998 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
12999 			struct lpfc_iocbq *cmdiocbq,
13000 			struct lpfc_iocbq *rspiocbq)
13001 {
13002 	wait_queue_head_t *pdone_q;
13003 	unsigned long iflags;
13004 	struct lpfc_io_buf *lpfc_cmd;
13005 	size_t offset = offsetof(struct lpfc_iocbq, wqe);
13006 
13007 	spin_lock_irqsave(&phba->hbalock, iflags);
13008 	if (cmdiocbq->cmd_flag & LPFC_IO_WAKE_TMO) {
13009 
13010 		/*
13011 		 * A time out has occurred for the iocb.  If a time out
13012 		 * completion handler has been supplied, call it.  Otherwise,
13013 		 * just free the iocbq.
13014 		 */
13015 
13016 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13017 		cmdiocbq->cmd_cmpl = cmdiocbq->wait_cmd_cmpl;
13018 		cmdiocbq->wait_cmd_cmpl = NULL;
13019 		if (cmdiocbq->cmd_cmpl)
13020 			cmdiocbq->cmd_cmpl(phba, cmdiocbq, NULL);
13021 		else
13022 			lpfc_sli_release_iocbq(phba, cmdiocbq);
13023 		return;
13024 	}
13025 
13026 	/* Copy the contents of the local rspiocb into the caller's buffer. */
13027 	cmdiocbq->cmd_flag |= LPFC_IO_WAKE;
13028 	if (cmdiocbq->rsp_iocb && rspiocbq)
13029 		memcpy((char *)cmdiocbq->rsp_iocb + offset,
13030 		       (char *)rspiocbq + offset, sizeof(*rspiocbq) - offset);
13031 
13032 	/* Set the exchange busy flag for task management commands */
13033 	if ((cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
13034 	    !(cmdiocbq->cmd_flag & LPFC_IO_LIBDFC)) {
13035 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
13036 					cur_iocbq);
13037 		if (rspiocbq && (rspiocbq->cmd_flag & LPFC_EXCHANGE_BUSY))
13038 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
13039 		else
13040 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
13041 	}
13042 
13043 	pdone_q = cmdiocbq->context_un.wait_queue;
13044 	if (pdone_q)
13045 		wake_up(pdone_q);
13046 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13047 	return;
13048 }
13049 
13050 /**
13051  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
13052  * @phba: Pointer to HBA context object..
13053  * @piocbq: Pointer to command iocb.
13054  * @flag: Flag to test.
13055  *
13056  * This routine grabs the hbalock and then test the cmd_flag to
13057  * see if the passed in flag is set.
13058  * Returns:
13059  * 1 if flag is set.
13060  * 0 if flag is not set.
13061  **/
13062 static int
13063 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
13064 		 struct lpfc_iocbq *piocbq, uint32_t flag)
13065 {
13066 	unsigned long iflags;
13067 	int ret;
13068 
13069 	spin_lock_irqsave(&phba->hbalock, iflags);
13070 	ret = piocbq->cmd_flag & flag;
13071 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13072 	return ret;
13073 
13074 }
13075 
13076 /**
13077  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
13078  * @phba: Pointer to HBA context object..
13079  * @ring_number: Ring number
13080  * @piocb: Pointer to command iocb.
13081  * @prspiocbq: Pointer to response iocb.
13082  * @timeout: Timeout in number of seconds.
13083  *
13084  * This function issues the iocb to firmware and waits for the
13085  * iocb to complete. The cmd_cmpl field of the shall be used
13086  * to handle iocbs which time out. If the field is NULL, the
13087  * function shall free the iocbq structure.  If more clean up is
13088  * needed, the caller is expected to provide a completion function
13089  * that will provide the needed clean up.  If the iocb command is
13090  * not completed within timeout seconds, the function will either
13091  * free the iocbq structure (if cmd_cmpl == NULL) or execute the
13092  * completion function set in the cmd_cmpl field and then return
13093  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
13094  * resources if this function returns IOCB_TIMEDOUT.
13095  * The function waits for the iocb completion using an
13096  * non-interruptible wait.
13097  * This function will sleep while waiting for iocb completion.
13098  * So, this function should not be called from any context which
13099  * does not allow sleeping. Due to the same reason, this function
13100  * cannot be called with interrupt disabled.
13101  * This function assumes that the iocb completions occur while
13102  * this function sleep. So, this function cannot be called from
13103  * the thread which process iocb completion for this ring.
13104  * This function clears the cmd_flag of the iocb object before
13105  * issuing the iocb and the iocb completion handler sets this
13106  * flag and wakes this thread when the iocb completes.
13107  * The contents of the response iocb will be copied to prspiocbq
13108  * by the completion handler when the command completes.
13109  * This function returns IOCB_SUCCESS when success.
13110  * This function is called with no lock held.
13111  **/
13112 int
13113 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
13114 			 uint32_t ring_number,
13115 			 struct lpfc_iocbq *piocb,
13116 			 struct lpfc_iocbq *prspiocbq,
13117 			 uint32_t timeout)
13118 {
13119 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
13120 	long timeleft, timeout_req = 0;
13121 	int retval = IOCB_SUCCESS;
13122 	uint32_t creg_val;
13123 	struct lpfc_iocbq *iocb;
13124 	int txq_cnt = 0;
13125 	int txcmplq_cnt = 0;
13126 	struct lpfc_sli_ring *pring;
13127 	unsigned long iflags;
13128 	bool iocb_completed = true;
13129 
13130 	if (phba->sli_rev >= LPFC_SLI_REV4) {
13131 		lpfc_sli_prep_wqe(phba, piocb);
13132 
13133 		pring = lpfc_sli4_calc_ring(phba, piocb);
13134 	} else
13135 		pring = &phba->sli.sli3_ring[ring_number];
13136 	/*
13137 	 * If the caller has provided a response iocbq buffer, then rsp_iocb
13138 	 * is NULL or its an error.
13139 	 */
13140 	if (prspiocbq) {
13141 		if (piocb->rsp_iocb)
13142 			return IOCB_ERROR;
13143 		piocb->rsp_iocb = prspiocbq;
13144 	}
13145 
13146 	piocb->wait_cmd_cmpl = piocb->cmd_cmpl;
13147 	piocb->cmd_cmpl = lpfc_sli_wake_iocb_wait;
13148 	piocb->context_un.wait_queue = &done_q;
13149 	piocb->cmd_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
13150 
13151 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13152 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13153 			return IOCB_ERROR;
13154 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
13155 		writel(creg_val, phba->HCregaddr);
13156 		readl(phba->HCregaddr); /* flush */
13157 	}
13158 
13159 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
13160 				     SLI_IOCB_RET_IOCB);
13161 	if (retval == IOCB_SUCCESS) {
13162 		timeout_req = msecs_to_jiffies(timeout * 1000);
13163 		timeleft = wait_event_timeout(done_q,
13164 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
13165 				timeout_req);
13166 		spin_lock_irqsave(&phba->hbalock, iflags);
13167 		if (!(piocb->cmd_flag & LPFC_IO_WAKE)) {
13168 
13169 			/*
13170 			 * IOCB timed out.  Inform the wake iocb wait
13171 			 * completion function and set local status
13172 			 */
13173 
13174 			iocb_completed = false;
13175 			piocb->cmd_flag |= LPFC_IO_WAKE_TMO;
13176 		}
13177 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13178 		if (iocb_completed) {
13179 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13180 					"0331 IOCB wake signaled\n");
13181 			/* Note: we are not indicating if the IOCB has a success
13182 			 * status or not - that's for the caller to check.
13183 			 * IOCB_SUCCESS means just that the command was sent and
13184 			 * completed. Not that it completed successfully.
13185 			 * */
13186 		} else if (timeleft == 0) {
13187 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13188 					"0338 IOCB wait timeout error - no "
13189 					"wake response Data x%x\n", timeout);
13190 			retval = IOCB_TIMEDOUT;
13191 		} else {
13192 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13193 					"0330 IOCB wake NOT set, "
13194 					"Data x%x x%lx\n",
13195 					timeout, (timeleft / jiffies));
13196 			retval = IOCB_TIMEDOUT;
13197 		}
13198 	} else if (retval == IOCB_BUSY) {
13199 		if (phba->cfg_log_verbose & LOG_SLI) {
13200 			list_for_each_entry(iocb, &pring->txq, list) {
13201 				txq_cnt++;
13202 			}
13203 			list_for_each_entry(iocb, &pring->txcmplq, list) {
13204 				txcmplq_cnt++;
13205 			}
13206 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13207 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
13208 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
13209 		}
13210 		return retval;
13211 	} else {
13212 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13213 				"0332 IOCB wait issue failed, Data x%x\n",
13214 				retval);
13215 		retval = IOCB_ERROR;
13216 	}
13217 
13218 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13219 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13220 			return IOCB_ERROR;
13221 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
13222 		writel(creg_val, phba->HCregaddr);
13223 		readl(phba->HCregaddr); /* flush */
13224 	}
13225 
13226 	if (prspiocbq)
13227 		piocb->rsp_iocb = NULL;
13228 
13229 	piocb->context_un.wait_queue = NULL;
13230 	piocb->cmd_cmpl = NULL;
13231 	return retval;
13232 }
13233 
13234 /**
13235  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
13236  * @phba: Pointer to HBA context object.
13237  * @pmboxq: Pointer to driver mailbox object.
13238  * @timeout: Timeout in number of seconds.
13239  *
13240  * This function issues the mailbox to firmware and waits for the
13241  * mailbox command to complete. If the mailbox command is not
13242  * completed within timeout seconds, it returns MBX_TIMEOUT.
13243  * The function waits for the mailbox completion using an
13244  * interruptible wait. If the thread is woken up due to a
13245  * signal, MBX_TIMEOUT error is returned to the caller. Caller
13246  * should not free the mailbox resources, if this function returns
13247  * MBX_TIMEOUT.
13248  * This function will sleep while waiting for mailbox completion.
13249  * So, this function should not be called from any context which
13250  * does not allow sleeping. Due to the same reason, this function
13251  * cannot be called with interrupt disabled.
13252  * This function assumes that the mailbox completion occurs while
13253  * this function sleep. So, this function cannot be called from
13254  * the worker thread which processes mailbox completion.
13255  * This function is called in the context of HBA management
13256  * applications.
13257  * This function returns MBX_SUCCESS when successful.
13258  * This function is called with no lock held.
13259  **/
13260 int
13261 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
13262 			 uint32_t timeout)
13263 {
13264 	struct completion mbox_done;
13265 	int retval;
13266 	unsigned long flag;
13267 
13268 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
13269 	/* setup wake call as IOCB callback */
13270 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
13271 
13272 	/* setup context3 field to pass wait_queue pointer to wake function  */
13273 	init_completion(&mbox_done);
13274 	pmboxq->context3 = &mbox_done;
13275 	/* now issue the command */
13276 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
13277 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
13278 		wait_for_completion_timeout(&mbox_done,
13279 					    msecs_to_jiffies(timeout * 1000));
13280 
13281 		spin_lock_irqsave(&phba->hbalock, flag);
13282 		pmboxq->context3 = NULL;
13283 		/*
13284 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
13285 		 * else do not free the resources.
13286 		 */
13287 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
13288 			retval = MBX_SUCCESS;
13289 		} else {
13290 			retval = MBX_TIMEOUT;
13291 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13292 		}
13293 		spin_unlock_irqrestore(&phba->hbalock, flag);
13294 	}
13295 	return retval;
13296 }
13297 
13298 /**
13299  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
13300  * @phba: Pointer to HBA context.
13301  * @mbx_action: Mailbox shutdown options.
13302  *
13303  * This function is called to shutdown the driver's mailbox sub-system.
13304  * It first marks the mailbox sub-system is in a block state to prevent
13305  * the asynchronous mailbox command from issued off the pending mailbox
13306  * command queue. If the mailbox command sub-system shutdown is due to
13307  * HBA error conditions such as EEH or ERATT, this routine shall invoke
13308  * the mailbox sub-system flush routine to forcefully bring down the
13309  * mailbox sub-system. Otherwise, if it is due to normal condition (such
13310  * as with offline or HBA function reset), this routine will wait for the
13311  * outstanding mailbox command to complete before invoking the mailbox
13312  * sub-system flush routine to gracefully bring down mailbox sub-system.
13313  **/
13314 void
13315 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
13316 {
13317 	struct lpfc_sli *psli = &phba->sli;
13318 	unsigned long timeout;
13319 
13320 	if (mbx_action == LPFC_MBX_NO_WAIT) {
13321 		/* delay 100ms for port state */
13322 		msleep(100);
13323 		lpfc_sli_mbox_sys_flush(phba);
13324 		return;
13325 	}
13326 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
13327 
13328 	/* Disable softirqs, including timers from obtaining phba->hbalock */
13329 	local_bh_disable();
13330 
13331 	spin_lock_irq(&phba->hbalock);
13332 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13333 
13334 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
13335 		/* Determine how long we might wait for the active mailbox
13336 		 * command to be gracefully completed by firmware.
13337 		 */
13338 		if (phba->sli.mbox_active)
13339 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
13340 						phba->sli.mbox_active) *
13341 						1000) + jiffies;
13342 		spin_unlock_irq(&phba->hbalock);
13343 
13344 		/* Enable softirqs again, done with phba->hbalock */
13345 		local_bh_enable();
13346 
13347 		while (phba->sli.mbox_active) {
13348 			/* Check active mailbox complete status every 2ms */
13349 			msleep(2);
13350 			if (time_after(jiffies, timeout))
13351 				/* Timeout, let the mailbox flush routine to
13352 				 * forcefully release active mailbox command
13353 				 */
13354 				break;
13355 		}
13356 	} else {
13357 		spin_unlock_irq(&phba->hbalock);
13358 
13359 		/* Enable softirqs again, done with phba->hbalock */
13360 		local_bh_enable();
13361 	}
13362 
13363 	lpfc_sli_mbox_sys_flush(phba);
13364 }
13365 
13366 /**
13367  * lpfc_sli_eratt_read - read sli-3 error attention events
13368  * @phba: Pointer to HBA context.
13369  *
13370  * This function is called to read the SLI3 device error attention registers
13371  * for possible error attention events. The caller must hold the hostlock
13372  * with spin_lock_irq().
13373  *
13374  * This function returns 1 when there is Error Attention in the Host Attention
13375  * Register and returns 0 otherwise.
13376  **/
13377 static int
13378 lpfc_sli_eratt_read(struct lpfc_hba *phba)
13379 {
13380 	uint32_t ha_copy;
13381 
13382 	/* Read chip Host Attention (HA) register */
13383 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
13384 		goto unplug_err;
13385 
13386 	if (ha_copy & HA_ERATT) {
13387 		/* Read host status register to retrieve error event */
13388 		if (lpfc_sli_read_hs(phba))
13389 			goto unplug_err;
13390 
13391 		/* Check if there is a deferred error condition is active */
13392 		if ((HS_FFER1 & phba->work_hs) &&
13393 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13394 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
13395 			phba->hba_flag |= DEFER_ERATT;
13396 			/* Clear all interrupt enable conditions */
13397 			writel(0, phba->HCregaddr);
13398 			readl(phba->HCregaddr);
13399 		}
13400 
13401 		/* Set the driver HA work bitmap */
13402 		phba->work_ha |= HA_ERATT;
13403 		/* Indicate polling handles this ERATT */
13404 		phba->hba_flag |= HBA_ERATT_HANDLED;
13405 		return 1;
13406 	}
13407 	return 0;
13408 
13409 unplug_err:
13410 	/* Set the driver HS work bitmap */
13411 	phba->work_hs |= UNPLUG_ERR;
13412 	/* Set the driver HA work bitmap */
13413 	phba->work_ha |= HA_ERATT;
13414 	/* Indicate polling handles this ERATT */
13415 	phba->hba_flag |= HBA_ERATT_HANDLED;
13416 	return 1;
13417 }
13418 
13419 /**
13420  * lpfc_sli4_eratt_read - read sli-4 error attention events
13421  * @phba: Pointer to HBA context.
13422  *
13423  * This function is called to read the SLI4 device error attention registers
13424  * for possible error attention events. The caller must hold the hostlock
13425  * with spin_lock_irq().
13426  *
13427  * This function returns 1 when there is Error Attention in the Host Attention
13428  * Register and returns 0 otherwise.
13429  **/
13430 static int
13431 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
13432 {
13433 	uint32_t uerr_sta_hi, uerr_sta_lo;
13434 	uint32_t if_type, portsmphr;
13435 	struct lpfc_register portstat_reg;
13436 	u32 logmask;
13437 
13438 	/*
13439 	 * For now, use the SLI4 device internal unrecoverable error
13440 	 * registers for error attention. This can be changed later.
13441 	 */
13442 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
13443 	switch (if_type) {
13444 	case LPFC_SLI_INTF_IF_TYPE_0:
13445 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
13446 			&uerr_sta_lo) ||
13447 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
13448 			&uerr_sta_hi)) {
13449 			phba->work_hs |= UNPLUG_ERR;
13450 			phba->work_ha |= HA_ERATT;
13451 			phba->hba_flag |= HBA_ERATT_HANDLED;
13452 			return 1;
13453 		}
13454 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
13455 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
13456 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13457 					"1423 HBA Unrecoverable error: "
13458 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
13459 					"ue_mask_lo_reg=0x%x, "
13460 					"ue_mask_hi_reg=0x%x\n",
13461 					uerr_sta_lo, uerr_sta_hi,
13462 					phba->sli4_hba.ue_mask_lo,
13463 					phba->sli4_hba.ue_mask_hi);
13464 			phba->work_status[0] = uerr_sta_lo;
13465 			phba->work_status[1] = uerr_sta_hi;
13466 			phba->work_ha |= HA_ERATT;
13467 			phba->hba_flag |= HBA_ERATT_HANDLED;
13468 			return 1;
13469 		}
13470 		break;
13471 	case LPFC_SLI_INTF_IF_TYPE_2:
13472 	case LPFC_SLI_INTF_IF_TYPE_6:
13473 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
13474 			&portstat_reg.word0) ||
13475 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
13476 			&portsmphr)){
13477 			phba->work_hs |= UNPLUG_ERR;
13478 			phba->work_ha |= HA_ERATT;
13479 			phba->hba_flag |= HBA_ERATT_HANDLED;
13480 			return 1;
13481 		}
13482 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
13483 			phba->work_status[0] =
13484 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
13485 			phba->work_status[1] =
13486 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
13487 			logmask = LOG_TRACE_EVENT;
13488 			if (phba->work_status[0] ==
13489 				SLIPORT_ERR1_REG_ERR_CODE_2 &&
13490 			    phba->work_status[1] == SLIPORT_ERR2_REG_FW_RESTART)
13491 				logmask = LOG_SLI;
13492 			lpfc_printf_log(phba, KERN_ERR, logmask,
13493 					"2885 Port Status Event: "
13494 					"port status reg 0x%x, "
13495 					"port smphr reg 0x%x, "
13496 					"error 1=0x%x, error 2=0x%x\n",
13497 					portstat_reg.word0,
13498 					portsmphr,
13499 					phba->work_status[0],
13500 					phba->work_status[1]);
13501 			phba->work_ha |= HA_ERATT;
13502 			phba->hba_flag |= HBA_ERATT_HANDLED;
13503 			return 1;
13504 		}
13505 		break;
13506 	case LPFC_SLI_INTF_IF_TYPE_1:
13507 	default:
13508 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13509 				"2886 HBA Error Attention on unsupported "
13510 				"if type %d.", if_type);
13511 		return 1;
13512 	}
13513 
13514 	return 0;
13515 }
13516 
13517 /**
13518  * lpfc_sli_check_eratt - check error attention events
13519  * @phba: Pointer to HBA context.
13520  *
13521  * This function is called from timer soft interrupt context to check HBA's
13522  * error attention register bit for error attention events.
13523  *
13524  * This function returns 1 when there is Error Attention in the Host Attention
13525  * Register and returns 0 otherwise.
13526  **/
13527 int
13528 lpfc_sli_check_eratt(struct lpfc_hba *phba)
13529 {
13530 	uint32_t ha_copy;
13531 
13532 	/* If somebody is waiting to handle an eratt, don't process it
13533 	 * here. The brdkill function will do this.
13534 	 */
13535 	if (phba->link_flag & LS_IGNORE_ERATT)
13536 		return 0;
13537 
13538 	/* Check if interrupt handler handles this ERATT */
13539 	spin_lock_irq(&phba->hbalock);
13540 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
13541 		/* Interrupt handler has handled ERATT */
13542 		spin_unlock_irq(&phba->hbalock);
13543 		return 0;
13544 	}
13545 
13546 	/*
13547 	 * If there is deferred error attention, do not check for error
13548 	 * attention
13549 	 */
13550 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13551 		spin_unlock_irq(&phba->hbalock);
13552 		return 0;
13553 	}
13554 
13555 	/* If PCI channel is offline, don't process it */
13556 	if (unlikely(pci_channel_offline(phba->pcidev))) {
13557 		spin_unlock_irq(&phba->hbalock);
13558 		return 0;
13559 	}
13560 
13561 	switch (phba->sli_rev) {
13562 	case LPFC_SLI_REV2:
13563 	case LPFC_SLI_REV3:
13564 		/* Read chip Host Attention (HA) register */
13565 		ha_copy = lpfc_sli_eratt_read(phba);
13566 		break;
13567 	case LPFC_SLI_REV4:
13568 		/* Read device Uncoverable Error (UERR) registers */
13569 		ha_copy = lpfc_sli4_eratt_read(phba);
13570 		break;
13571 	default:
13572 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13573 				"0299 Invalid SLI revision (%d)\n",
13574 				phba->sli_rev);
13575 		ha_copy = 0;
13576 		break;
13577 	}
13578 	spin_unlock_irq(&phba->hbalock);
13579 
13580 	return ha_copy;
13581 }
13582 
13583 /**
13584  * lpfc_intr_state_check - Check device state for interrupt handling
13585  * @phba: Pointer to HBA context.
13586  *
13587  * This inline routine checks whether a device or its PCI slot is in a state
13588  * that the interrupt should be handled.
13589  *
13590  * This function returns 0 if the device or the PCI slot is in a state that
13591  * interrupt should be handled, otherwise -EIO.
13592  */
13593 static inline int
13594 lpfc_intr_state_check(struct lpfc_hba *phba)
13595 {
13596 	/* If the pci channel is offline, ignore all the interrupts */
13597 	if (unlikely(pci_channel_offline(phba->pcidev)))
13598 		return -EIO;
13599 
13600 	/* Update device level interrupt statistics */
13601 	phba->sli.slistat.sli_intr++;
13602 
13603 	/* Ignore all interrupts during initialization. */
13604 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
13605 		return -EIO;
13606 
13607 	return 0;
13608 }
13609 
13610 /**
13611  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
13612  * @irq: Interrupt number.
13613  * @dev_id: The device context pointer.
13614  *
13615  * This function is directly called from the PCI layer as an interrupt
13616  * service routine when device with SLI-3 interface spec is enabled with
13617  * MSI-X multi-message interrupt mode and there are slow-path events in
13618  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
13619  * interrupt mode, this function is called as part of the device-level
13620  * interrupt handler. When the PCI slot is in error recovery or the HBA
13621  * is undergoing initialization, the interrupt handler will not process
13622  * the interrupt. The link attention and ELS ring attention events are
13623  * handled by the worker thread. The interrupt handler signals the worker
13624  * thread and returns for these events. This function is called without
13625  * any lock held. It gets the hbalock to access and update SLI data
13626  * structures.
13627  *
13628  * This function returns IRQ_HANDLED when interrupt is handled else it
13629  * returns IRQ_NONE.
13630  **/
13631 irqreturn_t
13632 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
13633 {
13634 	struct lpfc_hba  *phba;
13635 	uint32_t ha_copy, hc_copy;
13636 	uint32_t work_ha_copy;
13637 	unsigned long status;
13638 	unsigned long iflag;
13639 	uint32_t control;
13640 
13641 	MAILBOX_t *mbox, *pmbox;
13642 	struct lpfc_vport *vport;
13643 	struct lpfc_nodelist *ndlp;
13644 	struct lpfc_dmabuf *mp;
13645 	LPFC_MBOXQ_t *pmb;
13646 	int rc;
13647 
13648 	/*
13649 	 * Get the driver's phba structure from the dev_id and
13650 	 * assume the HBA is not interrupting.
13651 	 */
13652 	phba = (struct lpfc_hba *)dev_id;
13653 
13654 	if (unlikely(!phba))
13655 		return IRQ_NONE;
13656 
13657 	/*
13658 	 * Stuff needs to be attented to when this function is invoked as an
13659 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13660 	 */
13661 	if (phba->intr_type == MSIX) {
13662 		/* Check device state for handling interrupt */
13663 		if (lpfc_intr_state_check(phba))
13664 			return IRQ_NONE;
13665 		/* Need to read HA REG for slow-path events */
13666 		spin_lock_irqsave(&phba->hbalock, iflag);
13667 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13668 			goto unplug_error;
13669 		/* If somebody is waiting to handle an eratt don't process it
13670 		 * here. The brdkill function will do this.
13671 		 */
13672 		if (phba->link_flag & LS_IGNORE_ERATT)
13673 			ha_copy &= ~HA_ERATT;
13674 		/* Check the need for handling ERATT in interrupt handler */
13675 		if (ha_copy & HA_ERATT) {
13676 			if (phba->hba_flag & HBA_ERATT_HANDLED)
13677 				/* ERATT polling has handled ERATT */
13678 				ha_copy &= ~HA_ERATT;
13679 			else
13680 				/* Indicate interrupt handler handles ERATT */
13681 				phba->hba_flag |= HBA_ERATT_HANDLED;
13682 		}
13683 
13684 		/*
13685 		 * If there is deferred error attention, do not check for any
13686 		 * interrupt.
13687 		 */
13688 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13689 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13690 			return IRQ_NONE;
13691 		}
13692 
13693 		/* Clear up only attention source related to slow-path */
13694 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
13695 			goto unplug_error;
13696 
13697 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
13698 			HC_LAINT_ENA | HC_ERINT_ENA),
13699 			phba->HCregaddr);
13700 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
13701 			phba->HAregaddr);
13702 		writel(hc_copy, phba->HCregaddr);
13703 		readl(phba->HAregaddr); /* flush */
13704 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13705 	} else
13706 		ha_copy = phba->ha_copy;
13707 
13708 	work_ha_copy = ha_copy & phba->work_ha_mask;
13709 
13710 	if (work_ha_copy) {
13711 		if (work_ha_copy & HA_LATT) {
13712 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
13713 				/*
13714 				 * Turn off Link Attention interrupts
13715 				 * until CLEAR_LA done
13716 				 */
13717 				spin_lock_irqsave(&phba->hbalock, iflag);
13718 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
13719 				if (lpfc_readl(phba->HCregaddr, &control))
13720 					goto unplug_error;
13721 				control &= ~HC_LAINT_ENA;
13722 				writel(control, phba->HCregaddr);
13723 				readl(phba->HCregaddr); /* flush */
13724 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13725 			}
13726 			else
13727 				work_ha_copy &= ~HA_LATT;
13728 		}
13729 
13730 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
13731 			/*
13732 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
13733 			 * the only slow ring.
13734 			 */
13735 			status = (work_ha_copy &
13736 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
13737 			status >>= (4*LPFC_ELS_RING);
13738 			if (status & HA_RXMASK) {
13739 				spin_lock_irqsave(&phba->hbalock, iflag);
13740 				if (lpfc_readl(phba->HCregaddr, &control))
13741 					goto unplug_error;
13742 
13743 				lpfc_debugfs_slow_ring_trc(phba,
13744 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
13745 				control, status,
13746 				(uint32_t)phba->sli.slistat.sli_intr);
13747 
13748 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
13749 					lpfc_debugfs_slow_ring_trc(phba,
13750 						"ISR Disable ring:"
13751 						"pwork:x%x hawork:x%x wait:x%x",
13752 						phba->work_ha, work_ha_copy,
13753 						(uint32_t)((unsigned long)
13754 						&phba->work_waitq));
13755 
13756 					control &=
13757 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
13758 					writel(control, phba->HCregaddr);
13759 					readl(phba->HCregaddr); /* flush */
13760 				}
13761 				else {
13762 					lpfc_debugfs_slow_ring_trc(phba,
13763 						"ISR slow ring:   pwork:"
13764 						"x%x hawork:x%x wait:x%x",
13765 						phba->work_ha, work_ha_copy,
13766 						(uint32_t)((unsigned long)
13767 						&phba->work_waitq));
13768 				}
13769 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13770 			}
13771 		}
13772 		spin_lock_irqsave(&phba->hbalock, iflag);
13773 		if (work_ha_copy & HA_ERATT) {
13774 			if (lpfc_sli_read_hs(phba))
13775 				goto unplug_error;
13776 			/*
13777 			 * Check if there is a deferred error condition
13778 			 * is active
13779 			 */
13780 			if ((HS_FFER1 & phba->work_hs) &&
13781 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13782 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
13783 				  phba->work_hs)) {
13784 				phba->hba_flag |= DEFER_ERATT;
13785 				/* Clear all interrupt enable conditions */
13786 				writel(0, phba->HCregaddr);
13787 				readl(phba->HCregaddr);
13788 			}
13789 		}
13790 
13791 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
13792 			pmb = phba->sli.mbox_active;
13793 			pmbox = &pmb->u.mb;
13794 			mbox = phba->mbox;
13795 			vport = pmb->vport;
13796 
13797 			/* First check out the status word */
13798 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
13799 			if (pmbox->mbxOwner != OWN_HOST) {
13800 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13801 				/*
13802 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
13803 				 * mbxStatus <status>
13804 				 */
13805 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13806 						"(%d):0304 Stray Mailbox "
13807 						"Interrupt mbxCommand x%x "
13808 						"mbxStatus x%x\n",
13809 						(vport ? vport->vpi : 0),
13810 						pmbox->mbxCommand,
13811 						pmbox->mbxStatus);
13812 				/* clear mailbox attention bit */
13813 				work_ha_copy &= ~HA_MBATT;
13814 			} else {
13815 				phba->sli.mbox_active = NULL;
13816 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13817 				phba->last_completion_time = jiffies;
13818 				del_timer(&phba->sli.mbox_tmo);
13819 				if (pmb->mbox_cmpl) {
13820 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
13821 							MAILBOX_CMD_SIZE);
13822 					if (pmb->out_ext_byte_len &&
13823 						pmb->ctx_buf)
13824 						lpfc_sli_pcimem_bcopy(
13825 						phba->mbox_ext,
13826 						pmb->ctx_buf,
13827 						pmb->out_ext_byte_len);
13828 				}
13829 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13830 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13831 
13832 					lpfc_debugfs_disc_trc(vport,
13833 						LPFC_DISC_TRC_MBOX_VPORT,
13834 						"MBOX dflt rpi: : "
13835 						"status:x%x rpi:x%x",
13836 						(uint32_t)pmbox->mbxStatus,
13837 						pmbox->un.varWords[0], 0);
13838 
13839 					if (!pmbox->mbxStatus) {
13840 						mp = (struct lpfc_dmabuf *)
13841 							(pmb->ctx_buf);
13842 						ndlp = (struct lpfc_nodelist *)
13843 							pmb->ctx_ndlp;
13844 
13845 						/* Reg_LOGIN of dflt RPI was
13846 						 * successful. new lets get
13847 						 * rid of the RPI using the
13848 						 * same mbox buffer.
13849 						 */
13850 						lpfc_unreg_login(phba,
13851 							vport->vpi,
13852 							pmbox->un.varWords[0],
13853 							pmb);
13854 						pmb->mbox_cmpl =
13855 							lpfc_mbx_cmpl_dflt_rpi;
13856 						pmb->ctx_buf = mp;
13857 						pmb->ctx_ndlp = ndlp;
13858 						pmb->vport = vport;
13859 						rc = lpfc_sli_issue_mbox(phba,
13860 								pmb,
13861 								MBX_NOWAIT);
13862 						if (rc != MBX_BUSY)
13863 							lpfc_printf_log(phba,
13864 							KERN_ERR,
13865 							LOG_TRACE_EVENT,
13866 							"0350 rc should have"
13867 							"been MBX_BUSY\n");
13868 						if (rc != MBX_NOT_FINISHED)
13869 							goto send_current_mbox;
13870 					}
13871 				}
13872 				spin_lock_irqsave(
13873 						&phba->pport->work_port_lock,
13874 						iflag);
13875 				phba->pport->work_port_events &=
13876 					~WORKER_MBOX_TMO;
13877 				spin_unlock_irqrestore(
13878 						&phba->pport->work_port_lock,
13879 						iflag);
13880 
13881 				/* Do NOT queue MBX_HEARTBEAT to the worker
13882 				 * thread for processing.
13883 				 */
13884 				if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13885 					/* Process mbox now */
13886 					phba->sli.mbox_active = NULL;
13887 					phba->sli.sli_flag &=
13888 						~LPFC_SLI_MBOX_ACTIVE;
13889 					if (pmb->mbox_cmpl)
13890 						pmb->mbox_cmpl(phba, pmb);
13891 				} else {
13892 					/* Queue to worker thread to process */
13893 					lpfc_mbox_cmpl_put(phba, pmb);
13894 				}
13895 			}
13896 		} else
13897 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13898 
13899 		if ((work_ha_copy & HA_MBATT) &&
13900 		    (phba->sli.mbox_active == NULL)) {
13901 send_current_mbox:
13902 			/* Process next mailbox command if there is one */
13903 			do {
13904 				rc = lpfc_sli_issue_mbox(phba, NULL,
13905 							 MBX_NOWAIT);
13906 			} while (rc == MBX_NOT_FINISHED);
13907 			if (rc != MBX_SUCCESS)
13908 				lpfc_printf_log(phba, KERN_ERR,
13909 						LOG_TRACE_EVENT,
13910 						"0349 rc should be "
13911 						"MBX_SUCCESS\n");
13912 		}
13913 
13914 		spin_lock_irqsave(&phba->hbalock, iflag);
13915 		phba->work_ha |= work_ha_copy;
13916 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13917 		lpfc_worker_wake_up(phba);
13918 	}
13919 	return IRQ_HANDLED;
13920 unplug_error:
13921 	spin_unlock_irqrestore(&phba->hbalock, iflag);
13922 	return IRQ_HANDLED;
13923 
13924 } /* lpfc_sli_sp_intr_handler */
13925 
13926 /**
13927  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13928  * @irq: Interrupt number.
13929  * @dev_id: The device context pointer.
13930  *
13931  * This function is directly called from the PCI layer as an interrupt
13932  * service routine when device with SLI-3 interface spec is enabled with
13933  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13934  * ring event in the HBA. However, when the device is enabled with either
13935  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13936  * device-level interrupt handler. When the PCI slot is in error recovery
13937  * or the HBA is undergoing initialization, the interrupt handler will not
13938  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13939  * the intrrupt context. This function is called without any lock held.
13940  * It gets the hbalock to access and update SLI data structures.
13941  *
13942  * This function returns IRQ_HANDLED when interrupt is handled else it
13943  * returns IRQ_NONE.
13944  **/
13945 irqreturn_t
13946 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13947 {
13948 	struct lpfc_hba  *phba;
13949 	uint32_t ha_copy;
13950 	unsigned long status;
13951 	unsigned long iflag;
13952 	struct lpfc_sli_ring *pring;
13953 
13954 	/* Get the driver's phba structure from the dev_id and
13955 	 * assume the HBA is not interrupting.
13956 	 */
13957 	phba = (struct lpfc_hba *) dev_id;
13958 
13959 	if (unlikely(!phba))
13960 		return IRQ_NONE;
13961 
13962 	/*
13963 	 * Stuff needs to be attented to when this function is invoked as an
13964 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13965 	 */
13966 	if (phba->intr_type == MSIX) {
13967 		/* Check device state for handling interrupt */
13968 		if (lpfc_intr_state_check(phba))
13969 			return IRQ_NONE;
13970 		/* Need to read HA REG for FCP ring and other ring events */
13971 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13972 			return IRQ_HANDLED;
13973 		/* Clear up only attention source related to fast-path */
13974 		spin_lock_irqsave(&phba->hbalock, iflag);
13975 		/*
13976 		 * If there is deferred error attention, do not check for
13977 		 * any interrupt.
13978 		 */
13979 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13980 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13981 			return IRQ_NONE;
13982 		}
13983 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
13984 			phba->HAregaddr);
13985 		readl(phba->HAregaddr); /* flush */
13986 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13987 	} else
13988 		ha_copy = phba->ha_copy;
13989 
13990 	/*
13991 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
13992 	 */
13993 	ha_copy &= ~(phba->work_ha_mask);
13994 
13995 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13996 	status >>= (4*LPFC_FCP_RING);
13997 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
13998 	if (status & HA_RXMASK)
13999 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
14000 
14001 	if (phba->cfg_multi_ring_support == 2) {
14002 		/*
14003 		 * Process all events on extra ring. Take the optimized path
14004 		 * for extra ring IO.
14005 		 */
14006 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14007 		status >>= (4*LPFC_EXTRA_RING);
14008 		if (status & HA_RXMASK) {
14009 			lpfc_sli_handle_fast_ring_event(phba,
14010 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
14011 					status);
14012 		}
14013 	}
14014 	return IRQ_HANDLED;
14015 }  /* lpfc_sli_fp_intr_handler */
14016 
14017 /**
14018  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
14019  * @irq: Interrupt number.
14020  * @dev_id: The device context pointer.
14021  *
14022  * This function is the HBA device-level interrupt handler to device with
14023  * SLI-3 interface spec, called from the PCI layer when either MSI or
14024  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
14025  * requires driver attention. This function invokes the slow-path interrupt
14026  * attention handling function and fast-path interrupt attention handling
14027  * function in turn to process the relevant HBA attention events. This
14028  * function is called without any lock held. It gets the hbalock to access
14029  * and update SLI data structures.
14030  *
14031  * This function returns IRQ_HANDLED when interrupt is handled, else it
14032  * returns IRQ_NONE.
14033  **/
14034 irqreturn_t
14035 lpfc_sli_intr_handler(int irq, void *dev_id)
14036 {
14037 	struct lpfc_hba  *phba;
14038 	irqreturn_t sp_irq_rc, fp_irq_rc;
14039 	unsigned long status1, status2;
14040 	uint32_t hc_copy;
14041 
14042 	/*
14043 	 * Get the driver's phba structure from the dev_id and
14044 	 * assume the HBA is not interrupting.
14045 	 */
14046 	phba = (struct lpfc_hba *) dev_id;
14047 
14048 	if (unlikely(!phba))
14049 		return IRQ_NONE;
14050 
14051 	/* Check device state for handling interrupt */
14052 	if (lpfc_intr_state_check(phba))
14053 		return IRQ_NONE;
14054 
14055 	spin_lock(&phba->hbalock);
14056 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
14057 		spin_unlock(&phba->hbalock);
14058 		return IRQ_HANDLED;
14059 	}
14060 
14061 	if (unlikely(!phba->ha_copy)) {
14062 		spin_unlock(&phba->hbalock);
14063 		return IRQ_NONE;
14064 	} else if (phba->ha_copy & HA_ERATT) {
14065 		if (phba->hba_flag & HBA_ERATT_HANDLED)
14066 			/* ERATT polling has handled ERATT */
14067 			phba->ha_copy &= ~HA_ERATT;
14068 		else
14069 			/* Indicate interrupt handler handles ERATT */
14070 			phba->hba_flag |= HBA_ERATT_HANDLED;
14071 	}
14072 
14073 	/*
14074 	 * If there is deferred error attention, do not check for any interrupt.
14075 	 */
14076 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
14077 		spin_unlock(&phba->hbalock);
14078 		return IRQ_NONE;
14079 	}
14080 
14081 	/* Clear attention sources except link and error attentions */
14082 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
14083 		spin_unlock(&phba->hbalock);
14084 		return IRQ_HANDLED;
14085 	}
14086 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
14087 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
14088 		phba->HCregaddr);
14089 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
14090 	writel(hc_copy, phba->HCregaddr);
14091 	readl(phba->HAregaddr); /* flush */
14092 	spin_unlock(&phba->hbalock);
14093 
14094 	/*
14095 	 * Invokes slow-path host attention interrupt handling as appropriate.
14096 	 */
14097 
14098 	/* status of events with mailbox and link attention */
14099 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
14100 
14101 	/* status of events with ELS ring */
14102 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
14103 	status2 >>= (4*LPFC_ELS_RING);
14104 
14105 	if (status1 || (status2 & HA_RXMASK))
14106 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
14107 	else
14108 		sp_irq_rc = IRQ_NONE;
14109 
14110 	/*
14111 	 * Invoke fast-path host attention interrupt handling as appropriate.
14112 	 */
14113 
14114 	/* status of events with FCP ring */
14115 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
14116 	status1 >>= (4*LPFC_FCP_RING);
14117 
14118 	/* status of events with extra ring */
14119 	if (phba->cfg_multi_ring_support == 2) {
14120 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14121 		status2 >>= (4*LPFC_EXTRA_RING);
14122 	} else
14123 		status2 = 0;
14124 
14125 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
14126 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
14127 	else
14128 		fp_irq_rc = IRQ_NONE;
14129 
14130 	/* Return device-level interrupt handling status */
14131 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
14132 }  /* lpfc_sli_intr_handler */
14133 
14134 /**
14135  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
14136  * @phba: pointer to lpfc hba data structure.
14137  *
14138  * This routine is invoked by the worker thread to process all the pending
14139  * SLI4 els abort xri events.
14140  **/
14141 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
14142 {
14143 	struct lpfc_cq_event *cq_event;
14144 	unsigned long iflags;
14145 
14146 	/* First, declare the els xri abort event has been handled */
14147 	spin_lock_irqsave(&phba->hbalock, iflags);
14148 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
14149 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14150 
14151 	/* Now, handle all the els xri abort events */
14152 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14153 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
14154 		/* Get the first event from the head of the event queue */
14155 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
14156 				 cq_event, struct lpfc_cq_event, list);
14157 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14158 				       iflags);
14159 		/* Notify aborted XRI for ELS work queue */
14160 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
14161 
14162 		/* Free the event processed back to the free pool */
14163 		lpfc_sli4_cq_event_release(phba, cq_event);
14164 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14165 				  iflags);
14166 	}
14167 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14168 }
14169 
14170 /**
14171  * lpfc_sli4_els_preprocess_rspiocbq - Get response iocbq from els wcqe
14172  * @phba: Pointer to HBA context object.
14173  * @irspiocbq: Pointer to work-queue completion queue entry.
14174  *
14175  * This routine handles an ELS work-queue completion event and construct
14176  * a pseudo response ELS IOCBQ from the SLI4 ELS WCQE for the common
14177  * discovery engine to handle.
14178  *
14179  * Return: Pointer to the receive IOCBQ, NULL otherwise.
14180  **/
14181 static struct lpfc_iocbq *
14182 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
14183 				  struct lpfc_iocbq *irspiocbq)
14184 {
14185 	struct lpfc_sli_ring *pring;
14186 	struct lpfc_iocbq *cmdiocbq;
14187 	struct lpfc_wcqe_complete *wcqe;
14188 	unsigned long iflags;
14189 
14190 	pring = lpfc_phba_elsring(phba);
14191 	if (unlikely(!pring))
14192 		return NULL;
14193 
14194 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
14195 	spin_lock_irqsave(&pring->ring_lock, iflags);
14196 	pring->stats.iocb_event++;
14197 	/* Look up the ELS command IOCB and create pseudo response IOCB */
14198 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14199 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14200 	if (unlikely(!cmdiocbq)) {
14201 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
14202 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14203 				"0386 ELS complete with no corresponding "
14204 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
14205 				wcqe->word0, wcqe->total_data_placed,
14206 				wcqe->parameter, wcqe->word3);
14207 		lpfc_sli_release_iocbq(phba, irspiocbq);
14208 		return NULL;
14209 	}
14210 
14211 	memcpy(&irspiocbq->wqe, &cmdiocbq->wqe, sizeof(union lpfc_wqe128));
14212 	memcpy(&irspiocbq->wcqe_cmpl, wcqe, sizeof(*wcqe));
14213 
14214 	/* Put the iocb back on the txcmplq */
14215 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
14216 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
14217 
14218 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
14219 		spin_lock_irqsave(&phba->hbalock, iflags);
14220 		irspiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
14221 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14222 	}
14223 
14224 	return irspiocbq;
14225 }
14226 
14227 inline struct lpfc_cq_event *
14228 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
14229 {
14230 	struct lpfc_cq_event *cq_event;
14231 
14232 	/* Allocate a new internal CQ_EVENT entry */
14233 	cq_event = lpfc_sli4_cq_event_alloc(phba);
14234 	if (!cq_event) {
14235 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14236 				"0602 Failed to alloc CQ_EVENT entry\n");
14237 		return NULL;
14238 	}
14239 
14240 	/* Move the CQE into the event */
14241 	memcpy(&cq_event->cqe, entry, size);
14242 	return cq_event;
14243 }
14244 
14245 /**
14246  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
14247  * @phba: Pointer to HBA context object.
14248  * @mcqe: Pointer to mailbox completion queue entry.
14249  *
14250  * This routine process a mailbox completion queue entry with asynchronous
14251  * event.
14252  *
14253  * Return: true if work posted to worker thread, otherwise false.
14254  **/
14255 static bool
14256 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14257 {
14258 	struct lpfc_cq_event *cq_event;
14259 	unsigned long iflags;
14260 
14261 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14262 			"0392 Async Event: word0:x%x, word1:x%x, "
14263 			"word2:x%x, word3:x%x\n", mcqe->word0,
14264 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
14265 
14266 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
14267 	if (!cq_event)
14268 		return false;
14269 
14270 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
14271 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
14272 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
14273 
14274 	/* Set the async event flag */
14275 	spin_lock_irqsave(&phba->hbalock, iflags);
14276 	phba->hba_flag |= ASYNC_EVENT;
14277 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14278 
14279 	return true;
14280 }
14281 
14282 /**
14283  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
14284  * @phba: Pointer to HBA context object.
14285  * @mcqe: Pointer to mailbox completion queue entry.
14286  *
14287  * This routine process a mailbox completion queue entry with mailbox
14288  * completion event.
14289  *
14290  * Return: true if work posted to worker thread, otherwise false.
14291  **/
14292 static bool
14293 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14294 {
14295 	uint32_t mcqe_status;
14296 	MAILBOX_t *mbox, *pmbox;
14297 	struct lpfc_mqe *mqe;
14298 	struct lpfc_vport *vport;
14299 	struct lpfc_nodelist *ndlp;
14300 	struct lpfc_dmabuf *mp;
14301 	unsigned long iflags;
14302 	LPFC_MBOXQ_t *pmb;
14303 	bool workposted = false;
14304 	int rc;
14305 
14306 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
14307 	if (!bf_get(lpfc_trailer_completed, mcqe))
14308 		goto out_no_mqe_complete;
14309 
14310 	/* Get the reference to the active mbox command */
14311 	spin_lock_irqsave(&phba->hbalock, iflags);
14312 	pmb = phba->sli.mbox_active;
14313 	if (unlikely(!pmb)) {
14314 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14315 				"1832 No pending MBOX command to handle\n");
14316 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14317 		goto out_no_mqe_complete;
14318 	}
14319 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14320 	mqe = &pmb->u.mqe;
14321 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
14322 	mbox = phba->mbox;
14323 	vport = pmb->vport;
14324 
14325 	/* Reset heartbeat timer */
14326 	phba->last_completion_time = jiffies;
14327 	del_timer(&phba->sli.mbox_tmo);
14328 
14329 	/* Move mbox data to caller's mailbox region, do endian swapping */
14330 	if (pmb->mbox_cmpl && mbox)
14331 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
14332 
14333 	/*
14334 	 * For mcqe errors, conditionally move a modified error code to
14335 	 * the mbox so that the error will not be missed.
14336 	 */
14337 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
14338 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
14339 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
14340 			bf_set(lpfc_mqe_status, mqe,
14341 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
14342 	}
14343 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
14344 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
14345 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
14346 				      "MBOX dflt rpi: status:x%x rpi:x%x",
14347 				      mcqe_status,
14348 				      pmbox->un.varWords[0], 0);
14349 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
14350 			mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
14351 			ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
14352 
14353 			/* Reg_LOGIN of dflt RPI was successful. Mark the
14354 			 * node as having an UNREG_LOGIN in progress to stop
14355 			 * an unsolicited PLOGI from the same NPortId from
14356 			 * starting another mailbox transaction.
14357 			 */
14358 			spin_lock_irqsave(&ndlp->lock, iflags);
14359 			ndlp->nlp_flag |= NLP_UNREG_INP;
14360 			spin_unlock_irqrestore(&ndlp->lock, iflags);
14361 			lpfc_unreg_login(phba, vport->vpi,
14362 					 pmbox->un.varWords[0], pmb);
14363 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
14364 			pmb->ctx_buf = mp;
14365 
14366 			/* No reference taken here.  This is a default
14367 			 * RPI reg/immediate unreg cycle. The reference was
14368 			 * taken in the reg rpi path and is released when
14369 			 * this mailbox completes.
14370 			 */
14371 			pmb->ctx_ndlp = ndlp;
14372 			pmb->vport = vport;
14373 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
14374 			if (rc != MBX_BUSY)
14375 				lpfc_printf_log(phba, KERN_ERR,
14376 						LOG_TRACE_EVENT,
14377 						"0385 rc should "
14378 						"have been MBX_BUSY\n");
14379 			if (rc != MBX_NOT_FINISHED)
14380 				goto send_current_mbox;
14381 		}
14382 	}
14383 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
14384 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
14385 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
14386 
14387 	/* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
14388 	if (pmbox->mbxCommand == MBX_HEARTBEAT) {
14389 		spin_lock_irqsave(&phba->hbalock, iflags);
14390 		/* Release the mailbox command posting token */
14391 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14392 		phba->sli.mbox_active = NULL;
14393 		if (bf_get(lpfc_trailer_consumed, mcqe))
14394 			lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14395 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14396 
14397 		/* Post the next mbox command, if there is one */
14398 		lpfc_sli4_post_async_mbox(phba);
14399 
14400 		/* Process cmpl now */
14401 		if (pmb->mbox_cmpl)
14402 			pmb->mbox_cmpl(phba, pmb);
14403 		return false;
14404 	}
14405 
14406 	/* There is mailbox completion work to queue to the worker thread */
14407 	spin_lock_irqsave(&phba->hbalock, iflags);
14408 	__lpfc_mbox_cmpl_put(phba, pmb);
14409 	phba->work_ha |= HA_MBATT;
14410 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14411 	workposted = true;
14412 
14413 send_current_mbox:
14414 	spin_lock_irqsave(&phba->hbalock, iflags);
14415 	/* Release the mailbox command posting token */
14416 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14417 	/* Setting active mailbox pointer need to be in sync to flag clear */
14418 	phba->sli.mbox_active = NULL;
14419 	if (bf_get(lpfc_trailer_consumed, mcqe))
14420 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14421 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14422 	/* Wake up worker thread to post the next pending mailbox command */
14423 	lpfc_worker_wake_up(phba);
14424 	return workposted;
14425 
14426 out_no_mqe_complete:
14427 	spin_lock_irqsave(&phba->hbalock, iflags);
14428 	if (bf_get(lpfc_trailer_consumed, mcqe))
14429 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14430 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14431 	return false;
14432 }
14433 
14434 /**
14435  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
14436  * @phba: Pointer to HBA context object.
14437  * @cq: Pointer to associated CQ
14438  * @cqe: Pointer to mailbox completion queue entry.
14439  *
14440  * This routine process a mailbox completion queue entry, it invokes the
14441  * proper mailbox complete handling or asynchronous event handling routine
14442  * according to the MCQE's async bit.
14443  *
14444  * Return: true if work posted to worker thread, otherwise false.
14445  **/
14446 static bool
14447 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14448 			 struct lpfc_cqe *cqe)
14449 {
14450 	struct lpfc_mcqe mcqe;
14451 	bool workposted;
14452 
14453 	cq->CQ_mbox++;
14454 
14455 	/* Copy the mailbox MCQE and convert endian order as needed */
14456 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
14457 
14458 	/* Invoke the proper event handling routine */
14459 	if (!bf_get(lpfc_trailer_async, &mcqe))
14460 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
14461 	else
14462 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
14463 	return workposted;
14464 }
14465 
14466 /**
14467  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
14468  * @phba: Pointer to HBA context object.
14469  * @cq: Pointer to associated CQ
14470  * @wcqe: Pointer to work-queue completion queue entry.
14471  *
14472  * This routine handles an ELS work-queue completion event.
14473  *
14474  * Return: true if work posted to worker thread, otherwise false.
14475  **/
14476 static bool
14477 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14478 			     struct lpfc_wcqe_complete *wcqe)
14479 {
14480 	struct lpfc_iocbq *irspiocbq;
14481 	unsigned long iflags;
14482 	struct lpfc_sli_ring *pring = cq->pring;
14483 	int txq_cnt = 0;
14484 	int txcmplq_cnt = 0;
14485 
14486 	/* Check for response status */
14487 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14488 		/* Log the error status */
14489 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14490 				"0357 ELS CQE error: status=x%x: "
14491 				"CQE: %08x %08x %08x %08x\n",
14492 				bf_get(lpfc_wcqe_c_status, wcqe),
14493 				wcqe->word0, wcqe->total_data_placed,
14494 				wcqe->parameter, wcqe->word3);
14495 	}
14496 
14497 	/* Get an irspiocbq for later ELS response processing use */
14498 	irspiocbq = lpfc_sli_get_iocbq(phba);
14499 	if (!irspiocbq) {
14500 		if (!list_empty(&pring->txq))
14501 			txq_cnt++;
14502 		if (!list_empty(&pring->txcmplq))
14503 			txcmplq_cnt++;
14504 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14505 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
14506 			"els_txcmplq_cnt=%d\n",
14507 			txq_cnt, phba->iocb_cnt,
14508 			txcmplq_cnt);
14509 		return false;
14510 	}
14511 
14512 	/* Save off the slow-path queue event for work thread to process */
14513 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
14514 	spin_lock_irqsave(&phba->hbalock, iflags);
14515 	list_add_tail(&irspiocbq->cq_event.list,
14516 		      &phba->sli4_hba.sp_queue_event);
14517 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
14518 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14519 
14520 	return true;
14521 }
14522 
14523 /**
14524  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
14525  * @phba: Pointer to HBA context object.
14526  * @wcqe: Pointer to work-queue completion queue entry.
14527  *
14528  * This routine handles slow-path WQ entry consumed event by invoking the
14529  * proper WQ release routine to the slow-path WQ.
14530  **/
14531 static void
14532 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
14533 			     struct lpfc_wcqe_release *wcqe)
14534 {
14535 	/* sanity check on queue memory */
14536 	if (unlikely(!phba->sli4_hba.els_wq))
14537 		return;
14538 	/* Check for the slow-path ELS work queue */
14539 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
14540 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
14541 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14542 	else
14543 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14544 				"2579 Slow-path wqe consume event carries "
14545 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
14546 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
14547 				phba->sli4_hba.els_wq->queue_id);
14548 }
14549 
14550 /**
14551  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
14552  * @phba: Pointer to HBA context object.
14553  * @cq: Pointer to a WQ completion queue.
14554  * @wcqe: Pointer to work-queue completion queue entry.
14555  *
14556  * This routine handles an XRI abort event.
14557  *
14558  * Return: true if work posted to worker thread, otherwise false.
14559  **/
14560 static bool
14561 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
14562 				   struct lpfc_queue *cq,
14563 				   struct sli4_wcqe_xri_aborted *wcqe)
14564 {
14565 	bool workposted = false;
14566 	struct lpfc_cq_event *cq_event;
14567 	unsigned long iflags;
14568 
14569 	switch (cq->subtype) {
14570 	case LPFC_IO:
14571 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
14572 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14573 			/* Notify aborted XRI for NVME work queue */
14574 			if (phba->nvmet_support)
14575 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
14576 		}
14577 		workposted = false;
14578 		break;
14579 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
14580 	case LPFC_ELS:
14581 		cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
14582 		if (!cq_event) {
14583 			workposted = false;
14584 			break;
14585 		}
14586 		cq_event->hdwq = cq->hdwq;
14587 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14588 				  iflags);
14589 		list_add_tail(&cq_event->list,
14590 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
14591 		/* Set the els xri abort event flag */
14592 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
14593 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14594 				       iflags);
14595 		workposted = true;
14596 		break;
14597 	default:
14598 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14599 				"0603 Invalid CQ subtype %d: "
14600 				"%08x %08x %08x %08x\n",
14601 				cq->subtype, wcqe->word0, wcqe->parameter,
14602 				wcqe->word2, wcqe->word3);
14603 		workposted = false;
14604 		break;
14605 	}
14606 	return workposted;
14607 }
14608 
14609 #define FC_RCTL_MDS_DIAGS	0xF4
14610 
14611 /**
14612  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
14613  * @phba: Pointer to HBA context object.
14614  * @rcqe: Pointer to receive-queue completion queue entry.
14615  *
14616  * This routine process a receive-queue completion queue entry.
14617  *
14618  * Return: true if work posted to worker thread, otherwise false.
14619  **/
14620 static bool
14621 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
14622 {
14623 	bool workposted = false;
14624 	struct fc_frame_header *fc_hdr;
14625 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
14626 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
14627 	struct lpfc_nvmet_tgtport *tgtp;
14628 	struct hbq_dmabuf *dma_buf;
14629 	uint32_t status, rq_id;
14630 	unsigned long iflags;
14631 
14632 	/* sanity check on queue memory */
14633 	if (unlikely(!hrq) || unlikely(!drq))
14634 		return workposted;
14635 
14636 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14637 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14638 	else
14639 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14640 	if (rq_id != hrq->queue_id)
14641 		goto out;
14642 
14643 	status = bf_get(lpfc_rcqe_status, rcqe);
14644 	switch (status) {
14645 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14646 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14647 				"2537 Receive Frame Truncated!!\n");
14648 		fallthrough;
14649 	case FC_STATUS_RQ_SUCCESS:
14650 		spin_lock_irqsave(&phba->hbalock, iflags);
14651 		lpfc_sli4_rq_release(hrq, drq);
14652 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14653 		if (!dma_buf) {
14654 			hrq->RQ_no_buf_found++;
14655 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14656 			goto out;
14657 		}
14658 		hrq->RQ_rcv_buf++;
14659 		hrq->RQ_buf_posted--;
14660 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
14661 
14662 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14663 
14664 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
14665 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
14666 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14667 			/* Handle MDS Loopback frames */
14668 			if  (!(phba->pport->load_flag & FC_UNLOADING))
14669 				lpfc_sli4_handle_mds_loopback(phba->pport,
14670 							      dma_buf);
14671 			else
14672 				lpfc_in_buf_free(phba, &dma_buf->dbuf);
14673 			break;
14674 		}
14675 
14676 		/* save off the frame for the work thread to process */
14677 		list_add_tail(&dma_buf->cq_event.list,
14678 			      &phba->sli4_hba.sp_queue_event);
14679 		/* Frame received */
14680 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
14681 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14682 		workposted = true;
14683 		break;
14684 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14685 		if (phba->nvmet_support) {
14686 			tgtp = phba->targetport->private;
14687 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14688 					"6402 RQE Error x%x, posted %d err_cnt "
14689 					"%d: %x %x %x\n",
14690 					status, hrq->RQ_buf_posted,
14691 					hrq->RQ_no_posted_buf,
14692 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14693 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14694 					atomic_read(&tgtp->xmt_fcp_release));
14695 		}
14696 		fallthrough;
14697 
14698 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14699 		hrq->RQ_no_posted_buf++;
14700 		/* Post more buffers if possible */
14701 		spin_lock_irqsave(&phba->hbalock, iflags);
14702 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
14703 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14704 		workposted = true;
14705 		break;
14706 	case FC_STATUS_RQ_DMA_FAILURE:
14707 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14708 				"2564 RQE DMA Error x%x, x%08x x%08x x%08x "
14709 				"x%08x\n",
14710 				status, rcqe->word0, rcqe->word1,
14711 				rcqe->word2, rcqe->word3);
14712 
14713 		/* If IV set, no further recovery */
14714 		if (bf_get(lpfc_rcqe_iv, rcqe))
14715 			break;
14716 
14717 		/* recycle consumed resource */
14718 		spin_lock_irqsave(&phba->hbalock, iflags);
14719 		lpfc_sli4_rq_release(hrq, drq);
14720 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14721 		if (!dma_buf) {
14722 			hrq->RQ_no_buf_found++;
14723 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14724 			break;
14725 		}
14726 		hrq->RQ_rcv_buf++;
14727 		hrq->RQ_buf_posted--;
14728 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14729 		lpfc_in_buf_free(phba, &dma_buf->dbuf);
14730 		break;
14731 	default:
14732 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14733 				"2565 Unexpected RQE Status x%x, w0-3 x%08x "
14734 				"x%08x x%08x x%08x\n",
14735 				status, rcqe->word0, rcqe->word1,
14736 				rcqe->word2, rcqe->word3);
14737 		break;
14738 	}
14739 out:
14740 	return workposted;
14741 }
14742 
14743 /**
14744  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
14745  * @phba: Pointer to HBA context object.
14746  * @cq: Pointer to the completion queue.
14747  * @cqe: Pointer to a completion queue entry.
14748  *
14749  * This routine process a slow-path work-queue or receive queue completion queue
14750  * entry.
14751  *
14752  * Return: true if work posted to worker thread, otherwise false.
14753  **/
14754 static bool
14755 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14756 			 struct lpfc_cqe *cqe)
14757 {
14758 	struct lpfc_cqe cqevt;
14759 	bool workposted = false;
14760 
14761 	/* Copy the work queue CQE and convert endian order if needed */
14762 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14763 
14764 	/* Check and process for different type of WCQE and dispatch */
14765 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
14766 	case CQE_CODE_COMPL_WQE:
14767 		/* Process the WQ/RQ complete event */
14768 		phba->last_completion_time = jiffies;
14769 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14770 				(struct lpfc_wcqe_complete *)&cqevt);
14771 		break;
14772 	case CQE_CODE_RELEASE_WQE:
14773 		/* Process the WQ release event */
14774 		lpfc_sli4_sp_handle_rel_wcqe(phba,
14775 				(struct lpfc_wcqe_release *)&cqevt);
14776 		break;
14777 	case CQE_CODE_XRI_ABORTED:
14778 		/* Process the WQ XRI abort event */
14779 		phba->last_completion_time = jiffies;
14780 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14781 				(struct sli4_wcqe_xri_aborted *)&cqevt);
14782 		break;
14783 	case CQE_CODE_RECEIVE:
14784 	case CQE_CODE_RECEIVE_V1:
14785 		/* Process the RQ event */
14786 		phba->last_completion_time = jiffies;
14787 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
14788 				(struct lpfc_rcqe *)&cqevt);
14789 		break;
14790 	default:
14791 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14792 				"0388 Not a valid WCQE code: x%x\n",
14793 				bf_get(lpfc_cqe_code, &cqevt));
14794 		break;
14795 	}
14796 	return workposted;
14797 }
14798 
14799 /**
14800  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14801  * @phba: Pointer to HBA context object.
14802  * @eqe: Pointer to fast-path event queue entry.
14803  * @speq: Pointer to slow-path event queue.
14804  *
14805  * This routine process a event queue entry from the slow-path event queue.
14806  * It will check the MajorCode and MinorCode to determine this is for a
14807  * completion event on a completion queue, if not, an error shall be logged
14808  * and just return. Otherwise, it will get to the corresponding completion
14809  * queue and process all the entries on that completion queue, rearm the
14810  * completion queue, and then return.
14811  *
14812  **/
14813 static void
14814 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14815 	struct lpfc_queue *speq)
14816 {
14817 	struct lpfc_queue *cq = NULL, *childq;
14818 	uint16_t cqid;
14819 	int ret = 0;
14820 
14821 	/* Get the reference to the corresponding CQ */
14822 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14823 
14824 	list_for_each_entry(childq, &speq->child_list, list) {
14825 		if (childq->queue_id == cqid) {
14826 			cq = childq;
14827 			break;
14828 		}
14829 	}
14830 	if (unlikely(!cq)) {
14831 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14832 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14833 					"0365 Slow-path CQ identifier "
14834 					"(%d) does not exist\n", cqid);
14835 		return;
14836 	}
14837 
14838 	/* Save EQ associated with this CQ */
14839 	cq->assoc_qp = speq;
14840 
14841 	if (is_kdump_kernel())
14842 		ret = queue_work(phba->wq, &cq->spwork);
14843 	else
14844 		ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14845 
14846 	if (!ret)
14847 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14848 				"0390 Cannot schedule queue work "
14849 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14850 				cqid, cq->queue_id, raw_smp_processor_id());
14851 }
14852 
14853 /**
14854  * __lpfc_sli4_process_cq - Process elements of a CQ
14855  * @phba: Pointer to HBA context object.
14856  * @cq: Pointer to CQ to be processed
14857  * @handler: Routine to process each cqe
14858  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14859  *
14860  * This routine processes completion queue entries in a CQ. While a valid
14861  * queue element is found, the handler is called. During processing checks
14862  * are made for periodic doorbell writes to let the hardware know of
14863  * element consumption.
14864  *
14865  * If the max limit on cqes to process is hit, or there are no more valid
14866  * entries, the loop stops. If we processed a sufficient number of elements,
14867  * meaning there is sufficient load, rather than rearming and generating
14868  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14869  * indicates no rescheduling.
14870  *
14871  * Returns True if work scheduled, False otherwise.
14872  **/
14873 static bool
14874 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14875 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14876 			struct lpfc_cqe *), unsigned long *delay)
14877 {
14878 	struct lpfc_cqe *cqe;
14879 	bool workposted = false;
14880 	int count = 0, consumed = 0;
14881 	bool arm = true;
14882 
14883 	/* default - no reschedule */
14884 	*delay = 0;
14885 
14886 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14887 		goto rearm_and_exit;
14888 
14889 	/* Process all the entries to the CQ */
14890 	cq->q_flag = 0;
14891 	cqe = lpfc_sli4_cq_get(cq);
14892 	while (cqe) {
14893 		workposted |= handler(phba, cq, cqe);
14894 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
14895 
14896 		consumed++;
14897 		if (!(++count % cq->max_proc_limit))
14898 			break;
14899 
14900 		if (!(count % cq->notify_interval)) {
14901 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14902 						LPFC_QUEUE_NOARM);
14903 			consumed = 0;
14904 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14905 		}
14906 
14907 		if (count == LPFC_NVMET_CQ_NOTIFY)
14908 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14909 
14910 		cqe = lpfc_sli4_cq_get(cq);
14911 	}
14912 	if (count >= phba->cfg_cq_poll_threshold) {
14913 		*delay = 1;
14914 		arm = false;
14915 	}
14916 
14917 	/* Track the max number of CQEs processed in 1 EQ */
14918 	if (count > cq->CQ_max_cqe)
14919 		cq->CQ_max_cqe = count;
14920 
14921 	cq->assoc_qp->EQ_cqe_cnt += count;
14922 
14923 	/* Catch the no cq entry condition */
14924 	if (unlikely(count == 0))
14925 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14926 				"0369 No entry from completion queue "
14927 				"qid=%d\n", cq->queue_id);
14928 
14929 	xchg(&cq->queue_claimed, 0);
14930 
14931 rearm_and_exit:
14932 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14933 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14934 
14935 	return workposted;
14936 }
14937 
14938 /**
14939  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14940  * @cq: pointer to CQ to process
14941  *
14942  * This routine calls the cq processing routine with a handler specific
14943  * to the type of queue bound to it.
14944  *
14945  * The CQ routine returns two values: the first is the calling status,
14946  * which indicates whether work was queued to the  background discovery
14947  * thread. If true, the routine should wakeup the discovery thread;
14948  * the second is the delay parameter. If non-zero, rather than rearming
14949  * the CQ and yet another interrupt, the CQ handler should be queued so
14950  * that it is processed in a subsequent polling action. The value of
14951  * the delay indicates when to reschedule it.
14952  **/
14953 static void
14954 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14955 {
14956 	struct lpfc_hba *phba = cq->phba;
14957 	unsigned long delay;
14958 	bool workposted = false;
14959 	int ret = 0;
14960 
14961 	/* Process and rearm the CQ */
14962 	switch (cq->type) {
14963 	case LPFC_MCQ:
14964 		workposted |= __lpfc_sli4_process_cq(phba, cq,
14965 						lpfc_sli4_sp_handle_mcqe,
14966 						&delay);
14967 		break;
14968 	case LPFC_WCQ:
14969 		if (cq->subtype == LPFC_IO)
14970 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14971 						lpfc_sli4_fp_handle_cqe,
14972 						&delay);
14973 		else
14974 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14975 						lpfc_sli4_sp_handle_cqe,
14976 						&delay);
14977 		break;
14978 	default:
14979 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14980 				"0370 Invalid completion queue type (%d)\n",
14981 				cq->type);
14982 		return;
14983 	}
14984 
14985 	if (delay) {
14986 		if (is_kdump_kernel())
14987 			ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
14988 						delay);
14989 		else
14990 			ret = queue_delayed_work_on(cq->chann, phba->wq,
14991 						&cq->sched_spwork, delay);
14992 		if (!ret)
14993 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14994 				"0394 Cannot schedule queue work "
14995 				"for cqid=%d on CPU %d\n",
14996 				cq->queue_id, cq->chann);
14997 	}
14998 
14999 	/* wake up worker thread if there are works to be done */
15000 	if (workposted)
15001 		lpfc_worker_wake_up(phba);
15002 }
15003 
15004 /**
15005  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
15006  *   interrupt
15007  * @work: pointer to work element
15008  *
15009  * translates from the work handler and calls the slow-path handler.
15010  **/
15011 static void
15012 lpfc_sli4_sp_process_cq(struct work_struct *work)
15013 {
15014 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
15015 
15016 	__lpfc_sli4_sp_process_cq(cq);
15017 }
15018 
15019 /**
15020  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
15021  * @work: pointer to work element
15022  *
15023  * translates from the work handler and calls the slow-path handler.
15024  **/
15025 static void
15026 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
15027 {
15028 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15029 					struct lpfc_queue, sched_spwork);
15030 
15031 	__lpfc_sli4_sp_process_cq(cq);
15032 }
15033 
15034 /**
15035  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
15036  * @phba: Pointer to HBA context object.
15037  * @cq: Pointer to associated CQ
15038  * @wcqe: Pointer to work-queue completion queue entry.
15039  *
15040  * This routine process a fast-path work queue completion entry from fast-path
15041  * event queue for FCP command response completion.
15042  **/
15043 static void
15044 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15045 			     struct lpfc_wcqe_complete *wcqe)
15046 {
15047 	struct lpfc_sli_ring *pring = cq->pring;
15048 	struct lpfc_iocbq *cmdiocbq;
15049 	unsigned long iflags;
15050 
15051 	/* Check for response status */
15052 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
15053 		/* If resource errors reported from HBA, reduce queue
15054 		 * depth of the SCSI device.
15055 		 */
15056 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
15057 		     IOSTAT_LOCAL_REJECT)) &&
15058 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
15059 		     IOERR_NO_RESOURCES))
15060 			phba->lpfc_rampdown_queue_depth(phba);
15061 
15062 		/* Log the cmpl status */
15063 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15064 				"0373 FCP CQE cmpl: status=x%x: "
15065 				"CQE: %08x %08x %08x %08x\n",
15066 				bf_get(lpfc_wcqe_c_status, wcqe),
15067 				wcqe->word0, wcqe->total_data_placed,
15068 				wcqe->parameter, wcqe->word3);
15069 	}
15070 
15071 	/* Look up the FCP command IOCB and create pseudo response IOCB */
15072 	spin_lock_irqsave(&pring->ring_lock, iflags);
15073 	pring->stats.iocb_event++;
15074 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
15075 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15076 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
15077 	if (unlikely(!cmdiocbq)) {
15078 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15079 				"0374 FCP complete with no corresponding "
15080 				"cmdiocb: iotag (%d)\n",
15081 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15082 		return;
15083 	}
15084 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
15085 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
15086 #endif
15087 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
15088 		spin_lock_irqsave(&phba->hbalock, iflags);
15089 		cmdiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
15090 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15091 	}
15092 
15093 	if (cmdiocbq->cmd_cmpl) {
15094 		/* For FCP the flag is cleared in cmd_cmpl */
15095 		if (!(cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
15096 		    cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED) {
15097 			spin_lock_irqsave(&phba->hbalock, iflags);
15098 			cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
15099 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15100 		}
15101 
15102 		/* Pass the cmd_iocb and the wcqe to the upper layer */
15103 		memcpy(&cmdiocbq->wcqe_cmpl, wcqe,
15104 		       sizeof(struct lpfc_wcqe_complete));
15105 		cmdiocbq->cmd_cmpl(phba, cmdiocbq, cmdiocbq);
15106 	} else {
15107 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15108 				"0375 FCP cmdiocb not callback function "
15109 				"iotag: (%d)\n",
15110 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15111 	}
15112 }
15113 
15114 /**
15115  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
15116  * @phba: Pointer to HBA context object.
15117  * @cq: Pointer to completion queue.
15118  * @wcqe: Pointer to work-queue completion queue entry.
15119  *
15120  * This routine handles an fast-path WQ entry consumed event by invoking the
15121  * proper WQ release routine to the slow-path WQ.
15122  **/
15123 static void
15124 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15125 			     struct lpfc_wcqe_release *wcqe)
15126 {
15127 	struct lpfc_queue *childwq;
15128 	bool wqid_matched = false;
15129 	uint16_t hba_wqid;
15130 
15131 	/* Check for fast-path FCP work queue release */
15132 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
15133 	list_for_each_entry(childwq, &cq->child_list, list) {
15134 		if (childwq->queue_id == hba_wqid) {
15135 			lpfc_sli4_wq_release(childwq,
15136 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
15137 			if (childwq->q_flag & HBA_NVMET_WQFULL)
15138 				lpfc_nvmet_wqfull_process(phba, childwq);
15139 			wqid_matched = true;
15140 			break;
15141 		}
15142 	}
15143 	/* Report warning log message if no match found */
15144 	if (wqid_matched != true)
15145 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15146 				"2580 Fast-path wqe consume event carries "
15147 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
15148 }
15149 
15150 /**
15151  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
15152  * @phba: Pointer to HBA context object.
15153  * @cq: Pointer to completion queue.
15154  * @rcqe: Pointer to receive-queue completion queue entry.
15155  *
15156  * This routine process a receive-queue completion queue entry.
15157  *
15158  * Return: true if work posted to worker thread, otherwise false.
15159  **/
15160 static bool
15161 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15162 			    struct lpfc_rcqe *rcqe)
15163 {
15164 	bool workposted = false;
15165 	struct lpfc_queue *hrq;
15166 	struct lpfc_queue *drq;
15167 	struct rqb_dmabuf *dma_buf;
15168 	struct fc_frame_header *fc_hdr;
15169 	struct lpfc_nvmet_tgtport *tgtp;
15170 	uint32_t status, rq_id;
15171 	unsigned long iflags;
15172 	uint32_t fctl, idx;
15173 
15174 	if ((phba->nvmet_support == 0) ||
15175 	    (phba->sli4_hba.nvmet_cqset == NULL))
15176 		return workposted;
15177 
15178 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
15179 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
15180 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
15181 
15182 	/* sanity check on queue memory */
15183 	if (unlikely(!hrq) || unlikely(!drq))
15184 		return workposted;
15185 
15186 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
15187 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
15188 	else
15189 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
15190 
15191 	if ((phba->nvmet_support == 0) ||
15192 	    (rq_id != hrq->queue_id))
15193 		return workposted;
15194 
15195 	status = bf_get(lpfc_rcqe_status, rcqe);
15196 	switch (status) {
15197 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
15198 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15199 				"6126 Receive Frame Truncated!!\n");
15200 		fallthrough;
15201 	case FC_STATUS_RQ_SUCCESS:
15202 		spin_lock_irqsave(&phba->hbalock, iflags);
15203 		lpfc_sli4_rq_release(hrq, drq);
15204 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15205 		if (!dma_buf) {
15206 			hrq->RQ_no_buf_found++;
15207 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15208 			goto out;
15209 		}
15210 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15211 		hrq->RQ_rcv_buf++;
15212 		hrq->RQ_buf_posted--;
15213 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
15214 
15215 		/* Just some basic sanity checks on FCP Command frame */
15216 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
15217 			fc_hdr->fh_f_ctl[1] << 8 |
15218 			fc_hdr->fh_f_ctl[2]);
15219 		if (((fctl &
15220 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
15221 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
15222 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
15223 			goto drop;
15224 
15225 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
15226 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
15227 			lpfc_nvmet_unsol_fcp_event(
15228 				phba, idx, dma_buf, cq->isr_timestamp,
15229 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
15230 			return false;
15231 		}
15232 drop:
15233 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15234 		break;
15235 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
15236 		if (phba->nvmet_support) {
15237 			tgtp = phba->targetport->private;
15238 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15239 					"6401 RQE Error x%x, posted %d err_cnt "
15240 					"%d: %x %x %x\n",
15241 					status, hrq->RQ_buf_posted,
15242 					hrq->RQ_no_posted_buf,
15243 					atomic_read(&tgtp->rcv_fcp_cmd_in),
15244 					atomic_read(&tgtp->rcv_fcp_cmd_out),
15245 					atomic_read(&tgtp->xmt_fcp_release));
15246 		}
15247 		fallthrough;
15248 
15249 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
15250 		hrq->RQ_no_posted_buf++;
15251 		/* Post more buffers if possible */
15252 		break;
15253 	case FC_STATUS_RQ_DMA_FAILURE:
15254 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15255 				"2575 RQE DMA Error x%x, x%08x x%08x x%08x "
15256 				"x%08x\n",
15257 				status, rcqe->word0, rcqe->word1,
15258 				rcqe->word2, rcqe->word3);
15259 
15260 		/* If IV set, no further recovery */
15261 		if (bf_get(lpfc_rcqe_iv, rcqe))
15262 			break;
15263 
15264 		/* recycle consumed resource */
15265 		spin_lock_irqsave(&phba->hbalock, iflags);
15266 		lpfc_sli4_rq_release(hrq, drq);
15267 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15268 		if (!dma_buf) {
15269 			hrq->RQ_no_buf_found++;
15270 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15271 			break;
15272 		}
15273 		hrq->RQ_rcv_buf++;
15274 		hrq->RQ_buf_posted--;
15275 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15276 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15277 		break;
15278 	default:
15279 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15280 				"2576 Unexpected RQE Status x%x, w0-3 x%08x "
15281 				"x%08x x%08x x%08x\n",
15282 				status, rcqe->word0, rcqe->word1,
15283 				rcqe->word2, rcqe->word3);
15284 		break;
15285 	}
15286 out:
15287 	return workposted;
15288 }
15289 
15290 /**
15291  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
15292  * @phba: adapter with cq
15293  * @cq: Pointer to the completion queue.
15294  * @cqe: Pointer to fast-path completion queue entry.
15295  *
15296  * This routine process a fast-path work queue completion entry from fast-path
15297  * event queue for FCP command response completion.
15298  *
15299  * Return: true if work posted to worker thread, otherwise false.
15300  **/
15301 static bool
15302 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15303 			 struct lpfc_cqe *cqe)
15304 {
15305 	struct lpfc_wcqe_release wcqe;
15306 	bool workposted = false;
15307 
15308 	/* Copy the work queue CQE and convert endian order if needed */
15309 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
15310 
15311 	/* Check and process for different type of WCQE and dispatch */
15312 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
15313 	case CQE_CODE_COMPL_WQE:
15314 	case CQE_CODE_NVME_ERSP:
15315 		cq->CQ_wq++;
15316 		/* Process the WQ complete event */
15317 		phba->last_completion_time = jiffies;
15318 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
15319 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
15320 				(struct lpfc_wcqe_complete *)&wcqe);
15321 		break;
15322 	case CQE_CODE_RELEASE_WQE:
15323 		cq->CQ_release_wqe++;
15324 		/* Process the WQ release event */
15325 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
15326 				(struct lpfc_wcqe_release *)&wcqe);
15327 		break;
15328 	case CQE_CODE_XRI_ABORTED:
15329 		cq->CQ_xri_aborted++;
15330 		/* Process the WQ XRI abort event */
15331 		phba->last_completion_time = jiffies;
15332 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
15333 				(struct sli4_wcqe_xri_aborted *)&wcqe);
15334 		break;
15335 	case CQE_CODE_RECEIVE_V1:
15336 	case CQE_CODE_RECEIVE:
15337 		phba->last_completion_time = jiffies;
15338 		if (cq->subtype == LPFC_NVMET) {
15339 			workposted = lpfc_sli4_nvmet_handle_rcqe(
15340 				phba, cq, (struct lpfc_rcqe *)&wcqe);
15341 		}
15342 		break;
15343 	default:
15344 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15345 				"0144 Not a valid CQE code: x%x\n",
15346 				bf_get(lpfc_wcqe_c_code, &wcqe));
15347 		break;
15348 	}
15349 	return workposted;
15350 }
15351 
15352 /**
15353  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
15354  * @cq: Pointer to CQ to be processed
15355  *
15356  * This routine calls the cq processing routine with the handler for
15357  * fast path CQEs.
15358  *
15359  * The CQ routine returns two values: the first is the calling status,
15360  * which indicates whether work was queued to the  background discovery
15361  * thread. If true, the routine should wakeup the discovery thread;
15362  * the second is the delay parameter. If non-zero, rather than rearming
15363  * the CQ and yet another interrupt, the CQ handler should be queued so
15364  * that it is processed in a subsequent polling action. The value of
15365  * the delay indicates when to reschedule it.
15366  **/
15367 static void
15368 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq)
15369 {
15370 	struct lpfc_hba *phba = cq->phba;
15371 	unsigned long delay;
15372 	bool workposted = false;
15373 	int ret;
15374 
15375 	/* process and rearm the CQ */
15376 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
15377 					     &delay);
15378 
15379 	if (delay) {
15380 		if (is_kdump_kernel())
15381 			ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
15382 						delay);
15383 		else
15384 			ret = queue_delayed_work_on(cq->chann, phba->wq,
15385 						&cq->sched_irqwork, delay);
15386 		if (!ret)
15387 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15388 					"0367 Cannot schedule queue work "
15389 					"for cqid=%d on CPU %d\n",
15390 					cq->queue_id, cq->chann);
15391 	}
15392 
15393 	/* wake up worker thread if there are works to be done */
15394 	if (workposted)
15395 		lpfc_worker_wake_up(phba);
15396 }
15397 
15398 /**
15399  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
15400  *   interrupt
15401  * @work: pointer to work element
15402  *
15403  * translates from the work handler and calls the fast-path handler.
15404  **/
15405 static void
15406 lpfc_sli4_hba_process_cq(struct work_struct *work)
15407 {
15408 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
15409 
15410 	__lpfc_sli4_hba_process_cq(cq);
15411 }
15412 
15413 /**
15414  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
15415  * @phba: Pointer to HBA context object.
15416  * @eq: Pointer to the queue structure.
15417  * @eqe: Pointer to fast-path event queue entry.
15418  * @poll_mode: poll_mode to execute processing the cq.
15419  *
15420  * This routine process a event queue entry from the fast-path event queue.
15421  * It will check the MajorCode and MinorCode to determine this is for a
15422  * completion event on a completion queue, if not, an error shall be logged
15423  * and just return. Otherwise, it will get to the corresponding completion
15424  * queue and process all the entries on the completion queue, rearm the
15425  * completion queue, and then return.
15426  **/
15427 static void
15428 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
15429 			 struct lpfc_eqe *eqe, enum lpfc_poll_mode poll_mode)
15430 {
15431 	struct lpfc_queue *cq = NULL;
15432 	uint32_t qidx = eq->hdwq;
15433 	uint16_t cqid, id;
15434 	int ret;
15435 
15436 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
15437 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15438 				"0366 Not a valid completion "
15439 				"event: majorcode=x%x, minorcode=x%x\n",
15440 				bf_get_le32(lpfc_eqe_major_code, eqe),
15441 				bf_get_le32(lpfc_eqe_minor_code, eqe));
15442 		return;
15443 	}
15444 
15445 	/* Get the reference to the corresponding CQ */
15446 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
15447 
15448 	/* Use the fast lookup method first */
15449 	if (cqid <= phba->sli4_hba.cq_max) {
15450 		cq = phba->sli4_hba.cq_lookup[cqid];
15451 		if (cq)
15452 			goto  work_cq;
15453 	}
15454 
15455 	/* Next check for NVMET completion */
15456 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
15457 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
15458 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
15459 			/* Process NVMET unsol rcv */
15460 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
15461 			goto  process_cq;
15462 		}
15463 	}
15464 
15465 	if (phba->sli4_hba.nvmels_cq &&
15466 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
15467 		/* Process NVME unsol rcv */
15468 		cq = phba->sli4_hba.nvmels_cq;
15469 	}
15470 
15471 	/* Otherwise this is a Slow path event */
15472 	if (cq == NULL) {
15473 		lpfc_sli4_sp_handle_eqe(phba, eqe,
15474 					phba->sli4_hba.hdwq[qidx].hba_eq);
15475 		return;
15476 	}
15477 
15478 process_cq:
15479 	if (unlikely(cqid != cq->queue_id)) {
15480 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15481 				"0368 Miss-matched fast-path completion "
15482 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
15483 				cqid, cq->queue_id);
15484 		return;
15485 	}
15486 
15487 work_cq:
15488 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
15489 	if (phba->ktime_on)
15490 		cq->isr_timestamp = ktime_get_ns();
15491 	else
15492 		cq->isr_timestamp = 0;
15493 #endif
15494 
15495 	switch (poll_mode) {
15496 	case LPFC_THREADED_IRQ:
15497 		__lpfc_sli4_hba_process_cq(cq);
15498 		break;
15499 	case LPFC_QUEUE_WORK:
15500 	default:
15501 		if (is_kdump_kernel())
15502 			ret = queue_work(phba->wq, &cq->irqwork);
15503 		else
15504 			ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
15505 		if (!ret)
15506 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15507 					"0383 Cannot schedule queue work "
15508 					"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
15509 					cqid, cq->queue_id,
15510 					raw_smp_processor_id());
15511 		break;
15512 	}
15513 }
15514 
15515 /**
15516  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
15517  * @work: pointer to work element
15518  *
15519  * translates from the work handler and calls the fast-path handler.
15520  **/
15521 static void
15522 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
15523 {
15524 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15525 					struct lpfc_queue, sched_irqwork);
15526 
15527 	__lpfc_sli4_hba_process_cq(cq);
15528 }
15529 
15530 /**
15531  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
15532  * @irq: Interrupt number.
15533  * @dev_id: The device context pointer.
15534  *
15535  * This function is directly called from the PCI layer as an interrupt
15536  * service routine when device with SLI-4 interface spec is enabled with
15537  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
15538  * ring event in the HBA. However, when the device is enabled with either
15539  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
15540  * device-level interrupt handler. When the PCI slot is in error recovery
15541  * or the HBA is undergoing initialization, the interrupt handler will not
15542  * process the interrupt. The SCSI FCP fast-path ring event are handled in
15543  * the intrrupt context. This function is called without any lock held.
15544  * It gets the hbalock to access and update SLI data structures. Note that,
15545  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
15546  * equal to that of FCP CQ index.
15547  *
15548  * The link attention and ELS ring attention events are handled
15549  * by the worker thread. The interrupt handler signals the worker thread
15550  * and returns for these events. This function is called without any lock
15551  * held. It gets the hbalock to access and update SLI data structures.
15552  *
15553  * This function returns IRQ_HANDLED when interrupt is handled, IRQ_WAKE_THREAD
15554  * when interrupt is scheduled to be handled from a threaded irq context, or
15555  * else returns IRQ_NONE.
15556  **/
15557 irqreturn_t
15558 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
15559 {
15560 	struct lpfc_hba *phba;
15561 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
15562 	struct lpfc_queue *fpeq;
15563 	unsigned long iflag;
15564 	int hba_eqidx;
15565 	int ecount = 0;
15566 	struct lpfc_eq_intr_info *eqi;
15567 
15568 	/* Get the driver's phba structure from the dev_id */
15569 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
15570 	phba = hba_eq_hdl->phba;
15571 	hba_eqidx = hba_eq_hdl->idx;
15572 
15573 	if (unlikely(!phba))
15574 		return IRQ_NONE;
15575 	if (unlikely(!phba->sli4_hba.hdwq))
15576 		return IRQ_NONE;
15577 
15578 	/* Get to the EQ struct associated with this vector */
15579 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
15580 	if (unlikely(!fpeq))
15581 		return IRQ_NONE;
15582 
15583 	/* Check device state for handling interrupt */
15584 	if (unlikely(lpfc_intr_state_check(phba))) {
15585 		/* Check again for link_state with lock held */
15586 		spin_lock_irqsave(&phba->hbalock, iflag);
15587 		if (phba->link_state < LPFC_LINK_DOWN)
15588 			/* Flush, clear interrupt, and rearm the EQ */
15589 			lpfc_sli4_eqcq_flush(phba, fpeq);
15590 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15591 		return IRQ_NONE;
15592 	}
15593 
15594 	switch (fpeq->poll_mode) {
15595 	case LPFC_THREADED_IRQ:
15596 		/* CGN mgmt is mutually exclusive from irq processing */
15597 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
15598 			return IRQ_WAKE_THREAD;
15599 		fallthrough;
15600 	case LPFC_QUEUE_WORK:
15601 	default:
15602 		eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
15603 		eqi->icnt++;
15604 
15605 		fpeq->last_cpu = raw_smp_processor_id();
15606 
15607 		if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
15608 		    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
15609 		    phba->cfg_auto_imax &&
15610 		    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
15611 		    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
15612 			lpfc_sli4_mod_hba_eq_delay(phba, fpeq,
15613 						   LPFC_MAX_AUTO_EQ_DELAY);
15614 
15615 		/* process and rearm the EQ */
15616 		ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
15617 					      LPFC_QUEUE_WORK);
15618 
15619 		if (unlikely(ecount == 0)) {
15620 			fpeq->EQ_no_entry++;
15621 			if (phba->intr_type == MSIX)
15622 				/* MSI-X treated interrupt served as no EQ share INT */
15623 				lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15624 						"0358 MSI-X interrupt with no EQE\n");
15625 			else
15626 				/* Non MSI-X treated on interrupt as EQ share INT */
15627 				return IRQ_NONE;
15628 		}
15629 	}
15630 
15631 	return IRQ_HANDLED;
15632 } /* lpfc_sli4_hba_intr_handler */
15633 
15634 /**
15635  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
15636  * @irq: Interrupt number.
15637  * @dev_id: The device context pointer.
15638  *
15639  * This function is the device-level interrupt handler to device with SLI-4
15640  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
15641  * interrupt mode is enabled and there is an event in the HBA which requires
15642  * driver attention. This function invokes the slow-path interrupt attention
15643  * handling function and fast-path interrupt attention handling function in
15644  * turn to process the relevant HBA attention events. This function is called
15645  * without any lock held. It gets the hbalock to access and update SLI data
15646  * structures.
15647  *
15648  * This function returns IRQ_HANDLED when interrupt is handled, else it
15649  * returns IRQ_NONE.
15650  **/
15651 irqreturn_t
15652 lpfc_sli4_intr_handler(int irq, void *dev_id)
15653 {
15654 	struct lpfc_hba  *phba;
15655 	irqreturn_t hba_irq_rc;
15656 	bool hba_handled = false;
15657 	int qidx;
15658 
15659 	/* Get the driver's phba structure from the dev_id */
15660 	phba = (struct lpfc_hba *)dev_id;
15661 
15662 	if (unlikely(!phba))
15663 		return IRQ_NONE;
15664 
15665 	/*
15666 	 * Invoke fast-path host attention interrupt handling as appropriate.
15667 	 */
15668 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
15669 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
15670 					&phba->sli4_hba.hba_eq_hdl[qidx]);
15671 		if (hba_irq_rc == IRQ_HANDLED)
15672 			hba_handled |= true;
15673 	}
15674 
15675 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
15676 } /* lpfc_sli4_intr_handler */
15677 
15678 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
15679 {
15680 	struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
15681 	struct lpfc_queue *eq;
15682 
15683 	rcu_read_lock();
15684 
15685 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
15686 		lpfc_sli4_poll_eq(eq);
15687 	if (!list_empty(&phba->poll_list))
15688 		mod_timer(&phba->cpuhp_poll_timer,
15689 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15690 
15691 	rcu_read_unlock();
15692 }
15693 
15694 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
15695 {
15696 	struct lpfc_hba *phba = eq->phba;
15697 
15698 	/* kickstart slowpath processing if needed */
15699 	if (list_empty(&phba->poll_list))
15700 		mod_timer(&phba->cpuhp_poll_timer,
15701 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15702 
15703 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
15704 	synchronize_rcu();
15705 }
15706 
15707 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
15708 {
15709 	struct lpfc_hba *phba = eq->phba;
15710 
15711 	/* Disable slowpath processing for this eq.  Kick start the eq
15712 	 * by RE-ARMING the eq's ASAP
15713 	 */
15714 	list_del_rcu(&eq->_poll_list);
15715 	synchronize_rcu();
15716 
15717 	if (list_empty(&phba->poll_list))
15718 		del_timer_sync(&phba->cpuhp_poll_timer);
15719 }
15720 
15721 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
15722 {
15723 	struct lpfc_queue *eq, *next;
15724 
15725 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
15726 		list_del(&eq->_poll_list);
15727 
15728 	INIT_LIST_HEAD(&phba->poll_list);
15729 	synchronize_rcu();
15730 }
15731 
15732 static inline void
15733 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
15734 {
15735 	if (mode == eq->mode)
15736 		return;
15737 	/*
15738 	 * currently this function is only called during a hotplug
15739 	 * event and the cpu on which this function is executing
15740 	 * is going offline.  By now the hotplug has instructed
15741 	 * the scheduler to remove this cpu from cpu active mask.
15742 	 * So we don't need to work about being put aside by the
15743 	 * scheduler for a high priority process.  Yes, the inte-
15744 	 * rrupts could come but they are known to retire ASAP.
15745 	 */
15746 
15747 	/* Disable polling in the fastpath */
15748 	WRITE_ONCE(eq->mode, mode);
15749 	/* flush out the store buffer */
15750 	smp_wmb();
15751 
15752 	/*
15753 	 * Add this eq to the polling list and start polling. For
15754 	 * a grace period both interrupt handler and poller will
15755 	 * try to process the eq _but_ that's fine.  We have a
15756 	 * synchronization mechanism in place (queue_claimed) to
15757 	 * deal with it.  This is just a draining phase for int-
15758 	 * errupt handler (not eq's) as we have guranteed through
15759 	 * barrier that all the CPUs have seen the new CQ_POLLED
15760 	 * state. which will effectively disable the REARMING of
15761 	 * the EQ.  The whole idea is eq's die off eventually as
15762 	 * we are not rearming EQ's anymore.
15763 	 */
15764 	mode ? lpfc_sli4_add_to_poll_list(eq) :
15765 	       lpfc_sli4_remove_from_poll_list(eq);
15766 }
15767 
15768 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15769 {
15770 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15771 }
15772 
15773 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15774 {
15775 	struct lpfc_hba *phba = eq->phba;
15776 
15777 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15778 
15779 	/* Kick start for the pending io's in h/w.
15780 	 * Once we switch back to interrupt processing on a eq
15781 	 * the io path completion will only arm eq's when it
15782 	 * receives a completion.  But since eq's are in disa-
15783 	 * rmed state it doesn't receive a completion.  This
15784 	 * creates a deadlock scenaro.
15785 	 */
15786 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15787 }
15788 
15789 /**
15790  * lpfc_sli4_queue_free - free a queue structure and associated memory
15791  * @queue: The queue structure to free.
15792  *
15793  * This function frees a queue structure and the DMAable memory used for
15794  * the host resident queue. This function must be called after destroying the
15795  * queue on the HBA.
15796  **/
15797 void
15798 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15799 {
15800 	struct lpfc_dmabuf *dmabuf;
15801 
15802 	if (!queue)
15803 		return;
15804 
15805 	if (!list_empty(&queue->wq_list))
15806 		list_del(&queue->wq_list);
15807 
15808 	while (!list_empty(&queue->page_list)) {
15809 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15810 				 list);
15811 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15812 				  dmabuf->virt, dmabuf->phys);
15813 		kfree(dmabuf);
15814 	}
15815 	if (queue->rqbp) {
15816 		lpfc_free_rq_buffer(queue->phba, queue);
15817 		kfree(queue->rqbp);
15818 	}
15819 
15820 	if (!list_empty(&queue->cpu_list))
15821 		list_del(&queue->cpu_list);
15822 
15823 	kfree(queue);
15824 	return;
15825 }
15826 
15827 /**
15828  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15829  * @phba: The HBA that this queue is being created on.
15830  * @page_size: The size of a queue page
15831  * @entry_size: The size of each queue entry for this queue.
15832  * @entry_count: The number of entries that this queue will handle.
15833  * @cpu: The cpu that will primarily utilize this queue.
15834  *
15835  * This function allocates a queue structure and the DMAable memory used for
15836  * the host resident queue. This function must be called before creating the
15837  * queue on the HBA.
15838  **/
15839 struct lpfc_queue *
15840 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15841 		      uint32_t entry_size, uint32_t entry_count, int cpu)
15842 {
15843 	struct lpfc_queue *queue;
15844 	struct lpfc_dmabuf *dmabuf;
15845 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15846 	uint16_t x, pgcnt;
15847 
15848 	if (!phba->sli4_hba.pc_sli4_params.supported)
15849 		hw_page_size = page_size;
15850 
15851 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15852 
15853 	/* If needed, Adjust page count to match the max the adapter supports */
15854 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15855 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15856 
15857 	queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
15858 			     GFP_KERNEL, cpu_to_node(cpu));
15859 	if (!queue)
15860 		return NULL;
15861 
15862 	INIT_LIST_HEAD(&queue->list);
15863 	INIT_LIST_HEAD(&queue->_poll_list);
15864 	INIT_LIST_HEAD(&queue->wq_list);
15865 	INIT_LIST_HEAD(&queue->wqfull_list);
15866 	INIT_LIST_HEAD(&queue->page_list);
15867 	INIT_LIST_HEAD(&queue->child_list);
15868 	INIT_LIST_HEAD(&queue->cpu_list);
15869 
15870 	/* Set queue parameters now.  If the system cannot provide memory
15871 	 * resources, the free routine needs to know what was allocated.
15872 	 */
15873 	queue->page_count = pgcnt;
15874 	queue->q_pgs = (void **)&queue[1];
15875 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
15876 	queue->entry_size = entry_size;
15877 	queue->entry_count = entry_count;
15878 	queue->page_size = hw_page_size;
15879 	queue->phba = phba;
15880 
15881 	for (x = 0; x < queue->page_count; x++) {
15882 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15883 				      dev_to_node(&phba->pcidev->dev));
15884 		if (!dmabuf)
15885 			goto out_fail;
15886 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15887 						  hw_page_size, &dmabuf->phys,
15888 						  GFP_KERNEL);
15889 		if (!dmabuf->virt) {
15890 			kfree(dmabuf);
15891 			goto out_fail;
15892 		}
15893 		dmabuf->buffer_tag = x;
15894 		list_add_tail(&dmabuf->list, &queue->page_list);
15895 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
15896 		queue->q_pgs[x] = dmabuf->virt;
15897 	}
15898 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15899 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15900 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15901 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15902 
15903 	/* notify_interval will be set during q creation */
15904 
15905 	return queue;
15906 out_fail:
15907 	lpfc_sli4_queue_free(queue);
15908 	return NULL;
15909 }
15910 
15911 /**
15912  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15913  * @phba: HBA structure that indicates port to create a queue on.
15914  * @pci_barset: PCI BAR set flag.
15915  *
15916  * This function shall perform iomap of the specified PCI BAR address to host
15917  * memory address if not already done so and return it. The returned host
15918  * memory address can be NULL.
15919  */
15920 static void __iomem *
15921 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15922 {
15923 	if (!phba->pcidev)
15924 		return NULL;
15925 
15926 	switch (pci_barset) {
15927 	case WQ_PCI_BAR_0_AND_1:
15928 		return phba->pci_bar0_memmap_p;
15929 	case WQ_PCI_BAR_2_AND_3:
15930 		return phba->pci_bar2_memmap_p;
15931 	case WQ_PCI_BAR_4_AND_5:
15932 		return phba->pci_bar4_memmap_p;
15933 	default:
15934 		break;
15935 	}
15936 	return NULL;
15937 }
15938 
15939 /**
15940  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
15941  * @phba: HBA structure that EQs are on.
15942  * @startq: The starting EQ index to modify
15943  * @numq: The number of EQs (consecutive indexes) to modify
15944  * @usdelay: amount of delay
15945  *
15946  * This function revises the EQ delay on 1 or more EQs. The EQ delay
15947  * is set either by writing to a register (if supported by the SLI Port)
15948  * or by mailbox command. The mailbox command allows several EQs to be
15949  * updated at once.
15950  *
15951  * The @phba struct is used to send a mailbox command to HBA. The @startq
15952  * is used to get the starting EQ index to change. The @numq value is
15953  * used to specify how many consecutive EQ indexes, starting at EQ index,
15954  * are to be changed. This function is asynchronous and will wait for any
15955  * mailbox commands to finish before returning.
15956  *
15957  * On success this function will return a zero. If unable to allocate
15958  * enough memory this function will return -ENOMEM. If a mailbox command
15959  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
15960  * have had their delay multipler changed.
15961  **/
15962 void
15963 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
15964 			 uint32_t numq, uint32_t usdelay)
15965 {
15966 	struct lpfc_mbx_modify_eq_delay *eq_delay;
15967 	LPFC_MBOXQ_t *mbox;
15968 	struct lpfc_queue *eq;
15969 	int cnt = 0, rc, length;
15970 	uint32_t shdr_status, shdr_add_status;
15971 	uint32_t dmult;
15972 	int qidx;
15973 	union lpfc_sli4_cfg_shdr *shdr;
15974 
15975 	if (startq >= phba->cfg_irq_chann)
15976 		return;
15977 
15978 	if (usdelay > 0xFFFF) {
15979 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
15980 				"6429 usdelay %d too large. Scaled down to "
15981 				"0xFFFF.\n", usdelay);
15982 		usdelay = 0xFFFF;
15983 	}
15984 
15985 	/* set values by EQ_DELAY register if supported */
15986 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
15987 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15988 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15989 			if (!eq)
15990 				continue;
15991 
15992 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
15993 
15994 			if (++cnt >= numq)
15995 				break;
15996 		}
15997 		return;
15998 	}
15999 
16000 	/* Otherwise, set values by mailbox cmd */
16001 
16002 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16003 	if (!mbox) {
16004 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16005 				"6428 Failed allocating mailbox cmd buffer."
16006 				" EQ delay was not set.\n");
16007 		return;
16008 	}
16009 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
16010 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16011 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16012 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
16013 			 length, LPFC_SLI4_MBX_EMBED);
16014 	eq_delay = &mbox->u.mqe.un.eq_delay;
16015 
16016 	/* Calculate delay multiper from maximum interrupt per second */
16017 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
16018 	if (dmult)
16019 		dmult--;
16020 	if (dmult > LPFC_DMULT_MAX)
16021 		dmult = LPFC_DMULT_MAX;
16022 
16023 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
16024 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
16025 		if (!eq)
16026 			continue;
16027 		eq->q_mode = usdelay;
16028 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
16029 		eq_delay->u.request.eq[cnt].phase = 0;
16030 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
16031 
16032 		if (++cnt >= numq)
16033 			break;
16034 	}
16035 	eq_delay->u.request.num_eq = cnt;
16036 
16037 	mbox->vport = phba->pport;
16038 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16039 	mbox->ctx_ndlp = NULL;
16040 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16041 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
16042 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16043 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16044 	if (shdr_status || shdr_add_status || rc) {
16045 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16046 				"2512 MODIFY_EQ_DELAY mailbox failed with "
16047 				"status x%x add_status x%x, mbx status x%x\n",
16048 				shdr_status, shdr_add_status, rc);
16049 	}
16050 	mempool_free(mbox, phba->mbox_mem_pool);
16051 	return;
16052 }
16053 
16054 /**
16055  * lpfc_eq_create - Create an Event Queue on the HBA
16056  * @phba: HBA structure that indicates port to create a queue on.
16057  * @eq: The queue structure to use to create the event queue.
16058  * @imax: The maximum interrupt per second limit.
16059  *
16060  * This function creates an event queue, as detailed in @eq, on a port,
16061  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
16062  *
16063  * The @phba struct is used to send mailbox command to HBA. The @eq struct
16064  * is used to get the entry count and entry size that are necessary to
16065  * determine the number of pages to allocate and use for this queue. This
16066  * function will send the EQ_CREATE mailbox command to the HBA to setup the
16067  * event queue. This function is asynchronous and will wait for the mailbox
16068  * command to finish before continuing.
16069  *
16070  * On success this function will return a zero. If unable to allocate enough
16071  * memory this function will return -ENOMEM. If the queue create mailbox command
16072  * fails this function will return -ENXIO.
16073  **/
16074 int
16075 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
16076 {
16077 	struct lpfc_mbx_eq_create *eq_create;
16078 	LPFC_MBOXQ_t *mbox;
16079 	int rc, length, status = 0;
16080 	struct lpfc_dmabuf *dmabuf;
16081 	uint32_t shdr_status, shdr_add_status;
16082 	union lpfc_sli4_cfg_shdr *shdr;
16083 	uint16_t dmult;
16084 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16085 
16086 	/* sanity check on queue memory */
16087 	if (!eq)
16088 		return -ENODEV;
16089 	if (!phba->sli4_hba.pc_sli4_params.supported)
16090 		hw_page_size = SLI4_PAGE_SIZE;
16091 
16092 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16093 	if (!mbox)
16094 		return -ENOMEM;
16095 	length = (sizeof(struct lpfc_mbx_eq_create) -
16096 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16097 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16098 			 LPFC_MBOX_OPCODE_EQ_CREATE,
16099 			 length, LPFC_SLI4_MBX_EMBED);
16100 	eq_create = &mbox->u.mqe.un.eq_create;
16101 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
16102 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
16103 	       eq->page_count);
16104 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
16105 	       LPFC_EQE_SIZE);
16106 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
16107 
16108 	/* Use version 2 of CREATE_EQ if eqav is set */
16109 	if (phba->sli4_hba.pc_sli4_params.eqav) {
16110 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16111 		       LPFC_Q_CREATE_VERSION_2);
16112 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
16113 		       phba->sli4_hba.pc_sli4_params.eqav);
16114 	}
16115 
16116 	/* don't setup delay multiplier using EQ_CREATE */
16117 	dmult = 0;
16118 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
16119 	       dmult);
16120 	switch (eq->entry_count) {
16121 	default:
16122 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16123 				"0360 Unsupported EQ count. (%d)\n",
16124 				eq->entry_count);
16125 		if (eq->entry_count < 256) {
16126 			status = -EINVAL;
16127 			goto out;
16128 		}
16129 		fallthrough;	/* otherwise default to smallest count */
16130 	case 256:
16131 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16132 		       LPFC_EQ_CNT_256);
16133 		break;
16134 	case 512:
16135 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16136 		       LPFC_EQ_CNT_512);
16137 		break;
16138 	case 1024:
16139 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16140 		       LPFC_EQ_CNT_1024);
16141 		break;
16142 	case 2048:
16143 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16144 		       LPFC_EQ_CNT_2048);
16145 		break;
16146 	case 4096:
16147 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16148 		       LPFC_EQ_CNT_4096);
16149 		break;
16150 	}
16151 	list_for_each_entry(dmabuf, &eq->page_list, list) {
16152 		memset(dmabuf->virt, 0, hw_page_size);
16153 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16154 					putPaddrLow(dmabuf->phys);
16155 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16156 					putPaddrHigh(dmabuf->phys);
16157 	}
16158 	mbox->vport = phba->pport;
16159 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16160 	mbox->ctx_buf = NULL;
16161 	mbox->ctx_ndlp = NULL;
16162 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16163 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16164 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16165 	if (shdr_status || shdr_add_status || rc) {
16166 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16167 				"2500 EQ_CREATE mailbox failed with "
16168 				"status x%x add_status x%x, mbx status x%x\n",
16169 				shdr_status, shdr_add_status, rc);
16170 		status = -ENXIO;
16171 	}
16172 	eq->type = LPFC_EQ;
16173 	eq->subtype = LPFC_NONE;
16174 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
16175 	if (eq->queue_id == 0xFFFF)
16176 		status = -ENXIO;
16177 	eq->host_index = 0;
16178 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
16179 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
16180 out:
16181 	mempool_free(mbox, phba->mbox_mem_pool);
16182 	return status;
16183 }
16184 
16185 /**
16186  * lpfc_sli4_hba_intr_handler_th - SLI4 HBA threaded interrupt handler
16187  * @irq: Interrupt number.
16188  * @dev_id: The device context pointer.
16189  *
16190  * This routine is a mirror of lpfc_sli4_hba_intr_handler, but executed within
16191  * threaded irq context.
16192  *
16193  * Returns
16194  * IRQ_HANDLED - interrupt is handled
16195  * IRQ_NONE - otherwise
16196  **/
16197 irqreturn_t lpfc_sli4_hba_intr_handler_th(int irq, void *dev_id)
16198 {
16199 	struct lpfc_hba *phba;
16200 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
16201 	struct lpfc_queue *fpeq;
16202 	int ecount = 0;
16203 	int hba_eqidx;
16204 	struct lpfc_eq_intr_info *eqi;
16205 
16206 	/* Get the driver's phba structure from the dev_id */
16207 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
16208 	phba = hba_eq_hdl->phba;
16209 	hba_eqidx = hba_eq_hdl->idx;
16210 
16211 	if (unlikely(!phba))
16212 		return IRQ_NONE;
16213 	if (unlikely(!phba->sli4_hba.hdwq))
16214 		return IRQ_NONE;
16215 
16216 	/* Get to the EQ struct associated with this vector */
16217 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
16218 	if (unlikely(!fpeq))
16219 		return IRQ_NONE;
16220 
16221 	eqi = per_cpu_ptr(phba->sli4_hba.eq_info, raw_smp_processor_id());
16222 	eqi->icnt++;
16223 
16224 	fpeq->last_cpu = raw_smp_processor_id();
16225 
16226 	if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
16227 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
16228 	    phba->cfg_auto_imax &&
16229 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
16230 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
16231 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
16232 
16233 	/* process and rearm the EQ */
16234 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
16235 				      LPFC_THREADED_IRQ);
16236 
16237 	if (unlikely(ecount == 0)) {
16238 		fpeq->EQ_no_entry++;
16239 		if (phba->intr_type == MSIX)
16240 			/* MSI-X treated interrupt served as no EQ share INT */
16241 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
16242 					"3358 MSI-X interrupt with no EQE\n");
16243 		else
16244 			/* Non MSI-X treated on interrupt as EQ share INT */
16245 			return IRQ_NONE;
16246 	}
16247 	return IRQ_HANDLED;
16248 }
16249 
16250 /**
16251  * lpfc_cq_create - Create a Completion Queue on the HBA
16252  * @phba: HBA structure that indicates port to create a queue on.
16253  * @cq: The queue structure to use to create the completion queue.
16254  * @eq: The event queue to bind this completion queue to.
16255  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16256  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16257  *
16258  * This function creates a completion queue, as detailed in @wq, on a port,
16259  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
16260  *
16261  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16262  * is used to get the entry count and entry size that are necessary to
16263  * determine the number of pages to allocate and use for this queue. The @eq
16264  * is used to indicate which event queue to bind this completion queue to. This
16265  * function will send the CQ_CREATE mailbox command to the HBA to setup the
16266  * completion queue. This function is asynchronous and will wait for the mailbox
16267  * command to finish before continuing.
16268  *
16269  * On success this function will return a zero. If unable to allocate enough
16270  * memory this function will return -ENOMEM. If the queue create mailbox command
16271  * fails this function will return -ENXIO.
16272  **/
16273 int
16274 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
16275 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
16276 {
16277 	struct lpfc_mbx_cq_create *cq_create;
16278 	struct lpfc_dmabuf *dmabuf;
16279 	LPFC_MBOXQ_t *mbox;
16280 	int rc, length, status = 0;
16281 	uint32_t shdr_status, shdr_add_status;
16282 	union lpfc_sli4_cfg_shdr *shdr;
16283 
16284 	/* sanity check on queue memory */
16285 	if (!cq || !eq)
16286 		return -ENODEV;
16287 
16288 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16289 	if (!mbox)
16290 		return -ENOMEM;
16291 	length = (sizeof(struct lpfc_mbx_cq_create) -
16292 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16293 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16294 			 LPFC_MBOX_OPCODE_CQ_CREATE,
16295 			 length, LPFC_SLI4_MBX_EMBED);
16296 	cq_create = &mbox->u.mqe.un.cq_create;
16297 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
16298 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
16299 		    cq->page_count);
16300 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
16301 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
16302 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16303 	       phba->sli4_hba.pc_sli4_params.cqv);
16304 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
16305 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
16306 		       (cq->page_size / SLI4_PAGE_SIZE));
16307 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
16308 		       eq->queue_id);
16309 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
16310 		       phba->sli4_hba.pc_sli4_params.cqav);
16311 	} else {
16312 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
16313 		       eq->queue_id);
16314 	}
16315 	switch (cq->entry_count) {
16316 	case 2048:
16317 	case 4096:
16318 		if (phba->sli4_hba.pc_sli4_params.cqv ==
16319 		    LPFC_Q_CREATE_VERSION_2) {
16320 			cq_create->u.request.context.lpfc_cq_context_count =
16321 				cq->entry_count;
16322 			bf_set(lpfc_cq_context_count,
16323 			       &cq_create->u.request.context,
16324 			       LPFC_CQ_CNT_WORD7);
16325 			break;
16326 		}
16327 		fallthrough;
16328 	default:
16329 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16330 				"0361 Unsupported CQ count: "
16331 				"entry cnt %d sz %d pg cnt %d\n",
16332 				cq->entry_count, cq->entry_size,
16333 				cq->page_count);
16334 		if (cq->entry_count < 256) {
16335 			status = -EINVAL;
16336 			goto out;
16337 		}
16338 		fallthrough;	/* otherwise default to smallest count */
16339 	case 256:
16340 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16341 		       LPFC_CQ_CNT_256);
16342 		break;
16343 	case 512:
16344 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16345 		       LPFC_CQ_CNT_512);
16346 		break;
16347 	case 1024:
16348 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16349 		       LPFC_CQ_CNT_1024);
16350 		break;
16351 	}
16352 	list_for_each_entry(dmabuf, &cq->page_list, list) {
16353 		memset(dmabuf->virt, 0, cq->page_size);
16354 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16355 					putPaddrLow(dmabuf->phys);
16356 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16357 					putPaddrHigh(dmabuf->phys);
16358 	}
16359 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16360 
16361 	/* The IOCTL status is embedded in the mailbox subheader. */
16362 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16363 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16364 	if (shdr_status || shdr_add_status || rc) {
16365 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16366 				"2501 CQ_CREATE mailbox failed with "
16367 				"status x%x add_status x%x, mbx status x%x\n",
16368 				shdr_status, shdr_add_status, rc);
16369 		status = -ENXIO;
16370 		goto out;
16371 	}
16372 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16373 	if (cq->queue_id == 0xFFFF) {
16374 		status = -ENXIO;
16375 		goto out;
16376 	}
16377 	/* link the cq onto the parent eq child list */
16378 	list_add_tail(&cq->list, &eq->child_list);
16379 	/* Set up completion queue's type and subtype */
16380 	cq->type = type;
16381 	cq->subtype = subtype;
16382 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16383 	cq->assoc_qid = eq->queue_id;
16384 	cq->assoc_qp = eq;
16385 	cq->host_index = 0;
16386 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16387 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
16388 
16389 	if (cq->queue_id > phba->sli4_hba.cq_max)
16390 		phba->sli4_hba.cq_max = cq->queue_id;
16391 out:
16392 	mempool_free(mbox, phba->mbox_mem_pool);
16393 	return status;
16394 }
16395 
16396 /**
16397  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
16398  * @phba: HBA structure that indicates port to create a queue on.
16399  * @cqp: The queue structure array to use to create the completion queues.
16400  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
16401  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16402  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16403  *
16404  * This function creates a set of  completion queue, s to support MRQ
16405  * as detailed in @cqp, on a port,
16406  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
16407  *
16408  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16409  * is used to get the entry count and entry size that are necessary to
16410  * determine the number of pages to allocate and use for this queue. The @eq
16411  * is used to indicate which event queue to bind this completion queue to. This
16412  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
16413  * completion queue. This function is asynchronous and will wait for the mailbox
16414  * command to finish before continuing.
16415  *
16416  * On success this function will return a zero. If unable to allocate enough
16417  * memory this function will return -ENOMEM. If the queue create mailbox command
16418  * fails this function will return -ENXIO.
16419  **/
16420 int
16421 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
16422 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
16423 		   uint32_t subtype)
16424 {
16425 	struct lpfc_queue *cq;
16426 	struct lpfc_queue *eq;
16427 	struct lpfc_mbx_cq_create_set *cq_set;
16428 	struct lpfc_dmabuf *dmabuf;
16429 	LPFC_MBOXQ_t *mbox;
16430 	int rc, length, alloclen, status = 0;
16431 	int cnt, idx, numcq, page_idx = 0;
16432 	uint32_t shdr_status, shdr_add_status;
16433 	union lpfc_sli4_cfg_shdr *shdr;
16434 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16435 
16436 	/* sanity check on queue memory */
16437 	numcq = phba->cfg_nvmet_mrq;
16438 	if (!cqp || !hdwq || !numcq)
16439 		return -ENODEV;
16440 
16441 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16442 	if (!mbox)
16443 		return -ENOMEM;
16444 
16445 	length = sizeof(struct lpfc_mbx_cq_create_set);
16446 	length += ((numcq * cqp[0]->page_count) *
16447 		   sizeof(struct dma_address));
16448 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16449 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
16450 			LPFC_SLI4_MBX_NEMBED);
16451 	if (alloclen < length) {
16452 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16453 				"3098 Allocated DMA memory size (%d) is "
16454 				"less than the requested DMA memory size "
16455 				"(%d)\n", alloclen, length);
16456 		status = -ENOMEM;
16457 		goto out;
16458 	}
16459 	cq_set = mbox->sge_array->addr[0];
16460 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
16461 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
16462 
16463 	for (idx = 0; idx < numcq; idx++) {
16464 		cq = cqp[idx];
16465 		eq = hdwq[idx].hba_eq;
16466 		if (!cq || !eq) {
16467 			status = -ENOMEM;
16468 			goto out;
16469 		}
16470 		if (!phba->sli4_hba.pc_sli4_params.supported)
16471 			hw_page_size = cq->page_size;
16472 
16473 		switch (idx) {
16474 		case 0:
16475 			bf_set(lpfc_mbx_cq_create_set_page_size,
16476 			       &cq_set->u.request,
16477 			       (hw_page_size / SLI4_PAGE_SIZE));
16478 			bf_set(lpfc_mbx_cq_create_set_num_pages,
16479 			       &cq_set->u.request, cq->page_count);
16480 			bf_set(lpfc_mbx_cq_create_set_evt,
16481 			       &cq_set->u.request, 1);
16482 			bf_set(lpfc_mbx_cq_create_set_valid,
16483 			       &cq_set->u.request, 1);
16484 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
16485 			       &cq_set->u.request, 0);
16486 			bf_set(lpfc_mbx_cq_create_set_num_cq,
16487 			       &cq_set->u.request, numcq);
16488 			bf_set(lpfc_mbx_cq_create_set_autovalid,
16489 			       &cq_set->u.request,
16490 			       phba->sli4_hba.pc_sli4_params.cqav);
16491 			switch (cq->entry_count) {
16492 			case 2048:
16493 			case 4096:
16494 				if (phba->sli4_hba.pc_sli4_params.cqv ==
16495 				    LPFC_Q_CREATE_VERSION_2) {
16496 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16497 					       &cq_set->u.request,
16498 						cq->entry_count);
16499 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16500 					       &cq_set->u.request,
16501 					       LPFC_CQ_CNT_WORD7);
16502 					break;
16503 				}
16504 				fallthrough;
16505 			default:
16506 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16507 						"3118 Bad CQ count. (%d)\n",
16508 						cq->entry_count);
16509 				if (cq->entry_count < 256) {
16510 					status = -EINVAL;
16511 					goto out;
16512 				}
16513 				fallthrough;	/* otherwise default to smallest */
16514 			case 256:
16515 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16516 				       &cq_set->u.request, LPFC_CQ_CNT_256);
16517 				break;
16518 			case 512:
16519 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16520 				       &cq_set->u.request, LPFC_CQ_CNT_512);
16521 				break;
16522 			case 1024:
16523 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16524 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
16525 				break;
16526 			}
16527 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
16528 			       &cq_set->u.request, eq->queue_id);
16529 			break;
16530 		case 1:
16531 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
16532 			       &cq_set->u.request, eq->queue_id);
16533 			break;
16534 		case 2:
16535 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
16536 			       &cq_set->u.request, eq->queue_id);
16537 			break;
16538 		case 3:
16539 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
16540 			       &cq_set->u.request, eq->queue_id);
16541 			break;
16542 		case 4:
16543 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
16544 			       &cq_set->u.request, eq->queue_id);
16545 			break;
16546 		case 5:
16547 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
16548 			       &cq_set->u.request, eq->queue_id);
16549 			break;
16550 		case 6:
16551 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
16552 			       &cq_set->u.request, eq->queue_id);
16553 			break;
16554 		case 7:
16555 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
16556 			       &cq_set->u.request, eq->queue_id);
16557 			break;
16558 		case 8:
16559 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
16560 			       &cq_set->u.request, eq->queue_id);
16561 			break;
16562 		case 9:
16563 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
16564 			       &cq_set->u.request, eq->queue_id);
16565 			break;
16566 		case 10:
16567 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
16568 			       &cq_set->u.request, eq->queue_id);
16569 			break;
16570 		case 11:
16571 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
16572 			       &cq_set->u.request, eq->queue_id);
16573 			break;
16574 		case 12:
16575 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
16576 			       &cq_set->u.request, eq->queue_id);
16577 			break;
16578 		case 13:
16579 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
16580 			       &cq_set->u.request, eq->queue_id);
16581 			break;
16582 		case 14:
16583 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
16584 			       &cq_set->u.request, eq->queue_id);
16585 			break;
16586 		case 15:
16587 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
16588 			       &cq_set->u.request, eq->queue_id);
16589 			break;
16590 		}
16591 
16592 		/* link the cq onto the parent eq child list */
16593 		list_add_tail(&cq->list, &eq->child_list);
16594 		/* Set up completion queue's type and subtype */
16595 		cq->type = type;
16596 		cq->subtype = subtype;
16597 		cq->assoc_qid = eq->queue_id;
16598 		cq->assoc_qp = eq;
16599 		cq->host_index = 0;
16600 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16601 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
16602 					 cq->entry_count);
16603 		cq->chann = idx;
16604 
16605 		rc = 0;
16606 		list_for_each_entry(dmabuf, &cq->page_list, list) {
16607 			memset(dmabuf->virt, 0, hw_page_size);
16608 			cnt = page_idx + dmabuf->buffer_tag;
16609 			cq_set->u.request.page[cnt].addr_lo =
16610 					putPaddrLow(dmabuf->phys);
16611 			cq_set->u.request.page[cnt].addr_hi =
16612 					putPaddrHigh(dmabuf->phys);
16613 			rc++;
16614 		}
16615 		page_idx += rc;
16616 	}
16617 
16618 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16619 
16620 	/* The IOCTL status is embedded in the mailbox subheader. */
16621 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16622 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16623 	if (shdr_status || shdr_add_status || rc) {
16624 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16625 				"3119 CQ_CREATE_SET mailbox failed with "
16626 				"status x%x add_status x%x, mbx status x%x\n",
16627 				shdr_status, shdr_add_status, rc);
16628 		status = -ENXIO;
16629 		goto out;
16630 	}
16631 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
16632 	if (rc == 0xFFFF) {
16633 		status = -ENXIO;
16634 		goto out;
16635 	}
16636 
16637 	for (idx = 0; idx < numcq; idx++) {
16638 		cq = cqp[idx];
16639 		cq->queue_id = rc + idx;
16640 		if (cq->queue_id > phba->sli4_hba.cq_max)
16641 			phba->sli4_hba.cq_max = cq->queue_id;
16642 	}
16643 
16644 out:
16645 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16646 	return status;
16647 }
16648 
16649 /**
16650  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
16651  * @phba: HBA structure that indicates port to create a queue on.
16652  * @mq: The queue structure to use to create the mailbox queue.
16653  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
16654  * @cq: The completion queue to associate with this cq.
16655  *
16656  * This function provides failback (fb) functionality when the
16657  * mq_create_ext fails on older FW generations.  It's purpose is identical
16658  * to mq_create_ext otherwise.
16659  *
16660  * This routine cannot fail as all attributes were previously accessed and
16661  * initialized in mq_create_ext.
16662  **/
16663 static void
16664 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
16665 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
16666 {
16667 	struct lpfc_mbx_mq_create *mq_create;
16668 	struct lpfc_dmabuf *dmabuf;
16669 	int length;
16670 
16671 	length = (sizeof(struct lpfc_mbx_mq_create) -
16672 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16673 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16674 			 LPFC_MBOX_OPCODE_MQ_CREATE,
16675 			 length, LPFC_SLI4_MBX_EMBED);
16676 	mq_create = &mbox->u.mqe.un.mq_create;
16677 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
16678 	       mq->page_count);
16679 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
16680 	       cq->queue_id);
16681 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
16682 	switch (mq->entry_count) {
16683 	case 16:
16684 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16685 		       LPFC_MQ_RING_SIZE_16);
16686 		break;
16687 	case 32:
16688 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16689 		       LPFC_MQ_RING_SIZE_32);
16690 		break;
16691 	case 64:
16692 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16693 		       LPFC_MQ_RING_SIZE_64);
16694 		break;
16695 	case 128:
16696 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16697 		       LPFC_MQ_RING_SIZE_128);
16698 		break;
16699 	}
16700 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16701 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16702 			putPaddrLow(dmabuf->phys);
16703 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16704 			putPaddrHigh(dmabuf->phys);
16705 	}
16706 }
16707 
16708 /**
16709  * lpfc_mq_create - Create a mailbox Queue on the HBA
16710  * @phba: HBA structure that indicates port to create a queue on.
16711  * @mq: The queue structure to use to create the mailbox queue.
16712  * @cq: The completion queue to associate with this cq.
16713  * @subtype: The queue's subtype.
16714  *
16715  * This function creates a mailbox queue, as detailed in @mq, on a port,
16716  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
16717  *
16718  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16719  * is used to get the entry count and entry size that are necessary to
16720  * determine the number of pages to allocate and use for this queue. This
16721  * function will send the MQ_CREATE mailbox command to the HBA to setup the
16722  * mailbox queue. This function is asynchronous and will wait for the mailbox
16723  * command to finish before continuing.
16724  *
16725  * On success this function will return a zero. If unable to allocate enough
16726  * memory this function will return -ENOMEM. If the queue create mailbox command
16727  * fails this function will return -ENXIO.
16728  **/
16729 int32_t
16730 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
16731 	       struct lpfc_queue *cq, uint32_t subtype)
16732 {
16733 	struct lpfc_mbx_mq_create *mq_create;
16734 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
16735 	struct lpfc_dmabuf *dmabuf;
16736 	LPFC_MBOXQ_t *mbox;
16737 	int rc, length, status = 0;
16738 	uint32_t shdr_status, shdr_add_status;
16739 	union lpfc_sli4_cfg_shdr *shdr;
16740 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16741 
16742 	/* sanity check on queue memory */
16743 	if (!mq || !cq)
16744 		return -ENODEV;
16745 	if (!phba->sli4_hba.pc_sli4_params.supported)
16746 		hw_page_size = SLI4_PAGE_SIZE;
16747 
16748 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16749 	if (!mbox)
16750 		return -ENOMEM;
16751 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
16752 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16753 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16754 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
16755 			 length, LPFC_SLI4_MBX_EMBED);
16756 
16757 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
16758 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
16759 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
16760 	       &mq_create_ext->u.request, mq->page_count);
16761 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
16762 	       &mq_create_ext->u.request, 1);
16763 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
16764 	       &mq_create_ext->u.request, 1);
16765 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
16766 	       &mq_create_ext->u.request, 1);
16767 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
16768 	       &mq_create_ext->u.request, 1);
16769 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
16770 	       &mq_create_ext->u.request, 1);
16771 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
16772 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16773 	       phba->sli4_hba.pc_sli4_params.mqv);
16774 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
16775 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
16776 		       cq->queue_id);
16777 	else
16778 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
16779 		       cq->queue_id);
16780 	switch (mq->entry_count) {
16781 	default:
16782 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16783 				"0362 Unsupported MQ count. (%d)\n",
16784 				mq->entry_count);
16785 		if (mq->entry_count < 16) {
16786 			status = -EINVAL;
16787 			goto out;
16788 		}
16789 		fallthrough;	/* otherwise default to smallest count */
16790 	case 16:
16791 		bf_set(lpfc_mq_context_ring_size,
16792 		       &mq_create_ext->u.request.context,
16793 		       LPFC_MQ_RING_SIZE_16);
16794 		break;
16795 	case 32:
16796 		bf_set(lpfc_mq_context_ring_size,
16797 		       &mq_create_ext->u.request.context,
16798 		       LPFC_MQ_RING_SIZE_32);
16799 		break;
16800 	case 64:
16801 		bf_set(lpfc_mq_context_ring_size,
16802 		       &mq_create_ext->u.request.context,
16803 		       LPFC_MQ_RING_SIZE_64);
16804 		break;
16805 	case 128:
16806 		bf_set(lpfc_mq_context_ring_size,
16807 		       &mq_create_ext->u.request.context,
16808 		       LPFC_MQ_RING_SIZE_128);
16809 		break;
16810 	}
16811 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16812 		memset(dmabuf->virt, 0, hw_page_size);
16813 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16814 					putPaddrLow(dmabuf->phys);
16815 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16816 					putPaddrHigh(dmabuf->phys);
16817 	}
16818 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16819 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16820 			      &mq_create_ext->u.response);
16821 	if (rc != MBX_SUCCESS) {
16822 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16823 				"2795 MQ_CREATE_EXT failed with "
16824 				"status x%x. Failback to MQ_CREATE.\n",
16825 				rc);
16826 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16827 		mq_create = &mbox->u.mqe.un.mq_create;
16828 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16829 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16830 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16831 				      &mq_create->u.response);
16832 	}
16833 
16834 	/* The IOCTL status is embedded in the mailbox subheader. */
16835 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16836 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16837 	if (shdr_status || shdr_add_status || rc) {
16838 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16839 				"2502 MQ_CREATE mailbox failed with "
16840 				"status x%x add_status x%x, mbx status x%x\n",
16841 				shdr_status, shdr_add_status, rc);
16842 		status = -ENXIO;
16843 		goto out;
16844 	}
16845 	if (mq->queue_id == 0xFFFF) {
16846 		status = -ENXIO;
16847 		goto out;
16848 	}
16849 	mq->type = LPFC_MQ;
16850 	mq->assoc_qid = cq->queue_id;
16851 	mq->subtype = subtype;
16852 	mq->host_index = 0;
16853 	mq->hba_index = 0;
16854 
16855 	/* link the mq onto the parent cq child list */
16856 	list_add_tail(&mq->list, &cq->child_list);
16857 out:
16858 	mempool_free(mbox, phba->mbox_mem_pool);
16859 	return status;
16860 }
16861 
16862 /**
16863  * lpfc_wq_create - Create a Work Queue on the HBA
16864  * @phba: HBA structure that indicates port to create a queue on.
16865  * @wq: The queue structure to use to create the work queue.
16866  * @cq: The completion queue to bind this work queue to.
16867  * @subtype: The subtype of the work queue indicating its functionality.
16868  *
16869  * This function creates a work queue, as detailed in @wq, on a port, described
16870  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16871  *
16872  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16873  * is used to get the entry count and entry size that are necessary to
16874  * determine the number of pages to allocate and use for this queue. The @cq
16875  * is used to indicate which completion queue to bind this work queue to. This
16876  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16877  * work queue. This function is asynchronous and will wait for the mailbox
16878  * command to finish before continuing.
16879  *
16880  * On success this function will return a zero. If unable to allocate enough
16881  * memory this function will return -ENOMEM. If the queue create mailbox command
16882  * fails this function will return -ENXIO.
16883  **/
16884 int
16885 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16886 	       struct lpfc_queue *cq, uint32_t subtype)
16887 {
16888 	struct lpfc_mbx_wq_create *wq_create;
16889 	struct lpfc_dmabuf *dmabuf;
16890 	LPFC_MBOXQ_t *mbox;
16891 	int rc, length, status = 0;
16892 	uint32_t shdr_status, shdr_add_status;
16893 	union lpfc_sli4_cfg_shdr *shdr;
16894 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16895 	struct dma_address *page;
16896 	void __iomem *bar_memmap_p;
16897 	uint32_t db_offset;
16898 	uint16_t pci_barset;
16899 	uint8_t dpp_barset;
16900 	uint32_t dpp_offset;
16901 	uint8_t wq_create_version;
16902 #ifdef CONFIG_X86
16903 	unsigned long pg_addr;
16904 #endif
16905 
16906 	/* sanity check on queue memory */
16907 	if (!wq || !cq)
16908 		return -ENODEV;
16909 	if (!phba->sli4_hba.pc_sli4_params.supported)
16910 		hw_page_size = wq->page_size;
16911 
16912 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16913 	if (!mbox)
16914 		return -ENOMEM;
16915 	length = (sizeof(struct lpfc_mbx_wq_create) -
16916 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16917 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16918 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16919 			 length, LPFC_SLI4_MBX_EMBED);
16920 	wq_create = &mbox->u.mqe.un.wq_create;
16921 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16922 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16923 		    wq->page_count);
16924 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16925 		    cq->queue_id);
16926 
16927 	/* wqv is the earliest version supported, NOT the latest */
16928 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16929 	       phba->sli4_hba.pc_sli4_params.wqv);
16930 
16931 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16932 	    (wq->page_size > SLI4_PAGE_SIZE))
16933 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
16934 	else
16935 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
16936 
16937 	switch (wq_create_version) {
16938 	case LPFC_Q_CREATE_VERSION_1:
16939 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
16940 		       wq->entry_count);
16941 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16942 		       LPFC_Q_CREATE_VERSION_1);
16943 
16944 		switch (wq->entry_size) {
16945 		default:
16946 		case 64:
16947 			bf_set(lpfc_mbx_wq_create_wqe_size,
16948 			       &wq_create->u.request_1,
16949 			       LPFC_WQ_WQE_SIZE_64);
16950 			break;
16951 		case 128:
16952 			bf_set(lpfc_mbx_wq_create_wqe_size,
16953 			       &wq_create->u.request_1,
16954 			       LPFC_WQ_WQE_SIZE_128);
16955 			break;
16956 		}
16957 		/* Request DPP by default */
16958 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
16959 		bf_set(lpfc_mbx_wq_create_page_size,
16960 		       &wq_create->u.request_1,
16961 		       (wq->page_size / SLI4_PAGE_SIZE));
16962 		page = wq_create->u.request_1.page;
16963 		break;
16964 	default:
16965 		page = wq_create->u.request.page;
16966 		break;
16967 	}
16968 
16969 	list_for_each_entry(dmabuf, &wq->page_list, list) {
16970 		memset(dmabuf->virt, 0, hw_page_size);
16971 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
16972 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
16973 	}
16974 
16975 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16976 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
16977 
16978 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16979 	/* The IOCTL status is embedded in the mailbox subheader. */
16980 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16981 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16982 	if (shdr_status || shdr_add_status || rc) {
16983 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16984 				"2503 WQ_CREATE mailbox failed with "
16985 				"status x%x add_status x%x, mbx status x%x\n",
16986 				shdr_status, shdr_add_status, rc);
16987 		status = -ENXIO;
16988 		goto out;
16989 	}
16990 
16991 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
16992 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
16993 					&wq_create->u.response);
16994 	else
16995 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
16996 					&wq_create->u.response_1);
16997 
16998 	if (wq->queue_id == 0xFFFF) {
16999 		status = -ENXIO;
17000 		goto out;
17001 	}
17002 
17003 	wq->db_format = LPFC_DB_LIST_FORMAT;
17004 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
17005 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
17006 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
17007 					       &wq_create->u.response);
17008 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
17009 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
17010 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17011 						"3265 WQ[%d] doorbell format "
17012 						"not supported: x%x\n",
17013 						wq->queue_id, wq->db_format);
17014 				status = -EINVAL;
17015 				goto out;
17016 			}
17017 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
17018 					    &wq_create->u.response);
17019 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17020 								   pci_barset);
17021 			if (!bar_memmap_p) {
17022 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17023 						"3263 WQ[%d] failed to memmap "
17024 						"pci barset:x%x\n",
17025 						wq->queue_id, pci_barset);
17026 				status = -ENOMEM;
17027 				goto out;
17028 			}
17029 			db_offset = wq_create->u.response.doorbell_offset;
17030 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
17031 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
17032 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17033 						"3252 WQ[%d] doorbell offset "
17034 						"not supported: x%x\n",
17035 						wq->queue_id, db_offset);
17036 				status = -EINVAL;
17037 				goto out;
17038 			}
17039 			wq->db_regaddr = bar_memmap_p + db_offset;
17040 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17041 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
17042 					"format:x%x\n", wq->queue_id,
17043 					pci_barset, db_offset, wq->db_format);
17044 		} else
17045 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17046 	} else {
17047 		/* Check if DPP was honored by the firmware */
17048 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
17049 				    &wq_create->u.response_1);
17050 		if (wq->dpp_enable) {
17051 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
17052 					    &wq_create->u.response_1);
17053 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17054 								   pci_barset);
17055 			if (!bar_memmap_p) {
17056 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17057 						"3267 WQ[%d] failed to memmap "
17058 						"pci barset:x%x\n",
17059 						wq->queue_id, pci_barset);
17060 				status = -ENOMEM;
17061 				goto out;
17062 			}
17063 			db_offset = wq_create->u.response_1.doorbell_offset;
17064 			wq->db_regaddr = bar_memmap_p + db_offset;
17065 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
17066 					    &wq_create->u.response_1);
17067 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
17068 					    &wq_create->u.response_1);
17069 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17070 								   dpp_barset);
17071 			if (!bar_memmap_p) {
17072 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17073 						"3268 WQ[%d] failed to memmap "
17074 						"pci barset:x%x\n",
17075 						wq->queue_id, dpp_barset);
17076 				status = -ENOMEM;
17077 				goto out;
17078 			}
17079 			dpp_offset = wq_create->u.response_1.dpp_offset;
17080 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
17081 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17082 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
17083 					"dpp_id:x%x dpp_barset:x%x "
17084 					"dpp_offset:x%x\n",
17085 					wq->queue_id, pci_barset, db_offset,
17086 					wq->dpp_id, dpp_barset, dpp_offset);
17087 
17088 #ifdef CONFIG_X86
17089 			/* Enable combined writes for DPP aperture */
17090 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
17091 			rc = set_memory_wc(pg_addr, 1);
17092 			if (rc) {
17093 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17094 					"3272 Cannot setup Combined "
17095 					"Write on WQ[%d] - disable DPP\n",
17096 					wq->queue_id);
17097 				phba->cfg_enable_dpp = 0;
17098 			}
17099 #else
17100 			phba->cfg_enable_dpp = 0;
17101 #endif
17102 		} else
17103 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17104 	}
17105 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
17106 	if (wq->pring == NULL) {
17107 		status = -ENOMEM;
17108 		goto out;
17109 	}
17110 	wq->type = LPFC_WQ;
17111 	wq->assoc_qid = cq->queue_id;
17112 	wq->subtype = subtype;
17113 	wq->host_index = 0;
17114 	wq->hba_index = 0;
17115 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
17116 
17117 	/* link the wq onto the parent cq child list */
17118 	list_add_tail(&wq->list, &cq->child_list);
17119 out:
17120 	mempool_free(mbox, phba->mbox_mem_pool);
17121 	return status;
17122 }
17123 
17124 /**
17125  * lpfc_rq_create - Create a Receive Queue on the HBA
17126  * @phba: HBA structure that indicates port to create a queue on.
17127  * @hrq: The queue structure to use to create the header receive queue.
17128  * @drq: The queue structure to use to create the data receive queue.
17129  * @cq: The completion queue to bind this work queue to.
17130  * @subtype: The subtype of the work queue indicating its functionality.
17131  *
17132  * This function creates a receive buffer queue pair , as detailed in @hrq and
17133  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17134  * to the HBA.
17135  *
17136  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17137  * struct is used to get the entry count that is necessary to determine the
17138  * number of pages to use for this queue. The @cq is used to indicate which
17139  * completion queue to bind received buffers that are posted to these queues to.
17140  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17141  * receive queue pair. This function is asynchronous and will wait for the
17142  * mailbox command to finish before continuing.
17143  *
17144  * On success this function will return a zero. If unable to allocate enough
17145  * memory this function will return -ENOMEM. If the queue create mailbox command
17146  * fails this function will return -ENXIO.
17147  **/
17148 int
17149 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17150 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
17151 {
17152 	struct lpfc_mbx_rq_create *rq_create;
17153 	struct lpfc_dmabuf *dmabuf;
17154 	LPFC_MBOXQ_t *mbox;
17155 	int rc, length, status = 0;
17156 	uint32_t shdr_status, shdr_add_status;
17157 	union lpfc_sli4_cfg_shdr *shdr;
17158 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17159 	void __iomem *bar_memmap_p;
17160 	uint32_t db_offset;
17161 	uint16_t pci_barset;
17162 
17163 	/* sanity check on queue memory */
17164 	if (!hrq || !drq || !cq)
17165 		return -ENODEV;
17166 	if (!phba->sli4_hba.pc_sli4_params.supported)
17167 		hw_page_size = SLI4_PAGE_SIZE;
17168 
17169 	if (hrq->entry_count != drq->entry_count)
17170 		return -EINVAL;
17171 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17172 	if (!mbox)
17173 		return -ENOMEM;
17174 	length = (sizeof(struct lpfc_mbx_rq_create) -
17175 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17176 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17177 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17178 			 length, LPFC_SLI4_MBX_EMBED);
17179 	rq_create = &mbox->u.mqe.un.rq_create;
17180 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17181 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17182 	       phba->sli4_hba.pc_sli4_params.rqv);
17183 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17184 		bf_set(lpfc_rq_context_rqe_count_1,
17185 		       &rq_create->u.request.context,
17186 		       hrq->entry_count);
17187 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
17188 		bf_set(lpfc_rq_context_rqe_size,
17189 		       &rq_create->u.request.context,
17190 		       LPFC_RQE_SIZE_8);
17191 		bf_set(lpfc_rq_context_page_size,
17192 		       &rq_create->u.request.context,
17193 		       LPFC_RQ_PAGE_SIZE_4096);
17194 	} else {
17195 		switch (hrq->entry_count) {
17196 		default:
17197 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17198 					"2535 Unsupported RQ count. (%d)\n",
17199 					hrq->entry_count);
17200 			if (hrq->entry_count < 512) {
17201 				status = -EINVAL;
17202 				goto out;
17203 			}
17204 			fallthrough;	/* otherwise default to smallest count */
17205 		case 512:
17206 			bf_set(lpfc_rq_context_rqe_count,
17207 			       &rq_create->u.request.context,
17208 			       LPFC_RQ_RING_SIZE_512);
17209 			break;
17210 		case 1024:
17211 			bf_set(lpfc_rq_context_rqe_count,
17212 			       &rq_create->u.request.context,
17213 			       LPFC_RQ_RING_SIZE_1024);
17214 			break;
17215 		case 2048:
17216 			bf_set(lpfc_rq_context_rqe_count,
17217 			       &rq_create->u.request.context,
17218 			       LPFC_RQ_RING_SIZE_2048);
17219 			break;
17220 		case 4096:
17221 			bf_set(lpfc_rq_context_rqe_count,
17222 			       &rq_create->u.request.context,
17223 			       LPFC_RQ_RING_SIZE_4096);
17224 			break;
17225 		}
17226 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
17227 		       LPFC_HDR_BUF_SIZE);
17228 	}
17229 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17230 	       cq->queue_id);
17231 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17232 	       hrq->page_count);
17233 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
17234 		memset(dmabuf->virt, 0, hw_page_size);
17235 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17236 					putPaddrLow(dmabuf->phys);
17237 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17238 					putPaddrHigh(dmabuf->phys);
17239 	}
17240 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17241 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17242 
17243 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17244 	/* The IOCTL status is embedded in the mailbox subheader. */
17245 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17246 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17247 	if (shdr_status || shdr_add_status || rc) {
17248 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17249 				"2504 RQ_CREATE mailbox failed with "
17250 				"status x%x add_status x%x, mbx status x%x\n",
17251 				shdr_status, shdr_add_status, rc);
17252 		status = -ENXIO;
17253 		goto out;
17254 	}
17255 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17256 	if (hrq->queue_id == 0xFFFF) {
17257 		status = -ENXIO;
17258 		goto out;
17259 	}
17260 
17261 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
17262 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
17263 					&rq_create->u.response);
17264 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
17265 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
17266 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17267 					"3262 RQ [%d] doorbell format not "
17268 					"supported: x%x\n", hrq->queue_id,
17269 					hrq->db_format);
17270 			status = -EINVAL;
17271 			goto out;
17272 		}
17273 
17274 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
17275 				    &rq_create->u.response);
17276 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
17277 		if (!bar_memmap_p) {
17278 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17279 					"3269 RQ[%d] failed to memmap pci "
17280 					"barset:x%x\n", hrq->queue_id,
17281 					pci_barset);
17282 			status = -ENOMEM;
17283 			goto out;
17284 		}
17285 
17286 		db_offset = rq_create->u.response.doorbell_offset;
17287 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
17288 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
17289 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17290 					"3270 RQ[%d] doorbell offset not "
17291 					"supported: x%x\n", hrq->queue_id,
17292 					db_offset);
17293 			status = -EINVAL;
17294 			goto out;
17295 		}
17296 		hrq->db_regaddr = bar_memmap_p + db_offset;
17297 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17298 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
17299 				"format:x%x\n", hrq->queue_id, pci_barset,
17300 				db_offset, hrq->db_format);
17301 	} else {
17302 		hrq->db_format = LPFC_DB_RING_FORMAT;
17303 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17304 	}
17305 	hrq->type = LPFC_HRQ;
17306 	hrq->assoc_qid = cq->queue_id;
17307 	hrq->subtype = subtype;
17308 	hrq->host_index = 0;
17309 	hrq->hba_index = 0;
17310 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17311 
17312 	/* now create the data queue */
17313 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17314 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17315 			 length, LPFC_SLI4_MBX_EMBED);
17316 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17317 	       phba->sli4_hba.pc_sli4_params.rqv);
17318 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17319 		bf_set(lpfc_rq_context_rqe_count_1,
17320 		       &rq_create->u.request.context, hrq->entry_count);
17321 		if (subtype == LPFC_NVMET)
17322 			rq_create->u.request.context.buffer_size =
17323 				LPFC_NVMET_DATA_BUF_SIZE;
17324 		else
17325 			rq_create->u.request.context.buffer_size =
17326 				LPFC_DATA_BUF_SIZE;
17327 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
17328 		       LPFC_RQE_SIZE_8);
17329 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
17330 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
17331 	} else {
17332 		switch (drq->entry_count) {
17333 		default:
17334 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17335 					"2536 Unsupported RQ count. (%d)\n",
17336 					drq->entry_count);
17337 			if (drq->entry_count < 512) {
17338 				status = -EINVAL;
17339 				goto out;
17340 			}
17341 			fallthrough;	/* otherwise default to smallest count */
17342 		case 512:
17343 			bf_set(lpfc_rq_context_rqe_count,
17344 			       &rq_create->u.request.context,
17345 			       LPFC_RQ_RING_SIZE_512);
17346 			break;
17347 		case 1024:
17348 			bf_set(lpfc_rq_context_rqe_count,
17349 			       &rq_create->u.request.context,
17350 			       LPFC_RQ_RING_SIZE_1024);
17351 			break;
17352 		case 2048:
17353 			bf_set(lpfc_rq_context_rqe_count,
17354 			       &rq_create->u.request.context,
17355 			       LPFC_RQ_RING_SIZE_2048);
17356 			break;
17357 		case 4096:
17358 			bf_set(lpfc_rq_context_rqe_count,
17359 			       &rq_create->u.request.context,
17360 			       LPFC_RQ_RING_SIZE_4096);
17361 			break;
17362 		}
17363 		if (subtype == LPFC_NVMET)
17364 			bf_set(lpfc_rq_context_buf_size,
17365 			       &rq_create->u.request.context,
17366 			       LPFC_NVMET_DATA_BUF_SIZE);
17367 		else
17368 			bf_set(lpfc_rq_context_buf_size,
17369 			       &rq_create->u.request.context,
17370 			       LPFC_DATA_BUF_SIZE);
17371 	}
17372 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17373 	       cq->queue_id);
17374 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17375 	       drq->page_count);
17376 	list_for_each_entry(dmabuf, &drq->page_list, list) {
17377 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17378 					putPaddrLow(dmabuf->phys);
17379 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17380 					putPaddrHigh(dmabuf->phys);
17381 	}
17382 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17383 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17384 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17385 	/* The IOCTL status is embedded in the mailbox subheader. */
17386 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17387 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17388 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17389 	if (shdr_status || shdr_add_status || rc) {
17390 		status = -ENXIO;
17391 		goto out;
17392 	}
17393 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17394 	if (drq->queue_id == 0xFFFF) {
17395 		status = -ENXIO;
17396 		goto out;
17397 	}
17398 	drq->type = LPFC_DRQ;
17399 	drq->assoc_qid = cq->queue_id;
17400 	drq->subtype = subtype;
17401 	drq->host_index = 0;
17402 	drq->hba_index = 0;
17403 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17404 
17405 	/* link the header and data RQs onto the parent cq child list */
17406 	list_add_tail(&hrq->list, &cq->child_list);
17407 	list_add_tail(&drq->list, &cq->child_list);
17408 
17409 out:
17410 	mempool_free(mbox, phba->mbox_mem_pool);
17411 	return status;
17412 }
17413 
17414 /**
17415  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
17416  * @phba: HBA structure that indicates port to create a queue on.
17417  * @hrqp: The queue structure array to use to create the header receive queues.
17418  * @drqp: The queue structure array to use to create the data receive queues.
17419  * @cqp: The completion queue array to bind these receive queues to.
17420  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
17421  *
17422  * This function creates a receive buffer queue pair , as detailed in @hrq and
17423  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17424  * to the HBA.
17425  *
17426  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17427  * struct is used to get the entry count that is necessary to determine the
17428  * number of pages to use for this queue. The @cq is used to indicate which
17429  * completion queue to bind received buffers that are posted to these queues to.
17430  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17431  * receive queue pair. This function is asynchronous and will wait for the
17432  * mailbox command to finish before continuing.
17433  *
17434  * On success this function will return a zero. If unable to allocate enough
17435  * memory this function will return -ENOMEM. If the queue create mailbox command
17436  * fails this function will return -ENXIO.
17437  **/
17438 int
17439 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
17440 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
17441 		uint32_t subtype)
17442 {
17443 	struct lpfc_queue *hrq, *drq, *cq;
17444 	struct lpfc_mbx_rq_create_v2 *rq_create;
17445 	struct lpfc_dmabuf *dmabuf;
17446 	LPFC_MBOXQ_t *mbox;
17447 	int rc, length, alloclen, status = 0;
17448 	int cnt, idx, numrq, page_idx = 0;
17449 	uint32_t shdr_status, shdr_add_status;
17450 	union lpfc_sli4_cfg_shdr *shdr;
17451 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17452 
17453 	numrq = phba->cfg_nvmet_mrq;
17454 	/* sanity check on array memory */
17455 	if (!hrqp || !drqp || !cqp || !numrq)
17456 		return -ENODEV;
17457 	if (!phba->sli4_hba.pc_sli4_params.supported)
17458 		hw_page_size = SLI4_PAGE_SIZE;
17459 
17460 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17461 	if (!mbox)
17462 		return -ENOMEM;
17463 
17464 	length = sizeof(struct lpfc_mbx_rq_create_v2);
17465 	length += ((2 * numrq * hrqp[0]->page_count) *
17466 		   sizeof(struct dma_address));
17467 
17468 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17469 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
17470 				    LPFC_SLI4_MBX_NEMBED);
17471 	if (alloclen < length) {
17472 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17473 				"3099 Allocated DMA memory size (%d) is "
17474 				"less than the requested DMA memory size "
17475 				"(%d)\n", alloclen, length);
17476 		status = -ENOMEM;
17477 		goto out;
17478 	}
17479 
17480 
17481 
17482 	rq_create = mbox->sge_array->addr[0];
17483 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
17484 
17485 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
17486 	cnt = 0;
17487 
17488 	for (idx = 0; idx < numrq; idx++) {
17489 		hrq = hrqp[idx];
17490 		drq = drqp[idx];
17491 		cq  = cqp[idx];
17492 
17493 		/* sanity check on queue memory */
17494 		if (!hrq || !drq || !cq) {
17495 			status = -ENODEV;
17496 			goto out;
17497 		}
17498 
17499 		if (hrq->entry_count != drq->entry_count) {
17500 			status = -EINVAL;
17501 			goto out;
17502 		}
17503 
17504 		if (idx == 0) {
17505 			bf_set(lpfc_mbx_rq_create_num_pages,
17506 			       &rq_create->u.request,
17507 			       hrq->page_count);
17508 			bf_set(lpfc_mbx_rq_create_rq_cnt,
17509 			       &rq_create->u.request, (numrq * 2));
17510 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
17511 			       1);
17512 			bf_set(lpfc_rq_context_base_cq,
17513 			       &rq_create->u.request.context,
17514 			       cq->queue_id);
17515 			bf_set(lpfc_rq_context_data_size,
17516 			       &rq_create->u.request.context,
17517 			       LPFC_NVMET_DATA_BUF_SIZE);
17518 			bf_set(lpfc_rq_context_hdr_size,
17519 			       &rq_create->u.request.context,
17520 			       LPFC_HDR_BUF_SIZE);
17521 			bf_set(lpfc_rq_context_rqe_count_1,
17522 			       &rq_create->u.request.context,
17523 			       hrq->entry_count);
17524 			bf_set(lpfc_rq_context_rqe_size,
17525 			       &rq_create->u.request.context,
17526 			       LPFC_RQE_SIZE_8);
17527 			bf_set(lpfc_rq_context_page_size,
17528 			       &rq_create->u.request.context,
17529 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
17530 		}
17531 		rc = 0;
17532 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
17533 			memset(dmabuf->virt, 0, hw_page_size);
17534 			cnt = page_idx + dmabuf->buffer_tag;
17535 			rq_create->u.request.page[cnt].addr_lo =
17536 					putPaddrLow(dmabuf->phys);
17537 			rq_create->u.request.page[cnt].addr_hi =
17538 					putPaddrHigh(dmabuf->phys);
17539 			rc++;
17540 		}
17541 		page_idx += rc;
17542 
17543 		rc = 0;
17544 		list_for_each_entry(dmabuf, &drq->page_list, list) {
17545 			memset(dmabuf->virt, 0, hw_page_size);
17546 			cnt = page_idx + dmabuf->buffer_tag;
17547 			rq_create->u.request.page[cnt].addr_lo =
17548 					putPaddrLow(dmabuf->phys);
17549 			rq_create->u.request.page[cnt].addr_hi =
17550 					putPaddrHigh(dmabuf->phys);
17551 			rc++;
17552 		}
17553 		page_idx += rc;
17554 
17555 		hrq->db_format = LPFC_DB_RING_FORMAT;
17556 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17557 		hrq->type = LPFC_HRQ;
17558 		hrq->assoc_qid = cq->queue_id;
17559 		hrq->subtype = subtype;
17560 		hrq->host_index = 0;
17561 		hrq->hba_index = 0;
17562 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17563 
17564 		drq->db_format = LPFC_DB_RING_FORMAT;
17565 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17566 		drq->type = LPFC_DRQ;
17567 		drq->assoc_qid = cq->queue_id;
17568 		drq->subtype = subtype;
17569 		drq->host_index = 0;
17570 		drq->hba_index = 0;
17571 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17572 
17573 		list_add_tail(&hrq->list, &cq->child_list);
17574 		list_add_tail(&drq->list, &cq->child_list);
17575 	}
17576 
17577 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17578 	/* The IOCTL status is embedded in the mailbox subheader. */
17579 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17580 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17581 	if (shdr_status || shdr_add_status || rc) {
17582 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17583 				"3120 RQ_CREATE mailbox failed with "
17584 				"status x%x add_status x%x, mbx status x%x\n",
17585 				shdr_status, shdr_add_status, rc);
17586 		status = -ENXIO;
17587 		goto out;
17588 	}
17589 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17590 	if (rc == 0xFFFF) {
17591 		status = -ENXIO;
17592 		goto out;
17593 	}
17594 
17595 	/* Initialize all RQs with associated queue id */
17596 	for (idx = 0; idx < numrq; idx++) {
17597 		hrq = hrqp[idx];
17598 		hrq->queue_id = rc + (2 * idx);
17599 		drq = drqp[idx];
17600 		drq->queue_id = rc + (2 * idx) + 1;
17601 	}
17602 
17603 out:
17604 	lpfc_sli4_mbox_cmd_free(phba, mbox);
17605 	return status;
17606 }
17607 
17608 /**
17609  * lpfc_eq_destroy - Destroy an event Queue on the HBA
17610  * @phba: HBA structure that indicates port to destroy a queue on.
17611  * @eq: The queue structure associated with the queue to destroy.
17612  *
17613  * This function destroys a queue, as detailed in @eq by sending an mailbox
17614  * command, specific to the type of queue, to the HBA.
17615  *
17616  * The @eq struct is used to get the queue ID of the queue to destroy.
17617  *
17618  * On success this function will return a zero. If the queue destroy mailbox
17619  * command fails this function will return -ENXIO.
17620  **/
17621 int
17622 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
17623 {
17624 	LPFC_MBOXQ_t *mbox;
17625 	int rc, length, status = 0;
17626 	uint32_t shdr_status, shdr_add_status;
17627 	union lpfc_sli4_cfg_shdr *shdr;
17628 
17629 	/* sanity check on queue memory */
17630 	if (!eq)
17631 		return -ENODEV;
17632 
17633 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
17634 	if (!mbox)
17635 		return -ENOMEM;
17636 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
17637 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17638 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17639 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
17640 			 length, LPFC_SLI4_MBX_EMBED);
17641 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
17642 	       eq->queue_id);
17643 	mbox->vport = eq->phba->pport;
17644 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17645 
17646 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
17647 	/* The IOCTL status is embedded in the mailbox subheader. */
17648 	shdr = (union lpfc_sli4_cfg_shdr *)
17649 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
17650 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17651 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17652 	if (shdr_status || shdr_add_status || rc) {
17653 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17654 				"2505 EQ_DESTROY mailbox failed with "
17655 				"status x%x add_status x%x, mbx status x%x\n",
17656 				shdr_status, shdr_add_status, rc);
17657 		status = -ENXIO;
17658 	}
17659 
17660 	/* Remove eq from any list */
17661 	list_del_init(&eq->list);
17662 	mempool_free(mbox, eq->phba->mbox_mem_pool);
17663 	return status;
17664 }
17665 
17666 /**
17667  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
17668  * @phba: HBA structure that indicates port to destroy a queue on.
17669  * @cq: The queue structure associated with the queue to destroy.
17670  *
17671  * This function destroys a queue, as detailed in @cq by sending an mailbox
17672  * command, specific to the type of queue, to the HBA.
17673  *
17674  * The @cq struct is used to get the queue ID of the queue to destroy.
17675  *
17676  * On success this function will return a zero. If the queue destroy mailbox
17677  * command fails this function will return -ENXIO.
17678  **/
17679 int
17680 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
17681 {
17682 	LPFC_MBOXQ_t *mbox;
17683 	int rc, length, status = 0;
17684 	uint32_t shdr_status, shdr_add_status;
17685 	union lpfc_sli4_cfg_shdr *shdr;
17686 
17687 	/* sanity check on queue memory */
17688 	if (!cq)
17689 		return -ENODEV;
17690 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
17691 	if (!mbox)
17692 		return -ENOMEM;
17693 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
17694 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17695 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17696 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
17697 			 length, LPFC_SLI4_MBX_EMBED);
17698 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
17699 	       cq->queue_id);
17700 	mbox->vport = cq->phba->pport;
17701 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17702 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
17703 	/* The IOCTL status is embedded in the mailbox subheader. */
17704 	shdr = (union lpfc_sli4_cfg_shdr *)
17705 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
17706 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17707 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17708 	if (shdr_status || shdr_add_status || rc) {
17709 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17710 				"2506 CQ_DESTROY mailbox failed with "
17711 				"status x%x add_status x%x, mbx status x%x\n",
17712 				shdr_status, shdr_add_status, rc);
17713 		status = -ENXIO;
17714 	}
17715 	/* Remove cq from any list */
17716 	list_del_init(&cq->list);
17717 	mempool_free(mbox, cq->phba->mbox_mem_pool);
17718 	return status;
17719 }
17720 
17721 /**
17722  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
17723  * @phba: HBA structure that indicates port to destroy a queue on.
17724  * @mq: The queue structure associated with the queue to destroy.
17725  *
17726  * This function destroys a queue, as detailed in @mq by sending an mailbox
17727  * command, specific to the type of queue, to the HBA.
17728  *
17729  * The @mq struct is used to get the queue ID of the queue to destroy.
17730  *
17731  * On success this function will return a zero. If the queue destroy mailbox
17732  * command fails this function will return -ENXIO.
17733  **/
17734 int
17735 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
17736 {
17737 	LPFC_MBOXQ_t *mbox;
17738 	int rc, length, status = 0;
17739 	uint32_t shdr_status, shdr_add_status;
17740 	union lpfc_sli4_cfg_shdr *shdr;
17741 
17742 	/* sanity check on queue memory */
17743 	if (!mq)
17744 		return -ENODEV;
17745 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
17746 	if (!mbox)
17747 		return -ENOMEM;
17748 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
17749 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17750 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17751 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
17752 			 length, LPFC_SLI4_MBX_EMBED);
17753 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
17754 	       mq->queue_id);
17755 	mbox->vport = mq->phba->pport;
17756 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17757 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
17758 	/* The IOCTL status is embedded in the mailbox subheader. */
17759 	shdr = (union lpfc_sli4_cfg_shdr *)
17760 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
17761 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17762 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17763 	if (shdr_status || shdr_add_status || rc) {
17764 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17765 				"2507 MQ_DESTROY mailbox failed with "
17766 				"status x%x add_status x%x, mbx status x%x\n",
17767 				shdr_status, shdr_add_status, rc);
17768 		status = -ENXIO;
17769 	}
17770 	/* Remove mq from any list */
17771 	list_del_init(&mq->list);
17772 	mempool_free(mbox, mq->phba->mbox_mem_pool);
17773 	return status;
17774 }
17775 
17776 /**
17777  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
17778  * @phba: HBA structure that indicates port to destroy a queue on.
17779  * @wq: The queue structure associated with the queue to destroy.
17780  *
17781  * This function destroys a queue, as detailed in @wq by sending an mailbox
17782  * command, specific to the type of queue, to the HBA.
17783  *
17784  * The @wq struct is used to get the queue ID of the queue to destroy.
17785  *
17786  * On success this function will return a zero. If the queue destroy mailbox
17787  * command fails this function will return -ENXIO.
17788  **/
17789 int
17790 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
17791 {
17792 	LPFC_MBOXQ_t *mbox;
17793 	int rc, length, status = 0;
17794 	uint32_t shdr_status, shdr_add_status;
17795 	union lpfc_sli4_cfg_shdr *shdr;
17796 
17797 	/* sanity check on queue memory */
17798 	if (!wq)
17799 		return -ENODEV;
17800 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17801 	if (!mbox)
17802 		return -ENOMEM;
17803 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
17804 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17805 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17806 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17807 			 length, LPFC_SLI4_MBX_EMBED);
17808 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17809 	       wq->queue_id);
17810 	mbox->vport = wq->phba->pport;
17811 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17812 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17813 	shdr = (union lpfc_sli4_cfg_shdr *)
17814 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17815 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17816 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17817 	if (shdr_status || shdr_add_status || rc) {
17818 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17819 				"2508 WQ_DESTROY mailbox failed with "
17820 				"status x%x add_status x%x, mbx status x%x\n",
17821 				shdr_status, shdr_add_status, rc);
17822 		status = -ENXIO;
17823 	}
17824 	/* Remove wq from any list */
17825 	list_del_init(&wq->list);
17826 	kfree(wq->pring);
17827 	wq->pring = NULL;
17828 	mempool_free(mbox, wq->phba->mbox_mem_pool);
17829 	return status;
17830 }
17831 
17832 /**
17833  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17834  * @phba: HBA structure that indicates port to destroy a queue on.
17835  * @hrq: The queue structure associated with the queue to destroy.
17836  * @drq: The queue structure associated with the queue to destroy.
17837  *
17838  * This function destroys a queue, as detailed in @rq by sending an mailbox
17839  * command, specific to the type of queue, to the HBA.
17840  *
17841  * The @rq struct is used to get the queue ID of the queue to destroy.
17842  *
17843  * On success this function will return a zero. If the queue destroy mailbox
17844  * command fails this function will return -ENXIO.
17845  **/
17846 int
17847 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17848 		struct lpfc_queue *drq)
17849 {
17850 	LPFC_MBOXQ_t *mbox;
17851 	int rc, length, status = 0;
17852 	uint32_t shdr_status, shdr_add_status;
17853 	union lpfc_sli4_cfg_shdr *shdr;
17854 
17855 	/* sanity check on queue memory */
17856 	if (!hrq || !drq)
17857 		return -ENODEV;
17858 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17859 	if (!mbox)
17860 		return -ENOMEM;
17861 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
17862 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17863 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17864 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17865 			 length, LPFC_SLI4_MBX_EMBED);
17866 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17867 	       hrq->queue_id);
17868 	mbox->vport = hrq->phba->pport;
17869 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17870 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17871 	/* The IOCTL status is embedded in the mailbox subheader. */
17872 	shdr = (union lpfc_sli4_cfg_shdr *)
17873 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17874 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17875 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17876 	if (shdr_status || shdr_add_status || rc) {
17877 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17878 				"2509 RQ_DESTROY mailbox failed with "
17879 				"status x%x add_status x%x, mbx status x%x\n",
17880 				shdr_status, shdr_add_status, rc);
17881 		mempool_free(mbox, hrq->phba->mbox_mem_pool);
17882 		return -ENXIO;
17883 	}
17884 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17885 	       drq->queue_id);
17886 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17887 	shdr = (union lpfc_sli4_cfg_shdr *)
17888 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17889 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17890 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17891 	if (shdr_status || shdr_add_status || rc) {
17892 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17893 				"2510 RQ_DESTROY mailbox failed with "
17894 				"status x%x add_status x%x, mbx status x%x\n",
17895 				shdr_status, shdr_add_status, rc);
17896 		status = -ENXIO;
17897 	}
17898 	list_del_init(&hrq->list);
17899 	list_del_init(&drq->list);
17900 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
17901 	return status;
17902 }
17903 
17904 /**
17905  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17906  * @phba: The virtual port for which this call being executed.
17907  * @pdma_phys_addr0: Physical address of the 1st SGL page.
17908  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
17909  * @xritag: the xritag that ties this io to the SGL pages.
17910  *
17911  * This routine will post the sgl pages for the IO that has the xritag
17912  * that is in the iocbq structure. The xritag is assigned during iocbq
17913  * creation and persists for as long as the driver is loaded.
17914  * if the caller has fewer than 256 scatter gather segments to map then
17915  * pdma_phys_addr1 should be 0.
17916  * If the caller needs to map more than 256 scatter gather segment then
17917  * pdma_phys_addr1 should be a valid physical address.
17918  * physical address for SGLs must be 64 byte aligned.
17919  * If you are going to map 2 SGL's then the first one must have 256 entries
17920  * the second sgl can have between 1 and 256 entries.
17921  *
17922  * Return codes:
17923  * 	0 - Success
17924  * 	-ENXIO, -ENOMEM - Failure
17925  **/
17926 int
17927 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
17928 		dma_addr_t pdma_phys_addr0,
17929 		dma_addr_t pdma_phys_addr1,
17930 		uint16_t xritag)
17931 {
17932 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
17933 	LPFC_MBOXQ_t *mbox;
17934 	int rc;
17935 	uint32_t shdr_status, shdr_add_status;
17936 	uint32_t mbox_tmo;
17937 	union lpfc_sli4_cfg_shdr *shdr;
17938 
17939 	if (xritag == NO_XRI) {
17940 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17941 				"0364 Invalid param:\n");
17942 		return -EINVAL;
17943 	}
17944 
17945 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17946 	if (!mbox)
17947 		return -ENOMEM;
17948 
17949 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17950 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17951 			sizeof(struct lpfc_mbx_post_sgl_pages) -
17952 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17953 
17954 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
17955 				&mbox->u.mqe.un.post_sgl_pages;
17956 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
17957 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
17958 
17959 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
17960 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
17961 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
17962 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
17963 
17964 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
17965 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
17966 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
17967 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
17968 	if (!phba->sli4_hba.intr_enable)
17969 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17970 	else {
17971 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17972 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17973 	}
17974 	/* The IOCTL status is embedded in the mailbox subheader. */
17975 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
17976 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17977 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17978 	if (!phba->sli4_hba.intr_enable)
17979 		mempool_free(mbox, phba->mbox_mem_pool);
17980 	else if (rc != MBX_TIMEOUT)
17981 		mempool_free(mbox, phba->mbox_mem_pool);
17982 	if (shdr_status || shdr_add_status || rc) {
17983 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17984 				"2511 POST_SGL mailbox failed with "
17985 				"status x%x add_status x%x, mbx status x%x\n",
17986 				shdr_status, shdr_add_status, rc);
17987 	}
17988 	return 0;
17989 }
17990 
17991 /**
17992  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
17993  * @phba: pointer to lpfc hba data structure.
17994  *
17995  * This routine is invoked to post rpi header templates to the
17996  * HBA consistent with the SLI-4 interface spec.  This routine
17997  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
17998  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
17999  *
18000  * Returns
18001  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
18002  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
18003  **/
18004 static uint16_t
18005 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
18006 {
18007 	unsigned long xri;
18008 
18009 	/*
18010 	 * Fetch the next logical xri.  Because this index is logical,
18011 	 * the driver starts at 0 each time.
18012 	 */
18013 	spin_lock_irq(&phba->hbalock);
18014 	xri = find_first_zero_bit(phba->sli4_hba.xri_bmask,
18015 				 phba->sli4_hba.max_cfg_param.max_xri);
18016 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
18017 		spin_unlock_irq(&phba->hbalock);
18018 		return NO_XRI;
18019 	} else {
18020 		set_bit(xri, phba->sli4_hba.xri_bmask);
18021 		phba->sli4_hba.max_cfg_param.xri_used++;
18022 	}
18023 	spin_unlock_irq(&phba->hbalock);
18024 	return xri;
18025 }
18026 
18027 /**
18028  * __lpfc_sli4_free_xri - Release an xri for reuse.
18029  * @phba: pointer to lpfc hba data structure.
18030  * @xri: xri to release.
18031  *
18032  * This routine is invoked to release an xri to the pool of
18033  * available rpis maintained by the driver.
18034  **/
18035 static void
18036 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18037 {
18038 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
18039 		phba->sli4_hba.max_cfg_param.xri_used--;
18040 	}
18041 }
18042 
18043 /**
18044  * lpfc_sli4_free_xri - Release an xri for reuse.
18045  * @phba: pointer to lpfc hba data structure.
18046  * @xri: xri to release.
18047  *
18048  * This routine is invoked to release an xri to the pool of
18049  * available rpis maintained by the driver.
18050  **/
18051 void
18052 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18053 {
18054 	spin_lock_irq(&phba->hbalock);
18055 	__lpfc_sli4_free_xri(phba, xri);
18056 	spin_unlock_irq(&phba->hbalock);
18057 }
18058 
18059 /**
18060  * lpfc_sli4_next_xritag - Get an xritag for the io
18061  * @phba: Pointer to HBA context object.
18062  *
18063  * This function gets an xritag for the iocb. If there is no unused xritag
18064  * it will return 0xffff.
18065  * The function returns the allocated xritag if successful, else returns zero.
18066  * Zero is not a valid xritag.
18067  * The caller is not required to hold any lock.
18068  **/
18069 uint16_t
18070 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
18071 {
18072 	uint16_t xri_index;
18073 
18074 	xri_index = lpfc_sli4_alloc_xri(phba);
18075 	if (xri_index == NO_XRI)
18076 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18077 				"2004 Failed to allocate XRI.last XRITAG is %d"
18078 				" Max XRI is %d, Used XRI is %d\n",
18079 				xri_index,
18080 				phba->sli4_hba.max_cfg_param.max_xri,
18081 				phba->sli4_hba.max_cfg_param.xri_used);
18082 	return xri_index;
18083 }
18084 
18085 /**
18086  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
18087  * @phba: pointer to lpfc hba data structure.
18088  * @post_sgl_list: pointer to els sgl entry list.
18089  * @post_cnt: number of els sgl entries on the list.
18090  *
18091  * This routine is invoked to post a block of driver's sgl pages to the
18092  * HBA using non-embedded mailbox command. No Lock is held. This routine
18093  * is only called when the driver is loading and after all IO has been
18094  * stopped.
18095  **/
18096 static int
18097 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
18098 			    struct list_head *post_sgl_list,
18099 			    int post_cnt)
18100 {
18101 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
18102 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18103 	struct sgl_page_pairs *sgl_pg_pairs;
18104 	void *viraddr;
18105 	LPFC_MBOXQ_t *mbox;
18106 	uint32_t reqlen, alloclen, pg_pairs;
18107 	uint32_t mbox_tmo;
18108 	uint16_t xritag_start = 0;
18109 	int rc = 0;
18110 	uint32_t shdr_status, shdr_add_status;
18111 	union lpfc_sli4_cfg_shdr *shdr;
18112 
18113 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
18114 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18115 	if (reqlen > SLI4_PAGE_SIZE) {
18116 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18117 				"2559 Block sgl registration required DMA "
18118 				"size (%d) great than a page\n", reqlen);
18119 		return -ENOMEM;
18120 	}
18121 
18122 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18123 	if (!mbox)
18124 		return -ENOMEM;
18125 
18126 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18127 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18128 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
18129 			 LPFC_SLI4_MBX_NEMBED);
18130 
18131 	if (alloclen < reqlen) {
18132 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18133 				"0285 Allocated DMA memory size (%d) is "
18134 				"less than the requested DMA memory "
18135 				"size (%d)\n", alloclen, reqlen);
18136 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18137 		return -ENOMEM;
18138 	}
18139 	/* Set up the SGL pages in the non-embedded DMA pages */
18140 	viraddr = mbox->sge_array->addr[0];
18141 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18142 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18143 
18144 	pg_pairs = 0;
18145 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
18146 		/* Set up the sge entry */
18147 		sgl_pg_pairs->sgl_pg0_addr_lo =
18148 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
18149 		sgl_pg_pairs->sgl_pg0_addr_hi =
18150 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
18151 		sgl_pg_pairs->sgl_pg1_addr_lo =
18152 				cpu_to_le32(putPaddrLow(0));
18153 		sgl_pg_pairs->sgl_pg1_addr_hi =
18154 				cpu_to_le32(putPaddrHigh(0));
18155 
18156 		/* Keep the first xritag on the list */
18157 		if (pg_pairs == 0)
18158 			xritag_start = sglq_entry->sli4_xritag;
18159 		sgl_pg_pairs++;
18160 		pg_pairs++;
18161 	}
18162 
18163 	/* Complete initialization and perform endian conversion. */
18164 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18165 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
18166 	sgl->word0 = cpu_to_le32(sgl->word0);
18167 
18168 	if (!phba->sli4_hba.intr_enable)
18169 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18170 	else {
18171 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18172 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18173 	}
18174 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
18175 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18176 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18177 	if (!phba->sli4_hba.intr_enable)
18178 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18179 	else if (rc != MBX_TIMEOUT)
18180 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18181 	if (shdr_status || shdr_add_status || rc) {
18182 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18183 				"2513 POST_SGL_BLOCK mailbox command failed "
18184 				"status x%x add_status x%x mbx status x%x\n",
18185 				shdr_status, shdr_add_status, rc);
18186 		rc = -ENXIO;
18187 	}
18188 	return rc;
18189 }
18190 
18191 /**
18192  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
18193  * @phba: pointer to lpfc hba data structure.
18194  * @nblist: pointer to nvme buffer list.
18195  * @count: number of scsi buffers on the list.
18196  *
18197  * This routine is invoked to post a block of @count scsi sgl pages from a
18198  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
18199  * No Lock is held.
18200  *
18201  **/
18202 static int
18203 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
18204 			    int count)
18205 {
18206 	struct lpfc_io_buf *lpfc_ncmd;
18207 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18208 	struct sgl_page_pairs *sgl_pg_pairs;
18209 	void *viraddr;
18210 	LPFC_MBOXQ_t *mbox;
18211 	uint32_t reqlen, alloclen, pg_pairs;
18212 	uint32_t mbox_tmo;
18213 	uint16_t xritag_start = 0;
18214 	int rc = 0;
18215 	uint32_t shdr_status, shdr_add_status;
18216 	dma_addr_t pdma_phys_bpl1;
18217 	union lpfc_sli4_cfg_shdr *shdr;
18218 
18219 	/* Calculate the requested length of the dma memory */
18220 	reqlen = count * sizeof(struct sgl_page_pairs) +
18221 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18222 	if (reqlen > SLI4_PAGE_SIZE) {
18223 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
18224 				"6118 Block sgl registration required DMA "
18225 				"size (%d) great than a page\n", reqlen);
18226 		return -ENOMEM;
18227 	}
18228 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18229 	if (!mbox) {
18230 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18231 				"6119 Failed to allocate mbox cmd memory\n");
18232 		return -ENOMEM;
18233 	}
18234 
18235 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18236 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18237 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
18238 				    reqlen, LPFC_SLI4_MBX_NEMBED);
18239 
18240 	if (alloclen < reqlen) {
18241 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18242 				"6120 Allocated DMA memory size (%d) is "
18243 				"less than the requested DMA memory "
18244 				"size (%d)\n", alloclen, reqlen);
18245 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18246 		return -ENOMEM;
18247 	}
18248 
18249 	/* Get the first SGE entry from the non-embedded DMA memory */
18250 	viraddr = mbox->sge_array->addr[0];
18251 
18252 	/* Set up the SGL pages in the non-embedded DMA pages */
18253 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18254 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18255 
18256 	pg_pairs = 0;
18257 	list_for_each_entry(lpfc_ncmd, nblist, list) {
18258 		/* Set up the sge entry */
18259 		sgl_pg_pairs->sgl_pg0_addr_lo =
18260 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
18261 		sgl_pg_pairs->sgl_pg0_addr_hi =
18262 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
18263 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
18264 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
18265 						SGL_PAGE_SIZE;
18266 		else
18267 			pdma_phys_bpl1 = 0;
18268 		sgl_pg_pairs->sgl_pg1_addr_lo =
18269 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
18270 		sgl_pg_pairs->sgl_pg1_addr_hi =
18271 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
18272 		/* Keep the first xritag on the list */
18273 		if (pg_pairs == 0)
18274 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
18275 		sgl_pg_pairs++;
18276 		pg_pairs++;
18277 	}
18278 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18279 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
18280 	/* Perform endian conversion if necessary */
18281 	sgl->word0 = cpu_to_le32(sgl->word0);
18282 
18283 	if (!phba->sli4_hba.intr_enable) {
18284 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18285 	} else {
18286 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18287 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18288 	}
18289 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
18290 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18291 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18292 	if (!phba->sli4_hba.intr_enable)
18293 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18294 	else if (rc != MBX_TIMEOUT)
18295 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18296 	if (shdr_status || shdr_add_status || rc) {
18297 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18298 				"6125 POST_SGL_BLOCK mailbox command failed "
18299 				"status x%x add_status x%x mbx status x%x\n",
18300 				shdr_status, shdr_add_status, rc);
18301 		rc = -ENXIO;
18302 	}
18303 	return rc;
18304 }
18305 
18306 /**
18307  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
18308  * @phba: pointer to lpfc hba data structure.
18309  * @post_nblist: pointer to the nvme buffer list.
18310  * @sb_count: number of nvme buffers.
18311  *
18312  * This routine walks a list of nvme buffers that was passed in. It attempts
18313  * to construct blocks of nvme buffer sgls which contains contiguous xris and
18314  * uses the non-embedded SGL block post mailbox commands to post to the port.
18315  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
18316  * embedded SGL post mailbox command for posting. The @post_nblist passed in
18317  * must be local list, thus no lock is needed when manipulate the list.
18318  *
18319  * Returns: 0 = failure, non-zero number of successfully posted buffers.
18320  **/
18321 int
18322 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
18323 			   struct list_head *post_nblist, int sb_count)
18324 {
18325 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
18326 	int status, sgl_size;
18327 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
18328 	dma_addr_t pdma_phys_sgl1;
18329 	int last_xritag = NO_XRI;
18330 	int cur_xritag;
18331 	LIST_HEAD(prep_nblist);
18332 	LIST_HEAD(blck_nblist);
18333 	LIST_HEAD(nvme_nblist);
18334 
18335 	/* sanity check */
18336 	if (sb_count <= 0)
18337 		return -EINVAL;
18338 
18339 	sgl_size = phba->cfg_sg_dma_buf_size;
18340 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
18341 		list_del_init(&lpfc_ncmd->list);
18342 		block_cnt++;
18343 		if ((last_xritag != NO_XRI) &&
18344 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
18345 			/* a hole in xri block, form a sgl posting block */
18346 			list_splice_init(&prep_nblist, &blck_nblist);
18347 			post_cnt = block_cnt - 1;
18348 			/* prepare list for next posting block */
18349 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18350 			block_cnt = 1;
18351 		} else {
18352 			/* prepare list for next posting block */
18353 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18354 			/* enough sgls for non-embed sgl mbox command */
18355 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
18356 				list_splice_init(&prep_nblist, &blck_nblist);
18357 				post_cnt = block_cnt;
18358 				block_cnt = 0;
18359 			}
18360 		}
18361 		num_posting++;
18362 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18363 
18364 		/* end of repost sgl list condition for NVME buffers */
18365 		if (num_posting == sb_count) {
18366 			if (post_cnt == 0) {
18367 				/* last sgl posting block */
18368 				list_splice_init(&prep_nblist, &blck_nblist);
18369 				post_cnt = block_cnt;
18370 			} else if (block_cnt == 1) {
18371 				/* last single sgl with non-contiguous xri */
18372 				if (sgl_size > SGL_PAGE_SIZE)
18373 					pdma_phys_sgl1 =
18374 						lpfc_ncmd->dma_phys_sgl +
18375 						SGL_PAGE_SIZE;
18376 				else
18377 					pdma_phys_sgl1 = 0;
18378 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18379 				status = lpfc_sli4_post_sgl(
18380 						phba, lpfc_ncmd->dma_phys_sgl,
18381 						pdma_phys_sgl1, cur_xritag);
18382 				if (status) {
18383 					/* Post error.  Buffer unavailable. */
18384 					lpfc_ncmd->flags |=
18385 						LPFC_SBUF_NOT_POSTED;
18386 				} else {
18387 					/* Post success. Bffer available. */
18388 					lpfc_ncmd->flags &=
18389 						~LPFC_SBUF_NOT_POSTED;
18390 					lpfc_ncmd->status = IOSTAT_SUCCESS;
18391 					num_posted++;
18392 				}
18393 				/* success, put on NVME buffer sgl list */
18394 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18395 			}
18396 		}
18397 
18398 		/* continue until a nembed page worth of sgls */
18399 		if (post_cnt == 0)
18400 			continue;
18401 
18402 		/* post block of NVME buffer list sgls */
18403 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
18404 						     post_cnt);
18405 
18406 		/* don't reset xirtag due to hole in xri block */
18407 		if (block_cnt == 0)
18408 			last_xritag = NO_XRI;
18409 
18410 		/* reset NVME buffer post count for next round of posting */
18411 		post_cnt = 0;
18412 
18413 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
18414 		while (!list_empty(&blck_nblist)) {
18415 			list_remove_head(&blck_nblist, lpfc_ncmd,
18416 					 struct lpfc_io_buf, list);
18417 			if (status) {
18418 				/* Post error.  Mark buffer unavailable. */
18419 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
18420 			} else {
18421 				/* Post success, Mark buffer available. */
18422 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
18423 				lpfc_ncmd->status = IOSTAT_SUCCESS;
18424 				num_posted++;
18425 			}
18426 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18427 		}
18428 	}
18429 	/* Push NVME buffers with sgl posted to the available list */
18430 	lpfc_io_buf_replenish(phba, &nvme_nblist);
18431 
18432 	return num_posted;
18433 }
18434 
18435 /**
18436  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
18437  * @phba: pointer to lpfc_hba struct that the frame was received on
18438  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18439  *
18440  * This function checks the fields in the @fc_hdr to see if the FC frame is a
18441  * valid type of frame that the LPFC driver will handle. This function will
18442  * return a zero if the frame is a valid frame or a non zero value when the
18443  * frame does not pass the check.
18444  **/
18445 static int
18446 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
18447 {
18448 	/*  make rctl_names static to save stack space */
18449 	struct fc_vft_header *fc_vft_hdr;
18450 	uint32_t *header = (uint32_t *) fc_hdr;
18451 
18452 #define FC_RCTL_MDS_DIAGS	0xF4
18453 
18454 	switch (fc_hdr->fh_r_ctl) {
18455 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
18456 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
18457 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
18458 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
18459 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
18460 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
18461 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
18462 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
18463 	case FC_RCTL_ELS_REQ:	/* extended link services request */
18464 	case FC_RCTL_ELS_REP:	/* extended link services reply */
18465 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
18466 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
18467 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
18468 	case FC_RCTL_BA_RMC: 	/* remove connection */
18469 	case FC_RCTL_BA_ACC:	/* basic accept */
18470 	case FC_RCTL_BA_RJT:	/* basic reject */
18471 	case FC_RCTL_BA_PRMT:
18472 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
18473 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
18474 	case FC_RCTL_P_RJT:	/* port reject */
18475 	case FC_RCTL_F_RJT:	/* fabric reject */
18476 	case FC_RCTL_P_BSY:	/* port busy */
18477 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
18478 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
18479 	case FC_RCTL_LCR:	/* link credit reset */
18480 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
18481 	case FC_RCTL_END:	/* end */
18482 		break;
18483 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
18484 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18485 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
18486 		return lpfc_fc_frame_check(phba, fc_hdr);
18487 	case FC_RCTL_BA_NOP:	/* basic link service NOP */
18488 	default:
18489 		goto drop;
18490 	}
18491 
18492 	switch (fc_hdr->fh_type) {
18493 	case FC_TYPE_BLS:
18494 	case FC_TYPE_ELS:
18495 	case FC_TYPE_FCP:
18496 	case FC_TYPE_CT:
18497 	case FC_TYPE_NVME:
18498 		break;
18499 	case FC_TYPE_IP:
18500 	case FC_TYPE_ILS:
18501 	default:
18502 		goto drop;
18503 	}
18504 
18505 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
18506 			"2538 Received frame rctl:x%x, type:x%x, "
18507 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
18508 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
18509 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
18510 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
18511 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
18512 			be32_to_cpu(header[6]));
18513 	return 0;
18514 drop:
18515 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
18516 			"2539 Dropped frame rctl:x%x type:x%x\n",
18517 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18518 	return 1;
18519 }
18520 
18521 /**
18522  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
18523  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18524  *
18525  * This function processes the FC header to retrieve the VFI from the VF
18526  * header, if one exists. This function will return the VFI if one exists
18527  * or 0 if no VSAN Header exists.
18528  **/
18529 static uint32_t
18530 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
18531 {
18532 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18533 
18534 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
18535 		return 0;
18536 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
18537 }
18538 
18539 /**
18540  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
18541  * @phba: Pointer to the HBA structure to search for the vport on
18542  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18543  * @fcfi: The FC Fabric ID that the frame came from
18544  * @did: Destination ID to match against
18545  *
18546  * This function searches the @phba for a vport that matches the content of the
18547  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
18548  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
18549  * returns the matching vport pointer or NULL if unable to match frame to a
18550  * vport.
18551  **/
18552 static struct lpfc_vport *
18553 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
18554 		       uint16_t fcfi, uint32_t did)
18555 {
18556 	struct lpfc_vport **vports;
18557 	struct lpfc_vport *vport = NULL;
18558 	int i;
18559 
18560 	if (did == Fabric_DID)
18561 		return phba->pport;
18562 	if ((phba->pport->fc_flag & FC_PT2PT) &&
18563 		!(phba->link_state == LPFC_HBA_READY))
18564 		return phba->pport;
18565 
18566 	vports = lpfc_create_vport_work_array(phba);
18567 	if (vports != NULL) {
18568 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
18569 			if (phba->fcf.fcfi == fcfi &&
18570 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
18571 			    vports[i]->fc_myDID == did) {
18572 				vport = vports[i];
18573 				break;
18574 			}
18575 		}
18576 	}
18577 	lpfc_destroy_vport_work_array(phba, vports);
18578 	return vport;
18579 }
18580 
18581 /**
18582  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
18583  * @vport: The vport to work on.
18584  *
18585  * This function updates the receive sequence time stamp for this vport. The
18586  * receive sequence time stamp indicates the time that the last frame of the
18587  * the sequence that has been idle for the longest amount of time was received.
18588  * the driver uses this time stamp to indicate if any received sequences have
18589  * timed out.
18590  **/
18591 static void
18592 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
18593 {
18594 	struct lpfc_dmabuf *h_buf;
18595 	struct hbq_dmabuf *dmabuf = NULL;
18596 
18597 	/* get the oldest sequence on the rcv list */
18598 	h_buf = list_get_first(&vport->rcv_buffer_list,
18599 			       struct lpfc_dmabuf, list);
18600 	if (!h_buf)
18601 		return;
18602 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18603 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
18604 }
18605 
18606 /**
18607  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
18608  * @vport: The vport that the received sequences were sent to.
18609  *
18610  * This function cleans up all outstanding received sequences. This is called
18611  * by the driver when a link event or user action invalidates all the received
18612  * sequences.
18613  **/
18614 void
18615 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
18616 {
18617 	struct lpfc_dmabuf *h_buf, *hnext;
18618 	struct lpfc_dmabuf *d_buf, *dnext;
18619 	struct hbq_dmabuf *dmabuf = NULL;
18620 
18621 	/* start with the oldest sequence on the rcv list */
18622 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18623 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18624 		list_del_init(&dmabuf->hbuf.list);
18625 		list_for_each_entry_safe(d_buf, dnext,
18626 					 &dmabuf->dbuf.list, list) {
18627 			list_del_init(&d_buf->list);
18628 			lpfc_in_buf_free(vport->phba, d_buf);
18629 		}
18630 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18631 	}
18632 }
18633 
18634 /**
18635  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
18636  * @vport: The vport that the received sequences were sent to.
18637  *
18638  * This function determines whether any received sequences have timed out by
18639  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
18640  * indicates that there is at least one timed out sequence this routine will
18641  * go through the received sequences one at a time from most inactive to most
18642  * active to determine which ones need to be cleaned up. Once it has determined
18643  * that a sequence needs to be cleaned up it will simply free up the resources
18644  * without sending an abort.
18645  **/
18646 void
18647 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
18648 {
18649 	struct lpfc_dmabuf *h_buf, *hnext;
18650 	struct lpfc_dmabuf *d_buf, *dnext;
18651 	struct hbq_dmabuf *dmabuf = NULL;
18652 	unsigned long timeout;
18653 	int abort_count = 0;
18654 
18655 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18656 		   vport->rcv_buffer_time_stamp);
18657 	if (list_empty(&vport->rcv_buffer_list) ||
18658 	    time_before(jiffies, timeout))
18659 		return;
18660 	/* start with the oldest sequence on the rcv list */
18661 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18662 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18663 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18664 			   dmabuf->time_stamp);
18665 		if (time_before(jiffies, timeout))
18666 			break;
18667 		abort_count++;
18668 		list_del_init(&dmabuf->hbuf.list);
18669 		list_for_each_entry_safe(d_buf, dnext,
18670 					 &dmabuf->dbuf.list, list) {
18671 			list_del_init(&d_buf->list);
18672 			lpfc_in_buf_free(vport->phba, d_buf);
18673 		}
18674 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18675 	}
18676 	if (abort_count)
18677 		lpfc_update_rcv_time_stamp(vport);
18678 }
18679 
18680 /**
18681  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
18682  * @vport: pointer to a vitural port
18683  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
18684  *
18685  * This function searches through the existing incomplete sequences that have
18686  * been sent to this @vport. If the frame matches one of the incomplete
18687  * sequences then the dbuf in the @dmabuf is added to the list of frames that
18688  * make up that sequence. If no sequence is found that matches this frame then
18689  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
18690  * This function returns a pointer to the first dmabuf in the sequence list that
18691  * the frame was linked to.
18692  **/
18693 static struct hbq_dmabuf *
18694 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18695 {
18696 	struct fc_frame_header *new_hdr;
18697 	struct fc_frame_header *temp_hdr;
18698 	struct lpfc_dmabuf *d_buf;
18699 	struct lpfc_dmabuf *h_buf;
18700 	struct hbq_dmabuf *seq_dmabuf = NULL;
18701 	struct hbq_dmabuf *temp_dmabuf = NULL;
18702 	uint8_t	found = 0;
18703 
18704 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18705 	dmabuf->time_stamp = jiffies;
18706 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18707 
18708 	/* Use the hdr_buf to find the sequence that this frame belongs to */
18709 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18710 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18711 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18712 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18713 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18714 			continue;
18715 		/* found a pending sequence that matches this frame */
18716 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18717 		break;
18718 	}
18719 	if (!seq_dmabuf) {
18720 		/*
18721 		 * This indicates first frame received for this sequence.
18722 		 * Queue the buffer on the vport's rcv_buffer_list.
18723 		 */
18724 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18725 		lpfc_update_rcv_time_stamp(vport);
18726 		return dmabuf;
18727 	}
18728 	temp_hdr = seq_dmabuf->hbuf.virt;
18729 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
18730 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18731 		list_del_init(&seq_dmabuf->hbuf.list);
18732 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18733 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18734 		lpfc_update_rcv_time_stamp(vport);
18735 		return dmabuf;
18736 	}
18737 	/* move this sequence to the tail to indicate a young sequence */
18738 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
18739 	seq_dmabuf->time_stamp = jiffies;
18740 	lpfc_update_rcv_time_stamp(vport);
18741 	if (list_empty(&seq_dmabuf->dbuf.list)) {
18742 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18743 		return seq_dmabuf;
18744 	}
18745 	/* find the correct place in the sequence to insert this frame */
18746 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
18747 	while (!found) {
18748 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18749 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
18750 		/*
18751 		 * If the frame's sequence count is greater than the frame on
18752 		 * the list then insert the frame right after this frame
18753 		 */
18754 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
18755 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18756 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
18757 			found = 1;
18758 			break;
18759 		}
18760 
18761 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
18762 			break;
18763 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
18764 	}
18765 
18766 	if (found)
18767 		return seq_dmabuf;
18768 	return NULL;
18769 }
18770 
18771 /**
18772  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
18773  * @vport: pointer to a vitural port
18774  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18775  *
18776  * This function tries to abort from the partially assembed sequence, described
18777  * by the information from basic abbort @dmabuf. It checks to see whether such
18778  * partially assembled sequence held by the driver. If so, it shall free up all
18779  * the frames from the partially assembled sequence.
18780  *
18781  * Return
18782  * true  -- if there is matching partially assembled sequence present and all
18783  *          the frames freed with the sequence;
18784  * false -- if there is no matching partially assembled sequence present so
18785  *          nothing got aborted in the lower layer driver
18786  **/
18787 static bool
18788 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
18789 			    struct hbq_dmabuf *dmabuf)
18790 {
18791 	struct fc_frame_header *new_hdr;
18792 	struct fc_frame_header *temp_hdr;
18793 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
18794 	struct hbq_dmabuf *seq_dmabuf = NULL;
18795 
18796 	/* Use the hdr_buf to find the sequence that matches this frame */
18797 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18798 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
18799 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18800 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18801 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18802 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18803 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18804 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18805 			continue;
18806 		/* found a pending sequence that matches this frame */
18807 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18808 		break;
18809 	}
18810 
18811 	/* Free up all the frames from the partially assembled sequence */
18812 	if (seq_dmabuf) {
18813 		list_for_each_entry_safe(d_buf, n_buf,
18814 					 &seq_dmabuf->dbuf.list, list) {
18815 			list_del_init(&d_buf->list);
18816 			lpfc_in_buf_free(vport->phba, d_buf);
18817 		}
18818 		return true;
18819 	}
18820 	return false;
18821 }
18822 
18823 /**
18824  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18825  * @vport: pointer to a vitural port
18826  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18827  *
18828  * This function tries to abort from the assembed sequence from upper level
18829  * protocol, described by the information from basic abbort @dmabuf. It
18830  * checks to see whether such pending context exists at upper level protocol.
18831  * If so, it shall clean up the pending context.
18832  *
18833  * Return
18834  * true  -- if there is matching pending context of the sequence cleaned
18835  *          at ulp;
18836  * false -- if there is no matching pending context of the sequence present
18837  *          at ulp.
18838  **/
18839 static bool
18840 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18841 {
18842 	struct lpfc_hba *phba = vport->phba;
18843 	int handled;
18844 
18845 	/* Accepting abort at ulp with SLI4 only */
18846 	if (phba->sli_rev < LPFC_SLI_REV4)
18847 		return false;
18848 
18849 	/* Register all caring upper level protocols to attend abort */
18850 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18851 	if (handled)
18852 		return true;
18853 
18854 	return false;
18855 }
18856 
18857 /**
18858  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18859  * @phba: Pointer to HBA context object.
18860  * @cmd_iocbq: pointer to the command iocbq structure.
18861  * @rsp_iocbq: pointer to the response iocbq structure.
18862  *
18863  * This function handles the sequence abort response iocb command complete
18864  * event. It properly releases the memory allocated to the sequence abort
18865  * accept iocb.
18866  **/
18867 static void
18868 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18869 			     struct lpfc_iocbq *cmd_iocbq,
18870 			     struct lpfc_iocbq *rsp_iocbq)
18871 {
18872 	if (cmd_iocbq) {
18873 		lpfc_nlp_put(cmd_iocbq->ndlp);
18874 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
18875 	}
18876 
18877 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
18878 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18879 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18880 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
18881 			get_job_ulpstatus(phba, rsp_iocbq),
18882 			get_job_word4(phba, rsp_iocbq));
18883 }
18884 
18885 /**
18886  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
18887  * @phba: Pointer to HBA context object.
18888  * @xri: xri id in transaction.
18889  *
18890  * This function validates the xri maps to the known range of XRIs allocated an
18891  * used by the driver.
18892  **/
18893 uint16_t
18894 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
18895 		      uint16_t xri)
18896 {
18897 	uint16_t i;
18898 
18899 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
18900 		if (xri == phba->sli4_hba.xri_ids[i])
18901 			return i;
18902 	}
18903 	return NO_XRI;
18904 }
18905 
18906 /**
18907  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
18908  * @vport: pointer to a virtual port.
18909  * @fc_hdr: pointer to a FC frame header.
18910  * @aborted: was the partially assembled receive sequence successfully aborted
18911  *
18912  * This function sends a basic response to a previous unsol sequence abort
18913  * event after aborting the sequence handling.
18914  **/
18915 void
18916 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
18917 			struct fc_frame_header *fc_hdr, bool aborted)
18918 {
18919 	struct lpfc_hba *phba = vport->phba;
18920 	struct lpfc_iocbq *ctiocb = NULL;
18921 	struct lpfc_nodelist *ndlp;
18922 	uint16_t oxid, rxid, xri, lxri;
18923 	uint32_t sid, fctl;
18924 	union lpfc_wqe128 *icmd;
18925 	int rc;
18926 
18927 	if (!lpfc_is_link_up(phba))
18928 		return;
18929 
18930 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18931 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
18932 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
18933 
18934 	ndlp = lpfc_findnode_did(vport, sid);
18935 	if (!ndlp) {
18936 		ndlp = lpfc_nlp_init(vport, sid);
18937 		if (!ndlp) {
18938 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
18939 					 "1268 Failed to allocate ndlp for "
18940 					 "oxid:x%x SID:x%x\n", oxid, sid);
18941 			return;
18942 		}
18943 		/* Put ndlp onto pport node list */
18944 		lpfc_enqueue_node(vport, ndlp);
18945 	}
18946 
18947 	/* Allocate buffer for rsp iocb */
18948 	ctiocb = lpfc_sli_get_iocbq(phba);
18949 	if (!ctiocb)
18950 		return;
18951 
18952 	icmd = &ctiocb->wqe;
18953 
18954 	/* Extract the F_CTL field from FC_HDR */
18955 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
18956 
18957 	ctiocb->ndlp = lpfc_nlp_get(ndlp);
18958 	if (!ctiocb->ndlp) {
18959 		lpfc_sli_release_iocbq(phba, ctiocb);
18960 		return;
18961 	}
18962 
18963 	ctiocb->vport = phba->pport;
18964 	ctiocb->cmd_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
18965 	ctiocb->sli4_lxritag = NO_XRI;
18966 	ctiocb->sli4_xritag = NO_XRI;
18967 	ctiocb->abort_rctl = FC_RCTL_BA_ACC;
18968 
18969 	if (fctl & FC_FC_EX_CTX)
18970 		/* Exchange responder sent the abort so we
18971 		 * own the oxid.
18972 		 */
18973 		xri = oxid;
18974 	else
18975 		xri = rxid;
18976 	lxri = lpfc_sli4_xri_inrange(phba, xri);
18977 	if (lxri != NO_XRI)
18978 		lpfc_set_rrq_active(phba, ndlp, lxri,
18979 			(xri == oxid) ? rxid : oxid, 0);
18980 	/* For BA_ABTS from exchange responder, if the logical xri with
18981 	 * the oxid maps to the FCP XRI range, the port no longer has
18982 	 * that exchange context, send a BLS_RJT. Override the IOCB for
18983 	 * a BA_RJT.
18984 	 */
18985 	if ((fctl & FC_FC_EX_CTX) &&
18986 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
18987 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
18988 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
18989 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
18990 		       FC_BA_RJT_INV_XID);
18991 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
18992 		       FC_BA_RJT_UNABLE);
18993 	}
18994 
18995 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
18996 	 * the driver no longer has that exchange, send a BLS_RJT. Override
18997 	 * the IOCB for a BA_RJT.
18998 	 */
18999 	if (aborted == false) {
19000 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
19001 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
19002 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
19003 		       FC_BA_RJT_INV_XID);
19004 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
19005 		       FC_BA_RJT_UNABLE);
19006 	}
19007 
19008 	if (fctl & FC_FC_EX_CTX) {
19009 		/* ABTS sent by responder to CT exchange, construction
19010 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
19011 		 * field and RX_ID from ABTS for RX_ID field.
19012 		 */
19013 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_RSP;
19014 		bf_set(xmit_bls_rsp64_rxid, &icmd->xmit_bls_rsp, rxid);
19015 	} else {
19016 		/* ABTS sent by initiator to CT exchange, construction
19017 		 * of BA_ACC will need to allocate a new XRI as for the
19018 		 * XRI_TAG field.
19019 		 */
19020 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_INT;
19021 	}
19022 
19023 	/* OX_ID is invariable to who sent ABTS to CT exchange */
19024 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, oxid);
19025 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, rxid);
19026 
19027 	/* Use CT=VPI */
19028 	bf_set(wqe_els_did, &icmd->xmit_bls_rsp.wqe_dest,
19029 	       ndlp->nlp_DID);
19030 	bf_set(xmit_bls_rsp64_temprpi, &icmd->xmit_bls_rsp,
19031 	       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
19032 	bf_set(wqe_cmnd, &icmd->generic.wqe_com, CMD_XMIT_BLS_RSP64_CX);
19033 
19034 	/* Xmit CT abts response on exchange <xid> */
19035 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
19036 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
19037 			 ctiocb->abort_rctl, oxid, phba->link_state);
19038 
19039 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
19040 	if (rc == IOCB_ERROR) {
19041 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19042 				 "2925 Failed to issue CT ABTS RSP x%x on "
19043 				 "xri x%x, Data x%x\n",
19044 				 ctiocb->abort_rctl, oxid,
19045 				 phba->link_state);
19046 		lpfc_nlp_put(ndlp);
19047 		ctiocb->ndlp = NULL;
19048 		lpfc_sli_release_iocbq(phba, ctiocb);
19049 	}
19050 }
19051 
19052 /**
19053  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
19054  * @vport: Pointer to the vport on which this sequence was received
19055  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19056  *
19057  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
19058  * receive sequence is only partially assembed by the driver, it shall abort
19059  * the partially assembled frames for the sequence. Otherwise, if the
19060  * unsolicited receive sequence has been completely assembled and passed to
19061  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
19062  * unsolicited sequence has been aborted. After that, it will issue a basic
19063  * accept to accept the abort.
19064  **/
19065 static void
19066 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
19067 			     struct hbq_dmabuf *dmabuf)
19068 {
19069 	struct lpfc_hba *phba = vport->phba;
19070 	struct fc_frame_header fc_hdr;
19071 	uint32_t fctl;
19072 	bool aborted;
19073 
19074 	/* Make a copy of fc_hdr before the dmabuf being released */
19075 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
19076 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
19077 
19078 	if (fctl & FC_FC_EX_CTX) {
19079 		/* ABTS by responder to exchange, no cleanup needed */
19080 		aborted = true;
19081 	} else {
19082 		/* ABTS by initiator to exchange, need to do cleanup */
19083 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
19084 		if (aborted == false)
19085 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
19086 	}
19087 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19088 
19089 	if (phba->nvmet_support) {
19090 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
19091 		return;
19092 	}
19093 
19094 	/* Respond with BA_ACC or BA_RJT accordingly */
19095 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
19096 }
19097 
19098 /**
19099  * lpfc_seq_complete - Indicates if a sequence is complete
19100  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19101  *
19102  * This function checks the sequence, starting with the frame described by
19103  * @dmabuf, to see if all the frames associated with this sequence are present.
19104  * the frames associated with this sequence are linked to the @dmabuf using the
19105  * dbuf list. This function looks for two major things. 1) That the first frame
19106  * has a sequence count of zero. 2) There is a frame with last frame of sequence
19107  * set. 3) That there are no holes in the sequence count. The function will
19108  * return 1 when the sequence is complete, otherwise it will return 0.
19109  **/
19110 static int
19111 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
19112 {
19113 	struct fc_frame_header *hdr;
19114 	struct lpfc_dmabuf *d_buf;
19115 	struct hbq_dmabuf *seq_dmabuf;
19116 	uint32_t fctl;
19117 	int seq_count = 0;
19118 
19119 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19120 	/* make sure first fame of sequence has a sequence count of zero */
19121 	if (hdr->fh_seq_cnt != seq_count)
19122 		return 0;
19123 	fctl = (hdr->fh_f_ctl[0] << 16 |
19124 		hdr->fh_f_ctl[1] << 8 |
19125 		hdr->fh_f_ctl[2]);
19126 	/* If last frame of sequence we can return success. */
19127 	if (fctl & FC_FC_END_SEQ)
19128 		return 1;
19129 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
19130 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19131 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19132 		/* If there is a hole in the sequence count then fail. */
19133 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
19134 			return 0;
19135 		fctl = (hdr->fh_f_ctl[0] << 16 |
19136 			hdr->fh_f_ctl[1] << 8 |
19137 			hdr->fh_f_ctl[2]);
19138 		/* If last frame of sequence we can return success. */
19139 		if (fctl & FC_FC_END_SEQ)
19140 			return 1;
19141 	}
19142 	return 0;
19143 }
19144 
19145 /**
19146  * lpfc_prep_seq - Prep sequence for ULP processing
19147  * @vport: Pointer to the vport on which this sequence was received
19148  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
19149  *
19150  * This function takes a sequence, described by a list of frames, and creates
19151  * a list of iocbq structures to describe the sequence. This iocbq list will be
19152  * used to issue to the generic unsolicited sequence handler. This routine
19153  * returns a pointer to the first iocbq in the list. If the function is unable
19154  * to allocate an iocbq then it throw out the received frames that were not
19155  * able to be described and return a pointer to the first iocbq. If unable to
19156  * allocate any iocbqs (including the first) this function will return NULL.
19157  **/
19158 static struct lpfc_iocbq *
19159 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
19160 {
19161 	struct hbq_dmabuf *hbq_buf;
19162 	struct lpfc_dmabuf *d_buf, *n_buf;
19163 	struct lpfc_iocbq *first_iocbq, *iocbq;
19164 	struct fc_frame_header *fc_hdr;
19165 	uint32_t sid;
19166 	uint32_t len, tot_len;
19167 
19168 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19169 	/* remove from receive buffer list */
19170 	list_del_init(&seq_dmabuf->hbuf.list);
19171 	lpfc_update_rcv_time_stamp(vport);
19172 	/* get the Remote Port's SID */
19173 	sid = sli4_sid_from_fc_hdr(fc_hdr);
19174 	tot_len = 0;
19175 	/* Get an iocbq struct to fill in. */
19176 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
19177 	if (first_iocbq) {
19178 		/* Initialize the first IOCB. */
19179 		first_iocbq->wcqe_cmpl.total_data_placed = 0;
19180 		bf_set(lpfc_wcqe_c_status, &first_iocbq->wcqe_cmpl,
19181 		       IOSTAT_SUCCESS);
19182 		first_iocbq->vport = vport;
19183 
19184 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
19185 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
19186 			bf_set(els_rsp64_sid, &first_iocbq->wqe.xmit_els_rsp,
19187 			       sli4_did_from_fc_hdr(fc_hdr));
19188 		}
19189 
19190 		bf_set(wqe_ctxt_tag, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19191 		       NO_XRI);
19192 		bf_set(wqe_rcvoxid, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19193 		       be16_to_cpu(fc_hdr->fh_ox_id));
19194 
19195 		/* put the first buffer into the first iocb */
19196 		tot_len = bf_get(lpfc_rcqe_length,
19197 				 &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
19198 
19199 		first_iocbq->cmd_dmabuf = &seq_dmabuf->dbuf;
19200 		first_iocbq->bpl_dmabuf = NULL;
19201 		/* Keep track of the BDE count */
19202 		first_iocbq->wcqe_cmpl.word3 = 1;
19203 
19204 		if (tot_len > LPFC_DATA_BUF_SIZE)
19205 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize =
19206 				LPFC_DATA_BUF_SIZE;
19207 		else
19208 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize = tot_len;
19209 
19210 		first_iocbq->wcqe_cmpl.total_data_placed = tot_len;
19211 		bf_set(wqe_els_did, &first_iocbq->wqe.xmit_els_rsp.wqe_dest,
19212 		       sid);
19213 	}
19214 	iocbq = first_iocbq;
19215 	/*
19216 	 * Each IOCBq can have two Buffers assigned, so go through the list
19217 	 * of buffers for this sequence and save two buffers in each IOCBq
19218 	 */
19219 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
19220 		if (!iocbq) {
19221 			lpfc_in_buf_free(vport->phba, d_buf);
19222 			continue;
19223 		}
19224 		if (!iocbq->bpl_dmabuf) {
19225 			iocbq->bpl_dmabuf = d_buf;
19226 			iocbq->wcqe_cmpl.word3++;
19227 			/* We need to get the size out of the right CQE */
19228 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19229 			len = bf_get(lpfc_rcqe_length,
19230 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19231 			iocbq->unsol_rcv_len = len;
19232 			iocbq->wcqe_cmpl.total_data_placed += len;
19233 			tot_len += len;
19234 		} else {
19235 			iocbq = lpfc_sli_get_iocbq(vport->phba);
19236 			if (!iocbq) {
19237 				if (first_iocbq) {
19238 					bf_set(lpfc_wcqe_c_status,
19239 					       &first_iocbq->wcqe_cmpl,
19240 					       IOSTAT_SUCCESS);
19241 					first_iocbq->wcqe_cmpl.parameter =
19242 						IOERR_NO_RESOURCES;
19243 				}
19244 				lpfc_in_buf_free(vport->phba, d_buf);
19245 				continue;
19246 			}
19247 			/* We need to get the size out of the right CQE */
19248 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19249 			len = bf_get(lpfc_rcqe_length,
19250 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19251 			iocbq->cmd_dmabuf = d_buf;
19252 			iocbq->bpl_dmabuf = NULL;
19253 			iocbq->wcqe_cmpl.word3 = 1;
19254 
19255 			if (len > LPFC_DATA_BUF_SIZE)
19256 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19257 					LPFC_DATA_BUF_SIZE;
19258 			else
19259 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19260 					len;
19261 
19262 			tot_len += len;
19263 			iocbq->wcqe_cmpl.total_data_placed = tot_len;
19264 			bf_set(wqe_els_did, &iocbq->wqe.xmit_els_rsp.wqe_dest,
19265 			       sid);
19266 			list_add_tail(&iocbq->list, &first_iocbq->list);
19267 		}
19268 	}
19269 	/* Free the sequence's header buffer */
19270 	if (!first_iocbq)
19271 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
19272 
19273 	return first_iocbq;
19274 }
19275 
19276 static void
19277 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
19278 			  struct hbq_dmabuf *seq_dmabuf)
19279 {
19280 	struct fc_frame_header *fc_hdr;
19281 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
19282 	struct lpfc_hba *phba = vport->phba;
19283 
19284 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19285 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
19286 	if (!iocbq) {
19287 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19288 				"2707 Ring %d handler: Failed to allocate "
19289 				"iocb Rctl x%x Type x%x received\n",
19290 				LPFC_ELS_RING,
19291 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19292 		return;
19293 	}
19294 	if (!lpfc_complete_unsol_iocb(phba,
19295 				      phba->sli4_hba.els_wq->pring,
19296 				      iocbq, fc_hdr->fh_r_ctl,
19297 				      fc_hdr->fh_type)) {
19298 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19299 				"2540 Ring %d handler: unexpected Rctl "
19300 				"x%x Type x%x received\n",
19301 				LPFC_ELS_RING,
19302 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19303 		lpfc_in_buf_free(phba, &seq_dmabuf->dbuf);
19304 	}
19305 
19306 	/* Free iocb created in lpfc_prep_seq */
19307 	list_for_each_entry_safe(curr_iocb, next_iocb,
19308 				 &iocbq->list, list) {
19309 		list_del_init(&curr_iocb->list);
19310 		lpfc_sli_release_iocbq(phba, curr_iocb);
19311 	}
19312 	lpfc_sli_release_iocbq(phba, iocbq);
19313 }
19314 
19315 static void
19316 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
19317 			    struct lpfc_iocbq *rspiocb)
19318 {
19319 	struct lpfc_dmabuf *pcmd = cmdiocb->cmd_dmabuf;
19320 
19321 	if (pcmd && pcmd->virt)
19322 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19323 	kfree(pcmd);
19324 	lpfc_sli_release_iocbq(phba, cmdiocb);
19325 	lpfc_drain_txq(phba);
19326 }
19327 
19328 static void
19329 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
19330 			      struct hbq_dmabuf *dmabuf)
19331 {
19332 	struct fc_frame_header *fc_hdr;
19333 	struct lpfc_hba *phba = vport->phba;
19334 	struct lpfc_iocbq *iocbq = NULL;
19335 	union  lpfc_wqe128 *pwqe;
19336 	struct lpfc_dmabuf *pcmd = NULL;
19337 	uint32_t frame_len;
19338 	int rc;
19339 	unsigned long iflags;
19340 
19341 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19342 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
19343 
19344 	/* Send the received frame back */
19345 	iocbq = lpfc_sli_get_iocbq(phba);
19346 	if (!iocbq) {
19347 		/* Queue cq event and wakeup worker thread to process it */
19348 		spin_lock_irqsave(&phba->hbalock, iflags);
19349 		list_add_tail(&dmabuf->cq_event.list,
19350 			      &phba->sli4_hba.sp_queue_event);
19351 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
19352 		spin_unlock_irqrestore(&phba->hbalock, iflags);
19353 		lpfc_worker_wake_up(phba);
19354 		return;
19355 	}
19356 
19357 	/* Allocate buffer for command payload */
19358 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
19359 	if (pcmd)
19360 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
19361 					    &pcmd->phys);
19362 	if (!pcmd || !pcmd->virt)
19363 		goto exit;
19364 
19365 	INIT_LIST_HEAD(&pcmd->list);
19366 
19367 	/* copyin the payload */
19368 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
19369 
19370 	iocbq->cmd_dmabuf = pcmd;
19371 	iocbq->vport = vport;
19372 	iocbq->cmd_flag &= ~LPFC_FIP_ELS_ID_MASK;
19373 	iocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
19374 	iocbq->num_bdes = 0;
19375 
19376 	pwqe = &iocbq->wqe;
19377 	/* fill in BDE's for command */
19378 	pwqe->gen_req.bde.addrHigh = putPaddrHigh(pcmd->phys);
19379 	pwqe->gen_req.bde.addrLow = putPaddrLow(pcmd->phys);
19380 	pwqe->gen_req.bde.tus.f.bdeSize = frame_len;
19381 	pwqe->gen_req.bde.tus.f.bdeFlags = BUFF_TYPE_BDE_64;
19382 
19383 	pwqe->send_frame.frame_len = frame_len;
19384 	pwqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((__be32 *)fc_hdr));
19385 	pwqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((__be32 *)fc_hdr + 1));
19386 	pwqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((__be32 *)fc_hdr + 2));
19387 	pwqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((__be32 *)fc_hdr + 3));
19388 	pwqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((__be32 *)fc_hdr + 4));
19389 	pwqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((__be32 *)fc_hdr + 5));
19390 
19391 	pwqe->generic.wqe_com.word7 = 0;
19392 	pwqe->generic.wqe_com.word10 = 0;
19393 
19394 	bf_set(wqe_cmnd, &pwqe->generic.wqe_com, CMD_SEND_FRAME);
19395 	bf_set(wqe_sof, &pwqe->generic.wqe_com, 0x2E); /* SOF byte */
19396 	bf_set(wqe_eof, &pwqe->generic.wqe_com, 0x41); /* EOF byte */
19397 	bf_set(wqe_lenloc, &pwqe->generic.wqe_com, 1);
19398 	bf_set(wqe_xbl, &pwqe->generic.wqe_com, 1);
19399 	bf_set(wqe_dbde, &pwqe->generic.wqe_com, 1);
19400 	bf_set(wqe_xc, &pwqe->generic.wqe_com, 1);
19401 	bf_set(wqe_cmd_type, &pwqe->generic.wqe_com, 0xA);
19402 	bf_set(wqe_cqid, &pwqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
19403 	bf_set(wqe_xri_tag, &pwqe->generic.wqe_com, iocbq->sli4_xritag);
19404 	bf_set(wqe_reqtag, &pwqe->generic.wqe_com, iocbq->iotag);
19405 	bf_set(wqe_class, &pwqe->generic.wqe_com, CLASS3);
19406 	pwqe->generic.wqe_com.abort_tag = iocbq->iotag;
19407 
19408 	iocbq->cmd_cmpl = lpfc_sli4_mds_loopback_cmpl;
19409 
19410 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
19411 	if (rc == IOCB_ERROR)
19412 		goto exit;
19413 
19414 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19415 	return;
19416 
19417 exit:
19418 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
19419 			"2023 Unable to process MDS loopback frame\n");
19420 	if (pcmd && pcmd->virt)
19421 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19422 	kfree(pcmd);
19423 	if (iocbq)
19424 		lpfc_sli_release_iocbq(phba, iocbq);
19425 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19426 }
19427 
19428 /**
19429  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
19430  * @phba: Pointer to HBA context object.
19431  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
19432  *
19433  * This function is called with no lock held. This function processes all
19434  * the received buffers and gives it to upper layers when a received buffer
19435  * indicates that it is the final frame in the sequence. The interrupt
19436  * service routine processes received buffers at interrupt contexts.
19437  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
19438  * appropriate receive function when the final frame in a sequence is received.
19439  **/
19440 void
19441 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
19442 				 struct hbq_dmabuf *dmabuf)
19443 {
19444 	struct hbq_dmabuf *seq_dmabuf;
19445 	struct fc_frame_header *fc_hdr;
19446 	struct lpfc_vport *vport;
19447 	uint32_t fcfi;
19448 	uint32_t did;
19449 
19450 	/* Process each received buffer */
19451 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19452 
19453 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
19454 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
19455 		vport = phba->pport;
19456 		/* Handle MDS Loopback frames */
19457 		if  (!(phba->pport->load_flag & FC_UNLOADING))
19458 			lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19459 		else
19460 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19461 		return;
19462 	}
19463 
19464 	/* check to see if this a valid type of frame */
19465 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
19466 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19467 		return;
19468 	}
19469 
19470 	if ((bf_get(lpfc_cqe_code,
19471 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
19472 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
19473 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19474 	else
19475 		fcfi = bf_get(lpfc_rcqe_fcf_id,
19476 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19477 
19478 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
19479 		vport = phba->pport;
19480 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
19481 				"2023 MDS Loopback %d bytes\n",
19482 				bf_get(lpfc_rcqe_length,
19483 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
19484 		/* Handle MDS Loopback frames */
19485 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19486 		return;
19487 	}
19488 
19489 	/* d_id this frame is directed to */
19490 	did = sli4_did_from_fc_hdr(fc_hdr);
19491 
19492 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
19493 	if (!vport) {
19494 		/* throw out the frame */
19495 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19496 		return;
19497 	}
19498 
19499 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
19500 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
19501 		(did != Fabric_DID)) {
19502 		/*
19503 		 * Throw out the frame if we are not pt2pt.
19504 		 * The pt2pt protocol allows for discovery frames
19505 		 * to be received without a registered VPI.
19506 		 */
19507 		if (!(vport->fc_flag & FC_PT2PT) ||
19508 			(phba->link_state == LPFC_HBA_READY)) {
19509 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19510 			return;
19511 		}
19512 	}
19513 
19514 	/* Handle the basic abort sequence (BA_ABTS) event */
19515 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
19516 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
19517 		return;
19518 	}
19519 
19520 	/* Link this frame */
19521 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
19522 	if (!seq_dmabuf) {
19523 		/* unable to add frame to vport - throw it out */
19524 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19525 		return;
19526 	}
19527 	/* If not last frame in sequence continue processing frames. */
19528 	if (!lpfc_seq_complete(seq_dmabuf))
19529 		return;
19530 
19531 	/* Send the complete sequence to the upper layer protocol */
19532 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
19533 }
19534 
19535 /**
19536  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
19537  * @phba: pointer to lpfc hba data structure.
19538  *
19539  * This routine is invoked to post rpi header templates to the
19540  * HBA consistent with the SLI-4 interface spec.  This routine
19541  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19542  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19543  *
19544  * This routine does not require any locks.  It's usage is expected
19545  * to be driver load or reset recovery when the driver is
19546  * sequential.
19547  *
19548  * Return codes
19549  * 	0 - successful
19550  *      -EIO - The mailbox failed to complete successfully.
19551  * 	When this error occurs, the driver is not guaranteed
19552  *	to have any rpi regions posted to the device and
19553  *	must either attempt to repost the regions or take a
19554  *	fatal error.
19555  **/
19556 int
19557 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
19558 {
19559 	struct lpfc_rpi_hdr *rpi_page;
19560 	uint32_t rc = 0;
19561 	uint16_t lrpi = 0;
19562 
19563 	/* SLI4 ports that support extents do not require RPI headers. */
19564 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19565 		goto exit;
19566 	if (phba->sli4_hba.extents_in_use)
19567 		return -EIO;
19568 
19569 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
19570 		/*
19571 		 * Assign the rpi headers a physical rpi only if the driver
19572 		 * has not initialized those resources.  A port reset only
19573 		 * needs the headers posted.
19574 		 */
19575 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
19576 		    LPFC_RPI_RSRC_RDY)
19577 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19578 
19579 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
19580 		if (rc != MBX_SUCCESS) {
19581 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19582 					"2008 Error %d posting all rpi "
19583 					"headers\n", rc);
19584 			rc = -EIO;
19585 			break;
19586 		}
19587 	}
19588 
19589  exit:
19590 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
19591 	       LPFC_RPI_RSRC_RDY);
19592 	return rc;
19593 }
19594 
19595 /**
19596  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
19597  * @phba: pointer to lpfc hba data structure.
19598  * @rpi_page:  pointer to the rpi memory region.
19599  *
19600  * This routine is invoked to post a single rpi header to the
19601  * HBA consistent with the SLI-4 interface spec.  This memory region
19602  * maps up to 64 rpi context regions.
19603  *
19604  * Return codes
19605  * 	0 - successful
19606  * 	-ENOMEM - No available memory
19607  *      -EIO - The mailbox failed to complete successfully.
19608  **/
19609 int
19610 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
19611 {
19612 	LPFC_MBOXQ_t *mboxq;
19613 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
19614 	uint32_t rc = 0;
19615 	uint32_t shdr_status, shdr_add_status;
19616 	union lpfc_sli4_cfg_shdr *shdr;
19617 
19618 	/* SLI4 ports that support extents do not require RPI headers. */
19619 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19620 		return rc;
19621 	if (phba->sli4_hba.extents_in_use)
19622 		return -EIO;
19623 
19624 	/* The port is notified of the header region via a mailbox command. */
19625 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19626 	if (!mboxq) {
19627 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19628 				"2001 Unable to allocate memory for issuing "
19629 				"SLI_CONFIG_SPECIAL mailbox command\n");
19630 		return -ENOMEM;
19631 	}
19632 
19633 	/* Post all rpi memory regions to the port. */
19634 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
19635 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19636 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
19637 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
19638 			 sizeof(struct lpfc_sli4_cfg_mhdr),
19639 			 LPFC_SLI4_MBX_EMBED);
19640 
19641 
19642 	/* Post the physical rpi to the port for this rpi header. */
19643 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
19644 	       rpi_page->start_rpi);
19645 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
19646 	       hdr_tmpl, rpi_page->page_count);
19647 
19648 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
19649 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
19650 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19651 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
19652 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19653 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19654 	mempool_free(mboxq, phba->mbox_mem_pool);
19655 	if (shdr_status || shdr_add_status || rc) {
19656 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19657 				"2514 POST_RPI_HDR mailbox failed with "
19658 				"status x%x add_status x%x, mbx status x%x\n",
19659 				shdr_status, shdr_add_status, rc);
19660 		rc = -ENXIO;
19661 	} else {
19662 		/*
19663 		 * The next_rpi stores the next logical module-64 rpi value used
19664 		 * to post physical rpis in subsequent rpi postings.
19665 		 */
19666 		spin_lock_irq(&phba->hbalock);
19667 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
19668 		spin_unlock_irq(&phba->hbalock);
19669 	}
19670 	return rc;
19671 }
19672 
19673 /**
19674  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
19675  * @phba: pointer to lpfc hba data structure.
19676  *
19677  * This routine is invoked to post rpi header templates to the
19678  * HBA consistent with the SLI-4 interface spec.  This routine
19679  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19680  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19681  *
19682  * Returns
19683  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
19684  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
19685  **/
19686 int
19687 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
19688 {
19689 	unsigned long rpi;
19690 	uint16_t max_rpi, rpi_limit;
19691 	uint16_t rpi_remaining, lrpi = 0;
19692 	struct lpfc_rpi_hdr *rpi_hdr;
19693 	unsigned long iflag;
19694 
19695 	/*
19696 	 * Fetch the next logical rpi.  Because this index is logical,
19697 	 * the  driver starts at 0 each time.
19698 	 */
19699 	spin_lock_irqsave(&phba->hbalock, iflag);
19700 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
19701 	rpi_limit = phba->sli4_hba.next_rpi;
19702 
19703 	rpi = find_first_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit);
19704 	if (rpi >= rpi_limit)
19705 		rpi = LPFC_RPI_ALLOC_ERROR;
19706 	else {
19707 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
19708 		phba->sli4_hba.max_cfg_param.rpi_used++;
19709 		phba->sli4_hba.rpi_count++;
19710 	}
19711 	lpfc_printf_log(phba, KERN_INFO,
19712 			LOG_NODE | LOG_DISCOVERY,
19713 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
19714 			(int) rpi, max_rpi, rpi_limit);
19715 
19716 	/*
19717 	 * Don't try to allocate more rpi header regions if the device limit
19718 	 * has been exhausted.
19719 	 */
19720 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
19721 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
19722 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19723 		return rpi;
19724 	}
19725 
19726 	/*
19727 	 * RPI header postings are not required for SLI4 ports capable of
19728 	 * extents.
19729 	 */
19730 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
19731 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19732 		return rpi;
19733 	}
19734 
19735 	/*
19736 	 * If the driver is running low on rpi resources, allocate another
19737 	 * page now.  Note that the next_rpi value is used because
19738 	 * it represents how many are actually in use whereas max_rpi notes
19739 	 * how many are supported max by the device.
19740 	 */
19741 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
19742 	spin_unlock_irqrestore(&phba->hbalock, iflag);
19743 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
19744 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
19745 		if (!rpi_hdr) {
19746 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19747 					"2002 Error Could not grow rpi "
19748 					"count\n");
19749 		} else {
19750 			lrpi = rpi_hdr->start_rpi;
19751 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19752 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
19753 		}
19754 	}
19755 
19756 	return rpi;
19757 }
19758 
19759 /**
19760  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
19761  * @phba: pointer to lpfc hba data structure.
19762  * @rpi: rpi to free
19763  *
19764  * This routine is invoked to release an rpi to the pool of
19765  * available rpis maintained by the driver.
19766  **/
19767 static void
19768 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19769 {
19770 	/*
19771 	 * if the rpi value indicates a prior unreg has already
19772 	 * been done, skip the unreg.
19773 	 */
19774 	if (rpi == LPFC_RPI_ALLOC_ERROR)
19775 		return;
19776 
19777 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
19778 		phba->sli4_hba.rpi_count--;
19779 		phba->sli4_hba.max_cfg_param.rpi_used--;
19780 	} else {
19781 		lpfc_printf_log(phba, KERN_INFO,
19782 				LOG_NODE | LOG_DISCOVERY,
19783 				"2016 rpi %x not inuse\n",
19784 				rpi);
19785 	}
19786 }
19787 
19788 /**
19789  * lpfc_sli4_free_rpi - Release an rpi for reuse.
19790  * @phba: pointer to lpfc hba data structure.
19791  * @rpi: rpi to free
19792  *
19793  * This routine is invoked to release an rpi to the pool of
19794  * available rpis maintained by the driver.
19795  **/
19796 void
19797 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19798 {
19799 	spin_lock_irq(&phba->hbalock);
19800 	__lpfc_sli4_free_rpi(phba, rpi);
19801 	spin_unlock_irq(&phba->hbalock);
19802 }
19803 
19804 /**
19805  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19806  * @phba: pointer to lpfc hba data structure.
19807  *
19808  * This routine is invoked to remove the memory region that
19809  * provided rpi via a bitmask.
19810  **/
19811 void
19812 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19813 {
19814 	kfree(phba->sli4_hba.rpi_bmask);
19815 	kfree(phba->sli4_hba.rpi_ids);
19816 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19817 }
19818 
19819 /**
19820  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
19821  * @ndlp: pointer to lpfc nodelist data structure.
19822  * @cmpl: completion call-back.
19823  * @arg: data to load as MBox 'caller buffer information'
19824  *
19825  * This routine is invoked to remove the memory region that
19826  * provided rpi via a bitmask.
19827  **/
19828 int
19829 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19830 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
19831 {
19832 	LPFC_MBOXQ_t *mboxq;
19833 	struct lpfc_hba *phba = ndlp->phba;
19834 	int rc;
19835 
19836 	/* The port is notified of the header region via a mailbox command. */
19837 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19838 	if (!mboxq)
19839 		return -ENOMEM;
19840 
19841 	/* If cmpl assigned, then this nlp_get pairs with
19842 	 * lpfc_mbx_cmpl_resume_rpi.
19843 	 *
19844 	 * Else cmpl is NULL, then this nlp_get pairs with
19845 	 * lpfc_sli_def_mbox_cmpl.
19846 	 */
19847 	if (!lpfc_nlp_get(ndlp)) {
19848 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19849 				"2122 %s: Failed to get nlp ref\n",
19850 				__func__);
19851 		mempool_free(mboxq, phba->mbox_mem_pool);
19852 		return -EIO;
19853 	}
19854 
19855 	/* Post all rpi memory regions to the port. */
19856 	lpfc_resume_rpi(mboxq, ndlp);
19857 	if (cmpl) {
19858 		mboxq->mbox_cmpl = cmpl;
19859 		mboxq->ctx_buf = arg;
19860 	} else
19861 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19862 	mboxq->ctx_ndlp = ndlp;
19863 	mboxq->vport = ndlp->vport;
19864 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19865 	if (rc == MBX_NOT_FINISHED) {
19866 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19867 				"2010 Resume RPI Mailbox failed "
19868 				"status %d, mbxStatus x%x\n", rc,
19869 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19870 		lpfc_nlp_put(ndlp);
19871 		mempool_free(mboxq, phba->mbox_mem_pool);
19872 		return -EIO;
19873 	}
19874 	return 0;
19875 }
19876 
19877 /**
19878  * lpfc_sli4_init_vpi - Initialize a vpi with the port
19879  * @vport: Pointer to the vport for which the vpi is being initialized
19880  *
19881  * This routine is invoked to activate a vpi with the port.
19882  *
19883  * Returns:
19884  *    0 success
19885  *    -Evalue otherwise
19886  **/
19887 int
19888 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
19889 {
19890 	LPFC_MBOXQ_t *mboxq;
19891 	int rc = 0;
19892 	int retval = MBX_SUCCESS;
19893 	uint32_t mbox_tmo;
19894 	struct lpfc_hba *phba = vport->phba;
19895 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19896 	if (!mboxq)
19897 		return -ENOMEM;
19898 	lpfc_init_vpi(phba, mboxq, vport->vpi);
19899 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
19900 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
19901 	if (rc != MBX_SUCCESS) {
19902 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19903 				"2022 INIT VPI Mailbox failed "
19904 				"status %d, mbxStatus x%x\n", rc,
19905 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19906 		retval = -EIO;
19907 	}
19908 	if (rc != MBX_TIMEOUT)
19909 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
19910 
19911 	return retval;
19912 }
19913 
19914 /**
19915  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
19916  * @phba: pointer to lpfc hba data structure.
19917  * @mboxq: Pointer to mailbox object.
19918  *
19919  * This routine is invoked to manually add a single FCF record. The caller
19920  * must pass a completely initialized FCF_Record.  This routine takes
19921  * care of the nonembedded mailbox operations.
19922  **/
19923 static void
19924 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
19925 {
19926 	void *virt_addr;
19927 	union lpfc_sli4_cfg_shdr *shdr;
19928 	uint32_t shdr_status, shdr_add_status;
19929 
19930 	virt_addr = mboxq->sge_array->addr[0];
19931 	/* The IOCTL status is embedded in the mailbox subheader. */
19932 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
19933 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19934 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19935 
19936 	if ((shdr_status || shdr_add_status) &&
19937 		(shdr_status != STATUS_FCF_IN_USE))
19938 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19939 			"2558 ADD_FCF_RECORD mailbox failed with "
19940 			"status x%x add_status x%x\n",
19941 			shdr_status, shdr_add_status);
19942 
19943 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
19944 }
19945 
19946 /**
19947  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
19948  * @phba: pointer to lpfc hba data structure.
19949  * @fcf_record:  pointer to the initialized fcf record to add.
19950  *
19951  * This routine is invoked to manually add a single FCF record. The caller
19952  * must pass a completely initialized FCF_Record.  This routine takes
19953  * care of the nonembedded mailbox operations.
19954  **/
19955 int
19956 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
19957 {
19958 	int rc = 0;
19959 	LPFC_MBOXQ_t *mboxq;
19960 	uint8_t *bytep;
19961 	void *virt_addr;
19962 	struct lpfc_mbx_sge sge;
19963 	uint32_t alloc_len, req_len;
19964 	uint32_t fcfindex;
19965 
19966 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19967 	if (!mboxq) {
19968 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19969 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
19970 		return -ENOMEM;
19971 	}
19972 
19973 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
19974 		  sizeof(uint32_t);
19975 
19976 	/* Allocate DMA memory and set up the non-embedded mailbox command */
19977 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19978 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
19979 				     req_len, LPFC_SLI4_MBX_NEMBED);
19980 	if (alloc_len < req_len) {
19981 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19982 			"2523 Allocated DMA memory size (x%x) is "
19983 			"less than the requested DMA memory "
19984 			"size (x%x)\n", alloc_len, req_len);
19985 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19986 		return -ENOMEM;
19987 	}
19988 
19989 	/*
19990 	 * Get the first SGE entry from the non-embedded DMA memory.  This
19991 	 * routine only uses a single SGE.
19992 	 */
19993 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
19994 	virt_addr = mboxq->sge_array->addr[0];
19995 	/*
19996 	 * Configure the FCF record for FCFI 0.  This is the driver's
19997 	 * hardcoded default and gets used in nonFIP mode.
19998 	 */
19999 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
20000 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
20001 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
20002 
20003 	/*
20004 	 * Copy the fcf_index and the FCF Record Data. The data starts after
20005 	 * the FCoE header plus word10. The data copy needs to be endian
20006 	 * correct.
20007 	 */
20008 	bytep += sizeof(uint32_t);
20009 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
20010 	mboxq->vport = phba->pport;
20011 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
20012 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20013 	if (rc == MBX_NOT_FINISHED) {
20014 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20015 			"2515 ADD_FCF_RECORD mailbox failed with "
20016 			"status 0x%x\n", rc);
20017 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20018 		rc = -EIO;
20019 	} else
20020 		rc = 0;
20021 
20022 	return rc;
20023 }
20024 
20025 /**
20026  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
20027  * @phba: pointer to lpfc hba data structure.
20028  * @fcf_record:  pointer to the fcf record to write the default data.
20029  * @fcf_index: FCF table entry index.
20030  *
20031  * This routine is invoked to build the driver's default FCF record.  The
20032  * values used are hardcoded.  This routine handles memory initialization.
20033  *
20034  **/
20035 void
20036 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
20037 				struct fcf_record *fcf_record,
20038 				uint16_t fcf_index)
20039 {
20040 	memset(fcf_record, 0, sizeof(struct fcf_record));
20041 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
20042 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
20043 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
20044 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
20045 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
20046 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
20047 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
20048 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
20049 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
20050 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
20051 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
20052 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
20053 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
20054 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
20055 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
20056 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
20057 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
20058 	/* Set the VLAN bit map */
20059 	if (phba->valid_vlan) {
20060 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
20061 			= 1 << (phba->vlan_id % 8);
20062 	}
20063 }
20064 
20065 /**
20066  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
20067  * @phba: pointer to lpfc hba data structure.
20068  * @fcf_index: FCF table entry offset.
20069  *
20070  * This routine is invoked to scan the entire FCF table by reading FCF
20071  * record and processing it one at a time starting from the @fcf_index
20072  * for initial FCF discovery or fast FCF failover rediscovery.
20073  *
20074  * Return 0 if the mailbox command is submitted successfully, none 0
20075  * otherwise.
20076  **/
20077 int
20078 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20079 {
20080 	int rc = 0, error;
20081 	LPFC_MBOXQ_t *mboxq;
20082 
20083 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
20084 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
20085 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20086 	if (!mboxq) {
20087 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20088 				"2000 Failed to allocate mbox for "
20089 				"READ_FCF cmd\n");
20090 		error = -ENOMEM;
20091 		goto fail_fcf_scan;
20092 	}
20093 	/* Construct the read FCF record mailbox command */
20094 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20095 	if (rc) {
20096 		error = -EINVAL;
20097 		goto fail_fcf_scan;
20098 	}
20099 	/* Issue the mailbox command asynchronously */
20100 	mboxq->vport = phba->pport;
20101 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
20102 
20103 	spin_lock_irq(&phba->hbalock);
20104 	phba->hba_flag |= FCF_TS_INPROG;
20105 	spin_unlock_irq(&phba->hbalock);
20106 
20107 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20108 	if (rc == MBX_NOT_FINISHED)
20109 		error = -EIO;
20110 	else {
20111 		/* Reset eligible FCF count for new scan */
20112 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
20113 			phba->fcf.eligible_fcf_cnt = 0;
20114 		error = 0;
20115 	}
20116 fail_fcf_scan:
20117 	if (error) {
20118 		if (mboxq)
20119 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
20120 		/* FCF scan failed, clear FCF_TS_INPROG flag */
20121 		spin_lock_irq(&phba->hbalock);
20122 		phba->hba_flag &= ~FCF_TS_INPROG;
20123 		spin_unlock_irq(&phba->hbalock);
20124 	}
20125 	return error;
20126 }
20127 
20128 /**
20129  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
20130  * @phba: pointer to lpfc hba data structure.
20131  * @fcf_index: FCF table entry offset.
20132  *
20133  * This routine is invoked to read an FCF record indicated by @fcf_index
20134  * and to use it for FLOGI roundrobin FCF failover.
20135  *
20136  * Return 0 if the mailbox command is submitted successfully, none 0
20137  * otherwise.
20138  **/
20139 int
20140 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20141 {
20142 	int rc = 0, error;
20143 	LPFC_MBOXQ_t *mboxq;
20144 
20145 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20146 	if (!mboxq) {
20147 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20148 				"2763 Failed to allocate mbox for "
20149 				"READ_FCF cmd\n");
20150 		error = -ENOMEM;
20151 		goto fail_fcf_read;
20152 	}
20153 	/* Construct the read FCF record mailbox command */
20154 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20155 	if (rc) {
20156 		error = -EINVAL;
20157 		goto fail_fcf_read;
20158 	}
20159 	/* Issue the mailbox command asynchronously */
20160 	mboxq->vport = phba->pport;
20161 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
20162 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20163 	if (rc == MBX_NOT_FINISHED)
20164 		error = -EIO;
20165 	else
20166 		error = 0;
20167 
20168 fail_fcf_read:
20169 	if (error && mboxq)
20170 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20171 	return error;
20172 }
20173 
20174 /**
20175  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
20176  * @phba: pointer to lpfc hba data structure.
20177  * @fcf_index: FCF table entry offset.
20178  *
20179  * This routine is invoked to read an FCF record indicated by @fcf_index to
20180  * determine whether it's eligible for FLOGI roundrobin failover list.
20181  *
20182  * Return 0 if the mailbox command is submitted successfully, none 0
20183  * otherwise.
20184  **/
20185 int
20186 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20187 {
20188 	int rc = 0, error;
20189 	LPFC_MBOXQ_t *mboxq;
20190 
20191 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20192 	if (!mboxq) {
20193 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20194 				"2758 Failed to allocate mbox for "
20195 				"READ_FCF cmd\n");
20196 				error = -ENOMEM;
20197 				goto fail_fcf_read;
20198 	}
20199 	/* Construct the read FCF record mailbox command */
20200 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20201 	if (rc) {
20202 		error = -EINVAL;
20203 		goto fail_fcf_read;
20204 	}
20205 	/* Issue the mailbox command asynchronously */
20206 	mboxq->vport = phba->pport;
20207 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
20208 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20209 	if (rc == MBX_NOT_FINISHED)
20210 		error = -EIO;
20211 	else
20212 		error = 0;
20213 
20214 fail_fcf_read:
20215 	if (error && mboxq)
20216 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20217 	return error;
20218 }
20219 
20220 /**
20221  * lpfc_check_next_fcf_pri_level
20222  * @phba: pointer to the lpfc_hba struct for this port.
20223  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
20224  * routine when the rr_bmask is empty. The FCF indecies are put into the
20225  * rr_bmask based on their priority level. Starting from the highest priority
20226  * to the lowest. The most likely FCF candidate will be in the highest
20227  * priority group. When this routine is called it searches the fcf_pri list for
20228  * next lowest priority group and repopulates the rr_bmask with only those
20229  * fcf_indexes.
20230  * returns:
20231  * 1=success 0=failure
20232  **/
20233 static int
20234 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
20235 {
20236 	uint16_t next_fcf_pri;
20237 	uint16_t last_index;
20238 	struct lpfc_fcf_pri *fcf_pri;
20239 	int rc;
20240 	int ret = 0;
20241 
20242 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20243 			LPFC_SLI4_FCF_TBL_INDX_MAX);
20244 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20245 			"3060 Last IDX %d\n", last_index);
20246 
20247 	/* Verify the priority list has 2 or more entries */
20248 	spin_lock_irq(&phba->hbalock);
20249 	if (list_empty(&phba->fcf.fcf_pri_list) ||
20250 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
20251 		spin_unlock_irq(&phba->hbalock);
20252 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20253 			"3061 Last IDX %d\n", last_index);
20254 		return 0; /* Empty rr list */
20255 	}
20256 	spin_unlock_irq(&phba->hbalock);
20257 
20258 	next_fcf_pri = 0;
20259 	/*
20260 	 * Clear the rr_bmask and set all of the bits that are at this
20261 	 * priority.
20262 	 */
20263 	memset(phba->fcf.fcf_rr_bmask, 0,
20264 			sizeof(*phba->fcf.fcf_rr_bmask));
20265 	spin_lock_irq(&phba->hbalock);
20266 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20267 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
20268 			continue;
20269 		/*
20270 		 * the 1st priority that has not FLOGI failed
20271 		 * will be the highest.
20272 		 */
20273 		if (!next_fcf_pri)
20274 			next_fcf_pri = fcf_pri->fcf_rec.priority;
20275 		spin_unlock_irq(&phba->hbalock);
20276 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20277 			rc = lpfc_sli4_fcf_rr_index_set(phba,
20278 						fcf_pri->fcf_rec.fcf_index);
20279 			if (rc)
20280 				return 0;
20281 		}
20282 		spin_lock_irq(&phba->hbalock);
20283 	}
20284 	/*
20285 	 * if next_fcf_pri was not set above and the list is not empty then
20286 	 * we have failed flogis on all of them. So reset flogi failed
20287 	 * and start at the beginning.
20288 	 */
20289 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
20290 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20291 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
20292 			/*
20293 			 * the 1st priority that has not FLOGI failed
20294 			 * will be the highest.
20295 			 */
20296 			if (!next_fcf_pri)
20297 				next_fcf_pri = fcf_pri->fcf_rec.priority;
20298 			spin_unlock_irq(&phba->hbalock);
20299 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20300 				rc = lpfc_sli4_fcf_rr_index_set(phba,
20301 						fcf_pri->fcf_rec.fcf_index);
20302 				if (rc)
20303 					return 0;
20304 			}
20305 			spin_lock_irq(&phba->hbalock);
20306 		}
20307 	} else
20308 		ret = 1;
20309 	spin_unlock_irq(&phba->hbalock);
20310 
20311 	return ret;
20312 }
20313 /**
20314  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
20315  * @phba: pointer to lpfc hba data structure.
20316  *
20317  * This routine is to get the next eligible FCF record index in a round
20318  * robin fashion. If the next eligible FCF record index equals to the
20319  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
20320  * shall be returned, otherwise, the next eligible FCF record's index
20321  * shall be returned.
20322  **/
20323 uint16_t
20324 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
20325 {
20326 	uint16_t next_fcf_index;
20327 
20328 initial_priority:
20329 	/* Search start from next bit of currently registered FCF index */
20330 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
20331 
20332 next_priority:
20333 	/* Determine the next fcf index to check */
20334 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
20335 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
20336 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
20337 				       next_fcf_index);
20338 
20339 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
20340 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20341 		/*
20342 		 * If we have wrapped then we need to clear the bits that
20343 		 * have been tested so that we can detect when we should
20344 		 * change the priority level.
20345 		 */
20346 		next_fcf_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20347 					       LPFC_SLI4_FCF_TBL_INDX_MAX);
20348 	}
20349 
20350 
20351 	/* Check roundrobin failover list empty condition */
20352 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
20353 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
20354 		/*
20355 		 * If next fcf index is not found check if there are lower
20356 		 * Priority level fcf's in the fcf_priority list.
20357 		 * Set up the rr_bmask with all of the avaiable fcf bits
20358 		 * at that level and continue the selection process.
20359 		 */
20360 		if (lpfc_check_next_fcf_pri_level(phba))
20361 			goto initial_priority;
20362 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
20363 				"2844 No roundrobin failover FCF available\n");
20364 
20365 		return LPFC_FCOE_FCF_NEXT_NONE;
20366 	}
20367 
20368 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
20369 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
20370 		LPFC_FCF_FLOGI_FAILED) {
20371 		if (list_is_singular(&phba->fcf.fcf_pri_list))
20372 			return LPFC_FCOE_FCF_NEXT_NONE;
20373 
20374 		goto next_priority;
20375 	}
20376 
20377 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20378 			"2845 Get next roundrobin failover FCF (x%x)\n",
20379 			next_fcf_index);
20380 
20381 	return next_fcf_index;
20382 }
20383 
20384 /**
20385  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
20386  * @phba: pointer to lpfc hba data structure.
20387  * @fcf_index: index into the FCF table to 'set'
20388  *
20389  * This routine sets the FCF record index in to the eligible bmask for
20390  * roundrobin failover search. It checks to make sure that the index
20391  * does not go beyond the range of the driver allocated bmask dimension
20392  * before setting the bit.
20393  *
20394  * Returns 0 if the index bit successfully set, otherwise, it returns
20395  * -EINVAL.
20396  **/
20397 int
20398 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
20399 {
20400 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20401 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20402 				"2610 FCF (x%x) reached driver's book "
20403 				"keeping dimension:x%x\n",
20404 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20405 		return -EINVAL;
20406 	}
20407 	/* Set the eligible FCF record index bmask */
20408 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20409 
20410 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20411 			"2790 Set FCF (x%x) to roundrobin FCF failover "
20412 			"bmask\n", fcf_index);
20413 
20414 	return 0;
20415 }
20416 
20417 /**
20418  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
20419  * @phba: pointer to lpfc hba data structure.
20420  * @fcf_index: index into the FCF table to 'clear'
20421  *
20422  * This routine clears the FCF record index from the eligible bmask for
20423  * roundrobin failover search. It checks to make sure that the index
20424  * does not go beyond the range of the driver allocated bmask dimension
20425  * before clearing the bit.
20426  **/
20427 void
20428 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
20429 {
20430 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
20431 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20432 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20433 				"2762 FCF (x%x) reached driver's book "
20434 				"keeping dimension:x%x\n",
20435 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20436 		return;
20437 	}
20438 	/* Clear the eligible FCF record index bmask */
20439 	spin_lock_irq(&phba->hbalock);
20440 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
20441 				 list) {
20442 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
20443 			list_del_init(&fcf_pri->list);
20444 			break;
20445 		}
20446 	}
20447 	spin_unlock_irq(&phba->hbalock);
20448 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20449 
20450 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20451 			"2791 Clear FCF (x%x) from roundrobin failover "
20452 			"bmask\n", fcf_index);
20453 }
20454 
20455 /**
20456  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
20457  * @phba: pointer to lpfc hba data structure.
20458  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
20459  *
20460  * This routine is the completion routine for the rediscover FCF table mailbox
20461  * command. If the mailbox command returned failure, it will try to stop the
20462  * FCF rediscover wait timer.
20463  **/
20464 static void
20465 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
20466 {
20467 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20468 	uint32_t shdr_status, shdr_add_status;
20469 
20470 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20471 
20472 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20473 			     &redisc_fcf->header.cfg_shdr.response);
20474 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20475 			     &redisc_fcf->header.cfg_shdr.response);
20476 	if (shdr_status || shdr_add_status) {
20477 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20478 				"2746 Requesting for FCF rediscovery failed "
20479 				"status x%x add_status x%x\n",
20480 				shdr_status, shdr_add_status);
20481 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
20482 			spin_lock_irq(&phba->hbalock);
20483 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
20484 			spin_unlock_irq(&phba->hbalock);
20485 			/*
20486 			 * CVL event triggered FCF rediscover request failed,
20487 			 * last resort to re-try current registered FCF entry.
20488 			 */
20489 			lpfc_retry_pport_discovery(phba);
20490 		} else {
20491 			spin_lock_irq(&phba->hbalock);
20492 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
20493 			spin_unlock_irq(&phba->hbalock);
20494 			/*
20495 			 * DEAD FCF event triggered FCF rediscover request
20496 			 * failed, last resort to fail over as a link down
20497 			 * to FCF registration.
20498 			 */
20499 			lpfc_sli4_fcf_dead_failthrough(phba);
20500 		}
20501 	} else {
20502 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20503 				"2775 Start FCF rediscover quiescent timer\n");
20504 		/*
20505 		 * Start FCF rediscovery wait timer for pending FCF
20506 		 * before rescan FCF record table.
20507 		 */
20508 		lpfc_fcf_redisc_wait_start_timer(phba);
20509 	}
20510 
20511 	mempool_free(mbox, phba->mbox_mem_pool);
20512 }
20513 
20514 /**
20515  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
20516  * @phba: pointer to lpfc hba data structure.
20517  *
20518  * This routine is invoked to request for rediscovery of the entire FCF table
20519  * by the port.
20520  **/
20521 int
20522 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
20523 {
20524 	LPFC_MBOXQ_t *mbox;
20525 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20526 	int rc, length;
20527 
20528 	/* Cancel retry delay timers to all vports before FCF rediscover */
20529 	lpfc_cancel_all_vport_retry_delay_timer(phba);
20530 
20531 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20532 	if (!mbox) {
20533 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20534 				"2745 Failed to allocate mbox for "
20535 				"requesting FCF rediscover.\n");
20536 		return -ENOMEM;
20537 	}
20538 
20539 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
20540 		  sizeof(struct lpfc_sli4_cfg_mhdr));
20541 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
20542 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
20543 			 length, LPFC_SLI4_MBX_EMBED);
20544 
20545 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20546 	/* Set count to 0 for invalidating the entire FCF database */
20547 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
20548 
20549 	/* Issue the mailbox command asynchronously */
20550 	mbox->vport = phba->pport;
20551 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
20552 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
20553 
20554 	if (rc == MBX_NOT_FINISHED) {
20555 		mempool_free(mbox, phba->mbox_mem_pool);
20556 		return -EIO;
20557 	}
20558 	return 0;
20559 }
20560 
20561 /**
20562  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
20563  * @phba: pointer to lpfc hba data structure.
20564  *
20565  * This function is the failover routine as a last resort to the FCF DEAD
20566  * event when driver failed to perform fast FCF failover.
20567  **/
20568 void
20569 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
20570 {
20571 	uint32_t link_state;
20572 
20573 	/*
20574 	 * Last resort as FCF DEAD event failover will treat this as
20575 	 * a link down, but save the link state because we don't want
20576 	 * it to be changed to Link Down unless it is already down.
20577 	 */
20578 	link_state = phba->link_state;
20579 	lpfc_linkdown(phba);
20580 	phba->link_state = link_state;
20581 
20582 	/* Unregister FCF if no devices connected to it */
20583 	lpfc_unregister_unused_fcf(phba);
20584 }
20585 
20586 /**
20587  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
20588  * @phba: pointer to lpfc hba data structure.
20589  * @rgn23_data: pointer to configure region 23 data.
20590  *
20591  * This function gets SLI3 port configure region 23 data through memory dump
20592  * mailbox command. When it successfully retrieves data, the size of the data
20593  * will be returned, otherwise, 0 will be returned.
20594  **/
20595 static uint32_t
20596 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20597 {
20598 	LPFC_MBOXQ_t *pmb = NULL;
20599 	MAILBOX_t *mb;
20600 	uint32_t offset = 0;
20601 	int rc;
20602 
20603 	if (!rgn23_data)
20604 		return 0;
20605 
20606 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20607 	if (!pmb) {
20608 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20609 				"2600 failed to allocate mailbox memory\n");
20610 		return 0;
20611 	}
20612 	mb = &pmb->u.mb;
20613 
20614 	do {
20615 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
20616 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
20617 
20618 		if (rc != MBX_SUCCESS) {
20619 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20620 					"2601 failed to read config "
20621 					"region 23, rc 0x%x Status 0x%x\n",
20622 					rc, mb->mbxStatus);
20623 			mb->un.varDmp.word_cnt = 0;
20624 		}
20625 		/*
20626 		 * dump mem may return a zero when finished or we got a
20627 		 * mailbox error, either way we are done.
20628 		 */
20629 		if (mb->un.varDmp.word_cnt == 0)
20630 			break;
20631 
20632 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
20633 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
20634 
20635 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
20636 				       rgn23_data + offset,
20637 				       mb->un.varDmp.word_cnt);
20638 		offset += mb->un.varDmp.word_cnt;
20639 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
20640 
20641 	mempool_free(pmb, phba->mbox_mem_pool);
20642 	return offset;
20643 }
20644 
20645 /**
20646  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
20647  * @phba: pointer to lpfc hba data structure.
20648  * @rgn23_data: pointer to configure region 23 data.
20649  *
20650  * This function gets SLI4 port configure region 23 data through memory dump
20651  * mailbox command. When it successfully retrieves data, the size of the data
20652  * will be returned, otherwise, 0 will be returned.
20653  **/
20654 static uint32_t
20655 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20656 {
20657 	LPFC_MBOXQ_t *mboxq = NULL;
20658 	struct lpfc_dmabuf *mp = NULL;
20659 	struct lpfc_mqe *mqe;
20660 	uint32_t data_length = 0;
20661 	int rc;
20662 
20663 	if (!rgn23_data)
20664 		return 0;
20665 
20666 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20667 	if (!mboxq) {
20668 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20669 				"3105 failed to allocate mailbox memory\n");
20670 		return 0;
20671 	}
20672 
20673 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
20674 		goto out;
20675 	mqe = &mboxq->u.mqe;
20676 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
20677 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
20678 	if (rc)
20679 		goto out;
20680 	data_length = mqe->un.mb_words[5];
20681 	if (data_length == 0)
20682 		goto out;
20683 	if (data_length > DMP_RGN23_SIZE) {
20684 		data_length = 0;
20685 		goto out;
20686 	}
20687 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
20688 out:
20689 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
20690 	return data_length;
20691 }
20692 
20693 /**
20694  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
20695  * @phba: pointer to lpfc hba data structure.
20696  *
20697  * This function read region 23 and parse TLV for port status to
20698  * decide if the user disaled the port. If the TLV indicates the
20699  * port is disabled, the hba_flag is set accordingly.
20700  **/
20701 void
20702 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
20703 {
20704 	uint8_t *rgn23_data = NULL;
20705 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
20706 	uint32_t offset = 0;
20707 
20708 	/* Get adapter Region 23 data */
20709 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
20710 	if (!rgn23_data)
20711 		goto out;
20712 
20713 	if (phba->sli_rev < LPFC_SLI_REV4)
20714 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
20715 	else {
20716 		if_type = bf_get(lpfc_sli_intf_if_type,
20717 				 &phba->sli4_hba.sli_intf);
20718 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
20719 			goto out;
20720 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
20721 	}
20722 
20723 	if (!data_size)
20724 		goto out;
20725 
20726 	/* Check the region signature first */
20727 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
20728 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20729 			"2619 Config region 23 has bad signature\n");
20730 			goto out;
20731 	}
20732 	offset += 4;
20733 
20734 	/* Check the data structure version */
20735 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
20736 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20737 			"2620 Config region 23 has bad version\n");
20738 		goto out;
20739 	}
20740 	offset += 4;
20741 
20742 	/* Parse TLV entries in the region */
20743 	while (offset < data_size) {
20744 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
20745 			break;
20746 		/*
20747 		 * If the TLV is not driver specific TLV or driver id is
20748 		 * not linux driver id, skip the record.
20749 		 */
20750 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
20751 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
20752 		    (rgn23_data[offset + 3] != 0)) {
20753 			offset += rgn23_data[offset + 1] * 4 + 4;
20754 			continue;
20755 		}
20756 
20757 		/* Driver found a driver specific TLV in the config region */
20758 		sub_tlv_len = rgn23_data[offset + 1] * 4;
20759 		offset += 4;
20760 		tlv_offset = 0;
20761 
20762 		/*
20763 		 * Search for configured port state sub-TLV.
20764 		 */
20765 		while ((offset < data_size) &&
20766 			(tlv_offset < sub_tlv_len)) {
20767 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
20768 				offset += 4;
20769 				tlv_offset += 4;
20770 				break;
20771 			}
20772 			if (rgn23_data[offset] != PORT_STE_TYPE) {
20773 				offset += rgn23_data[offset + 1] * 4 + 4;
20774 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
20775 				continue;
20776 			}
20777 
20778 			/* This HBA contains PORT_STE configured */
20779 			if (!rgn23_data[offset + 2])
20780 				phba->hba_flag |= LINK_DISABLED;
20781 
20782 			goto out;
20783 		}
20784 	}
20785 
20786 out:
20787 	kfree(rgn23_data);
20788 	return;
20789 }
20790 
20791 /**
20792  * lpfc_log_fw_write_cmpl - logs firmware write completion status
20793  * @phba: pointer to lpfc hba data structure
20794  * @shdr_status: wr_object rsp's status field
20795  * @shdr_add_status: wr_object rsp's add_status field
20796  * @shdr_add_status_2: wr_object rsp's add_status_2 field
20797  * @shdr_change_status: wr_object rsp's change_status field
20798  * @shdr_csf: wr_object rsp's csf bit
20799  *
20800  * This routine is intended to be called after a firmware write completes.
20801  * It will log next action items to be performed by the user to instantiate
20802  * the newly downloaded firmware or reason for incompatibility.
20803  **/
20804 static void
20805 lpfc_log_fw_write_cmpl(struct lpfc_hba *phba, u32 shdr_status,
20806 		       u32 shdr_add_status, u32 shdr_add_status_2,
20807 		       u32 shdr_change_status, u32 shdr_csf)
20808 {
20809 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20810 			"4198 %s: flash_id x%02x, asic_rev x%02x, "
20811 			"status x%02x, add_status x%02x, add_status_2 x%02x, "
20812 			"change_status x%02x, csf %01x\n", __func__,
20813 			phba->sli4_hba.flash_id, phba->sli4_hba.asic_rev,
20814 			shdr_status, shdr_add_status, shdr_add_status_2,
20815 			shdr_change_status, shdr_csf);
20816 
20817 	if (shdr_add_status == LPFC_ADD_STATUS_INCOMPAT_OBJ) {
20818 		switch (shdr_add_status_2) {
20819 		case LPFC_ADD_STATUS_2_INCOMPAT_FLASH:
20820 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20821 				     "4199 Firmware write failed: "
20822 				     "image incompatible with flash x%02x\n",
20823 				     phba->sli4_hba.flash_id);
20824 			break;
20825 		case LPFC_ADD_STATUS_2_INCORRECT_ASIC:
20826 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20827 				     "4200 Firmware write failed: "
20828 				     "image incompatible with ASIC "
20829 				     "architecture x%02x\n",
20830 				     phba->sli4_hba.asic_rev);
20831 			break;
20832 		default:
20833 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20834 				     "4210 Firmware write failed: "
20835 				     "add_status_2 x%02x\n",
20836 				     shdr_add_status_2);
20837 			break;
20838 		}
20839 	} else if (!shdr_status && !shdr_add_status) {
20840 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20841 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20842 			if (shdr_csf)
20843 				shdr_change_status =
20844 						   LPFC_CHANGE_STATUS_PCI_RESET;
20845 		}
20846 
20847 		switch (shdr_change_status) {
20848 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20849 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20850 				     "3198 Firmware write complete: System "
20851 				     "reboot required to instantiate\n");
20852 			break;
20853 		case (LPFC_CHANGE_STATUS_FW_RESET):
20854 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20855 				     "3199 Firmware write complete: "
20856 				     "Firmware reset required to "
20857 				     "instantiate\n");
20858 			break;
20859 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20860 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20861 				     "3200 Firmware write complete: Port "
20862 				     "Migration or PCI Reset required to "
20863 				     "instantiate\n");
20864 			break;
20865 		case (LPFC_CHANGE_STATUS_PCI_RESET):
20866 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20867 				     "3201 Firmware write complete: PCI "
20868 				     "Reset required to instantiate\n");
20869 			break;
20870 		default:
20871 			break;
20872 		}
20873 	}
20874 }
20875 
20876 /**
20877  * lpfc_wr_object - write an object to the firmware
20878  * @phba: HBA structure that indicates port to create a queue on.
20879  * @dmabuf_list: list of dmabufs to write to the port.
20880  * @size: the total byte value of the objects to write to the port.
20881  * @offset: the current offset to be used to start the transfer.
20882  *
20883  * This routine will create a wr_object mailbox command to send to the port.
20884  * the mailbox command will be constructed using the dma buffers described in
20885  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
20886  * BDEs that the imbedded mailbox can support. The @offset variable will be
20887  * used to indicate the starting offset of the transfer and will also return
20888  * the offset after the write object mailbox has completed. @size is used to
20889  * determine the end of the object and whether the eof bit should be set.
20890  *
20891  * Return 0 is successful and offset will contain the new offset to use
20892  * for the next write.
20893  * Return negative value for error cases.
20894  **/
20895 int
20896 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
20897 	       uint32_t size, uint32_t *offset)
20898 {
20899 	struct lpfc_mbx_wr_object *wr_object;
20900 	LPFC_MBOXQ_t *mbox;
20901 	int rc = 0, i = 0;
20902 	int mbox_status = 0;
20903 	uint32_t shdr_status, shdr_add_status, shdr_add_status_2;
20904 	uint32_t shdr_change_status = 0, shdr_csf = 0;
20905 	uint32_t mbox_tmo;
20906 	struct lpfc_dmabuf *dmabuf;
20907 	uint32_t written = 0;
20908 	bool check_change_status = false;
20909 
20910 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20911 	if (!mbox)
20912 		return -ENOMEM;
20913 
20914 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
20915 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
20916 			sizeof(struct lpfc_mbx_wr_object) -
20917 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
20918 
20919 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
20920 	wr_object->u.request.write_offset = *offset;
20921 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
20922 	wr_object->u.request.object_name[0] =
20923 		cpu_to_le32(wr_object->u.request.object_name[0]);
20924 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
20925 	list_for_each_entry(dmabuf, dmabuf_list, list) {
20926 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
20927 			break;
20928 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
20929 		wr_object->u.request.bde[i].addrHigh =
20930 			putPaddrHigh(dmabuf->phys);
20931 		if (written + SLI4_PAGE_SIZE >= size) {
20932 			wr_object->u.request.bde[i].tus.f.bdeSize =
20933 				(size - written);
20934 			written += (size - written);
20935 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
20936 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
20937 			check_change_status = true;
20938 		} else {
20939 			wr_object->u.request.bde[i].tus.f.bdeSize =
20940 				SLI4_PAGE_SIZE;
20941 			written += SLI4_PAGE_SIZE;
20942 		}
20943 		i++;
20944 	}
20945 	wr_object->u.request.bde_count = i;
20946 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
20947 	if (!phba->sli4_hba.intr_enable)
20948 		mbox_status = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
20949 	else {
20950 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
20951 		mbox_status = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
20952 	}
20953 
20954 	/* The mbox status needs to be maintained to detect MBOX_TIMEOUT. */
20955 	rc = mbox_status;
20956 
20957 	/* The IOCTL status is embedded in the mailbox subheader. */
20958 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20959 			     &wr_object->header.cfg_shdr.response);
20960 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20961 				 &wr_object->header.cfg_shdr.response);
20962 	shdr_add_status_2 = bf_get(lpfc_mbox_hdr_add_status_2,
20963 				   &wr_object->header.cfg_shdr.response);
20964 	if (check_change_status) {
20965 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
20966 					    &wr_object->u.response);
20967 		shdr_csf = bf_get(lpfc_wr_object_csf,
20968 				  &wr_object->u.response);
20969 	}
20970 
20971 	if (shdr_status || shdr_add_status || shdr_add_status_2 || rc) {
20972 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20973 				"3025 Write Object mailbox failed with "
20974 				"status x%x add_status x%x, add_status_2 x%x, "
20975 				"mbx status x%x\n",
20976 				shdr_status, shdr_add_status, shdr_add_status_2,
20977 				rc);
20978 		rc = -ENXIO;
20979 		*offset = shdr_add_status;
20980 	} else {
20981 		*offset += wr_object->u.response.actual_write_length;
20982 	}
20983 
20984 	if (rc || check_change_status)
20985 		lpfc_log_fw_write_cmpl(phba, shdr_status, shdr_add_status,
20986 				       shdr_add_status_2, shdr_change_status,
20987 				       shdr_csf);
20988 
20989 	if (!phba->sli4_hba.intr_enable)
20990 		mempool_free(mbox, phba->mbox_mem_pool);
20991 	else if (mbox_status != MBX_TIMEOUT)
20992 		mempool_free(mbox, phba->mbox_mem_pool);
20993 
20994 	return rc;
20995 }
20996 
20997 /**
20998  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
20999  * @vport: pointer to vport data structure.
21000  *
21001  * This function iterate through the mailboxq and clean up all REG_LOGIN
21002  * and REG_VPI mailbox commands associated with the vport. This function
21003  * is called when driver want to restart discovery of the vport due to
21004  * a Clear Virtual Link event.
21005  **/
21006 void
21007 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
21008 {
21009 	struct lpfc_hba *phba = vport->phba;
21010 	LPFC_MBOXQ_t *mb, *nextmb;
21011 	struct lpfc_nodelist *ndlp;
21012 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
21013 	LIST_HEAD(mbox_cmd_list);
21014 	uint8_t restart_loop;
21015 
21016 	/* Clean up internally queued mailbox commands with the vport */
21017 	spin_lock_irq(&phba->hbalock);
21018 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
21019 		if (mb->vport != vport)
21020 			continue;
21021 
21022 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21023 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
21024 			continue;
21025 
21026 		list_move_tail(&mb->list, &mbox_cmd_list);
21027 	}
21028 	/* Clean up active mailbox command with the vport */
21029 	mb = phba->sli.mbox_active;
21030 	if (mb && (mb->vport == vport)) {
21031 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
21032 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
21033 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21034 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21035 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
21036 
21037 			/* This reference is local to this routine.  The
21038 			 * reference is removed at routine exit.
21039 			 */
21040 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
21041 
21042 			/* Unregister the RPI when mailbox complete */
21043 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21044 		}
21045 	}
21046 	/* Cleanup any mailbox completions which are not yet processed */
21047 	do {
21048 		restart_loop = 0;
21049 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
21050 			/*
21051 			 * If this mailox is already processed or it is
21052 			 * for another vport ignore it.
21053 			 */
21054 			if ((mb->vport != vport) ||
21055 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
21056 				continue;
21057 
21058 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21059 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
21060 				continue;
21061 
21062 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21063 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21064 				ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
21065 				/* Unregister the RPI when mailbox complete */
21066 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21067 				restart_loop = 1;
21068 				spin_unlock_irq(&phba->hbalock);
21069 				spin_lock(&ndlp->lock);
21070 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21071 				spin_unlock(&ndlp->lock);
21072 				spin_lock_irq(&phba->hbalock);
21073 				break;
21074 			}
21075 		}
21076 	} while (restart_loop);
21077 
21078 	spin_unlock_irq(&phba->hbalock);
21079 
21080 	/* Release the cleaned-up mailbox commands */
21081 	while (!list_empty(&mbox_cmd_list)) {
21082 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
21083 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21084 			ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
21085 			mb->ctx_ndlp = NULL;
21086 			if (ndlp) {
21087 				spin_lock(&ndlp->lock);
21088 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21089 				spin_unlock(&ndlp->lock);
21090 				lpfc_nlp_put(ndlp);
21091 			}
21092 		}
21093 		lpfc_mbox_rsrc_cleanup(phba, mb, MBOX_THD_UNLOCKED);
21094 	}
21095 
21096 	/* Release the ndlp with the cleaned-up active mailbox command */
21097 	if (act_mbx_ndlp) {
21098 		spin_lock(&act_mbx_ndlp->lock);
21099 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21100 		spin_unlock(&act_mbx_ndlp->lock);
21101 		lpfc_nlp_put(act_mbx_ndlp);
21102 	}
21103 }
21104 
21105 /**
21106  * lpfc_drain_txq - Drain the txq
21107  * @phba: Pointer to HBA context object.
21108  *
21109  * This function attempt to submit IOCBs on the txq
21110  * to the adapter.  For SLI4 adapters, the txq contains
21111  * ELS IOCBs that have been deferred because the there
21112  * are no SGLs.  This congestion can occur with large
21113  * vport counts during node discovery.
21114  **/
21115 
21116 uint32_t
21117 lpfc_drain_txq(struct lpfc_hba *phba)
21118 {
21119 	LIST_HEAD(completions);
21120 	struct lpfc_sli_ring *pring;
21121 	struct lpfc_iocbq *piocbq = NULL;
21122 	unsigned long iflags = 0;
21123 	char *fail_msg = NULL;
21124 	uint32_t txq_cnt = 0;
21125 	struct lpfc_queue *wq;
21126 	int ret = 0;
21127 
21128 	if (phba->link_flag & LS_MDS_LOOPBACK) {
21129 		/* MDS WQE are posted only to first WQ*/
21130 		wq = phba->sli4_hba.hdwq[0].io_wq;
21131 		if (unlikely(!wq))
21132 			return 0;
21133 		pring = wq->pring;
21134 	} else {
21135 		wq = phba->sli4_hba.els_wq;
21136 		if (unlikely(!wq))
21137 			return 0;
21138 		pring = lpfc_phba_elsring(phba);
21139 	}
21140 
21141 	if (unlikely(!pring) || list_empty(&pring->txq))
21142 		return 0;
21143 
21144 	spin_lock_irqsave(&pring->ring_lock, iflags);
21145 	list_for_each_entry(piocbq, &pring->txq, list) {
21146 		txq_cnt++;
21147 	}
21148 
21149 	if (txq_cnt > pring->txq_max)
21150 		pring->txq_max = txq_cnt;
21151 
21152 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
21153 
21154 	while (!list_empty(&pring->txq)) {
21155 		spin_lock_irqsave(&pring->ring_lock, iflags);
21156 
21157 		piocbq = lpfc_sli_ringtx_get(phba, pring);
21158 		if (!piocbq) {
21159 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21160 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21161 				"2823 txq empty and txq_cnt is %d\n ",
21162 				txq_cnt);
21163 			break;
21164 		}
21165 		txq_cnt--;
21166 
21167 		ret = __lpfc_sli_issue_iocb(phba, pring->ringno, piocbq, 0);
21168 
21169 		if (ret && ret != IOCB_BUSY) {
21170 			fail_msg = " - Cannot send IO ";
21171 			piocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21172 		}
21173 		if (fail_msg) {
21174 			piocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
21175 			/* Failed means we can't issue and need to cancel */
21176 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21177 					"2822 IOCB failed %s iotag 0x%x "
21178 					"xri 0x%x %d flg x%x\n",
21179 					fail_msg, piocbq->iotag,
21180 					piocbq->sli4_xritag, ret,
21181 					piocbq->cmd_flag);
21182 			list_add_tail(&piocbq->list, &completions);
21183 			fail_msg = NULL;
21184 		}
21185 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21186 		if (txq_cnt == 0 || ret == IOCB_BUSY)
21187 			break;
21188 	}
21189 	/* Cancel all the IOCBs that cannot be issued */
21190 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
21191 			      IOERR_SLI_ABORTED);
21192 
21193 	return txq_cnt;
21194 }
21195 
21196 /**
21197  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
21198  * @phba: Pointer to HBA context object.
21199  * @pwqeq: Pointer to command WQE.
21200  * @sglq: Pointer to the scatter gather queue object.
21201  *
21202  * This routine converts the bpl or bde that is in the WQE
21203  * to a sgl list for the sli4 hardware. The physical address
21204  * of the bpl/bde is converted back to a virtual address.
21205  * If the WQE contains a BPL then the list of BDE's is
21206  * converted to sli4_sge's. If the WQE contains a single
21207  * BDE then it is converted to a single sli_sge.
21208  * The WQE is still in cpu endianness so the contents of
21209  * the bpl can be used without byte swapping.
21210  *
21211  * Returns valid XRI = Success, NO_XRI = Failure.
21212  */
21213 static uint16_t
21214 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
21215 		 struct lpfc_sglq *sglq)
21216 {
21217 	uint16_t xritag = NO_XRI;
21218 	struct ulp_bde64 *bpl = NULL;
21219 	struct ulp_bde64 bde;
21220 	struct sli4_sge *sgl  = NULL;
21221 	struct lpfc_dmabuf *dmabuf;
21222 	union lpfc_wqe128 *wqe;
21223 	int numBdes = 0;
21224 	int i = 0;
21225 	uint32_t offset = 0; /* accumulated offset in the sg request list */
21226 	int inbound = 0; /* number of sg reply entries inbound from firmware */
21227 	uint32_t cmd;
21228 
21229 	if (!pwqeq || !sglq)
21230 		return xritag;
21231 
21232 	sgl  = (struct sli4_sge *)sglq->sgl;
21233 	wqe = &pwqeq->wqe;
21234 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
21235 
21236 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
21237 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
21238 		return sglq->sli4_xritag;
21239 	numBdes = pwqeq->num_bdes;
21240 	if (numBdes) {
21241 		/* The addrHigh and addrLow fields within the WQE
21242 		 * have not been byteswapped yet so there is no
21243 		 * need to swap them back.
21244 		 */
21245 		if (pwqeq->bpl_dmabuf)
21246 			dmabuf = pwqeq->bpl_dmabuf;
21247 		else
21248 			return xritag;
21249 
21250 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
21251 		if (!bpl)
21252 			return xritag;
21253 
21254 		for (i = 0; i < numBdes; i++) {
21255 			/* Should already be byte swapped. */
21256 			sgl->addr_hi = bpl->addrHigh;
21257 			sgl->addr_lo = bpl->addrLow;
21258 
21259 			sgl->word2 = le32_to_cpu(sgl->word2);
21260 			if ((i+1) == numBdes)
21261 				bf_set(lpfc_sli4_sge_last, sgl, 1);
21262 			else
21263 				bf_set(lpfc_sli4_sge_last, sgl, 0);
21264 			/* swap the size field back to the cpu so we
21265 			 * can assign it to the sgl.
21266 			 */
21267 			bde.tus.w = le32_to_cpu(bpl->tus.w);
21268 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
21269 			/* The offsets in the sgl need to be accumulated
21270 			 * separately for the request and reply lists.
21271 			 * The request is always first, the reply follows.
21272 			 */
21273 			switch (cmd) {
21274 			case CMD_GEN_REQUEST64_WQE:
21275 				/* add up the reply sg entries */
21276 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
21277 					inbound++;
21278 				/* first inbound? reset the offset */
21279 				if (inbound == 1)
21280 					offset = 0;
21281 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21282 				bf_set(lpfc_sli4_sge_type, sgl,
21283 					LPFC_SGE_TYPE_DATA);
21284 				offset += bde.tus.f.bdeSize;
21285 				break;
21286 			case CMD_FCP_TRSP64_WQE:
21287 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
21288 				bf_set(lpfc_sli4_sge_type, sgl,
21289 					LPFC_SGE_TYPE_DATA);
21290 				break;
21291 			case CMD_FCP_TSEND64_WQE:
21292 			case CMD_FCP_TRECEIVE64_WQE:
21293 				bf_set(lpfc_sli4_sge_type, sgl,
21294 					bpl->tus.f.bdeFlags);
21295 				if (i < 3)
21296 					offset = 0;
21297 				else
21298 					offset += bde.tus.f.bdeSize;
21299 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21300 				break;
21301 			}
21302 			sgl->word2 = cpu_to_le32(sgl->word2);
21303 			bpl++;
21304 			sgl++;
21305 		}
21306 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
21307 		/* The addrHigh and addrLow fields of the BDE have not
21308 		 * been byteswapped yet so they need to be swapped
21309 		 * before putting them in the sgl.
21310 		 */
21311 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
21312 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
21313 		sgl->word2 = le32_to_cpu(sgl->word2);
21314 		bf_set(lpfc_sli4_sge_last, sgl, 1);
21315 		sgl->word2 = cpu_to_le32(sgl->word2);
21316 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
21317 	}
21318 	return sglq->sli4_xritag;
21319 }
21320 
21321 /**
21322  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
21323  * @phba: Pointer to HBA context object.
21324  * @qp: Pointer to HDW queue.
21325  * @pwqe: Pointer to command WQE.
21326  **/
21327 int
21328 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21329 		    struct lpfc_iocbq *pwqe)
21330 {
21331 	union lpfc_wqe128 *wqe = &pwqe->wqe;
21332 	struct lpfc_async_xchg_ctx *ctxp;
21333 	struct lpfc_queue *wq;
21334 	struct lpfc_sglq *sglq;
21335 	struct lpfc_sli_ring *pring;
21336 	unsigned long iflags;
21337 	uint32_t ret = 0;
21338 
21339 	/* NVME_LS and NVME_LS ABTS requests. */
21340 	if (pwqe->cmd_flag & LPFC_IO_NVME_LS) {
21341 		pring =  phba->sli4_hba.nvmels_wq->pring;
21342 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21343 					  qp, wq_access);
21344 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
21345 		if (!sglq) {
21346 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21347 			return WQE_BUSY;
21348 		}
21349 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
21350 		pwqe->sli4_xritag = sglq->sli4_xritag;
21351 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
21352 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21353 			return WQE_ERROR;
21354 		}
21355 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21356 		       pwqe->sli4_xritag);
21357 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
21358 		if (ret) {
21359 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21360 			return ret;
21361 		}
21362 
21363 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21364 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21365 
21366 		lpfc_sli4_poll_eq(qp->hba_eq);
21367 		return 0;
21368 	}
21369 
21370 	/* NVME_FCREQ and NVME_ABTS requests */
21371 	if (pwqe->cmd_flag & (LPFC_IO_NVME | LPFC_IO_FCP | LPFC_IO_CMF)) {
21372 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21373 		wq = qp->io_wq;
21374 		pring = wq->pring;
21375 
21376 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21377 
21378 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21379 					  qp, wq_access);
21380 		ret = lpfc_sli4_wq_put(wq, wqe);
21381 		if (ret) {
21382 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21383 			return ret;
21384 		}
21385 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21386 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21387 
21388 		lpfc_sli4_poll_eq(qp->hba_eq);
21389 		return 0;
21390 	}
21391 
21392 	/* NVMET requests */
21393 	if (pwqe->cmd_flag & LPFC_IO_NVMET) {
21394 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21395 		wq = qp->io_wq;
21396 		pring = wq->pring;
21397 
21398 		ctxp = pwqe->context_un.axchg;
21399 		sglq = ctxp->ctxbuf->sglq;
21400 		if (pwqe->sli4_xritag ==  NO_XRI) {
21401 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
21402 			pwqe->sli4_xritag = sglq->sli4_xritag;
21403 		}
21404 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21405 		       pwqe->sli4_xritag);
21406 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21407 
21408 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21409 					  qp, wq_access);
21410 		ret = lpfc_sli4_wq_put(wq, wqe);
21411 		if (ret) {
21412 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21413 			return ret;
21414 		}
21415 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21416 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21417 
21418 		lpfc_sli4_poll_eq(qp->hba_eq);
21419 		return 0;
21420 	}
21421 	return WQE_ERROR;
21422 }
21423 
21424 /**
21425  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
21426  * @phba: Pointer to HBA context object.
21427  * @cmdiocb: Pointer to driver command iocb object.
21428  * @cmpl: completion function.
21429  *
21430  * Fill the appropriate fields for the abort WQE and call
21431  * internal routine lpfc_sli4_issue_wqe to send the WQE
21432  * This function is called with hbalock held and no ring_lock held.
21433  *
21434  * RETURNS 0 - SUCCESS
21435  **/
21436 
21437 int
21438 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
21439 			    void *cmpl)
21440 {
21441 	struct lpfc_vport *vport = cmdiocb->vport;
21442 	struct lpfc_iocbq *abtsiocb = NULL;
21443 	union lpfc_wqe128 *abtswqe;
21444 	struct lpfc_io_buf *lpfc_cmd;
21445 	int retval = IOCB_ERROR;
21446 	u16 xritag = cmdiocb->sli4_xritag;
21447 
21448 	/*
21449 	 * The scsi command can not be in txq and it is in flight because the
21450 	 * pCmd is still pointing at the SCSI command we have to abort. There
21451 	 * is no need to search the txcmplq. Just send an abort to the FW.
21452 	 */
21453 
21454 	abtsiocb = __lpfc_sli_get_iocbq(phba);
21455 	if (!abtsiocb)
21456 		return WQE_NORESOURCE;
21457 
21458 	/* Indicate the IO is being aborted by the driver. */
21459 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
21460 
21461 	abtswqe = &abtsiocb->wqe;
21462 	memset(abtswqe, 0, sizeof(*abtswqe));
21463 
21464 	if (!lpfc_is_link_up(phba) || (phba->link_flag & LS_EXTERNAL_LOOPBACK))
21465 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
21466 	bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
21467 	abtswqe->abort_cmd.rsrvd5 = 0;
21468 	abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
21469 	bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
21470 	bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
21471 	bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
21472 	bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
21473 	bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
21474 	bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
21475 
21476 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
21477 	abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
21478 	abtsiocb->cmd_flag |= LPFC_USE_FCPWQIDX;
21479 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
21480 		abtsiocb->cmd_flag |= LPFC_IO_FCP;
21481 	if (cmdiocb->cmd_flag & LPFC_IO_NVME)
21482 		abtsiocb->cmd_flag |= LPFC_IO_NVME;
21483 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
21484 		abtsiocb->cmd_flag |= LPFC_IO_FOF;
21485 	abtsiocb->vport = vport;
21486 	abtsiocb->cmd_cmpl = cmpl;
21487 
21488 	lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
21489 	retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
21490 
21491 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21492 			 "0359 Abort xri x%x, original iotag x%x, "
21493 			 "abort cmd iotag x%x retval x%x\n",
21494 			 xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
21495 
21496 	if (retval) {
21497 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21498 		__lpfc_sli_release_iocbq(phba, abtsiocb);
21499 	}
21500 
21501 	return retval;
21502 }
21503 
21504 #ifdef LPFC_MXP_STAT
21505 /**
21506  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
21507  * @phba: pointer to lpfc hba data structure.
21508  * @hwqid: belong to which HWQ.
21509  *
21510  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
21511  * 15 seconds after a test case is running.
21512  *
21513  * The user should call lpfc_debugfs_multixripools_write before running a test
21514  * case to clear stat_snapshot_taken. Then the user starts a test case. During
21515  * test case is running, stat_snapshot_taken is incremented by 1 every time when
21516  * this routine is called from heartbeat timer. When stat_snapshot_taken is
21517  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
21518  **/
21519 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
21520 {
21521 	struct lpfc_sli4_hdw_queue *qp;
21522 	struct lpfc_multixri_pool *multixri_pool;
21523 	struct lpfc_pvt_pool *pvt_pool;
21524 	struct lpfc_pbl_pool *pbl_pool;
21525 	u32 txcmplq_cnt;
21526 
21527 	qp = &phba->sli4_hba.hdwq[hwqid];
21528 	multixri_pool = qp->p_multixri_pool;
21529 	if (!multixri_pool)
21530 		return;
21531 
21532 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
21533 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21534 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21535 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21536 
21537 		multixri_pool->stat_pbl_count = pbl_pool->count;
21538 		multixri_pool->stat_pvt_count = pvt_pool->count;
21539 		multixri_pool->stat_busy_count = txcmplq_cnt;
21540 	}
21541 
21542 	multixri_pool->stat_snapshot_taken++;
21543 }
21544 #endif
21545 
21546 /**
21547  * lpfc_adjust_pvt_pool_count - Adjust private pool count
21548  * @phba: pointer to lpfc hba data structure.
21549  * @hwqid: belong to which HWQ.
21550  *
21551  * This routine moves some XRIs from private to public pool when private pool
21552  * is not busy.
21553  **/
21554 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
21555 {
21556 	struct lpfc_multixri_pool *multixri_pool;
21557 	u32 io_req_count;
21558 	u32 prev_io_req_count;
21559 
21560 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21561 	if (!multixri_pool)
21562 		return;
21563 	io_req_count = multixri_pool->io_req_count;
21564 	prev_io_req_count = multixri_pool->prev_io_req_count;
21565 
21566 	if (prev_io_req_count != io_req_count) {
21567 		/* Private pool is busy */
21568 		multixri_pool->prev_io_req_count = io_req_count;
21569 	} else {
21570 		/* Private pool is not busy.
21571 		 * Move XRIs from private to public pool.
21572 		 */
21573 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
21574 	}
21575 }
21576 
21577 /**
21578  * lpfc_adjust_high_watermark - Adjust high watermark
21579  * @phba: pointer to lpfc hba data structure.
21580  * @hwqid: belong to which HWQ.
21581  *
21582  * This routine sets high watermark as number of outstanding XRIs,
21583  * but make sure the new value is between xri_limit/2 and xri_limit.
21584  **/
21585 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
21586 {
21587 	u32 new_watermark;
21588 	u32 watermark_max;
21589 	u32 watermark_min;
21590 	u32 xri_limit;
21591 	u32 txcmplq_cnt;
21592 	u32 abts_io_bufs;
21593 	struct lpfc_multixri_pool *multixri_pool;
21594 	struct lpfc_sli4_hdw_queue *qp;
21595 
21596 	qp = &phba->sli4_hba.hdwq[hwqid];
21597 	multixri_pool = qp->p_multixri_pool;
21598 	if (!multixri_pool)
21599 		return;
21600 	xri_limit = multixri_pool->xri_limit;
21601 
21602 	watermark_max = xri_limit;
21603 	watermark_min = xri_limit / 2;
21604 
21605 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21606 	abts_io_bufs = qp->abts_scsi_io_bufs;
21607 	abts_io_bufs += qp->abts_nvme_io_bufs;
21608 
21609 	new_watermark = txcmplq_cnt + abts_io_bufs;
21610 	new_watermark = min(watermark_max, new_watermark);
21611 	new_watermark = max(watermark_min, new_watermark);
21612 	multixri_pool->pvt_pool.high_watermark = new_watermark;
21613 
21614 #ifdef LPFC_MXP_STAT
21615 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
21616 					  new_watermark);
21617 #endif
21618 }
21619 
21620 /**
21621  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
21622  * @phba: pointer to lpfc hba data structure.
21623  * @hwqid: belong to which HWQ.
21624  *
21625  * This routine is called from hearbeat timer when pvt_pool is idle.
21626  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
21627  * The first step moves (all - low_watermark) amount of XRIs.
21628  * The second step moves the rest of XRIs.
21629  **/
21630 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
21631 {
21632 	struct lpfc_pbl_pool *pbl_pool;
21633 	struct lpfc_pvt_pool *pvt_pool;
21634 	struct lpfc_sli4_hdw_queue *qp;
21635 	struct lpfc_io_buf *lpfc_ncmd;
21636 	struct lpfc_io_buf *lpfc_ncmd_next;
21637 	unsigned long iflag;
21638 	struct list_head tmp_list;
21639 	u32 tmp_count;
21640 
21641 	qp = &phba->sli4_hba.hdwq[hwqid];
21642 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
21643 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
21644 	tmp_count = 0;
21645 
21646 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
21647 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
21648 
21649 	if (pvt_pool->count > pvt_pool->low_watermark) {
21650 		/* Step 1: move (all - low_watermark) from pvt_pool
21651 		 * to pbl_pool
21652 		 */
21653 
21654 		/* Move low watermark of bufs from pvt_pool to tmp_list */
21655 		INIT_LIST_HEAD(&tmp_list);
21656 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21657 					 &pvt_pool->list, list) {
21658 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
21659 			tmp_count++;
21660 			if (tmp_count >= pvt_pool->low_watermark)
21661 				break;
21662 		}
21663 
21664 		/* Move all bufs from pvt_pool to pbl_pool */
21665 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21666 
21667 		/* Move all bufs from tmp_list to pvt_pool */
21668 		list_splice(&tmp_list, &pvt_pool->list);
21669 
21670 		pbl_pool->count += (pvt_pool->count - tmp_count);
21671 		pvt_pool->count = tmp_count;
21672 	} else {
21673 		/* Step 2: move the rest from pvt_pool to pbl_pool */
21674 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21675 		pbl_pool->count += pvt_pool->count;
21676 		pvt_pool->count = 0;
21677 	}
21678 
21679 	spin_unlock(&pvt_pool->lock);
21680 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21681 }
21682 
21683 /**
21684  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21685  * @phba: pointer to lpfc hba data structure
21686  * @qp: pointer to HDW queue
21687  * @pbl_pool: specified public free XRI pool
21688  * @pvt_pool: specified private free XRI pool
21689  * @count: number of XRIs to move
21690  *
21691  * This routine tries to move some free common bufs from the specified pbl_pool
21692  * to the specified pvt_pool. It might move less than count XRIs if there's not
21693  * enough in public pool.
21694  *
21695  * Return:
21696  *   true - if XRIs are successfully moved from the specified pbl_pool to the
21697  *          specified pvt_pool
21698  *   false - if the specified pbl_pool is empty or locked by someone else
21699  **/
21700 static bool
21701 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21702 			  struct lpfc_pbl_pool *pbl_pool,
21703 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
21704 {
21705 	struct lpfc_io_buf *lpfc_ncmd;
21706 	struct lpfc_io_buf *lpfc_ncmd_next;
21707 	unsigned long iflag;
21708 	int ret;
21709 
21710 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
21711 	if (ret) {
21712 		if (pbl_pool->count) {
21713 			/* Move a batch of XRIs from public to private pool */
21714 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
21715 			list_for_each_entry_safe(lpfc_ncmd,
21716 						 lpfc_ncmd_next,
21717 						 &pbl_pool->list,
21718 						 list) {
21719 				list_move_tail(&lpfc_ncmd->list,
21720 					       &pvt_pool->list);
21721 				pvt_pool->count++;
21722 				pbl_pool->count--;
21723 				count--;
21724 				if (count == 0)
21725 					break;
21726 			}
21727 
21728 			spin_unlock(&pvt_pool->lock);
21729 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21730 			return true;
21731 		}
21732 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21733 	}
21734 
21735 	return false;
21736 }
21737 
21738 /**
21739  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21740  * @phba: pointer to lpfc hba data structure.
21741  * @hwqid: belong to which HWQ.
21742  * @count: number of XRIs to move
21743  *
21744  * This routine tries to find some free common bufs in one of public pools with
21745  * Round Robin method. The search always starts from local hwqid, then the next
21746  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
21747  * a batch of free common bufs are moved to private pool on hwqid.
21748  * It might move less than count XRIs if there's not enough in public pool.
21749  **/
21750 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
21751 {
21752 	struct lpfc_multixri_pool *multixri_pool;
21753 	struct lpfc_multixri_pool *next_multixri_pool;
21754 	struct lpfc_pvt_pool *pvt_pool;
21755 	struct lpfc_pbl_pool *pbl_pool;
21756 	struct lpfc_sli4_hdw_queue *qp;
21757 	u32 next_hwqid;
21758 	u32 hwq_count;
21759 	int ret;
21760 
21761 	qp = &phba->sli4_hba.hdwq[hwqid];
21762 	multixri_pool = qp->p_multixri_pool;
21763 	pvt_pool = &multixri_pool->pvt_pool;
21764 	pbl_pool = &multixri_pool->pbl_pool;
21765 
21766 	/* Check if local pbl_pool is available */
21767 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
21768 	if (ret) {
21769 #ifdef LPFC_MXP_STAT
21770 		multixri_pool->local_pbl_hit_count++;
21771 #endif
21772 		return;
21773 	}
21774 
21775 	hwq_count = phba->cfg_hdw_queue;
21776 
21777 	/* Get the next hwqid which was found last time */
21778 	next_hwqid = multixri_pool->rrb_next_hwqid;
21779 
21780 	do {
21781 		/* Go to next hwq */
21782 		next_hwqid = (next_hwqid + 1) % hwq_count;
21783 
21784 		next_multixri_pool =
21785 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
21786 		pbl_pool = &next_multixri_pool->pbl_pool;
21787 
21788 		/* Check if the public free xri pool is available */
21789 		ret = _lpfc_move_xri_pbl_to_pvt(
21790 			phba, qp, pbl_pool, pvt_pool, count);
21791 
21792 		/* Exit while-loop if success or all hwqid are checked */
21793 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
21794 
21795 	/* Starting point for the next time */
21796 	multixri_pool->rrb_next_hwqid = next_hwqid;
21797 
21798 	if (!ret) {
21799 		/* stats: all public pools are empty*/
21800 		multixri_pool->pbl_empty_count++;
21801 	}
21802 
21803 #ifdef LPFC_MXP_STAT
21804 	if (ret) {
21805 		if (next_hwqid == hwqid)
21806 			multixri_pool->local_pbl_hit_count++;
21807 		else
21808 			multixri_pool->other_pbl_hit_count++;
21809 	}
21810 #endif
21811 }
21812 
21813 /**
21814  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
21815  * @phba: pointer to lpfc hba data structure.
21816  * @hwqid: belong to which HWQ.
21817  *
21818  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
21819  * low watermark.
21820  **/
21821 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
21822 {
21823 	struct lpfc_multixri_pool *multixri_pool;
21824 	struct lpfc_pvt_pool *pvt_pool;
21825 
21826 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21827 	pvt_pool = &multixri_pool->pvt_pool;
21828 
21829 	if (pvt_pool->count < pvt_pool->low_watermark)
21830 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21831 }
21832 
21833 /**
21834  * lpfc_release_io_buf - Return one IO buf back to free pool
21835  * @phba: pointer to lpfc hba data structure.
21836  * @lpfc_ncmd: IO buf to be returned.
21837  * @qp: belong to which HWQ.
21838  *
21839  * This routine returns one IO buf back to free pool. If this is an urgent IO,
21840  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
21841  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
21842  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
21843  * lpfc_io_buf_list_put.
21844  **/
21845 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
21846 			 struct lpfc_sli4_hdw_queue *qp)
21847 {
21848 	unsigned long iflag;
21849 	struct lpfc_pbl_pool *pbl_pool;
21850 	struct lpfc_pvt_pool *pvt_pool;
21851 	struct lpfc_epd_pool *epd_pool;
21852 	u32 txcmplq_cnt;
21853 	u32 xri_owned;
21854 	u32 xri_limit;
21855 	u32 abts_io_bufs;
21856 
21857 	/* MUST zero fields if buffer is reused by another protocol */
21858 	lpfc_ncmd->nvmeCmd = NULL;
21859 	lpfc_ncmd->cur_iocbq.cmd_cmpl = NULL;
21860 
21861 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
21862 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
21863 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
21864 
21865 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
21866 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
21867 
21868 	if (phba->cfg_xri_rebalancing) {
21869 		if (lpfc_ncmd->expedite) {
21870 			/* Return to expedite pool */
21871 			epd_pool = &phba->epd_pool;
21872 			spin_lock_irqsave(&epd_pool->lock, iflag);
21873 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21874 			epd_pool->count++;
21875 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
21876 			return;
21877 		}
21878 
21879 		/* Avoid invalid access if an IO sneaks in and is being rejected
21880 		 * just _after_ xri pools are destroyed in lpfc_offline.
21881 		 * Nothing much can be done at this point.
21882 		 */
21883 		if (!qp->p_multixri_pool)
21884 			return;
21885 
21886 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21887 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21888 
21889 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21890 		abts_io_bufs = qp->abts_scsi_io_bufs;
21891 		abts_io_bufs += qp->abts_nvme_io_bufs;
21892 
21893 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21894 		xri_limit = qp->p_multixri_pool->xri_limit;
21895 
21896 #ifdef LPFC_MXP_STAT
21897 		if (xri_owned <= xri_limit)
21898 			qp->p_multixri_pool->below_limit_count++;
21899 		else
21900 			qp->p_multixri_pool->above_limit_count++;
21901 #endif
21902 
21903 		/* XRI goes to either public or private free xri pool
21904 		 *     based on watermark and xri_limit
21905 		 */
21906 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
21907 		    (xri_owned < xri_limit &&
21908 		     pvt_pool->count < pvt_pool->high_watermark)) {
21909 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
21910 						  qp, free_pvt_pool);
21911 			list_add_tail(&lpfc_ncmd->list,
21912 				      &pvt_pool->list);
21913 			pvt_pool->count++;
21914 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21915 		} else {
21916 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
21917 						  qp, free_pub_pool);
21918 			list_add_tail(&lpfc_ncmd->list,
21919 				      &pbl_pool->list);
21920 			pbl_pool->count++;
21921 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21922 		}
21923 	} else {
21924 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
21925 					  qp, free_xri);
21926 		list_add_tail(&lpfc_ncmd->list,
21927 			      &qp->lpfc_io_buf_list_put);
21928 		qp->put_io_bufs++;
21929 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
21930 				       iflag);
21931 	}
21932 }
21933 
21934 /**
21935  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
21936  * @phba: pointer to lpfc hba data structure.
21937  * @qp: pointer to HDW queue
21938  * @pvt_pool: pointer to private pool data structure.
21939  * @ndlp: pointer to lpfc nodelist data structure.
21940  *
21941  * This routine tries to get one free IO buf from private pool.
21942  *
21943  * Return:
21944  *   pointer to one free IO buf - if private pool is not empty
21945  *   NULL - if private pool is empty
21946  **/
21947 static struct lpfc_io_buf *
21948 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
21949 				  struct lpfc_sli4_hdw_queue *qp,
21950 				  struct lpfc_pvt_pool *pvt_pool,
21951 				  struct lpfc_nodelist *ndlp)
21952 {
21953 	struct lpfc_io_buf *lpfc_ncmd;
21954 	struct lpfc_io_buf *lpfc_ncmd_next;
21955 	unsigned long iflag;
21956 
21957 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
21958 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21959 				 &pvt_pool->list, list) {
21960 		if (lpfc_test_rrq_active(
21961 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
21962 			continue;
21963 		list_del(&lpfc_ncmd->list);
21964 		pvt_pool->count--;
21965 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21966 		return lpfc_ncmd;
21967 	}
21968 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21969 
21970 	return NULL;
21971 }
21972 
21973 /**
21974  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
21975  * @phba: pointer to lpfc hba data structure.
21976  *
21977  * This routine tries to get one free IO buf from expedite pool.
21978  *
21979  * Return:
21980  *   pointer to one free IO buf - if expedite pool is not empty
21981  *   NULL - if expedite pool is empty
21982  **/
21983 static struct lpfc_io_buf *
21984 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
21985 {
21986 	struct lpfc_io_buf *lpfc_ncmd = NULL, *iter;
21987 	struct lpfc_io_buf *lpfc_ncmd_next;
21988 	unsigned long iflag;
21989 	struct lpfc_epd_pool *epd_pool;
21990 
21991 	epd_pool = &phba->epd_pool;
21992 
21993 	spin_lock_irqsave(&epd_pool->lock, iflag);
21994 	if (epd_pool->count > 0) {
21995 		list_for_each_entry_safe(iter, lpfc_ncmd_next,
21996 					 &epd_pool->list, list) {
21997 			list_del(&iter->list);
21998 			epd_pool->count--;
21999 			lpfc_ncmd = iter;
22000 			break;
22001 		}
22002 	}
22003 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
22004 
22005 	return lpfc_ncmd;
22006 }
22007 
22008 /**
22009  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
22010  * @phba: pointer to lpfc hba data structure.
22011  * @ndlp: pointer to lpfc nodelist data structure.
22012  * @hwqid: belong to which HWQ
22013  * @expedite: 1 means this request is urgent.
22014  *
22015  * This routine will do the following actions and then return a pointer to
22016  * one free IO buf.
22017  *
22018  * 1. If private free xri count is empty, move some XRIs from public to
22019  *    private pool.
22020  * 2. Get one XRI from private free xri pool.
22021  * 3. If we fail to get one from pvt_pool and this is an expedite request,
22022  *    get one free xri from expedite pool.
22023  *
22024  * Note: ndlp is only used on SCSI side for RRQ testing.
22025  *       The caller should pass NULL for ndlp on NVME side.
22026  *
22027  * Return:
22028  *   pointer to one free IO buf - if private pool is not empty
22029  *   NULL - if private pool is empty
22030  **/
22031 static struct lpfc_io_buf *
22032 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
22033 				    struct lpfc_nodelist *ndlp,
22034 				    int hwqid, int expedite)
22035 {
22036 	struct lpfc_sli4_hdw_queue *qp;
22037 	struct lpfc_multixri_pool *multixri_pool;
22038 	struct lpfc_pvt_pool *pvt_pool;
22039 	struct lpfc_io_buf *lpfc_ncmd;
22040 
22041 	qp = &phba->sli4_hba.hdwq[hwqid];
22042 	lpfc_ncmd = NULL;
22043 	if (!qp) {
22044 		lpfc_printf_log(phba, KERN_INFO,
22045 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22046 				"5556 NULL qp for hwqid  x%x\n", hwqid);
22047 		return lpfc_ncmd;
22048 	}
22049 	multixri_pool = qp->p_multixri_pool;
22050 	if (!multixri_pool) {
22051 		lpfc_printf_log(phba, KERN_INFO,
22052 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22053 				"5557 NULL multixri for hwqid  x%x\n", hwqid);
22054 		return lpfc_ncmd;
22055 	}
22056 	pvt_pool = &multixri_pool->pvt_pool;
22057 	if (!pvt_pool) {
22058 		lpfc_printf_log(phba, KERN_INFO,
22059 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22060 				"5558 NULL pvt_pool for hwqid  x%x\n", hwqid);
22061 		return lpfc_ncmd;
22062 	}
22063 	multixri_pool->io_req_count++;
22064 
22065 	/* If pvt_pool is empty, move some XRIs from public to private pool */
22066 	if (pvt_pool->count == 0)
22067 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
22068 
22069 	/* Get one XRI from private free xri pool */
22070 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
22071 
22072 	if (lpfc_ncmd) {
22073 		lpfc_ncmd->hdwq = qp;
22074 		lpfc_ncmd->hdwq_no = hwqid;
22075 	} else if (expedite) {
22076 		/* If we fail to get one from pvt_pool and this is an expedite
22077 		 * request, get one free xri from expedite pool.
22078 		 */
22079 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
22080 	}
22081 
22082 	return lpfc_ncmd;
22083 }
22084 
22085 static inline struct lpfc_io_buf *
22086 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
22087 {
22088 	struct lpfc_sli4_hdw_queue *qp;
22089 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
22090 
22091 	qp = &phba->sli4_hba.hdwq[idx];
22092 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
22093 				 &qp->lpfc_io_buf_list_get, list) {
22094 		if (lpfc_test_rrq_active(phba, ndlp,
22095 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
22096 			continue;
22097 
22098 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
22099 			continue;
22100 
22101 		list_del_init(&lpfc_cmd->list);
22102 		qp->get_io_bufs--;
22103 		lpfc_cmd->hdwq = qp;
22104 		lpfc_cmd->hdwq_no = idx;
22105 		return lpfc_cmd;
22106 	}
22107 	return NULL;
22108 }
22109 
22110 /**
22111  * lpfc_get_io_buf - Get one IO buffer from free pool
22112  * @phba: The HBA for which this call is being executed.
22113  * @ndlp: pointer to lpfc nodelist data structure.
22114  * @hwqid: belong to which HWQ
22115  * @expedite: 1 means this request is urgent.
22116  *
22117  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
22118  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
22119  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
22120  *
22121  * Note: ndlp is only used on SCSI side for RRQ testing.
22122  *       The caller should pass NULL for ndlp on NVME side.
22123  *
22124  * Return codes:
22125  *   NULL - Error
22126  *   Pointer to lpfc_io_buf - Success
22127  **/
22128 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
22129 				    struct lpfc_nodelist *ndlp,
22130 				    u32 hwqid, int expedite)
22131 {
22132 	struct lpfc_sli4_hdw_queue *qp;
22133 	unsigned long iflag;
22134 	struct lpfc_io_buf *lpfc_cmd;
22135 
22136 	qp = &phba->sli4_hba.hdwq[hwqid];
22137 	lpfc_cmd = NULL;
22138 	if (!qp) {
22139 		lpfc_printf_log(phba, KERN_WARNING,
22140 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22141 				"5555 NULL qp for hwqid  x%x\n", hwqid);
22142 		return lpfc_cmd;
22143 	}
22144 
22145 	if (phba->cfg_xri_rebalancing)
22146 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
22147 			phba, ndlp, hwqid, expedite);
22148 	else {
22149 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
22150 					  qp, alloc_xri_get);
22151 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
22152 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22153 		if (!lpfc_cmd) {
22154 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
22155 					  qp, alloc_xri_put);
22156 			list_splice(&qp->lpfc_io_buf_list_put,
22157 				    &qp->lpfc_io_buf_list_get);
22158 			qp->get_io_bufs += qp->put_io_bufs;
22159 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
22160 			qp->put_io_bufs = 0;
22161 			spin_unlock(&qp->io_buf_list_put_lock);
22162 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
22163 			    expedite)
22164 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22165 		}
22166 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
22167 	}
22168 
22169 	return lpfc_cmd;
22170 }
22171 
22172 /**
22173  * lpfc_read_object - Retrieve object data from HBA
22174  * @phba: The HBA for which this call is being executed.
22175  * @rdobject: Pathname of object data we want to read.
22176  * @datap: Pointer to where data will be copied to.
22177  * @datasz: size of data area
22178  *
22179  * This routine is limited to object sizes of LPFC_BPL_SIZE (1024) or less.
22180  * The data will be truncated if datasz is not large enough.
22181  * Version 1 is not supported with Embedded mbox cmd, so we must use version 0.
22182  * Returns the actual bytes read from the object.
22183  */
22184 int
22185 lpfc_read_object(struct lpfc_hba *phba, char *rdobject, uint32_t *datap,
22186 		 uint32_t datasz)
22187 {
22188 	struct lpfc_mbx_read_object *read_object;
22189 	LPFC_MBOXQ_t *mbox;
22190 	int rc, length, eof, j, byte_cnt = 0;
22191 	uint32_t shdr_status, shdr_add_status;
22192 	union lpfc_sli4_cfg_shdr *shdr;
22193 	struct lpfc_dmabuf *pcmd;
22194 	u32 rd_object_name[LPFC_MBX_OBJECT_NAME_LEN_DW] = {0};
22195 
22196 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
22197 	if (!mbox)
22198 		return -ENOMEM;
22199 	length = (sizeof(struct lpfc_mbx_read_object) -
22200 		  sizeof(struct lpfc_sli4_cfg_mhdr));
22201 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
22202 			 LPFC_MBOX_OPCODE_READ_OBJECT,
22203 			 length, LPFC_SLI4_MBX_EMBED);
22204 	read_object = &mbox->u.mqe.un.read_object;
22205 	shdr = (union lpfc_sli4_cfg_shdr *)&read_object->header.cfg_shdr;
22206 
22207 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_0);
22208 	bf_set(lpfc_mbx_rd_object_rlen, &read_object->u.request, datasz);
22209 	read_object->u.request.rd_object_offset = 0;
22210 	read_object->u.request.rd_object_cnt = 1;
22211 
22212 	memset((void *)read_object->u.request.rd_object_name, 0,
22213 	       LPFC_OBJ_NAME_SZ);
22214 	scnprintf((char *)rd_object_name, sizeof(rd_object_name), rdobject);
22215 	for (j = 0; j < strlen(rdobject); j++)
22216 		read_object->u.request.rd_object_name[j] =
22217 			cpu_to_le32(rd_object_name[j]);
22218 
22219 	pcmd = kmalloc(sizeof(*pcmd), GFP_KERNEL);
22220 	if (pcmd)
22221 		pcmd->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &pcmd->phys);
22222 	if (!pcmd || !pcmd->virt) {
22223 		kfree(pcmd);
22224 		mempool_free(mbox, phba->mbox_mem_pool);
22225 		return -ENOMEM;
22226 	}
22227 	memset((void *)pcmd->virt, 0, LPFC_BPL_SIZE);
22228 	read_object->u.request.rd_object_hbuf[0].pa_lo =
22229 		putPaddrLow(pcmd->phys);
22230 	read_object->u.request.rd_object_hbuf[0].pa_hi =
22231 		putPaddrHigh(pcmd->phys);
22232 	read_object->u.request.rd_object_hbuf[0].length = LPFC_BPL_SIZE;
22233 
22234 	mbox->vport = phba->pport;
22235 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
22236 	mbox->ctx_ndlp = NULL;
22237 
22238 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
22239 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
22240 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
22241 
22242 	if (shdr_status == STATUS_FAILED &&
22243 	    shdr_add_status == ADD_STATUS_INVALID_OBJECT_NAME) {
22244 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22245 				"4674 No port cfg file in FW.\n");
22246 		byte_cnt = -ENOENT;
22247 	} else if (shdr_status || shdr_add_status || rc) {
22248 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22249 				"2625 READ_OBJECT mailbox failed with "
22250 				"status x%x add_status x%x, mbx status x%x\n",
22251 				shdr_status, shdr_add_status, rc);
22252 		byte_cnt = -ENXIO;
22253 	} else {
22254 		/* Success */
22255 		length = read_object->u.response.rd_object_actual_rlen;
22256 		eof = bf_get(lpfc_mbx_rd_object_eof, &read_object->u.response);
22257 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_CGN_MGMT,
22258 				"2626 READ_OBJECT Success len %d:%d, EOF %d\n",
22259 				length, datasz, eof);
22260 
22261 		/* Detect the port config file exists but is empty */
22262 		if (!length && eof) {
22263 			byte_cnt = 0;
22264 			goto exit;
22265 		}
22266 
22267 		byte_cnt = length;
22268 		lpfc_sli_pcimem_bcopy(pcmd->virt, datap, byte_cnt);
22269 	}
22270 
22271  exit:
22272 	/* This is an embedded SLI4 mailbox with an external buffer allocated.
22273 	 * Free the pcmd and then cleanup with the correct routine.
22274 	 */
22275 	lpfc_mbuf_free(phba, pcmd->virt, pcmd->phys);
22276 	kfree(pcmd);
22277 	lpfc_sli4_mbox_cmd_free(phba, mbox);
22278 	return byte_cnt;
22279 }
22280 
22281 /**
22282  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
22283  * @phba: The HBA for which this call is being executed.
22284  * @lpfc_buf: IO buf structure to append the SGL chunk
22285  *
22286  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
22287  * and will allocate an SGL chunk if the pool is empty.
22288  *
22289  * Return codes:
22290  *   NULL - Error
22291  *   Pointer to sli4_hybrid_sgl - Success
22292  **/
22293 struct sli4_hybrid_sgl *
22294 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22295 {
22296 	struct sli4_hybrid_sgl *list_entry = NULL;
22297 	struct sli4_hybrid_sgl *tmp = NULL;
22298 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
22299 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22300 	struct list_head *buf_list = &hdwq->sgl_list;
22301 	unsigned long iflags;
22302 
22303 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22304 
22305 	if (likely(!list_empty(buf_list))) {
22306 		/* break off 1 chunk from the sgl_list */
22307 		list_for_each_entry_safe(list_entry, tmp,
22308 					 buf_list, list_node) {
22309 			list_move_tail(&list_entry->list_node,
22310 				       &lpfc_buf->dma_sgl_xtra_list);
22311 			break;
22312 		}
22313 	} else {
22314 		/* allocate more */
22315 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22316 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22317 				   cpu_to_node(hdwq->io_wq->chann));
22318 		if (!tmp) {
22319 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22320 					"8353 error kmalloc memory for HDWQ "
22321 					"%d %s\n",
22322 					lpfc_buf->hdwq_no, __func__);
22323 			return NULL;
22324 		}
22325 
22326 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
22327 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
22328 		if (!tmp->dma_sgl) {
22329 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22330 					"8354 error pool_alloc memory for HDWQ "
22331 					"%d %s\n",
22332 					lpfc_buf->hdwq_no, __func__);
22333 			kfree(tmp);
22334 			return NULL;
22335 		}
22336 
22337 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22338 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
22339 	}
22340 
22341 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
22342 					struct sli4_hybrid_sgl,
22343 					list_node);
22344 
22345 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22346 
22347 	return allocated_sgl;
22348 }
22349 
22350 /**
22351  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
22352  * @phba: The HBA for which this call is being executed.
22353  * @lpfc_buf: IO buf structure with the SGL chunk
22354  *
22355  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
22356  *
22357  * Return codes:
22358  *   0 - Success
22359  *   -EINVAL - Error
22360  **/
22361 int
22362 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22363 {
22364 	int rc = 0;
22365 	struct sli4_hybrid_sgl *list_entry = NULL;
22366 	struct sli4_hybrid_sgl *tmp = NULL;
22367 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22368 	struct list_head *buf_list = &hdwq->sgl_list;
22369 	unsigned long iflags;
22370 
22371 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22372 
22373 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
22374 		list_for_each_entry_safe(list_entry, tmp,
22375 					 &lpfc_buf->dma_sgl_xtra_list,
22376 					 list_node) {
22377 			list_move_tail(&list_entry->list_node,
22378 				       buf_list);
22379 		}
22380 	} else {
22381 		rc = -EINVAL;
22382 	}
22383 
22384 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22385 	return rc;
22386 }
22387 
22388 /**
22389  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
22390  * @phba: phba object
22391  * @hdwq: hdwq to cleanup sgl buff resources on
22392  *
22393  * This routine frees all SGL chunks of hdwq SGL chunk pool.
22394  *
22395  * Return codes:
22396  *   None
22397  **/
22398 void
22399 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
22400 		       struct lpfc_sli4_hdw_queue *hdwq)
22401 {
22402 	struct list_head *buf_list = &hdwq->sgl_list;
22403 	struct sli4_hybrid_sgl *list_entry = NULL;
22404 	struct sli4_hybrid_sgl *tmp = NULL;
22405 	unsigned long iflags;
22406 
22407 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22408 
22409 	/* Free sgl pool */
22410 	list_for_each_entry_safe(list_entry, tmp,
22411 				 buf_list, list_node) {
22412 		list_del(&list_entry->list_node);
22413 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
22414 			      list_entry->dma_sgl,
22415 			      list_entry->dma_phys_sgl);
22416 		kfree(list_entry);
22417 	}
22418 
22419 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22420 }
22421 
22422 /**
22423  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
22424  * @phba: The HBA for which this call is being executed.
22425  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
22426  *
22427  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
22428  * and will allocate an CMD/RSP buffer if the pool is empty.
22429  *
22430  * Return codes:
22431  *   NULL - Error
22432  *   Pointer to fcp_cmd_rsp_buf - Success
22433  **/
22434 struct fcp_cmd_rsp_buf *
22435 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22436 			      struct lpfc_io_buf *lpfc_buf)
22437 {
22438 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22439 	struct fcp_cmd_rsp_buf *tmp = NULL;
22440 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
22441 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22442 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22443 	unsigned long iflags;
22444 
22445 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22446 
22447 	if (likely(!list_empty(buf_list))) {
22448 		/* break off 1 chunk from the list */
22449 		list_for_each_entry_safe(list_entry, tmp,
22450 					 buf_list,
22451 					 list_node) {
22452 			list_move_tail(&list_entry->list_node,
22453 				       &lpfc_buf->dma_cmd_rsp_list);
22454 			break;
22455 		}
22456 	} else {
22457 		/* allocate more */
22458 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22459 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22460 				   cpu_to_node(hdwq->io_wq->chann));
22461 		if (!tmp) {
22462 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22463 					"8355 error kmalloc memory for HDWQ "
22464 					"%d %s\n",
22465 					lpfc_buf->hdwq_no, __func__);
22466 			return NULL;
22467 		}
22468 
22469 		tmp->fcp_cmnd = dma_pool_zalloc(phba->lpfc_cmd_rsp_buf_pool,
22470 						GFP_ATOMIC,
22471 						&tmp->fcp_cmd_rsp_dma_handle);
22472 
22473 		if (!tmp->fcp_cmnd) {
22474 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22475 					"8356 error pool_alloc memory for HDWQ "
22476 					"%d %s\n",
22477 					lpfc_buf->hdwq_no, __func__);
22478 			kfree(tmp);
22479 			return NULL;
22480 		}
22481 
22482 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
22483 				sizeof(struct fcp_cmnd));
22484 
22485 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22486 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
22487 	}
22488 
22489 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
22490 					struct fcp_cmd_rsp_buf,
22491 					list_node);
22492 
22493 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22494 
22495 	return allocated_buf;
22496 }
22497 
22498 /**
22499  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
22500  * @phba: The HBA for which this call is being executed.
22501  * @lpfc_buf: IO buf structure with the CMD/RSP buf
22502  *
22503  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
22504  *
22505  * Return codes:
22506  *   0 - Success
22507  *   -EINVAL - Error
22508  **/
22509 int
22510 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22511 			      struct lpfc_io_buf *lpfc_buf)
22512 {
22513 	int rc = 0;
22514 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22515 	struct fcp_cmd_rsp_buf *tmp = NULL;
22516 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22517 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22518 	unsigned long iflags;
22519 
22520 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22521 
22522 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
22523 		list_for_each_entry_safe(list_entry, tmp,
22524 					 &lpfc_buf->dma_cmd_rsp_list,
22525 					 list_node) {
22526 			list_move_tail(&list_entry->list_node,
22527 				       buf_list);
22528 		}
22529 	} else {
22530 		rc = -EINVAL;
22531 	}
22532 
22533 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22534 	return rc;
22535 }
22536 
22537 /**
22538  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
22539  * @phba: phba object
22540  * @hdwq: hdwq to cleanup cmd rsp buff resources on
22541  *
22542  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
22543  *
22544  * Return codes:
22545  *   None
22546  **/
22547 void
22548 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22549 			       struct lpfc_sli4_hdw_queue *hdwq)
22550 {
22551 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22552 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22553 	struct fcp_cmd_rsp_buf *tmp = NULL;
22554 	unsigned long iflags;
22555 
22556 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22557 
22558 	/* Free cmd_rsp buf pool */
22559 	list_for_each_entry_safe(list_entry, tmp,
22560 				 buf_list,
22561 				 list_node) {
22562 		list_del(&list_entry->list_node);
22563 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
22564 			      list_entry->fcp_cmnd,
22565 			      list_entry->fcp_cmd_rsp_dma_handle);
22566 		kfree(list_entry);
22567 	}
22568 
22569 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22570 }
22571 
22572 /**
22573  * lpfc_sli_prep_wqe - Prepare WQE for the command to be posted
22574  * @phba: phba object
22575  * @job: job entry of the command to be posted.
22576  *
22577  * Fill the common fields of the wqe for each of the command.
22578  *
22579  * Return codes:
22580  *	None
22581  **/
22582 void
22583 lpfc_sli_prep_wqe(struct lpfc_hba *phba, struct lpfc_iocbq *job)
22584 {
22585 	u8 cmnd;
22586 	u32 *pcmd;
22587 	u32 if_type = 0;
22588 	u32 fip, abort_tag;
22589 	struct lpfc_nodelist *ndlp = NULL;
22590 	union lpfc_wqe128 *wqe = &job->wqe;
22591 	u8 command_type = ELS_COMMAND_NON_FIP;
22592 
22593 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
22594 	/* The fcp commands will set command type */
22595 	if (job->cmd_flag &  LPFC_IO_FCP)
22596 		command_type = FCP_COMMAND;
22597 	else if (fip && (job->cmd_flag & LPFC_FIP_ELS_ID_MASK))
22598 		command_type = ELS_COMMAND_FIP;
22599 	else
22600 		command_type = ELS_COMMAND_NON_FIP;
22601 
22602 	abort_tag = job->iotag;
22603 	cmnd = bf_get(wqe_cmnd, &wqe->els_req.wqe_com);
22604 
22605 	switch (cmnd) {
22606 	case CMD_ELS_REQUEST64_WQE:
22607 		ndlp = job->ndlp;
22608 
22609 		if_type = bf_get(lpfc_sli_intf_if_type,
22610 				 &phba->sli4_hba.sli_intf);
22611 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22612 			pcmd = (u32 *)job->cmd_dmabuf->virt;
22613 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
22614 				     *pcmd == ELS_CMD_SCR ||
22615 				     *pcmd == ELS_CMD_RDF ||
22616 				     *pcmd == ELS_CMD_EDC ||
22617 				     *pcmd == ELS_CMD_RSCN_XMT ||
22618 				     *pcmd == ELS_CMD_FDISC ||
22619 				     *pcmd == ELS_CMD_LOGO ||
22620 				     *pcmd == ELS_CMD_QFPA ||
22621 				     *pcmd == ELS_CMD_UVEM ||
22622 				     *pcmd == ELS_CMD_PLOGI)) {
22623 				bf_set(els_req64_sp, &wqe->els_req, 1);
22624 				bf_set(els_req64_sid, &wqe->els_req,
22625 				       job->vport->fc_myDID);
22626 
22627 				if ((*pcmd == ELS_CMD_FLOGI) &&
22628 				    !(phba->fc_topology ==
22629 				      LPFC_TOPOLOGY_LOOP))
22630 					bf_set(els_req64_sid, &wqe->els_req, 0);
22631 
22632 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
22633 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22634 				       phba->vpi_ids[job->vport->vpi]);
22635 			} else if (pcmd) {
22636 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
22637 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22638 				       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22639 			}
22640 		}
22641 
22642 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
22643 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22644 
22645 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
22646 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
22647 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
22648 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22649 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
22650 		break;
22651 	case CMD_XMIT_ELS_RSP64_WQE:
22652 		ndlp = job->ndlp;
22653 
22654 		/* word4 */
22655 		wqe->xmit_els_rsp.word4 = 0;
22656 
22657 		if_type = bf_get(lpfc_sli_intf_if_type,
22658 				 &phba->sli4_hba.sli_intf);
22659 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22660 			if (job->vport->fc_flag & FC_PT2PT) {
22661 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22662 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22663 				       job->vport->fc_myDID);
22664 				if (job->vport->fc_myDID == Fabric_DID) {
22665 					bf_set(wqe_els_did,
22666 					       &wqe->xmit_els_rsp.wqe_dest, 0);
22667 				}
22668 			}
22669 		}
22670 
22671 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
22672 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
22673 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
22674 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
22675 		       LPFC_WQE_LENLOC_WORD3);
22676 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
22677 
22678 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
22679 			bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22680 			bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22681 			       job->vport->fc_myDID);
22682 			bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
22683 		}
22684 
22685 		if (phba->sli_rev == LPFC_SLI_REV4) {
22686 			bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
22687 			       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22688 
22689 			if (bf_get(wqe_ct, &wqe->xmit_els_rsp.wqe_com))
22690 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
22691 				       phba->vpi_ids[job->vport->vpi]);
22692 		}
22693 		command_type = OTHER_COMMAND;
22694 		break;
22695 	case CMD_GEN_REQUEST64_WQE:
22696 		/* Word 10 */
22697 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
22698 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
22699 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
22700 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22701 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
22702 		command_type = OTHER_COMMAND;
22703 		break;
22704 	case CMD_XMIT_SEQUENCE64_WQE:
22705 		if (phba->link_flag & LS_LOOPBACK_MODE)
22706 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
22707 
22708 		wqe->xmit_sequence.rsvd3 = 0;
22709 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
22710 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
22711 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
22712 		       LPFC_WQE_IOD_WRITE);
22713 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
22714 		       LPFC_WQE_LENLOC_WORD12);
22715 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
22716 		command_type = OTHER_COMMAND;
22717 		break;
22718 	case CMD_XMIT_BLS_RSP64_WQE:
22719 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
22720 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
22721 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
22722 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
22723 		       phba->vpi_ids[phba->pport->vpi]);
22724 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
22725 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
22726 		       LPFC_WQE_LENLOC_NONE);
22727 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
22728 		command_type = OTHER_COMMAND;
22729 		break;
22730 	case CMD_FCP_ICMND64_WQE:	/* task mgmt commands */
22731 	case CMD_ABORT_XRI_WQE:		/* abort iotag */
22732 	case CMD_SEND_FRAME:		/* mds loopback */
22733 		/* cases already formatted for sli4 wqe - no chgs necessary */
22734 		return;
22735 	default:
22736 		dump_stack();
22737 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
22738 				"6207 Invalid command 0x%x\n",
22739 				cmnd);
22740 		break;
22741 	}
22742 
22743 	wqe->generic.wqe_com.abort_tag = abort_tag;
22744 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, job->iotag);
22745 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
22746 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
22747 }
22748