xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision 47ebd031)
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/aer.h>
38 #include <linux/crash_dump.h>
39 #ifdef CONFIG_X86
40 #include <asm/set_memory.h>
41 #endif
42 
43 #include "lpfc_hw4.h"
44 #include "lpfc_hw.h"
45 #include "lpfc_sli.h"
46 #include "lpfc_sli4.h"
47 #include "lpfc_nl.h"
48 #include "lpfc_disc.h"
49 #include "lpfc.h"
50 #include "lpfc_scsi.h"
51 #include "lpfc_nvme.h"
52 #include "lpfc_crtn.h"
53 #include "lpfc_logmsg.h"
54 #include "lpfc_compat.h"
55 #include "lpfc_debugfs.h"
56 #include "lpfc_vport.h"
57 #include "lpfc_version.h"
58 
59 /* There are only four IOCB completion types. */
60 typedef enum _lpfc_iocb_type {
61 	LPFC_UNKNOWN_IOCB,
62 	LPFC_UNSOL_IOCB,
63 	LPFC_SOL_IOCB,
64 	LPFC_ABORT_IOCB
65 } lpfc_iocb_type;
66 
67 
68 /* Provide function prototypes local to this module. */
69 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
70 				  uint32_t);
71 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
72 			      uint8_t *, uint32_t *);
73 static struct lpfc_iocbq *
74 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
75 				  struct lpfc_iocbq *rspiocbq);
76 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
77 				      struct hbq_dmabuf *);
78 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
79 					  struct hbq_dmabuf *dmabuf);
80 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
81 				   struct lpfc_queue *cq, struct lpfc_cqe *cqe);
82 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
83 				       int);
84 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
85 				     struct lpfc_queue *eq,
86 				     struct lpfc_eqe *eqe);
87 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
88 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
89 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
90 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
91 				    struct lpfc_queue *cq,
92 				    struct lpfc_cqe *cqe);
93 static uint16_t lpfc_wqe_bpl2sgl(struct lpfc_hba *phba,
94 				 struct lpfc_iocbq *pwqeq,
95 				 struct lpfc_sglq *sglq);
96 
97 union lpfc_wqe128 lpfc_iread_cmd_template;
98 union lpfc_wqe128 lpfc_iwrite_cmd_template;
99 union lpfc_wqe128 lpfc_icmnd_cmd_template;
100 
101 /* Setup WQE templates for IOs */
102 void lpfc_wqe_cmd_template(void)
103 {
104 	union lpfc_wqe128 *wqe;
105 
106 	/* IREAD template */
107 	wqe = &lpfc_iread_cmd_template;
108 	memset(wqe, 0, sizeof(union lpfc_wqe128));
109 
110 	/* Word 0, 1, 2 - BDE is variable */
111 
112 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
113 
114 	/* Word 4 - total_xfer_len is variable */
115 
116 	/* Word 5 - is zero */
117 
118 	/* Word 6 - ctxt_tag, xri_tag is variable */
119 
120 	/* Word 7 */
121 	bf_set(wqe_cmnd, &wqe->fcp_iread.wqe_com, CMD_FCP_IREAD64_WQE);
122 	bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, PARM_READ_CHECK);
123 	bf_set(wqe_class, &wqe->fcp_iread.wqe_com, CLASS3);
124 	bf_set(wqe_ct, &wqe->fcp_iread.wqe_com, SLI4_CT_RPI);
125 
126 	/* Word 8 - abort_tag is variable */
127 
128 	/* Word 9  - reqtag is variable */
129 
130 	/* Word 10 - dbde, wqes is variable */
131 	bf_set(wqe_qosd, &wqe->fcp_iread.wqe_com, 0);
132 	bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
133 	bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com, LPFC_WQE_LENLOC_WORD4);
134 	bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
135 	bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
136 
137 	/* Word 11 - pbde is variable */
138 	bf_set(wqe_cmd_type, &wqe->fcp_iread.wqe_com, COMMAND_DATA_IN);
139 	bf_set(wqe_cqid, &wqe->fcp_iread.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
140 	bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
141 
142 	/* Word 12 - is zero */
143 
144 	/* Word 13, 14, 15 - PBDE is variable */
145 
146 	/* IWRITE template */
147 	wqe = &lpfc_iwrite_cmd_template;
148 	memset(wqe, 0, sizeof(union lpfc_wqe128));
149 
150 	/* Word 0, 1, 2 - BDE is variable */
151 
152 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
153 
154 	/* Word 4 - total_xfer_len is variable */
155 
156 	/* Word 5 - initial_xfer_len is variable */
157 
158 	/* Word 6 - ctxt_tag, xri_tag is variable */
159 
160 	/* Word 7 */
161 	bf_set(wqe_cmnd, &wqe->fcp_iwrite.wqe_com, CMD_FCP_IWRITE64_WQE);
162 	bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, PARM_READ_CHECK);
163 	bf_set(wqe_class, &wqe->fcp_iwrite.wqe_com, CLASS3);
164 	bf_set(wqe_ct, &wqe->fcp_iwrite.wqe_com, SLI4_CT_RPI);
165 
166 	/* Word 8 - abort_tag is variable */
167 
168 	/* Word 9  - reqtag is variable */
169 
170 	/* Word 10 - dbde, wqes is variable */
171 	bf_set(wqe_qosd, &wqe->fcp_iwrite.wqe_com, 0);
172 	bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
173 	bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_LENLOC_WORD4);
174 	bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
175 	bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
176 
177 	/* Word 11 - pbde is variable */
178 	bf_set(wqe_cmd_type, &wqe->fcp_iwrite.wqe_com, COMMAND_DATA_OUT);
179 	bf_set(wqe_cqid, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
180 	bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
181 
182 	/* Word 12 - is zero */
183 
184 	/* Word 13, 14, 15 - PBDE is variable */
185 
186 	/* ICMND template */
187 	wqe = &lpfc_icmnd_cmd_template;
188 	memset(wqe, 0, sizeof(union lpfc_wqe128));
189 
190 	/* Word 0, 1, 2 - BDE is variable */
191 
192 	/* Word 3 - payload_offset_len is variable */
193 
194 	/* Word 4, 5 - is zero */
195 
196 	/* Word 6 - ctxt_tag, xri_tag is variable */
197 
198 	/* Word 7 */
199 	bf_set(wqe_cmnd, &wqe->fcp_icmd.wqe_com, CMD_FCP_ICMND64_WQE);
200 	bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
201 	bf_set(wqe_class, &wqe->fcp_icmd.wqe_com, CLASS3);
202 	bf_set(wqe_ct, &wqe->fcp_icmd.wqe_com, SLI4_CT_RPI);
203 
204 	/* Word 8 - abort_tag is variable */
205 
206 	/* Word 9  - reqtag is variable */
207 
208 	/* Word 10 - dbde, wqes is variable */
209 	bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
210 	bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_NONE);
211 	bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com, LPFC_WQE_LENLOC_NONE);
212 	bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
213 	bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
214 
215 	/* Word 11 */
216 	bf_set(wqe_cmd_type, &wqe->fcp_icmd.wqe_com, COMMAND_DATA_IN);
217 	bf_set(wqe_cqid, &wqe->fcp_icmd.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
218 	bf_set(wqe_pbde, &wqe->fcp_icmd.wqe_com, 0);
219 
220 	/* Word 12, 13, 14, 15 - is zero */
221 }
222 
223 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
224 /**
225  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
226  * @srcp: Source memory pointer.
227  * @destp: Destination memory pointer.
228  * @cnt: Number of words required to be copied.
229  *       Must be a multiple of sizeof(uint64_t)
230  *
231  * This function is used for copying data between driver memory
232  * and the SLI WQ. This function also changes the endianness
233  * of each word if native endianness is different from SLI
234  * endianness. This function can be called with or without
235  * lock.
236  **/
237 static void
238 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
239 {
240 	uint64_t *src = srcp;
241 	uint64_t *dest = destp;
242 	int i;
243 
244 	for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
245 		*dest++ = *src++;
246 }
247 #else
248 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
249 #endif
250 
251 /**
252  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
253  * @q: The Work Queue to operate on.
254  * @wqe: The work Queue Entry to put on the Work queue.
255  *
256  * This routine will copy the contents of @wqe to the next available entry on
257  * the @q. This function will then ring the Work Queue Doorbell to signal the
258  * HBA to start processing the Work Queue Entry. This function returns 0 if
259  * successful. If no entries are available on @q then this function will return
260  * -ENOMEM.
261  * The caller is expected to hold the hbalock when calling this routine.
262  **/
263 static int
264 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
265 {
266 	union lpfc_wqe *temp_wqe;
267 	struct lpfc_register doorbell;
268 	uint32_t host_index;
269 	uint32_t idx;
270 	uint32_t i = 0;
271 	uint8_t *tmp;
272 	u32 if_type;
273 
274 	/* sanity check on queue memory */
275 	if (unlikely(!q))
276 		return -ENOMEM;
277 
278 	temp_wqe = lpfc_sli4_qe(q, q->host_index);
279 
280 	/* If the host has not yet processed the next entry then we are done */
281 	idx = ((q->host_index + 1) % q->entry_count);
282 	if (idx == q->hba_index) {
283 		q->WQ_overflow++;
284 		return -EBUSY;
285 	}
286 	q->WQ_posted++;
287 	/* set consumption flag every once in a while */
288 	if (!((q->host_index + 1) % q->notify_interval))
289 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
290 	else
291 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
292 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
293 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
294 	lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
295 	if (q->dpp_enable && q->phba->cfg_enable_dpp) {
296 		/* write to DPP aperture taking advatage of Combined Writes */
297 		tmp = (uint8_t *)temp_wqe;
298 #ifdef __raw_writeq
299 		for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
300 			__raw_writeq(*((uint64_t *)(tmp + i)),
301 					q->dpp_regaddr + i);
302 #else
303 		for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
304 			__raw_writel(*((uint32_t *)(tmp + i)),
305 					q->dpp_regaddr + i);
306 #endif
307 	}
308 	/* ensure WQE bcopy and DPP flushed before doorbell write */
309 	wmb();
310 
311 	/* Update the host index before invoking device */
312 	host_index = q->host_index;
313 
314 	q->host_index = idx;
315 
316 	/* Ring Doorbell */
317 	doorbell.word0 = 0;
318 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
319 		if (q->dpp_enable && q->phba->cfg_enable_dpp) {
320 			bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
321 			bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
322 			bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
323 			    q->dpp_id);
324 			bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
325 			    q->queue_id);
326 		} else {
327 			bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
328 			bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
329 
330 			/* Leave bits <23:16> clear for if_type 6 dpp */
331 			if_type = bf_get(lpfc_sli_intf_if_type,
332 					 &q->phba->sli4_hba.sli_intf);
333 			if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
334 				bf_set(lpfc_wq_db_list_fm_index, &doorbell,
335 				       host_index);
336 		}
337 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
338 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
339 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
340 	} else {
341 		return -EINVAL;
342 	}
343 	writel(doorbell.word0, q->db_regaddr);
344 
345 	return 0;
346 }
347 
348 /**
349  * lpfc_sli4_wq_release - Updates internal hba index for WQ
350  * @q: The Work Queue to operate on.
351  * @index: The index to advance the hba index to.
352  *
353  * This routine will update the HBA index of a queue to reflect consumption of
354  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
355  * an entry the host calls this function to update the queue's internal
356  * pointers.
357  **/
358 static void
359 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
360 {
361 	/* sanity check on queue memory */
362 	if (unlikely(!q))
363 		return;
364 
365 	q->hba_index = index;
366 }
367 
368 /**
369  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
370  * @q: The Mailbox Queue to operate on.
371  * @mqe: The Mailbox Queue Entry to put on the Work queue.
372  *
373  * This routine will copy the contents of @mqe to the next available entry on
374  * the @q. This function will then ring the Work Queue Doorbell to signal the
375  * HBA to start processing the Work Queue Entry. This function returns 0 if
376  * successful. If no entries are available on @q then this function will return
377  * -ENOMEM.
378  * The caller is expected to hold the hbalock when calling this routine.
379  **/
380 static uint32_t
381 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
382 {
383 	struct lpfc_mqe *temp_mqe;
384 	struct lpfc_register doorbell;
385 
386 	/* sanity check on queue memory */
387 	if (unlikely(!q))
388 		return -ENOMEM;
389 	temp_mqe = lpfc_sli4_qe(q, q->host_index);
390 
391 	/* If the host has not yet processed the next entry then we are done */
392 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
393 		return -ENOMEM;
394 	lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
395 	/* Save off the mailbox pointer for completion */
396 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
397 
398 	/* Update the host index before invoking device */
399 	q->host_index = ((q->host_index + 1) % q->entry_count);
400 
401 	/* Ring Doorbell */
402 	doorbell.word0 = 0;
403 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
404 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
405 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
406 	return 0;
407 }
408 
409 /**
410  * lpfc_sli4_mq_release - Updates internal hba index for MQ
411  * @q: The Mailbox Queue to operate on.
412  *
413  * This routine will update the HBA index of a queue to reflect consumption of
414  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
415  * an entry the host calls this function to update the queue's internal
416  * pointers. This routine returns the number of entries that were consumed by
417  * the HBA.
418  **/
419 static uint32_t
420 lpfc_sli4_mq_release(struct lpfc_queue *q)
421 {
422 	/* sanity check on queue memory */
423 	if (unlikely(!q))
424 		return 0;
425 
426 	/* Clear the mailbox pointer for completion */
427 	q->phba->mbox = NULL;
428 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
429 	return 1;
430 }
431 
432 /**
433  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
434  * @q: The Event Queue to get the first valid EQE from
435  *
436  * This routine will get the first valid Event Queue Entry from @q, update
437  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
438  * the Queue (no more work to do), or the Queue is full of EQEs that have been
439  * processed, but not popped back to the HBA then this routine will return NULL.
440  **/
441 static struct lpfc_eqe *
442 lpfc_sli4_eq_get(struct lpfc_queue *q)
443 {
444 	struct lpfc_eqe *eqe;
445 
446 	/* sanity check on queue memory */
447 	if (unlikely(!q))
448 		return NULL;
449 	eqe = lpfc_sli4_qe(q, q->host_index);
450 
451 	/* If the next EQE is not valid then we are done */
452 	if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
453 		return NULL;
454 
455 	/*
456 	 * insert barrier for instruction interlock : data from the hardware
457 	 * must have the valid bit checked before it can be copied and acted
458 	 * upon. Speculative instructions were allowing a bcopy at the start
459 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
460 	 * after our return, to copy data before the valid bit check above
461 	 * was done. As such, some of the copied data was stale. The barrier
462 	 * ensures the check is before any data is copied.
463 	 */
464 	mb();
465 	return eqe;
466 }
467 
468 /**
469  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
470  * @q: The Event Queue to disable interrupts
471  *
472  **/
473 void
474 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
475 {
476 	struct lpfc_register doorbell;
477 
478 	doorbell.word0 = 0;
479 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
480 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
481 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
482 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
483 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
484 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
485 }
486 
487 /**
488  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
489  * @q: The Event Queue to disable interrupts
490  *
491  **/
492 void
493 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
494 {
495 	struct lpfc_register doorbell;
496 
497 	doorbell.word0 = 0;
498 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
499 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
500 }
501 
502 /**
503  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
504  * @phba: adapter with EQ
505  * @q: The Event Queue that the host has completed processing for.
506  * @count: Number of elements that have been consumed
507  * @arm: Indicates whether the host wants to arms this CQ.
508  *
509  * This routine will notify the HBA, by ringing the doorbell, that count
510  * number of EQEs have been processed. The @arm parameter indicates whether
511  * the queue should be rearmed when ringing the doorbell.
512  **/
513 void
514 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
515 		     uint32_t count, bool arm)
516 {
517 	struct lpfc_register doorbell;
518 
519 	/* sanity check on queue memory */
520 	if (unlikely(!q || (count == 0 && !arm)))
521 		return;
522 
523 	/* ring doorbell for number popped */
524 	doorbell.word0 = 0;
525 	if (arm) {
526 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
527 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
528 	}
529 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
530 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
531 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
532 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
533 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
534 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
535 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
536 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
537 		readl(q->phba->sli4_hba.EQDBregaddr);
538 }
539 
540 /**
541  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
542  * @phba: adapter with EQ
543  * @q: The Event Queue that the host has completed processing for.
544  * @count: Number of elements that have been consumed
545  * @arm: Indicates whether the host wants to arms this CQ.
546  *
547  * This routine will notify the HBA, by ringing the doorbell, that count
548  * number of EQEs have been processed. The @arm parameter indicates whether
549  * the queue should be rearmed when ringing the doorbell.
550  **/
551 void
552 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
553 			  uint32_t count, bool arm)
554 {
555 	struct lpfc_register doorbell;
556 
557 	/* sanity check on queue memory */
558 	if (unlikely(!q || (count == 0 && !arm)))
559 		return;
560 
561 	/* ring doorbell for number popped */
562 	doorbell.word0 = 0;
563 	if (arm)
564 		bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
565 	bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
566 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
567 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
568 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
569 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
570 		readl(q->phba->sli4_hba.EQDBregaddr);
571 }
572 
573 static void
574 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
575 			struct lpfc_eqe *eqe)
576 {
577 	if (!phba->sli4_hba.pc_sli4_params.eqav)
578 		bf_set_le32(lpfc_eqe_valid, eqe, 0);
579 
580 	eq->host_index = ((eq->host_index + 1) % eq->entry_count);
581 
582 	/* if the index wrapped around, toggle the valid bit */
583 	if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
584 		eq->qe_valid = (eq->qe_valid) ? 0 : 1;
585 }
586 
587 static void
588 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
589 {
590 	struct lpfc_eqe *eqe = NULL;
591 	u32 eq_count = 0, cq_count = 0;
592 	struct lpfc_cqe *cqe = NULL;
593 	struct lpfc_queue *cq = NULL, *childq = NULL;
594 	int cqid = 0;
595 
596 	/* walk all the EQ entries and drop on the floor */
597 	eqe = lpfc_sli4_eq_get(eq);
598 	while (eqe) {
599 		/* Get the reference to the corresponding CQ */
600 		cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
601 		cq = NULL;
602 
603 		list_for_each_entry(childq, &eq->child_list, list) {
604 			if (childq->queue_id == cqid) {
605 				cq = childq;
606 				break;
607 			}
608 		}
609 		/* If CQ is valid, iterate through it and drop all the CQEs */
610 		if (cq) {
611 			cqe = lpfc_sli4_cq_get(cq);
612 			while (cqe) {
613 				__lpfc_sli4_consume_cqe(phba, cq, cqe);
614 				cq_count++;
615 				cqe = lpfc_sli4_cq_get(cq);
616 			}
617 			/* Clear and re-arm the CQ */
618 			phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
619 			    LPFC_QUEUE_REARM);
620 			cq_count = 0;
621 		}
622 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
623 		eq_count++;
624 		eqe = lpfc_sli4_eq_get(eq);
625 	}
626 
627 	/* Clear and re-arm the EQ */
628 	phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
629 }
630 
631 static int
632 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
633 		     uint8_t rearm)
634 {
635 	struct lpfc_eqe *eqe;
636 	int count = 0, consumed = 0;
637 
638 	if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
639 		goto rearm_and_exit;
640 
641 	eqe = lpfc_sli4_eq_get(eq);
642 	while (eqe) {
643 		lpfc_sli4_hba_handle_eqe(phba, eq, eqe);
644 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
645 
646 		consumed++;
647 		if (!(++count % eq->max_proc_limit))
648 			break;
649 
650 		if (!(count % eq->notify_interval)) {
651 			phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
652 							LPFC_QUEUE_NOARM);
653 			consumed = 0;
654 		}
655 
656 		eqe = lpfc_sli4_eq_get(eq);
657 	}
658 	eq->EQ_processed += count;
659 
660 	/* Track the max number of EQEs processed in 1 intr */
661 	if (count > eq->EQ_max_eqe)
662 		eq->EQ_max_eqe = count;
663 
664 	xchg(&eq->queue_claimed, 0);
665 
666 rearm_and_exit:
667 	/* Always clear the EQ. */
668 	phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
669 
670 	return count;
671 }
672 
673 /**
674  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
675  * @q: The Completion Queue to get the first valid CQE from
676  *
677  * This routine will get the first valid Completion Queue Entry from @q, update
678  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
679  * the Queue (no more work to do), or the Queue is full of CQEs that have been
680  * processed, but not popped back to the HBA then this routine will return NULL.
681  **/
682 static struct lpfc_cqe *
683 lpfc_sli4_cq_get(struct lpfc_queue *q)
684 {
685 	struct lpfc_cqe *cqe;
686 
687 	/* sanity check on queue memory */
688 	if (unlikely(!q))
689 		return NULL;
690 	cqe = lpfc_sli4_qe(q, q->host_index);
691 
692 	/* If the next CQE is not valid then we are done */
693 	if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
694 		return NULL;
695 
696 	/*
697 	 * insert barrier for instruction interlock : data from the hardware
698 	 * must have the valid bit checked before it can be copied and acted
699 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
700 	 * instructions allowing action on content before valid bit checked,
701 	 * add barrier here as well. May not be needed as "content" is a
702 	 * single 32-bit entity here (vs multi word structure for cq's).
703 	 */
704 	mb();
705 	return cqe;
706 }
707 
708 static void
709 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
710 			struct lpfc_cqe *cqe)
711 {
712 	if (!phba->sli4_hba.pc_sli4_params.cqav)
713 		bf_set_le32(lpfc_cqe_valid, cqe, 0);
714 
715 	cq->host_index = ((cq->host_index + 1) % cq->entry_count);
716 
717 	/* if the index wrapped around, toggle the valid bit */
718 	if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
719 		cq->qe_valid = (cq->qe_valid) ? 0 : 1;
720 }
721 
722 /**
723  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
724  * @phba: the adapter with the CQ
725  * @q: The Completion Queue that the host has completed processing for.
726  * @count: the number of elements that were consumed
727  * @arm: Indicates whether the host wants to arms this CQ.
728  *
729  * This routine will notify the HBA, by ringing the doorbell, that the
730  * CQEs have been processed. The @arm parameter specifies whether the
731  * queue should be rearmed when ringing the doorbell.
732  **/
733 void
734 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
735 		     uint32_t count, bool arm)
736 {
737 	struct lpfc_register doorbell;
738 
739 	/* sanity check on queue memory */
740 	if (unlikely(!q || (count == 0 && !arm)))
741 		return;
742 
743 	/* ring doorbell for number popped */
744 	doorbell.word0 = 0;
745 	if (arm)
746 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
747 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
748 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
749 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
750 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
751 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
752 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
753 }
754 
755 /**
756  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
757  * @phba: the adapter with the CQ
758  * @q: The Completion Queue that the host has completed processing for.
759  * @count: the number of elements that were consumed
760  * @arm: Indicates whether the host wants to arms this CQ.
761  *
762  * This routine will notify the HBA, by ringing the doorbell, that the
763  * CQEs have been processed. The @arm parameter specifies whether the
764  * queue should be rearmed when ringing the doorbell.
765  **/
766 void
767 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
768 			 uint32_t count, bool arm)
769 {
770 	struct lpfc_register doorbell;
771 
772 	/* sanity check on queue memory */
773 	if (unlikely(!q || (count == 0 && !arm)))
774 		return;
775 
776 	/* ring doorbell for number popped */
777 	doorbell.word0 = 0;
778 	if (arm)
779 		bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
780 	bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
781 	bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
782 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
783 }
784 
785 /*
786  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
787  *
788  * This routine will copy the contents of @wqe to the next available entry on
789  * the @q. This function will then ring the Receive Queue Doorbell to signal the
790  * HBA to start processing the Receive Queue Entry. This function returns the
791  * index that the rqe was copied to if successful. If no entries are available
792  * on @q then this function will return -ENOMEM.
793  * The caller is expected to hold the hbalock when calling this routine.
794  **/
795 int
796 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
797 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
798 {
799 	struct lpfc_rqe *temp_hrqe;
800 	struct lpfc_rqe *temp_drqe;
801 	struct lpfc_register doorbell;
802 	int hq_put_index;
803 	int dq_put_index;
804 
805 	/* sanity check on queue memory */
806 	if (unlikely(!hq) || unlikely(!dq))
807 		return -ENOMEM;
808 	hq_put_index = hq->host_index;
809 	dq_put_index = dq->host_index;
810 	temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
811 	temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
812 
813 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
814 		return -EINVAL;
815 	if (hq_put_index != dq_put_index)
816 		return -EINVAL;
817 	/* If the host has not yet processed the next entry then we are done */
818 	if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
819 		return -EBUSY;
820 	lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
821 	lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
822 
823 	/* Update the host index to point to the next slot */
824 	hq->host_index = ((hq_put_index + 1) % hq->entry_count);
825 	dq->host_index = ((dq_put_index + 1) % dq->entry_count);
826 	hq->RQ_buf_posted++;
827 
828 	/* Ring The Header Receive Queue Doorbell */
829 	if (!(hq->host_index % hq->notify_interval)) {
830 		doorbell.word0 = 0;
831 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
832 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
833 			       hq->notify_interval);
834 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
835 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
836 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
837 			       hq->notify_interval);
838 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
839 			       hq->host_index);
840 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
841 		} else {
842 			return -EINVAL;
843 		}
844 		writel(doorbell.word0, hq->db_regaddr);
845 	}
846 	return hq_put_index;
847 }
848 
849 /*
850  * lpfc_sli4_rq_release - Updates internal hba index for RQ
851  *
852  * This routine will update the HBA index of a queue to reflect consumption of
853  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
854  * consumed an entry the host calls this function to update the queue's
855  * internal pointers. This routine returns the number of entries that were
856  * consumed by the HBA.
857  **/
858 static uint32_t
859 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
860 {
861 	/* sanity check on queue memory */
862 	if (unlikely(!hq) || unlikely(!dq))
863 		return 0;
864 
865 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
866 		return 0;
867 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
868 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
869 	return 1;
870 }
871 
872 /**
873  * lpfc_cmd_iocb - Get next command iocb entry in the ring
874  * @phba: Pointer to HBA context object.
875  * @pring: Pointer to driver SLI ring object.
876  *
877  * This function returns pointer to next command iocb entry
878  * in the command ring. The caller must hold hbalock to prevent
879  * other threads consume the next command iocb.
880  * SLI-2/SLI-3 provide different sized iocbs.
881  **/
882 static inline IOCB_t *
883 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
884 {
885 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
886 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
887 }
888 
889 /**
890  * lpfc_resp_iocb - Get next response iocb entry in the ring
891  * @phba: Pointer to HBA context object.
892  * @pring: Pointer to driver SLI ring object.
893  *
894  * This function returns pointer to next response iocb entry
895  * in the response ring. The caller must hold hbalock to make sure
896  * that no other thread consume the next response iocb.
897  * SLI-2/SLI-3 provide different sized iocbs.
898  **/
899 static inline IOCB_t *
900 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
901 {
902 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
903 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
904 }
905 
906 /**
907  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
908  * @phba: Pointer to HBA context object.
909  *
910  * This function is called with hbalock held. This function
911  * allocates a new driver iocb object from the iocb pool. If the
912  * allocation is successful, it returns pointer to the newly
913  * allocated iocb object else it returns NULL.
914  **/
915 struct lpfc_iocbq *
916 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
917 {
918 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
919 	struct lpfc_iocbq * iocbq = NULL;
920 
921 	lockdep_assert_held(&phba->hbalock);
922 
923 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
924 	if (iocbq)
925 		phba->iocb_cnt++;
926 	if (phba->iocb_cnt > phba->iocb_max)
927 		phba->iocb_max = phba->iocb_cnt;
928 	return iocbq;
929 }
930 
931 /**
932  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
933  * @phba: Pointer to HBA context object.
934  * @xritag: XRI value.
935  *
936  * This function clears the sglq pointer from the array of active
937  * sglq's. The xritag that is passed in is used to index into the
938  * array. Before the xritag can be used it needs to be adjusted
939  * by subtracting the xribase.
940  *
941  * Returns sglq ponter = success, NULL = Failure.
942  **/
943 struct lpfc_sglq *
944 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
945 {
946 	struct lpfc_sglq *sglq;
947 
948 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
949 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
950 	return sglq;
951 }
952 
953 /**
954  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
955  * @phba: Pointer to HBA context object.
956  * @xritag: XRI value.
957  *
958  * This function returns the sglq pointer from the array of active
959  * sglq's. The xritag that is passed in is used to index into the
960  * array. Before the xritag can be used it needs to be adjusted
961  * by subtracting the xribase.
962  *
963  * Returns sglq ponter = success, NULL = Failure.
964  **/
965 struct lpfc_sglq *
966 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
967 {
968 	struct lpfc_sglq *sglq;
969 
970 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
971 	return sglq;
972 }
973 
974 /**
975  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
976  * @phba: Pointer to HBA context object.
977  * @xritag: xri used in this exchange.
978  * @rrq: The RRQ to be cleared.
979  *
980  **/
981 void
982 lpfc_clr_rrq_active(struct lpfc_hba *phba,
983 		    uint16_t xritag,
984 		    struct lpfc_node_rrq *rrq)
985 {
986 	struct lpfc_nodelist *ndlp = NULL;
987 
988 	/* Lookup did to verify if did is still active on this vport */
989 	if (rrq->vport)
990 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
991 
992 	if (!ndlp)
993 		goto out;
994 
995 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
996 		rrq->send_rrq = 0;
997 		rrq->xritag = 0;
998 		rrq->rrq_stop_time = 0;
999 	}
1000 out:
1001 	mempool_free(rrq, phba->rrq_pool);
1002 }
1003 
1004 /**
1005  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
1006  * @phba: Pointer to HBA context object.
1007  *
1008  * This function is called with hbalock held. This function
1009  * Checks if stop_time (ratov from setting rrq active) has
1010  * been reached, if it has and the send_rrq flag is set then
1011  * it will call lpfc_send_rrq. If the send_rrq flag is not set
1012  * then it will just call the routine to clear the rrq and
1013  * free the rrq resource.
1014  * The timer is set to the next rrq that is going to expire before
1015  * leaving the routine.
1016  *
1017  **/
1018 void
1019 lpfc_handle_rrq_active(struct lpfc_hba *phba)
1020 {
1021 	struct lpfc_node_rrq *rrq;
1022 	struct lpfc_node_rrq *nextrrq;
1023 	unsigned long next_time;
1024 	unsigned long iflags;
1025 	LIST_HEAD(send_rrq);
1026 
1027 	spin_lock_irqsave(&phba->hbalock, iflags);
1028 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1029 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1030 	list_for_each_entry_safe(rrq, nextrrq,
1031 				 &phba->active_rrq_list, list) {
1032 		if (time_after(jiffies, rrq->rrq_stop_time))
1033 			list_move(&rrq->list, &send_rrq);
1034 		else if (time_before(rrq->rrq_stop_time, next_time))
1035 			next_time = rrq->rrq_stop_time;
1036 	}
1037 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1038 	if ((!list_empty(&phba->active_rrq_list)) &&
1039 	    (!(phba->pport->load_flag & FC_UNLOADING)))
1040 		mod_timer(&phba->rrq_tmr, next_time);
1041 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
1042 		list_del(&rrq->list);
1043 		if (!rrq->send_rrq) {
1044 			/* this call will free the rrq */
1045 			lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1046 		} else if (lpfc_send_rrq(phba, rrq)) {
1047 			/* if we send the rrq then the completion handler
1048 			*  will clear the bit in the xribitmap.
1049 			*/
1050 			lpfc_clr_rrq_active(phba, rrq->xritag,
1051 					    rrq);
1052 		}
1053 	}
1054 }
1055 
1056 /**
1057  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
1058  * @vport: Pointer to vport context object.
1059  * @xri: The xri used in the exchange.
1060  * @did: The targets DID for this exchange.
1061  *
1062  * returns NULL = rrq not found in the phba->active_rrq_list.
1063  *         rrq = rrq for this xri and target.
1064  **/
1065 struct lpfc_node_rrq *
1066 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
1067 {
1068 	struct lpfc_hba *phba = vport->phba;
1069 	struct lpfc_node_rrq *rrq;
1070 	struct lpfc_node_rrq *nextrrq;
1071 	unsigned long iflags;
1072 
1073 	if (phba->sli_rev != LPFC_SLI_REV4)
1074 		return NULL;
1075 	spin_lock_irqsave(&phba->hbalock, iflags);
1076 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1077 		if (rrq->vport == vport && rrq->xritag == xri &&
1078 				rrq->nlp_DID == did){
1079 			list_del(&rrq->list);
1080 			spin_unlock_irqrestore(&phba->hbalock, iflags);
1081 			return rrq;
1082 		}
1083 	}
1084 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1085 	return NULL;
1086 }
1087 
1088 /**
1089  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
1090  * @vport: Pointer to vport context object.
1091  * @ndlp: Pointer to the lpfc_node_list structure.
1092  * If ndlp is NULL Remove all active RRQs for this vport from the
1093  * phba->active_rrq_list and clear the rrq.
1094  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
1095  **/
1096 void
1097 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
1098 
1099 {
1100 	struct lpfc_hba *phba = vport->phba;
1101 	struct lpfc_node_rrq *rrq;
1102 	struct lpfc_node_rrq *nextrrq;
1103 	unsigned long iflags;
1104 	LIST_HEAD(rrq_list);
1105 
1106 	if (phba->sli_rev != LPFC_SLI_REV4)
1107 		return;
1108 	if (!ndlp) {
1109 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
1110 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
1111 	}
1112 	spin_lock_irqsave(&phba->hbalock, iflags);
1113 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1114 		if (rrq->vport != vport)
1115 			continue;
1116 
1117 		if (!ndlp || ndlp == lpfc_findnode_did(vport, rrq->nlp_DID))
1118 			list_move(&rrq->list, &rrq_list);
1119 
1120 	}
1121 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1122 
1123 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1124 		list_del(&rrq->list);
1125 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1126 	}
1127 }
1128 
1129 /**
1130  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1131  * @phba: Pointer to HBA context object.
1132  * @ndlp: Targets nodelist pointer for this exchange.
1133  * @xritag: the xri in the bitmap to test.
1134  *
1135  * This function returns:
1136  * 0 = rrq not active for this xri
1137  * 1 = rrq is valid for this xri.
1138  **/
1139 int
1140 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1141 			uint16_t  xritag)
1142 {
1143 	if (!ndlp)
1144 		return 0;
1145 	if (!ndlp->active_rrqs_xri_bitmap)
1146 		return 0;
1147 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1148 		return 1;
1149 	else
1150 		return 0;
1151 }
1152 
1153 /**
1154  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1155  * @phba: Pointer to HBA context object.
1156  * @ndlp: nodelist pointer for this target.
1157  * @xritag: xri used in this exchange.
1158  * @rxid: Remote Exchange ID.
1159  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1160  *
1161  * This function takes the hbalock.
1162  * The active bit is always set in the active rrq xri_bitmap even
1163  * if there is no slot avaiable for the other rrq information.
1164  *
1165  * returns 0 rrq actived for this xri
1166  *         < 0 No memory or invalid ndlp.
1167  **/
1168 int
1169 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1170 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1171 {
1172 	unsigned long iflags;
1173 	struct lpfc_node_rrq *rrq;
1174 	int empty;
1175 
1176 	if (!ndlp)
1177 		return -EINVAL;
1178 
1179 	if (!phba->cfg_enable_rrq)
1180 		return -EINVAL;
1181 
1182 	spin_lock_irqsave(&phba->hbalock, iflags);
1183 	if (phba->pport->load_flag & FC_UNLOADING) {
1184 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1185 		goto out;
1186 	}
1187 
1188 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
1189 		goto out;
1190 
1191 	if (!ndlp->active_rrqs_xri_bitmap)
1192 		goto out;
1193 
1194 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1195 		goto out;
1196 
1197 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1198 	rrq = mempool_alloc(phba->rrq_pool, GFP_ATOMIC);
1199 	if (!rrq) {
1200 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1201 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1202 				" DID:0x%x Send:%d\n",
1203 				xritag, rxid, ndlp->nlp_DID, send_rrq);
1204 		return -EINVAL;
1205 	}
1206 	if (phba->cfg_enable_rrq == 1)
1207 		rrq->send_rrq = send_rrq;
1208 	else
1209 		rrq->send_rrq = 0;
1210 	rrq->xritag = xritag;
1211 	rrq->rrq_stop_time = jiffies +
1212 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1213 	rrq->nlp_DID = ndlp->nlp_DID;
1214 	rrq->vport = ndlp->vport;
1215 	rrq->rxid = rxid;
1216 	spin_lock_irqsave(&phba->hbalock, iflags);
1217 	empty = list_empty(&phba->active_rrq_list);
1218 	list_add_tail(&rrq->list, &phba->active_rrq_list);
1219 	phba->hba_flag |= HBA_RRQ_ACTIVE;
1220 	if (empty)
1221 		lpfc_worker_wake_up(phba);
1222 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1223 	return 0;
1224 out:
1225 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1226 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1227 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
1228 			" DID:0x%x Send:%d\n",
1229 			xritag, rxid, ndlp->nlp_DID, send_rrq);
1230 	return -EINVAL;
1231 }
1232 
1233 /**
1234  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1235  * @phba: Pointer to HBA context object.
1236  * @piocbq: Pointer to the iocbq.
1237  *
1238  * The driver calls this function with either the nvme ls ring lock
1239  * or the fc els ring lock held depending on the iocb usage.  This function
1240  * gets a new driver sglq object from the sglq list. If the list is not empty
1241  * then it is successful, it returns pointer to the newly allocated sglq
1242  * object else it returns NULL.
1243  **/
1244 static struct lpfc_sglq *
1245 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1246 {
1247 	struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1248 	struct lpfc_sglq *sglq = NULL;
1249 	struct lpfc_sglq *start_sglq = NULL;
1250 	struct lpfc_io_buf *lpfc_cmd;
1251 	struct lpfc_nodelist *ndlp;
1252 	int found = 0;
1253 	u8 cmnd;
1254 
1255 	cmnd = get_job_cmnd(phba, piocbq);
1256 
1257 	if (piocbq->cmd_flag & LPFC_IO_FCP) {
1258 		lpfc_cmd = piocbq->io_buf;
1259 		ndlp = lpfc_cmd->rdata->pnode;
1260 	} else  if ((cmnd == CMD_GEN_REQUEST64_CR) &&
1261 			!(piocbq->cmd_flag & LPFC_IO_LIBDFC)) {
1262 		ndlp = piocbq->ndlp;
1263 	} else  if (piocbq->cmd_flag & LPFC_IO_LIBDFC) {
1264 		if (piocbq->cmd_flag & LPFC_IO_LOOPBACK)
1265 			ndlp = NULL;
1266 		else
1267 			ndlp = piocbq->ndlp;
1268 	} else {
1269 		ndlp = piocbq->ndlp;
1270 	}
1271 
1272 	spin_lock(&phba->sli4_hba.sgl_list_lock);
1273 	list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1274 	start_sglq = sglq;
1275 	while (!found) {
1276 		if (!sglq)
1277 			break;
1278 		if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1279 		    test_bit(sglq->sli4_lxritag,
1280 		    ndlp->active_rrqs_xri_bitmap)) {
1281 			/* This xri has an rrq outstanding for this DID.
1282 			 * put it back in the list and get another xri.
1283 			 */
1284 			list_add_tail(&sglq->list, lpfc_els_sgl_list);
1285 			sglq = NULL;
1286 			list_remove_head(lpfc_els_sgl_list, sglq,
1287 						struct lpfc_sglq, list);
1288 			if (sglq == start_sglq) {
1289 				list_add_tail(&sglq->list, lpfc_els_sgl_list);
1290 				sglq = NULL;
1291 				break;
1292 			} else
1293 				continue;
1294 		}
1295 		sglq->ndlp = ndlp;
1296 		found = 1;
1297 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1298 		sglq->state = SGL_ALLOCATED;
1299 	}
1300 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
1301 	return sglq;
1302 }
1303 
1304 /**
1305  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1306  * @phba: Pointer to HBA context object.
1307  * @piocbq: Pointer to the iocbq.
1308  *
1309  * This function is called with the sgl_list lock held. This function
1310  * gets a new driver sglq object from the sglq list. If the
1311  * list is not empty then it is successful, it returns pointer to the newly
1312  * allocated sglq object else it returns NULL.
1313  **/
1314 struct lpfc_sglq *
1315 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1316 {
1317 	struct list_head *lpfc_nvmet_sgl_list;
1318 	struct lpfc_sglq *sglq = NULL;
1319 
1320 	lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1321 
1322 	lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1323 
1324 	list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1325 	if (!sglq)
1326 		return NULL;
1327 	phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1328 	sglq->state = SGL_ALLOCATED;
1329 	return sglq;
1330 }
1331 
1332 /**
1333  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1334  * @phba: Pointer to HBA context object.
1335  *
1336  * This function is called with no lock held. This function
1337  * allocates a new driver iocb object from the iocb pool. If the
1338  * allocation is successful, it returns pointer to the newly
1339  * allocated iocb object else it returns NULL.
1340  **/
1341 struct lpfc_iocbq *
1342 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1343 {
1344 	struct lpfc_iocbq * iocbq = NULL;
1345 	unsigned long iflags;
1346 
1347 	spin_lock_irqsave(&phba->hbalock, iflags);
1348 	iocbq = __lpfc_sli_get_iocbq(phba);
1349 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1350 	return iocbq;
1351 }
1352 
1353 /**
1354  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1355  * @phba: Pointer to HBA context object.
1356  * @iocbq: Pointer to driver iocb object.
1357  *
1358  * This function is called to release the driver iocb object
1359  * to the iocb pool. The iotag in the iocb object
1360  * does not change for each use of the iocb object. This function
1361  * clears all other fields of the iocb object when it is freed.
1362  * The sqlq structure that holds the xritag and phys and virtual
1363  * mappings for the scatter gather list is retrieved from the
1364  * active array of sglq. The get of the sglq pointer also clears
1365  * the entry in the array. If the status of the IO indiactes that
1366  * this IO was aborted then the sglq entry it put on the
1367  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1368  * IO has good status or fails for any other reason then the sglq
1369  * entry is added to the free list (lpfc_els_sgl_list). The hbalock is
1370  *  asserted held in the code path calling this routine.
1371  **/
1372 static void
1373 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1374 {
1375 	struct lpfc_sglq *sglq;
1376 	unsigned long iflag = 0;
1377 	struct lpfc_sli_ring *pring;
1378 
1379 	if (iocbq->sli4_xritag == NO_XRI)
1380 		sglq = NULL;
1381 	else
1382 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1383 
1384 
1385 	if (sglq)  {
1386 		if (iocbq->cmd_flag & LPFC_IO_NVMET) {
1387 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1388 					  iflag);
1389 			sglq->state = SGL_FREED;
1390 			sglq->ndlp = NULL;
1391 			list_add_tail(&sglq->list,
1392 				      &phba->sli4_hba.lpfc_nvmet_sgl_list);
1393 			spin_unlock_irqrestore(
1394 				&phba->sli4_hba.sgl_list_lock, iflag);
1395 			goto out;
1396 		}
1397 
1398 		if ((iocbq->cmd_flag & LPFC_EXCHANGE_BUSY) &&
1399 		    (!(unlikely(pci_channel_offline(phba->pcidev)))) &&
1400 		    sglq->state != SGL_XRI_ABORTED) {
1401 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1402 					  iflag);
1403 
1404 			/* Check if we can get a reference on ndlp */
1405 			if (sglq->ndlp && !lpfc_nlp_get(sglq->ndlp))
1406 				sglq->ndlp = NULL;
1407 
1408 			list_add(&sglq->list,
1409 				 &phba->sli4_hba.lpfc_abts_els_sgl_list);
1410 			spin_unlock_irqrestore(
1411 				&phba->sli4_hba.sgl_list_lock, iflag);
1412 		} else {
1413 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1414 					  iflag);
1415 			sglq->state = SGL_FREED;
1416 			sglq->ndlp = NULL;
1417 			list_add_tail(&sglq->list,
1418 				      &phba->sli4_hba.lpfc_els_sgl_list);
1419 			spin_unlock_irqrestore(
1420 				&phba->sli4_hba.sgl_list_lock, iflag);
1421 			pring = lpfc_phba_elsring(phba);
1422 			/* Check if TXQ queue needs to be serviced */
1423 			if (pring && (!list_empty(&pring->txq)))
1424 				lpfc_worker_wake_up(phba);
1425 		}
1426 	}
1427 
1428 out:
1429 	/*
1430 	 * Clean all volatile data fields, preserve iotag and node struct.
1431 	 */
1432 	memset_startat(iocbq, 0, wqe);
1433 	iocbq->sli4_lxritag = NO_XRI;
1434 	iocbq->sli4_xritag = NO_XRI;
1435 	iocbq->cmd_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET | LPFC_IO_CMF |
1436 			      LPFC_IO_NVME_LS);
1437 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1438 }
1439 
1440 
1441 /**
1442  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1443  * @phba: Pointer to HBA context object.
1444  * @iocbq: Pointer to driver iocb object.
1445  *
1446  * This function is called to release the driver iocb object to the
1447  * iocb pool. The iotag in the iocb object does not change for each
1448  * use of the iocb object. This function clears all other fields of
1449  * the iocb object when it is freed. The hbalock is asserted held in
1450  * the code path calling this routine.
1451  **/
1452 static void
1453 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1454 {
1455 
1456 	/*
1457 	 * Clean all volatile data fields, preserve iotag and node struct.
1458 	 */
1459 	memset_startat(iocbq, 0, iocb);
1460 	iocbq->sli4_xritag = NO_XRI;
1461 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1462 }
1463 
1464 /**
1465  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1466  * @phba: Pointer to HBA context object.
1467  * @iocbq: Pointer to driver iocb object.
1468  *
1469  * This function is called with hbalock held to release driver
1470  * iocb object to the iocb pool. The iotag in the iocb object
1471  * does not change for each use of the iocb object. This function
1472  * clears all other fields of the iocb object when it is freed.
1473  **/
1474 static void
1475 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1476 {
1477 	lockdep_assert_held(&phba->hbalock);
1478 
1479 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1480 	phba->iocb_cnt--;
1481 }
1482 
1483 /**
1484  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1485  * @phba: Pointer to HBA context object.
1486  * @iocbq: Pointer to driver iocb object.
1487  *
1488  * This function is called with no lock held to release the iocb to
1489  * iocb pool.
1490  **/
1491 void
1492 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1493 {
1494 	unsigned long iflags;
1495 
1496 	/*
1497 	 * Clean all volatile data fields, preserve iotag and node struct.
1498 	 */
1499 	spin_lock_irqsave(&phba->hbalock, iflags);
1500 	__lpfc_sli_release_iocbq(phba, iocbq);
1501 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1502 }
1503 
1504 /**
1505  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1506  * @phba: Pointer to HBA context object.
1507  * @iocblist: List of IOCBs.
1508  * @ulpstatus: ULP status in IOCB command field.
1509  * @ulpWord4: ULP word-4 in IOCB command field.
1510  *
1511  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1512  * on the list by invoking the complete callback function associated with the
1513  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1514  * fields.
1515  **/
1516 void
1517 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1518 		      uint32_t ulpstatus, uint32_t ulpWord4)
1519 {
1520 	struct lpfc_iocbq *piocb;
1521 
1522 	while (!list_empty(iocblist)) {
1523 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1524 		if (piocb->cmd_cmpl) {
1525 			if (piocb->cmd_flag & LPFC_IO_NVME) {
1526 				lpfc_nvme_cancel_iocb(phba, piocb,
1527 						      ulpstatus, ulpWord4);
1528 			} else {
1529 				if (phba->sli_rev == LPFC_SLI_REV4) {
1530 					bf_set(lpfc_wcqe_c_status,
1531 					       &piocb->wcqe_cmpl, ulpstatus);
1532 					piocb->wcqe_cmpl.parameter = ulpWord4;
1533 				} else {
1534 					piocb->iocb.ulpStatus = ulpstatus;
1535 					piocb->iocb.un.ulpWord[4] = ulpWord4;
1536 				}
1537 				(piocb->cmd_cmpl) (phba, piocb, piocb);
1538 			}
1539 		} else {
1540 			lpfc_sli_release_iocbq(phba, piocb);
1541 		}
1542 	}
1543 	return;
1544 }
1545 
1546 /**
1547  * lpfc_sli_iocb_cmd_type - Get the iocb type
1548  * @iocb_cmnd: iocb command code.
1549  *
1550  * This function is called by ring event handler function to get the iocb type.
1551  * This function translates the iocb command to an iocb command type used to
1552  * decide the final disposition of each completed IOCB.
1553  * The function returns
1554  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1555  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1556  * LPFC_ABORT_IOCB   if it is an abort iocb
1557  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1558  *
1559  * The caller is not required to hold any lock.
1560  **/
1561 static lpfc_iocb_type
1562 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1563 {
1564 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1565 
1566 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1567 		return 0;
1568 
1569 	switch (iocb_cmnd) {
1570 	case CMD_XMIT_SEQUENCE_CR:
1571 	case CMD_XMIT_SEQUENCE_CX:
1572 	case CMD_XMIT_BCAST_CN:
1573 	case CMD_XMIT_BCAST_CX:
1574 	case CMD_ELS_REQUEST_CR:
1575 	case CMD_ELS_REQUEST_CX:
1576 	case CMD_CREATE_XRI_CR:
1577 	case CMD_CREATE_XRI_CX:
1578 	case CMD_GET_RPI_CN:
1579 	case CMD_XMIT_ELS_RSP_CX:
1580 	case CMD_GET_RPI_CR:
1581 	case CMD_FCP_IWRITE_CR:
1582 	case CMD_FCP_IWRITE_CX:
1583 	case CMD_FCP_IREAD_CR:
1584 	case CMD_FCP_IREAD_CX:
1585 	case CMD_FCP_ICMND_CR:
1586 	case CMD_FCP_ICMND_CX:
1587 	case CMD_FCP_TSEND_CX:
1588 	case CMD_FCP_TRSP_CX:
1589 	case CMD_FCP_TRECEIVE_CX:
1590 	case CMD_FCP_AUTO_TRSP_CX:
1591 	case CMD_ADAPTER_MSG:
1592 	case CMD_ADAPTER_DUMP:
1593 	case CMD_XMIT_SEQUENCE64_CR:
1594 	case CMD_XMIT_SEQUENCE64_CX:
1595 	case CMD_XMIT_BCAST64_CN:
1596 	case CMD_XMIT_BCAST64_CX:
1597 	case CMD_ELS_REQUEST64_CR:
1598 	case CMD_ELS_REQUEST64_CX:
1599 	case CMD_FCP_IWRITE64_CR:
1600 	case CMD_FCP_IWRITE64_CX:
1601 	case CMD_FCP_IREAD64_CR:
1602 	case CMD_FCP_IREAD64_CX:
1603 	case CMD_FCP_ICMND64_CR:
1604 	case CMD_FCP_ICMND64_CX:
1605 	case CMD_FCP_TSEND64_CX:
1606 	case CMD_FCP_TRSP64_CX:
1607 	case CMD_FCP_TRECEIVE64_CX:
1608 	case CMD_GEN_REQUEST64_CR:
1609 	case CMD_GEN_REQUEST64_CX:
1610 	case CMD_XMIT_ELS_RSP64_CX:
1611 	case DSSCMD_IWRITE64_CR:
1612 	case DSSCMD_IWRITE64_CX:
1613 	case DSSCMD_IREAD64_CR:
1614 	case DSSCMD_IREAD64_CX:
1615 	case CMD_SEND_FRAME:
1616 		type = LPFC_SOL_IOCB;
1617 		break;
1618 	case CMD_ABORT_XRI_CN:
1619 	case CMD_ABORT_XRI_CX:
1620 	case CMD_CLOSE_XRI_CN:
1621 	case CMD_CLOSE_XRI_CX:
1622 	case CMD_XRI_ABORTED_CX:
1623 	case CMD_ABORT_MXRI64_CN:
1624 	case CMD_XMIT_BLS_RSP64_CX:
1625 		type = LPFC_ABORT_IOCB;
1626 		break;
1627 	case CMD_RCV_SEQUENCE_CX:
1628 	case CMD_RCV_ELS_REQ_CX:
1629 	case CMD_RCV_SEQUENCE64_CX:
1630 	case CMD_RCV_ELS_REQ64_CX:
1631 	case CMD_ASYNC_STATUS:
1632 	case CMD_IOCB_RCV_SEQ64_CX:
1633 	case CMD_IOCB_RCV_ELS64_CX:
1634 	case CMD_IOCB_RCV_CONT64_CX:
1635 	case CMD_IOCB_RET_XRI64_CX:
1636 		type = LPFC_UNSOL_IOCB;
1637 		break;
1638 	case CMD_IOCB_XMIT_MSEQ64_CR:
1639 	case CMD_IOCB_XMIT_MSEQ64_CX:
1640 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1641 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1642 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1643 	case CMD_IOCB_ABORT_EXTENDED_CN:
1644 	case CMD_IOCB_RET_HBQE64_CN:
1645 	case CMD_IOCB_FCP_IBIDIR64_CR:
1646 	case CMD_IOCB_FCP_IBIDIR64_CX:
1647 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1648 	case CMD_IOCB_LOGENTRY_CN:
1649 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1650 		printk("%s - Unhandled SLI-3 Command x%x\n",
1651 				__func__, iocb_cmnd);
1652 		type = LPFC_UNKNOWN_IOCB;
1653 		break;
1654 	default:
1655 		type = LPFC_UNKNOWN_IOCB;
1656 		break;
1657 	}
1658 
1659 	return type;
1660 }
1661 
1662 /**
1663  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1664  * @phba: Pointer to HBA context object.
1665  *
1666  * This function is called from SLI initialization code
1667  * to configure every ring of the HBA's SLI interface. The
1668  * caller is not required to hold any lock. This function issues
1669  * a config_ring mailbox command for each ring.
1670  * This function returns zero if successful else returns a negative
1671  * error code.
1672  **/
1673 static int
1674 lpfc_sli_ring_map(struct lpfc_hba *phba)
1675 {
1676 	struct lpfc_sli *psli = &phba->sli;
1677 	LPFC_MBOXQ_t *pmb;
1678 	MAILBOX_t *pmbox;
1679 	int i, rc, ret = 0;
1680 
1681 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1682 	if (!pmb)
1683 		return -ENOMEM;
1684 	pmbox = &pmb->u.mb;
1685 	phba->link_state = LPFC_INIT_MBX_CMDS;
1686 	for (i = 0; i < psli->num_rings; i++) {
1687 		lpfc_config_ring(phba, i, pmb);
1688 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1689 		if (rc != MBX_SUCCESS) {
1690 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1691 					"0446 Adapter failed to init (%d), "
1692 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1693 					"ring %d\n",
1694 					rc, pmbox->mbxCommand,
1695 					pmbox->mbxStatus, i);
1696 			phba->link_state = LPFC_HBA_ERROR;
1697 			ret = -ENXIO;
1698 			break;
1699 		}
1700 	}
1701 	mempool_free(pmb, phba->mbox_mem_pool);
1702 	return ret;
1703 }
1704 
1705 /**
1706  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1707  * @phba: Pointer to HBA context object.
1708  * @pring: Pointer to driver SLI ring object.
1709  * @piocb: Pointer to the driver iocb object.
1710  *
1711  * The driver calls this function with the hbalock held for SLI3 ports or
1712  * the ring lock held for SLI4 ports. The function adds the
1713  * new iocb to txcmplq of the given ring. This function always returns
1714  * 0. If this function is called for ELS ring, this function checks if
1715  * there is a vport associated with the ELS command. This function also
1716  * starts els_tmofunc timer if this is an ELS command.
1717  **/
1718 static int
1719 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1720 			struct lpfc_iocbq *piocb)
1721 {
1722 	u32 ulp_command = 0;
1723 
1724 	BUG_ON(!piocb);
1725 	ulp_command = get_job_cmnd(phba, piocb);
1726 
1727 	list_add_tail(&piocb->list, &pring->txcmplq);
1728 	piocb->cmd_flag |= LPFC_IO_ON_TXCMPLQ;
1729 	pring->txcmplq_cnt++;
1730 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1731 	   (ulp_command != CMD_ABORT_XRI_WQE) &&
1732 	   (ulp_command != CMD_ABORT_XRI_CN) &&
1733 	   (ulp_command != CMD_CLOSE_XRI_CN)) {
1734 		BUG_ON(!piocb->vport);
1735 		if (!(piocb->vport->load_flag & FC_UNLOADING))
1736 			mod_timer(&piocb->vport->els_tmofunc,
1737 				  jiffies +
1738 				  msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1739 	}
1740 
1741 	return 0;
1742 }
1743 
1744 /**
1745  * lpfc_sli_ringtx_get - Get first element of the txq
1746  * @phba: Pointer to HBA context object.
1747  * @pring: Pointer to driver SLI ring object.
1748  *
1749  * This function is called with hbalock held to get next
1750  * iocb in txq of the given ring. If there is any iocb in
1751  * the txq, the function returns first iocb in the list after
1752  * removing the iocb from the list, else it returns NULL.
1753  **/
1754 struct lpfc_iocbq *
1755 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1756 {
1757 	struct lpfc_iocbq *cmd_iocb;
1758 
1759 	lockdep_assert_held(&phba->hbalock);
1760 
1761 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1762 	return cmd_iocb;
1763 }
1764 
1765 /**
1766  * lpfc_cmf_sync_cmpl - Process a CMF_SYNC_WQE cmpl
1767  * @phba: Pointer to HBA context object.
1768  * @cmdiocb: Pointer to driver command iocb object.
1769  * @rspiocb: Pointer to driver response iocb object.
1770  *
1771  * This routine will inform the driver of any BW adjustments we need
1772  * to make. These changes will be picked up during the next CMF
1773  * timer interrupt. In addition, any BW changes will be logged
1774  * with LOG_CGN_MGMT.
1775  **/
1776 static void
1777 lpfc_cmf_sync_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
1778 		   struct lpfc_iocbq *rspiocb)
1779 {
1780 	union lpfc_wqe128 *wqe;
1781 	uint32_t status, info;
1782 	struct lpfc_wcqe_complete *wcqe = &rspiocb->wcqe_cmpl;
1783 	uint64_t bw, bwdif, slop;
1784 	uint64_t pcent, bwpcent;
1785 	int asig, afpin, sigcnt, fpincnt;
1786 	int wsigmax, wfpinmax, cg, tdp;
1787 	char *s;
1788 
1789 	/* First check for error */
1790 	status = bf_get(lpfc_wcqe_c_status, wcqe);
1791 	if (status) {
1792 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1793 				"6211 CMF_SYNC_WQE Error "
1794 				"req_tag x%x status x%x hwstatus x%x "
1795 				"tdatap x%x parm x%x\n",
1796 				bf_get(lpfc_wcqe_c_request_tag, wcqe),
1797 				bf_get(lpfc_wcqe_c_status, wcqe),
1798 				bf_get(lpfc_wcqe_c_hw_status, wcqe),
1799 				wcqe->total_data_placed,
1800 				wcqe->parameter);
1801 		goto out;
1802 	}
1803 
1804 	/* Gather congestion information on a successful cmpl */
1805 	info = wcqe->parameter;
1806 	phba->cmf_active_info = info;
1807 
1808 	/* See if firmware info count is valid or has changed */
1809 	if (info > LPFC_MAX_CMF_INFO || phba->cmf_info_per_interval == info)
1810 		info = 0;
1811 	else
1812 		phba->cmf_info_per_interval = info;
1813 
1814 	tdp = bf_get(lpfc_wcqe_c_cmf_bw, wcqe);
1815 	cg = bf_get(lpfc_wcqe_c_cmf_cg, wcqe);
1816 
1817 	/* Get BW requirement from firmware */
1818 	bw = (uint64_t)tdp * LPFC_CMF_BLK_SIZE;
1819 	if (!bw) {
1820 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1821 				"6212 CMF_SYNC_WQE x%x: NULL bw\n",
1822 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
1823 		goto out;
1824 	}
1825 
1826 	/* Gather information needed for logging if a BW change is required */
1827 	wqe = &cmdiocb->wqe;
1828 	asig = bf_get(cmf_sync_asig, &wqe->cmf_sync);
1829 	afpin = bf_get(cmf_sync_afpin, &wqe->cmf_sync);
1830 	fpincnt = bf_get(cmf_sync_wfpincnt, &wqe->cmf_sync);
1831 	sigcnt = bf_get(cmf_sync_wsigcnt, &wqe->cmf_sync);
1832 	if (phba->cmf_max_bytes_per_interval != bw ||
1833 	    (asig || afpin || sigcnt || fpincnt)) {
1834 		/* Are we increasing or decreasing BW */
1835 		if (phba->cmf_max_bytes_per_interval <  bw) {
1836 			bwdif = bw - phba->cmf_max_bytes_per_interval;
1837 			s = "Increase";
1838 		} else {
1839 			bwdif = phba->cmf_max_bytes_per_interval - bw;
1840 			s = "Decrease";
1841 		}
1842 
1843 		/* What is the change percentage */
1844 		slop = div_u64(phba->cmf_link_byte_count, 200); /*For rounding*/
1845 		pcent = div64_u64(bwdif * 100 + slop,
1846 				  phba->cmf_link_byte_count);
1847 		bwpcent = div64_u64(bw * 100 + slop,
1848 				    phba->cmf_link_byte_count);
1849 		/* Because of bytes adjustment due to shorter timer in
1850 		 * lpfc_cmf_timer() the cmf_link_byte_count can be shorter and
1851 		 * may seem like BW is above 100%.
1852 		 */
1853 		if (bwpcent > 100)
1854 			bwpcent = 100;
1855 
1856 		if (phba->cmf_max_bytes_per_interval < bw &&
1857 		    bwpcent > 95)
1858 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1859 					"6208 Congestion bandwidth "
1860 					"limits removed\n");
1861 		else if ((phba->cmf_max_bytes_per_interval > bw) &&
1862 			 ((bwpcent + pcent) <= 100) && ((bwpcent + pcent) > 95))
1863 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1864 					"6209 Congestion bandwidth "
1865 					"limits in effect\n");
1866 
1867 		if (asig) {
1868 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1869 					"6237 BW Threshold %lld%% (%lld): "
1870 					"%lld%% %s: Signal Alarm: cg:%d "
1871 					"Info:%u\n",
1872 					bwpcent, bw, pcent, s, cg,
1873 					phba->cmf_active_info);
1874 		} else if (afpin) {
1875 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1876 					"6238 BW Threshold %lld%% (%lld): "
1877 					"%lld%% %s: FPIN Alarm: cg:%d "
1878 					"Info:%u\n",
1879 					bwpcent, bw, pcent, s, cg,
1880 					phba->cmf_active_info);
1881 		} else if (sigcnt) {
1882 			wsigmax = bf_get(cmf_sync_wsigmax, &wqe->cmf_sync);
1883 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1884 					"6239 BW Threshold %lld%% (%lld): "
1885 					"%lld%% %s: Signal Warning: "
1886 					"Cnt %d Max %d: cg:%d Info:%u\n",
1887 					bwpcent, bw, pcent, s, sigcnt,
1888 					wsigmax, cg, phba->cmf_active_info);
1889 		} else if (fpincnt) {
1890 			wfpinmax = bf_get(cmf_sync_wfpinmax, &wqe->cmf_sync);
1891 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1892 					"6240 BW Threshold %lld%% (%lld): "
1893 					"%lld%% %s: FPIN Warning: "
1894 					"Cnt %d Max %d: cg:%d Info:%u\n",
1895 					bwpcent, bw, pcent, s, fpincnt,
1896 					wfpinmax, cg, phba->cmf_active_info);
1897 		} else {
1898 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1899 					"6241 BW Threshold %lld%% (%lld): "
1900 					"CMF %lld%% %s: cg:%d Info:%u\n",
1901 					bwpcent, bw, pcent, s, cg,
1902 					phba->cmf_active_info);
1903 		}
1904 	} else if (info) {
1905 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1906 				"6246 Info Threshold %u\n", info);
1907 	}
1908 
1909 	/* Save BW change to be picked up during next timer interrupt */
1910 	phba->cmf_last_sync_bw = bw;
1911 out:
1912 	lpfc_sli_release_iocbq(phba, cmdiocb);
1913 }
1914 
1915 /**
1916  * lpfc_issue_cmf_sync_wqe - Issue a CMF_SYNC_WQE
1917  * @phba: Pointer to HBA context object.
1918  * @ms:   ms to set in WQE interval, 0 means use init op
1919  * @total: Total rcv bytes for this interval
1920  *
1921  * This routine is called every CMF timer interrupt. Its purpose is
1922  * to issue a CMF_SYNC_WQE to the firmware to inform it of any events
1923  * that may indicate we have congestion (FPINs or Signals). Upon
1924  * completion, the firmware will indicate any BW restrictions the
1925  * driver may need to take.
1926  **/
1927 int
1928 lpfc_issue_cmf_sync_wqe(struct lpfc_hba *phba, u32 ms, u64 total)
1929 {
1930 	union lpfc_wqe128 *wqe;
1931 	struct lpfc_iocbq *sync_buf;
1932 	unsigned long iflags;
1933 	u32 ret_val;
1934 	u32 atot, wtot, max;
1935 	u16 warn_sync_period = 0;
1936 
1937 	/* First address any alarm / warning activity */
1938 	atot = atomic_xchg(&phba->cgn_sync_alarm_cnt, 0);
1939 	wtot = atomic_xchg(&phba->cgn_sync_warn_cnt, 0);
1940 
1941 	/* ONLY Managed mode will send the CMF_SYNC_WQE to the HBA */
1942 	if (phba->cmf_active_mode != LPFC_CFG_MANAGED ||
1943 	    phba->link_state == LPFC_LINK_DOWN)
1944 		return 0;
1945 
1946 	spin_lock_irqsave(&phba->hbalock, iflags);
1947 	sync_buf = __lpfc_sli_get_iocbq(phba);
1948 	if (!sync_buf) {
1949 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
1950 				"6244 No available WQEs for CMF_SYNC_WQE\n");
1951 		ret_val = ENOMEM;
1952 		goto out_unlock;
1953 	}
1954 
1955 	wqe = &sync_buf->wqe;
1956 
1957 	/* WQEs are reused.  Clear stale data and set key fields to zero */
1958 	memset(wqe, 0, sizeof(*wqe));
1959 
1960 	/* If this is the very first CMF_SYNC_WQE, issue an init operation */
1961 	if (!ms) {
1962 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1963 				"6441 CMF Init %d - CMF_SYNC_WQE\n",
1964 				phba->fc_eventTag);
1965 		bf_set(cmf_sync_op, &wqe->cmf_sync, 1); /* 1=init */
1966 		bf_set(cmf_sync_interval, &wqe->cmf_sync, LPFC_CMF_INTERVAL);
1967 		goto initpath;
1968 	}
1969 
1970 	bf_set(cmf_sync_op, &wqe->cmf_sync, 0); /* 0=recalc */
1971 	bf_set(cmf_sync_interval, &wqe->cmf_sync, ms);
1972 
1973 	/* Check for alarms / warnings */
1974 	if (atot) {
1975 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1976 			/* We hit an Signal alarm condition */
1977 			bf_set(cmf_sync_asig, &wqe->cmf_sync, 1);
1978 		} else {
1979 			/* We hit a FPIN alarm condition */
1980 			bf_set(cmf_sync_afpin, &wqe->cmf_sync, 1);
1981 		}
1982 	} else if (wtot) {
1983 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
1984 		    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1985 			/* We hit an Signal warning condition */
1986 			max = LPFC_SEC_TO_MSEC / lpfc_fabric_cgn_frequency *
1987 				lpfc_acqe_cgn_frequency;
1988 			bf_set(cmf_sync_wsigmax, &wqe->cmf_sync, max);
1989 			bf_set(cmf_sync_wsigcnt, &wqe->cmf_sync, wtot);
1990 			warn_sync_period = lpfc_acqe_cgn_frequency;
1991 		} else {
1992 			/* We hit a FPIN warning condition */
1993 			bf_set(cmf_sync_wfpinmax, &wqe->cmf_sync, 1);
1994 			bf_set(cmf_sync_wfpincnt, &wqe->cmf_sync, 1);
1995 			if (phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ)
1996 				warn_sync_period =
1997 				LPFC_MSECS_TO_SECS(phba->cgn_fpin_frequency);
1998 		}
1999 	}
2000 
2001 	/* Update total read blocks during previous timer interval */
2002 	wqe->cmf_sync.read_bytes = (u32)(total / LPFC_CMF_BLK_SIZE);
2003 
2004 initpath:
2005 	bf_set(cmf_sync_ver, &wqe->cmf_sync, LPFC_CMF_SYNC_VER);
2006 	wqe->cmf_sync.event_tag = phba->fc_eventTag;
2007 	bf_set(cmf_sync_cmnd, &wqe->cmf_sync, CMD_CMF_SYNC_WQE);
2008 
2009 	/* Setup reqtag to match the wqe completion. */
2010 	bf_set(cmf_sync_reqtag, &wqe->cmf_sync, sync_buf->iotag);
2011 
2012 	bf_set(cmf_sync_qosd, &wqe->cmf_sync, 1);
2013 	bf_set(cmf_sync_period, &wqe->cmf_sync, warn_sync_period);
2014 
2015 	bf_set(cmf_sync_cmd_type, &wqe->cmf_sync, CMF_SYNC_COMMAND);
2016 	bf_set(cmf_sync_wqec, &wqe->cmf_sync, 1);
2017 	bf_set(cmf_sync_cqid, &wqe->cmf_sync, LPFC_WQE_CQ_ID_DEFAULT);
2018 
2019 	sync_buf->vport = phba->pport;
2020 	sync_buf->cmd_cmpl = lpfc_cmf_sync_cmpl;
2021 	sync_buf->cmd_dmabuf = NULL;
2022 	sync_buf->rsp_dmabuf = NULL;
2023 	sync_buf->bpl_dmabuf = NULL;
2024 	sync_buf->sli4_xritag = NO_XRI;
2025 
2026 	sync_buf->cmd_flag |= LPFC_IO_CMF;
2027 	ret_val = lpfc_sli4_issue_wqe(phba, &phba->sli4_hba.hdwq[0], sync_buf);
2028 	if (ret_val) {
2029 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
2030 				"6214 Cannot issue CMF_SYNC_WQE: x%x\n",
2031 				ret_val);
2032 		__lpfc_sli_release_iocbq(phba, sync_buf);
2033 	}
2034 out_unlock:
2035 	spin_unlock_irqrestore(&phba->hbalock, iflags);
2036 	return ret_val;
2037 }
2038 
2039 /**
2040  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
2041  * @phba: Pointer to HBA context object.
2042  * @pring: Pointer to driver SLI ring object.
2043  *
2044  * This function is called with hbalock held and the caller must post the
2045  * iocb without releasing the lock. If the caller releases the lock,
2046  * iocb slot returned by the function is not guaranteed to be available.
2047  * The function returns pointer to the next available iocb slot if there
2048  * is available slot in the ring, else it returns NULL.
2049  * If the get index of the ring is ahead of the put index, the function
2050  * will post an error attention event to the worker thread to take the
2051  * HBA to offline state.
2052  **/
2053 static IOCB_t *
2054 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2055 {
2056 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2057 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
2058 
2059 	lockdep_assert_held(&phba->hbalock);
2060 
2061 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
2062 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
2063 		pring->sli.sli3.next_cmdidx = 0;
2064 
2065 	if (unlikely(pring->sli.sli3.local_getidx ==
2066 		pring->sli.sli3.next_cmdidx)) {
2067 
2068 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
2069 
2070 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
2071 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2072 					"0315 Ring %d issue: portCmdGet %d "
2073 					"is bigger than cmd ring %d\n",
2074 					pring->ringno,
2075 					pring->sli.sli3.local_getidx,
2076 					max_cmd_idx);
2077 
2078 			phba->link_state = LPFC_HBA_ERROR;
2079 			/*
2080 			 * All error attention handlers are posted to
2081 			 * worker thread
2082 			 */
2083 			phba->work_ha |= HA_ERATT;
2084 			phba->work_hs = HS_FFER3;
2085 
2086 			lpfc_worker_wake_up(phba);
2087 
2088 			return NULL;
2089 		}
2090 
2091 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
2092 			return NULL;
2093 	}
2094 
2095 	return lpfc_cmd_iocb(phba, pring);
2096 }
2097 
2098 /**
2099  * lpfc_sli_next_iotag - Get an iotag for the iocb
2100  * @phba: Pointer to HBA context object.
2101  * @iocbq: Pointer to driver iocb object.
2102  *
2103  * This function gets an iotag for the iocb. If there is no unused iotag and
2104  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
2105  * array and assigns a new iotag.
2106  * The function returns the allocated iotag if successful, else returns zero.
2107  * Zero is not a valid iotag.
2108  * The caller is not required to hold any lock.
2109  **/
2110 uint16_t
2111 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
2112 {
2113 	struct lpfc_iocbq **new_arr;
2114 	struct lpfc_iocbq **old_arr;
2115 	size_t new_len;
2116 	struct lpfc_sli *psli = &phba->sli;
2117 	uint16_t iotag;
2118 
2119 	spin_lock_irq(&phba->hbalock);
2120 	iotag = psli->last_iotag;
2121 	if(++iotag < psli->iocbq_lookup_len) {
2122 		psli->last_iotag = iotag;
2123 		psli->iocbq_lookup[iotag] = iocbq;
2124 		spin_unlock_irq(&phba->hbalock);
2125 		iocbq->iotag = iotag;
2126 		return iotag;
2127 	} else if (psli->iocbq_lookup_len < (0xffff
2128 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
2129 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
2130 		spin_unlock_irq(&phba->hbalock);
2131 		new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
2132 				  GFP_KERNEL);
2133 		if (new_arr) {
2134 			spin_lock_irq(&phba->hbalock);
2135 			old_arr = psli->iocbq_lookup;
2136 			if (new_len <= psli->iocbq_lookup_len) {
2137 				/* highly unprobable case */
2138 				kfree(new_arr);
2139 				iotag = psli->last_iotag;
2140 				if(++iotag < psli->iocbq_lookup_len) {
2141 					psli->last_iotag = iotag;
2142 					psli->iocbq_lookup[iotag] = iocbq;
2143 					spin_unlock_irq(&phba->hbalock);
2144 					iocbq->iotag = iotag;
2145 					return iotag;
2146 				}
2147 				spin_unlock_irq(&phba->hbalock);
2148 				return 0;
2149 			}
2150 			if (psli->iocbq_lookup)
2151 				memcpy(new_arr, old_arr,
2152 				       ((psli->last_iotag  + 1) *
2153 					sizeof (struct lpfc_iocbq *)));
2154 			psli->iocbq_lookup = new_arr;
2155 			psli->iocbq_lookup_len = new_len;
2156 			psli->last_iotag = iotag;
2157 			psli->iocbq_lookup[iotag] = iocbq;
2158 			spin_unlock_irq(&phba->hbalock);
2159 			iocbq->iotag = iotag;
2160 			kfree(old_arr);
2161 			return iotag;
2162 		}
2163 	} else
2164 		spin_unlock_irq(&phba->hbalock);
2165 
2166 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2167 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
2168 			psli->last_iotag);
2169 
2170 	return 0;
2171 }
2172 
2173 /**
2174  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
2175  * @phba: Pointer to HBA context object.
2176  * @pring: Pointer to driver SLI ring object.
2177  * @iocb: Pointer to iocb slot in the ring.
2178  * @nextiocb: Pointer to driver iocb object which need to be
2179  *            posted to firmware.
2180  *
2181  * This function is called to post a new iocb to the firmware. This
2182  * function copies the new iocb to ring iocb slot and updates the
2183  * ring pointers. It adds the new iocb to txcmplq if there is
2184  * a completion call back for this iocb else the function will free the
2185  * iocb object.  The hbalock is asserted held in the code path calling
2186  * this routine.
2187  **/
2188 static void
2189 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2190 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
2191 {
2192 	/*
2193 	 * Set up an iotag
2194 	 */
2195 	nextiocb->iocb.ulpIoTag = (nextiocb->cmd_cmpl) ? nextiocb->iotag : 0;
2196 
2197 
2198 	if (pring->ringno == LPFC_ELS_RING) {
2199 		lpfc_debugfs_slow_ring_trc(phba,
2200 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
2201 			*(((uint32_t *) &nextiocb->iocb) + 4),
2202 			*(((uint32_t *) &nextiocb->iocb) + 6),
2203 			*(((uint32_t *) &nextiocb->iocb) + 7));
2204 	}
2205 
2206 	/*
2207 	 * Issue iocb command to adapter
2208 	 */
2209 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
2210 	wmb();
2211 	pring->stats.iocb_cmd++;
2212 
2213 	/*
2214 	 * If there is no completion routine to call, we can release the
2215 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
2216 	 * that have no rsp ring completion, cmd_cmpl MUST be NULL.
2217 	 */
2218 	if (nextiocb->cmd_cmpl)
2219 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
2220 	else
2221 		__lpfc_sli_release_iocbq(phba, nextiocb);
2222 
2223 	/*
2224 	 * Let the HBA know what IOCB slot will be the next one the
2225 	 * driver will put a command into.
2226 	 */
2227 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
2228 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
2229 }
2230 
2231 /**
2232  * lpfc_sli_update_full_ring - Update the chip attention register
2233  * @phba: Pointer to HBA context object.
2234  * @pring: Pointer to driver SLI ring object.
2235  *
2236  * The caller is not required to hold any lock for calling this function.
2237  * This function updates the chip attention bits for the ring to inform firmware
2238  * that there are pending work to be done for this ring and requests an
2239  * interrupt when there is space available in the ring. This function is
2240  * called when the driver is unable to post more iocbs to the ring due
2241  * to unavailability of space in the ring.
2242  **/
2243 static void
2244 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2245 {
2246 	int ringno = pring->ringno;
2247 
2248 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
2249 
2250 	wmb();
2251 
2252 	/*
2253 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
2254 	 * The HBA will tell us when an IOCB entry is available.
2255 	 */
2256 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
2257 	readl(phba->CAregaddr); /* flush */
2258 
2259 	pring->stats.iocb_cmd_full++;
2260 }
2261 
2262 /**
2263  * lpfc_sli_update_ring - Update chip attention register
2264  * @phba: Pointer to HBA context object.
2265  * @pring: Pointer to driver SLI ring object.
2266  *
2267  * This function updates the chip attention register bit for the
2268  * given ring to inform HBA that there is more work to be done
2269  * in this ring. The caller is not required to hold any lock.
2270  **/
2271 static void
2272 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2273 {
2274 	int ringno = pring->ringno;
2275 
2276 	/*
2277 	 * Tell the HBA that there is work to do in this ring.
2278 	 */
2279 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
2280 		wmb();
2281 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
2282 		readl(phba->CAregaddr); /* flush */
2283 	}
2284 }
2285 
2286 /**
2287  * lpfc_sli_resume_iocb - Process iocbs in the txq
2288  * @phba: Pointer to HBA context object.
2289  * @pring: Pointer to driver SLI ring object.
2290  *
2291  * This function is called with hbalock held to post pending iocbs
2292  * in the txq to the firmware. This function is called when driver
2293  * detects space available in the ring.
2294  **/
2295 static void
2296 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2297 {
2298 	IOCB_t *iocb;
2299 	struct lpfc_iocbq *nextiocb;
2300 
2301 	lockdep_assert_held(&phba->hbalock);
2302 
2303 	/*
2304 	 * Check to see if:
2305 	 *  (a) there is anything on the txq to send
2306 	 *  (b) link is up
2307 	 *  (c) link attention events can be processed (fcp ring only)
2308 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
2309 	 */
2310 
2311 	if (lpfc_is_link_up(phba) &&
2312 	    (!list_empty(&pring->txq)) &&
2313 	    (pring->ringno != LPFC_FCP_RING ||
2314 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
2315 
2316 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
2317 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
2318 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
2319 
2320 		if (iocb)
2321 			lpfc_sli_update_ring(phba, pring);
2322 		else
2323 			lpfc_sli_update_full_ring(phba, pring);
2324 	}
2325 
2326 	return;
2327 }
2328 
2329 /**
2330  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
2331  * @phba: Pointer to HBA context object.
2332  * @hbqno: HBQ number.
2333  *
2334  * This function is called with hbalock held to get the next
2335  * available slot for the given HBQ. If there is free slot
2336  * available for the HBQ it will return pointer to the next available
2337  * HBQ entry else it will return NULL.
2338  **/
2339 static struct lpfc_hbq_entry *
2340 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
2341 {
2342 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
2343 
2344 	lockdep_assert_held(&phba->hbalock);
2345 
2346 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
2347 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
2348 		hbqp->next_hbqPutIdx = 0;
2349 
2350 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
2351 		uint32_t raw_index = phba->hbq_get[hbqno];
2352 		uint32_t getidx = le32_to_cpu(raw_index);
2353 
2354 		hbqp->local_hbqGetIdx = getidx;
2355 
2356 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
2357 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2358 					"1802 HBQ %d: local_hbqGetIdx "
2359 					"%u is > than hbqp->entry_count %u\n",
2360 					hbqno, hbqp->local_hbqGetIdx,
2361 					hbqp->entry_count);
2362 
2363 			phba->link_state = LPFC_HBA_ERROR;
2364 			return NULL;
2365 		}
2366 
2367 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
2368 			return NULL;
2369 	}
2370 
2371 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
2372 			hbqp->hbqPutIdx;
2373 }
2374 
2375 /**
2376  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
2377  * @phba: Pointer to HBA context object.
2378  *
2379  * This function is called with no lock held to free all the
2380  * hbq buffers while uninitializing the SLI interface. It also
2381  * frees the HBQ buffers returned by the firmware but not yet
2382  * processed by the upper layers.
2383  **/
2384 void
2385 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
2386 {
2387 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
2388 	struct hbq_dmabuf *hbq_buf;
2389 	unsigned long flags;
2390 	int i, hbq_count;
2391 
2392 	hbq_count = lpfc_sli_hbq_count();
2393 	/* Return all memory used by all HBQs */
2394 	spin_lock_irqsave(&phba->hbalock, flags);
2395 	for (i = 0; i < hbq_count; ++i) {
2396 		list_for_each_entry_safe(dmabuf, next_dmabuf,
2397 				&phba->hbqs[i].hbq_buffer_list, list) {
2398 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2399 			list_del(&hbq_buf->dbuf.list);
2400 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2401 		}
2402 		phba->hbqs[i].buffer_count = 0;
2403 	}
2404 
2405 	/* Mark the HBQs not in use */
2406 	phba->hbq_in_use = 0;
2407 	spin_unlock_irqrestore(&phba->hbalock, flags);
2408 }
2409 
2410 /**
2411  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2412  * @phba: Pointer to HBA context object.
2413  * @hbqno: HBQ number.
2414  * @hbq_buf: Pointer to HBQ buffer.
2415  *
2416  * This function is called with the hbalock held to post a
2417  * hbq buffer to the firmware. If the function finds an empty
2418  * slot in the HBQ, it will post the buffer. The function will return
2419  * pointer to the hbq entry if it successfully post the buffer
2420  * else it will return NULL.
2421  **/
2422 static int
2423 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2424 			 struct hbq_dmabuf *hbq_buf)
2425 {
2426 	lockdep_assert_held(&phba->hbalock);
2427 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2428 }
2429 
2430 /**
2431  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2432  * @phba: Pointer to HBA context object.
2433  * @hbqno: HBQ number.
2434  * @hbq_buf: Pointer to HBQ buffer.
2435  *
2436  * This function is called with the hbalock held to post a hbq buffer to the
2437  * firmware. If the function finds an empty slot in the HBQ, it will post the
2438  * buffer and place it on the hbq_buffer_list. The function will return zero if
2439  * it successfully post the buffer else it will return an error.
2440  **/
2441 static int
2442 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2443 			    struct hbq_dmabuf *hbq_buf)
2444 {
2445 	struct lpfc_hbq_entry *hbqe;
2446 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
2447 
2448 	lockdep_assert_held(&phba->hbalock);
2449 	/* Get next HBQ entry slot to use */
2450 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2451 	if (hbqe) {
2452 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
2453 
2454 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2455 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2456 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2457 		hbqe->bde.tus.f.bdeFlags = 0;
2458 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2459 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2460 				/* Sync SLIM */
2461 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2462 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2463 				/* flush */
2464 		readl(phba->hbq_put + hbqno);
2465 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2466 		return 0;
2467 	} else
2468 		return -ENOMEM;
2469 }
2470 
2471 /**
2472  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2473  * @phba: Pointer to HBA context object.
2474  * @hbqno: HBQ number.
2475  * @hbq_buf: Pointer to HBQ buffer.
2476  *
2477  * This function is called with the hbalock held to post an RQE to the SLI4
2478  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2479  * the hbq_buffer_list and return zero, otherwise it will return an error.
2480  **/
2481 static int
2482 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2483 			    struct hbq_dmabuf *hbq_buf)
2484 {
2485 	int rc;
2486 	struct lpfc_rqe hrqe;
2487 	struct lpfc_rqe drqe;
2488 	struct lpfc_queue *hrq;
2489 	struct lpfc_queue *drq;
2490 
2491 	if (hbqno != LPFC_ELS_HBQ)
2492 		return 1;
2493 	hrq = phba->sli4_hba.hdr_rq;
2494 	drq = phba->sli4_hba.dat_rq;
2495 
2496 	lockdep_assert_held(&phba->hbalock);
2497 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2498 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2499 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2500 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2501 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2502 	if (rc < 0)
2503 		return rc;
2504 	hbq_buf->tag = (rc | (hbqno << 16));
2505 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2506 	return 0;
2507 }
2508 
2509 /* HBQ for ELS and CT traffic. */
2510 static struct lpfc_hbq_init lpfc_els_hbq = {
2511 	.rn = 1,
2512 	.entry_count = 256,
2513 	.mask_count = 0,
2514 	.profile = 0,
2515 	.ring_mask = (1 << LPFC_ELS_RING),
2516 	.buffer_count = 0,
2517 	.init_count = 40,
2518 	.add_count = 40,
2519 };
2520 
2521 /* Array of HBQs */
2522 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2523 	&lpfc_els_hbq,
2524 };
2525 
2526 /**
2527  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2528  * @phba: Pointer to HBA context object.
2529  * @hbqno: HBQ number.
2530  * @count: Number of HBQ buffers to be posted.
2531  *
2532  * This function is called with no lock held to post more hbq buffers to the
2533  * given HBQ. The function returns the number of HBQ buffers successfully
2534  * posted.
2535  **/
2536 static int
2537 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2538 {
2539 	uint32_t i, posted = 0;
2540 	unsigned long flags;
2541 	struct hbq_dmabuf *hbq_buffer;
2542 	LIST_HEAD(hbq_buf_list);
2543 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2544 		return 0;
2545 
2546 	if ((phba->hbqs[hbqno].buffer_count + count) >
2547 	    lpfc_hbq_defs[hbqno]->entry_count)
2548 		count = lpfc_hbq_defs[hbqno]->entry_count -
2549 					phba->hbqs[hbqno].buffer_count;
2550 	if (!count)
2551 		return 0;
2552 	/* Allocate HBQ entries */
2553 	for (i = 0; i < count; i++) {
2554 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2555 		if (!hbq_buffer)
2556 			break;
2557 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2558 	}
2559 	/* Check whether HBQ is still in use */
2560 	spin_lock_irqsave(&phba->hbalock, flags);
2561 	if (!phba->hbq_in_use)
2562 		goto err;
2563 	while (!list_empty(&hbq_buf_list)) {
2564 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2565 				 dbuf.list);
2566 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2567 				      (hbqno << 16));
2568 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2569 			phba->hbqs[hbqno].buffer_count++;
2570 			posted++;
2571 		} else
2572 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2573 	}
2574 	spin_unlock_irqrestore(&phba->hbalock, flags);
2575 	return posted;
2576 err:
2577 	spin_unlock_irqrestore(&phba->hbalock, flags);
2578 	while (!list_empty(&hbq_buf_list)) {
2579 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2580 				 dbuf.list);
2581 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2582 	}
2583 	return 0;
2584 }
2585 
2586 /**
2587  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2588  * @phba: Pointer to HBA context object.
2589  * @qno: HBQ number.
2590  *
2591  * This function posts more buffers to the HBQ. This function
2592  * is called with no lock held. The function returns the number of HBQ entries
2593  * successfully allocated.
2594  **/
2595 int
2596 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2597 {
2598 	if (phba->sli_rev == LPFC_SLI_REV4)
2599 		return 0;
2600 	else
2601 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2602 					 lpfc_hbq_defs[qno]->add_count);
2603 }
2604 
2605 /**
2606  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2607  * @phba: Pointer to HBA context object.
2608  * @qno:  HBQ queue number.
2609  *
2610  * This function is called from SLI initialization code path with
2611  * no lock held to post initial HBQ buffers to firmware. The
2612  * function returns the number of HBQ entries successfully allocated.
2613  **/
2614 static int
2615 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2616 {
2617 	if (phba->sli_rev == LPFC_SLI_REV4)
2618 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2619 					lpfc_hbq_defs[qno]->entry_count);
2620 	else
2621 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2622 					 lpfc_hbq_defs[qno]->init_count);
2623 }
2624 
2625 /*
2626  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2627  *
2628  * This function removes the first hbq buffer on an hbq list and returns a
2629  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2630  **/
2631 static struct hbq_dmabuf *
2632 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2633 {
2634 	struct lpfc_dmabuf *d_buf;
2635 
2636 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2637 	if (!d_buf)
2638 		return NULL;
2639 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2640 }
2641 
2642 /**
2643  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2644  * @phba: Pointer to HBA context object.
2645  * @hrq: HBQ number.
2646  *
2647  * This function removes the first RQ buffer on an RQ buffer list and returns a
2648  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2649  **/
2650 static struct rqb_dmabuf *
2651 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2652 {
2653 	struct lpfc_dmabuf *h_buf;
2654 	struct lpfc_rqb *rqbp;
2655 
2656 	rqbp = hrq->rqbp;
2657 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2658 			 struct lpfc_dmabuf, list);
2659 	if (!h_buf)
2660 		return NULL;
2661 	rqbp->buffer_count--;
2662 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2663 }
2664 
2665 /**
2666  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2667  * @phba: Pointer to HBA context object.
2668  * @tag: Tag of the hbq buffer.
2669  *
2670  * This function searches for the hbq buffer associated with the given tag in
2671  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2672  * otherwise it returns NULL.
2673  **/
2674 static struct hbq_dmabuf *
2675 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2676 {
2677 	struct lpfc_dmabuf *d_buf;
2678 	struct hbq_dmabuf *hbq_buf;
2679 	uint32_t hbqno;
2680 
2681 	hbqno = tag >> 16;
2682 	if (hbqno >= LPFC_MAX_HBQS)
2683 		return NULL;
2684 
2685 	spin_lock_irq(&phba->hbalock);
2686 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2687 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2688 		if (hbq_buf->tag == tag) {
2689 			spin_unlock_irq(&phba->hbalock);
2690 			return hbq_buf;
2691 		}
2692 	}
2693 	spin_unlock_irq(&phba->hbalock);
2694 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2695 			"1803 Bad hbq tag. Data: x%x x%x\n",
2696 			tag, phba->hbqs[tag >> 16].buffer_count);
2697 	return NULL;
2698 }
2699 
2700 /**
2701  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2702  * @phba: Pointer to HBA context object.
2703  * @hbq_buffer: Pointer to HBQ buffer.
2704  *
2705  * This function is called with hbalock. This function gives back
2706  * the hbq buffer to firmware. If the HBQ does not have space to
2707  * post the buffer, it will free the buffer.
2708  **/
2709 void
2710 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2711 {
2712 	uint32_t hbqno;
2713 
2714 	if (hbq_buffer) {
2715 		hbqno = hbq_buffer->tag >> 16;
2716 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2717 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2718 	}
2719 }
2720 
2721 /**
2722  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2723  * @mbxCommand: mailbox command code.
2724  *
2725  * This function is called by the mailbox event handler function to verify
2726  * that the completed mailbox command is a legitimate mailbox command. If the
2727  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2728  * and the mailbox event handler will take the HBA offline.
2729  **/
2730 static int
2731 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2732 {
2733 	uint8_t ret;
2734 
2735 	switch (mbxCommand) {
2736 	case MBX_LOAD_SM:
2737 	case MBX_READ_NV:
2738 	case MBX_WRITE_NV:
2739 	case MBX_WRITE_VPARMS:
2740 	case MBX_RUN_BIU_DIAG:
2741 	case MBX_INIT_LINK:
2742 	case MBX_DOWN_LINK:
2743 	case MBX_CONFIG_LINK:
2744 	case MBX_CONFIG_RING:
2745 	case MBX_RESET_RING:
2746 	case MBX_READ_CONFIG:
2747 	case MBX_READ_RCONFIG:
2748 	case MBX_READ_SPARM:
2749 	case MBX_READ_STATUS:
2750 	case MBX_READ_RPI:
2751 	case MBX_READ_XRI:
2752 	case MBX_READ_REV:
2753 	case MBX_READ_LNK_STAT:
2754 	case MBX_REG_LOGIN:
2755 	case MBX_UNREG_LOGIN:
2756 	case MBX_CLEAR_LA:
2757 	case MBX_DUMP_MEMORY:
2758 	case MBX_DUMP_CONTEXT:
2759 	case MBX_RUN_DIAGS:
2760 	case MBX_RESTART:
2761 	case MBX_UPDATE_CFG:
2762 	case MBX_DOWN_LOAD:
2763 	case MBX_DEL_LD_ENTRY:
2764 	case MBX_RUN_PROGRAM:
2765 	case MBX_SET_MASK:
2766 	case MBX_SET_VARIABLE:
2767 	case MBX_UNREG_D_ID:
2768 	case MBX_KILL_BOARD:
2769 	case MBX_CONFIG_FARP:
2770 	case MBX_BEACON:
2771 	case MBX_LOAD_AREA:
2772 	case MBX_RUN_BIU_DIAG64:
2773 	case MBX_CONFIG_PORT:
2774 	case MBX_READ_SPARM64:
2775 	case MBX_READ_RPI64:
2776 	case MBX_REG_LOGIN64:
2777 	case MBX_READ_TOPOLOGY:
2778 	case MBX_WRITE_WWN:
2779 	case MBX_SET_DEBUG:
2780 	case MBX_LOAD_EXP_ROM:
2781 	case MBX_ASYNCEVT_ENABLE:
2782 	case MBX_REG_VPI:
2783 	case MBX_UNREG_VPI:
2784 	case MBX_HEARTBEAT:
2785 	case MBX_PORT_CAPABILITIES:
2786 	case MBX_PORT_IOV_CONTROL:
2787 	case MBX_SLI4_CONFIG:
2788 	case MBX_SLI4_REQ_FTRS:
2789 	case MBX_REG_FCFI:
2790 	case MBX_UNREG_FCFI:
2791 	case MBX_REG_VFI:
2792 	case MBX_UNREG_VFI:
2793 	case MBX_INIT_VPI:
2794 	case MBX_INIT_VFI:
2795 	case MBX_RESUME_RPI:
2796 	case MBX_READ_EVENT_LOG_STATUS:
2797 	case MBX_READ_EVENT_LOG:
2798 	case MBX_SECURITY_MGMT:
2799 	case MBX_AUTH_PORT:
2800 	case MBX_ACCESS_VDATA:
2801 		ret = mbxCommand;
2802 		break;
2803 	default:
2804 		ret = MBX_SHUTDOWN;
2805 		break;
2806 	}
2807 	return ret;
2808 }
2809 
2810 /**
2811  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2812  * @phba: Pointer to HBA context object.
2813  * @pmboxq: Pointer to mailbox command.
2814  *
2815  * This is completion handler function for mailbox commands issued from
2816  * lpfc_sli_issue_mbox_wait function. This function is called by the
2817  * mailbox event handler function with no lock held. This function
2818  * will wake up thread waiting on the wait queue pointed by context1
2819  * of the mailbox.
2820  **/
2821 void
2822 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2823 {
2824 	unsigned long drvr_flag;
2825 	struct completion *pmbox_done;
2826 
2827 	/*
2828 	 * If pmbox_done is empty, the driver thread gave up waiting and
2829 	 * continued running.
2830 	 */
2831 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2832 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2833 	pmbox_done = (struct completion *)pmboxq->context3;
2834 	if (pmbox_done)
2835 		complete(pmbox_done);
2836 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2837 	return;
2838 }
2839 
2840 static void
2841 __lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2842 {
2843 	unsigned long iflags;
2844 
2845 	if (ndlp->nlp_flag & NLP_RELEASE_RPI) {
2846 		lpfc_sli4_free_rpi(vport->phba, ndlp->nlp_rpi);
2847 		spin_lock_irqsave(&ndlp->lock, iflags);
2848 		ndlp->nlp_flag &= ~NLP_RELEASE_RPI;
2849 		ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
2850 		spin_unlock_irqrestore(&ndlp->lock, iflags);
2851 	}
2852 	ndlp->nlp_flag &= ~NLP_UNREG_INP;
2853 }
2854 
2855 void
2856 lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2857 {
2858 	__lpfc_sli_rpi_release(vport, ndlp);
2859 }
2860 
2861 /**
2862  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2863  * @phba: Pointer to HBA context object.
2864  * @pmb: Pointer to mailbox object.
2865  *
2866  * This function is the default mailbox completion handler. It
2867  * frees the memory resources associated with the completed mailbox
2868  * command. If the completed command is a REG_LOGIN mailbox command,
2869  * this function will issue a UREG_LOGIN to re-claim the RPI.
2870  **/
2871 void
2872 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2873 {
2874 	struct lpfc_vport  *vport = pmb->vport;
2875 	struct lpfc_dmabuf *mp;
2876 	struct lpfc_nodelist *ndlp;
2877 	struct Scsi_Host *shost;
2878 	uint16_t rpi, vpi;
2879 	int rc;
2880 
2881 	/*
2882 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2883 	 * is in re-discovery driver need to cleanup the RPI.
2884 	 */
2885 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2886 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2887 	    !pmb->u.mb.mbxStatus) {
2888 		mp = (struct lpfc_dmabuf *)pmb->ctx_buf;
2889 		if (mp) {
2890 			pmb->ctx_buf = NULL;
2891 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
2892 			kfree(mp);
2893 		}
2894 		rpi = pmb->u.mb.un.varWords[0];
2895 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2896 		if (phba->sli_rev == LPFC_SLI_REV4)
2897 			vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2898 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2899 		pmb->vport = vport;
2900 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2901 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2902 		if (rc != MBX_NOT_FINISHED)
2903 			return;
2904 	}
2905 
2906 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2907 		!(phba->pport->load_flag & FC_UNLOADING) &&
2908 		!pmb->u.mb.mbxStatus) {
2909 		shost = lpfc_shost_from_vport(vport);
2910 		spin_lock_irq(shost->host_lock);
2911 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2912 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2913 		spin_unlock_irq(shost->host_lock);
2914 	}
2915 
2916 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2917 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2918 		lpfc_nlp_put(ndlp);
2919 	}
2920 
2921 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2922 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2923 
2924 		/* Check to see if there are any deferred events to process */
2925 		if (ndlp) {
2926 			lpfc_printf_vlog(
2927 				vport,
2928 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2929 				"1438 UNREG cmpl deferred mbox x%x "
2930 				"on NPort x%x Data: x%x x%x x%px x%x x%x\n",
2931 				ndlp->nlp_rpi, ndlp->nlp_DID,
2932 				ndlp->nlp_flag, ndlp->nlp_defer_did,
2933 				ndlp, vport->load_flag, kref_read(&ndlp->kref));
2934 
2935 			if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2936 			    (ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING)) {
2937 				ndlp->nlp_flag &= ~NLP_UNREG_INP;
2938 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2939 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2940 			} else {
2941 				__lpfc_sli_rpi_release(vport, ndlp);
2942 			}
2943 
2944 			/* The unreg_login mailbox is complete and had a
2945 			 * reference that has to be released.  The PLOGI
2946 			 * got its own ref.
2947 			 */
2948 			lpfc_nlp_put(ndlp);
2949 			pmb->ctx_ndlp = NULL;
2950 		}
2951 	}
2952 
2953 	/* This nlp_put pairs with lpfc_sli4_resume_rpi */
2954 	if (pmb->u.mb.mbxCommand == MBX_RESUME_RPI) {
2955 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2956 		lpfc_nlp_put(ndlp);
2957 	}
2958 
2959 	/* Check security permission status on INIT_LINK mailbox command */
2960 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2961 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2962 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2963 				"2860 SLI authentication is required "
2964 				"for INIT_LINK but has not done yet\n");
2965 
2966 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2967 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2968 	else
2969 		lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2970 }
2971  /**
2972  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2973  * @phba: Pointer to HBA context object.
2974  * @pmb: Pointer to mailbox object.
2975  *
2976  * This function is the unreg rpi mailbox completion handler. It
2977  * frees the memory resources associated with the completed mailbox
2978  * command. An additional reference is put on the ndlp to prevent
2979  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2980  * the unreg mailbox command completes, this routine puts the
2981  * reference back.
2982  *
2983  **/
2984 void
2985 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2986 {
2987 	struct lpfc_vport  *vport = pmb->vport;
2988 	struct lpfc_nodelist *ndlp;
2989 
2990 	ndlp = pmb->ctx_ndlp;
2991 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2992 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2993 		    (bf_get(lpfc_sli_intf_if_type,
2994 		     &phba->sli4_hba.sli_intf) >=
2995 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2996 			if (ndlp) {
2997 				lpfc_printf_vlog(
2998 					 vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2999 					 "0010 UNREG_LOGIN vpi:%x "
3000 					 "rpi:%x DID:%x defer x%x flg x%x "
3001 					 "x%px\n",
3002 					 vport->vpi, ndlp->nlp_rpi,
3003 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
3004 					 ndlp->nlp_flag,
3005 					 ndlp);
3006 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
3007 
3008 				/* Check to see if there are any deferred
3009 				 * events to process
3010 				 */
3011 				if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
3012 				    (ndlp->nlp_defer_did !=
3013 				    NLP_EVT_NOTHING_PENDING)) {
3014 					lpfc_printf_vlog(
3015 						vport, KERN_INFO, LOG_DISCOVERY,
3016 						"4111 UNREG cmpl deferred "
3017 						"clr x%x on "
3018 						"NPort x%x Data: x%x x%px\n",
3019 						ndlp->nlp_rpi, ndlp->nlp_DID,
3020 						ndlp->nlp_defer_did, ndlp);
3021 					ndlp->nlp_flag &= ~NLP_UNREG_INP;
3022 					ndlp->nlp_defer_did =
3023 						NLP_EVT_NOTHING_PENDING;
3024 					lpfc_issue_els_plogi(
3025 						vport, ndlp->nlp_DID, 0);
3026 				} else {
3027 					__lpfc_sli_rpi_release(vport, ndlp);
3028 				}
3029 				lpfc_nlp_put(ndlp);
3030 			}
3031 		}
3032 	}
3033 
3034 	mempool_free(pmb, phba->mbox_mem_pool);
3035 }
3036 
3037 /**
3038  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
3039  * @phba: Pointer to HBA context object.
3040  *
3041  * This function is called with no lock held. This function processes all
3042  * the completed mailbox commands and gives it to upper layers. The interrupt
3043  * service routine processes mailbox completion interrupt and adds completed
3044  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
3045  * Worker thread call lpfc_sli_handle_mb_event, which will return the
3046  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
3047  * function returns the mailbox commands to the upper layer by calling the
3048  * completion handler function of each mailbox.
3049  **/
3050 int
3051 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
3052 {
3053 	MAILBOX_t *pmbox;
3054 	LPFC_MBOXQ_t *pmb;
3055 	int rc;
3056 	LIST_HEAD(cmplq);
3057 
3058 	phba->sli.slistat.mbox_event++;
3059 
3060 	/* Get all completed mailboxe buffers into the cmplq */
3061 	spin_lock_irq(&phba->hbalock);
3062 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
3063 	spin_unlock_irq(&phba->hbalock);
3064 
3065 	/* Get a Mailbox buffer to setup mailbox commands for callback */
3066 	do {
3067 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
3068 		if (pmb == NULL)
3069 			break;
3070 
3071 		pmbox = &pmb->u.mb;
3072 
3073 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
3074 			if (pmb->vport) {
3075 				lpfc_debugfs_disc_trc(pmb->vport,
3076 					LPFC_DISC_TRC_MBOX_VPORT,
3077 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
3078 					(uint32_t)pmbox->mbxCommand,
3079 					pmbox->un.varWords[0],
3080 					pmbox->un.varWords[1]);
3081 			}
3082 			else {
3083 				lpfc_debugfs_disc_trc(phba->pport,
3084 					LPFC_DISC_TRC_MBOX,
3085 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
3086 					(uint32_t)pmbox->mbxCommand,
3087 					pmbox->un.varWords[0],
3088 					pmbox->un.varWords[1]);
3089 			}
3090 		}
3091 
3092 		/*
3093 		 * It is a fatal error if unknown mbox command completion.
3094 		 */
3095 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
3096 		    MBX_SHUTDOWN) {
3097 			/* Unknown mailbox command compl */
3098 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3099 					"(%d):0323 Unknown Mailbox command "
3100 					"x%x (x%x/x%x) Cmpl\n",
3101 					pmb->vport ? pmb->vport->vpi :
3102 					LPFC_VPORT_UNKNOWN,
3103 					pmbox->mbxCommand,
3104 					lpfc_sli_config_mbox_subsys_get(phba,
3105 									pmb),
3106 					lpfc_sli_config_mbox_opcode_get(phba,
3107 									pmb));
3108 			phba->link_state = LPFC_HBA_ERROR;
3109 			phba->work_hs = HS_FFER3;
3110 			lpfc_handle_eratt(phba);
3111 			continue;
3112 		}
3113 
3114 		if (pmbox->mbxStatus) {
3115 			phba->sli.slistat.mbox_stat_err++;
3116 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
3117 				/* Mbox cmd cmpl error - RETRYing */
3118 				lpfc_printf_log(phba, KERN_INFO,
3119 					LOG_MBOX | LOG_SLI,
3120 					"(%d):0305 Mbox cmd cmpl "
3121 					"error - RETRYing Data: x%x "
3122 					"(x%x/x%x) x%x x%x x%x\n",
3123 					pmb->vport ? pmb->vport->vpi :
3124 					LPFC_VPORT_UNKNOWN,
3125 					pmbox->mbxCommand,
3126 					lpfc_sli_config_mbox_subsys_get(phba,
3127 									pmb),
3128 					lpfc_sli_config_mbox_opcode_get(phba,
3129 									pmb),
3130 					pmbox->mbxStatus,
3131 					pmbox->un.varWords[0],
3132 					pmb->vport ? pmb->vport->port_state :
3133 					LPFC_VPORT_UNKNOWN);
3134 				pmbox->mbxStatus = 0;
3135 				pmbox->mbxOwner = OWN_HOST;
3136 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3137 				if (rc != MBX_NOT_FINISHED)
3138 					continue;
3139 			}
3140 		}
3141 
3142 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
3143 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
3144 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
3145 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
3146 				"x%x x%x x%x\n",
3147 				pmb->vport ? pmb->vport->vpi : 0,
3148 				pmbox->mbxCommand,
3149 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
3150 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
3151 				pmb->mbox_cmpl,
3152 				*((uint32_t *) pmbox),
3153 				pmbox->un.varWords[0],
3154 				pmbox->un.varWords[1],
3155 				pmbox->un.varWords[2],
3156 				pmbox->un.varWords[3],
3157 				pmbox->un.varWords[4],
3158 				pmbox->un.varWords[5],
3159 				pmbox->un.varWords[6],
3160 				pmbox->un.varWords[7],
3161 				pmbox->un.varWords[8],
3162 				pmbox->un.varWords[9],
3163 				pmbox->un.varWords[10]);
3164 
3165 		if (pmb->mbox_cmpl)
3166 			pmb->mbox_cmpl(phba,pmb);
3167 	} while (1);
3168 	return 0;
3169 }
3170 
3171 /**
3172  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
3173  * @phba: Pointer to HBA context object.
3174  * @pring: Pointer to driver SLI ring object.
3175  * @tag: buffer tag.
3176  *
3177  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
3178  * is set in the tag the buffer is posted for a particular exchange,
3179  * the function will return the buffer without replacing the buffer.
3180  * If the buffer is for unsolicited ELS or CT traffic, this function
3181  * returns the buffer and also posts another buffer to the firmware.
3182  **/
3183 static struct lpfc_dmabuf *
3184 lpfc_sli_get_buff(struct lpfc_hba *phba,
3185 		  struct lpfc_sli_ring *pring,
3186 		  uint32_t tag)
3187 {
3188 	struct hbq_dmabuf *hbq_entry;
3189 
3190 	if (tag & QUE_BUFTAG_BIT)
3191 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
3192 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
3193 	if (!hbq_entry)
3194 		return NULL;
3195 	return &hbq_entry->dbuf;
3196 }
3197 
3198 /**
3199  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
3200  *                              containing a NVME LS request.
3201  * @phba: pointer to lpfc hba data structure.
3202  * @piocb: pointer to the iocbq struct representing the sequence starting
3203  *        frame.
3204  *
3205  * This routine initially validates the NVME LS, validates there is a login
3206  * with the port that sent the LS, and then calls the appropriate nvme host
3207  * or target LS request handler.
3208  **/
3209 static void
3210 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
3211 {
3212 	struct lpfc_nodelist *ndlp;
3213 	struct lpfc_dmabuf *d_buf;
3214 	struct hbq_dmabuf *nvmebuf;
3215 	struct fc_frame_header *fc_hdr;
3216 	struct lpfc_async_xchg_ctx *axchg = NULL;
3217 	char *failwhy = NULL;
3218 	uint32_t oxid, sid, did, fctl, size;
3219 	int ret = 1;
3220 
3221 	d_buf = piocb->cmd_dmabuf;
3222 
3223 	nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
3224 	fc_hdr = nvmebuf->hbuf.virt;
3225 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
3226 	sid = sli4_sid_from_fc_hdr(fc_hdr);
3227 	did = sli4_did_from_fc_hdr(fc_hdr);
3228 	fctl = (fc_hdr->fh_f_ctl[0] << 16 |
3229 		fc_hdr->fh_f_ctl[1] << 8 |
3230 		fc_hdr->fh_f_ctl[2]);
3231 	size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
3232 
3233 	lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
3234 			 oxid, size, sid);
3235 
3236 	if (phba->pport->load_flag & FC_UNLOADING) {
3237 		failwhy = "Driver Unloading";
3238 	} else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
3239 		failwhy = "NVME FC4 Disabled";
3240 	} else if (!phba->nvmet_support && !phba->pport->localport) {
3241 		failwhy = "No Localport";
3242 	} else if (phba->nvmet_support && !phba->targetport) {
3243 		failwhy = "No Targetport";
3244 	} else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
3245 		failwhy = "Bad NVME LS R_CTL";
3246 	} else if (unlikely((fctl & 0x00FF0000) !=
3247 			(FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
3248 		failwhy = "Bad NVME LS F_CTL";
3249 	} else {
3250 		axchg = kzalloc(sizeof(*axchg), GFP_ATOMIC);
3251 		if (!axchg)
3252 			failwhy = "No CTX memory";
3253 	}
3254 
3255 	if (unlikely(failwhy)) {
3256 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3257 				"6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
3258 				sid, oxid, failwhy);
3259 		goto out_fail;
3260 	}
3261 
3262 	/* validate the source of the LS is logged in */
3263 	ndlp = lpfc_findnode_did(phba->pport, sid);
3264 	if (!ndlp ||
3265 	    ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
3266 	     (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
3267 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
3268 				"6216 NVME Unsol rcv: No ndlp: "
3269 				"NPort_ID x%x oxid x%x\n",
3270 				sid, oxid);
3271 		goto out_fail;
3272 	}
3273 
3274 	axchg->phba = phba;
3275 	axchg->ndlp = ndlp;
3276 	axchg->size = size;
3277 	axchg->oxid = oxid;
3278 	axchg->sid = sid;
3279 	axchg->wqeq = NULL;
3280 	axchg->state = LPFC_NVME_STE_LS_RCV;
3281 	axchg->entry_cnt = 1;
3282 	axchg->rqb_buffer = (void *)nvmebuf;
3283 	axchg->hdwq = &phba->sli4_hba.hdwq[0];
3284 	axchg->payload = nvmebuf->dbuf.virt;
3285 	INIT_LIST_HEAD(&axchg->list);
3286 
3287 	if (phba->nvmet_support) {
3288 		ret = lpfc_nvmet_handle_lsreq(phba, axchg);
3289 		spin_lock_irq(&ndlp->lock);
3290 		if (!ret && !(ndlp->fc4_xpt_flags & NLP_XPT_HAS_HH)) {
3291 			ndlp->fc4_xpt_flags |= NLP_XPT_HAS_HH;
3292 			spin_unlock_irq(&ndlp->lock);
3293 
3294 			/* This reference is a single occurrence to hold the
3295 			 * node valid until the nvmet transport calls
3296 			 * host_release.
3297 			 */
3298 			if (!lpfc_nlp_get(ndlp))
3299 				goto out_fail;
3300 
3301 			lpfc_printf_log(phba, KERN_ERR, LOG_NODE,
3302 					"6206 NVMET unsol ls_req ndlp x%px "
3303 					"DID x%x xflags x%x refcnt %d\n",
3304 					ndlp, ndlp->nlp_DID,
3305 					ndlp->fc4_xpt_flags,
3306 					kref_read(&ndlp->kref));
3307 		} else {
3308 			spin_unlock_irq(&ndlp->lock);
3309 		}
3310 	} else {
3311 		ret = lpfc_nvme_handle_lsreq(phba, axchg);
3312 	}
3313 
3314 	/* if zero, LS was successfully handled. If non-zero, LS not handled */
3315 	if (!ret)
3316 		return;
3317 
3318 out_fail:
3319 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3320 			"6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
3321 			"NVMe%s handler failed %d\n",
3322 			did, sid, oxid,
3323 			(phba->nvmet_support) ? "T" : "I", ret);
3324 
3325 	/* recycle receive buffer */
3326 	lpfc_in_buf_free(phba, &nvmebuf->dbuf);
3327 
3328 	/* If start of new exchange, abort it */
3329 	if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
3330 		ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
3331 
3332 	if (ret)
3333 		kfree(axchg);
3334 }
3335 
3336 /**
3337  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
3338  * @phba: Pointer to HBA context object.
3339  * @pring: Pointer to driver SLI ring object.
3340  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
3341  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
3342  * @fch_type: the type for the first frame of the sequence.
3343  *
3344  * This function is called with no lock held. This function uses the r_ctl and
3345  * type of the received sequence to find the correct callback function to call
3346  * to process the sequence.
3347  **/
3348 static int
3349 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3350 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
3351 			 uint32_t fch_type)
3352 {
3353 	int i;
3354 
3355 	switch (fch_type) {
3356 	case FC_TYPE_NVME:
3357 		lpfc_nvme_unsol_ls_handler(phba, saveq);
3358 		return 1;
3359 	default:
3360 		break;
3361 	}
3362 
3363 	/* unSolicited Responses */
3364 	if (pring->prt[0].profile) {
3365 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
3366 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
3367 									saveq);
3368 		return 1;
3369 	}
3370 	/* We must search, based on rctl / type
3371 	   for the right routine */
3372 	for (i = 0; i < pring->num_mask; i++) {
3373 		if ((pring->prt[i].rctl == fch_r_ctl) &&
3374 		    (pring->prt[i].type == fch_type)) {
3375 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
3376 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
3377 						(phba, pring, saveq);
3378 			return 1;
3379 		}
3380 	}
3381 	return 0;
3382 }
3383 
3384 static void
3385 lpfc_sli_prep_unsol_wqe(struct lpfc_hba *phba,
3386 			struct lpfc_iocbq *saveq)
3387 {
3388 	IOCB_t *irsp;
3389 	union lpfc_wqe128 *wqe;
3390 	u16 i = 0;
3391 
3392 	irsp = &saveq->iocb;
3393 	wqe = &saveq->wqe;
3394 
3395 	/* Fill wcqe with the IOCB status fields */
3396 	bf_set(lpfc_wcqe_c_status, &saveq->wcqe_cmpl, irsp->ulpStatus);
3397 	saveq->wcqe_cmpl.word3 = irsp->ulpBdeCount;
3398 	saveq->wcqe_cmpl.parameter = irsp->un.ulpWord[4];
3399 	saveq->wcqe_cmpl.total_data_placed = irsp->unsli3.rcvsli3.acc_len;
3400 
3401 	/* Source ID */
3402 	bf_set(els_rsp64_sid, &wqe->xmit_els_rsp, irsp->un.rcvels.parmRo);
3403 
3404 	/* rx-id of the response frame */
3405 	bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com, irsp->ulpContext);
3406 
3407 	/* ox-id of the frame */
3408 	bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
3409 	       irsp->unsli3.rcvsli3.ox_id);
3410 
3411 	/* DID */
3412 	bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
3413 	       irsp->un.rcvels.remoteID);
3414 
3415 	/* unsol data len */
3416 	for (i = 0; i < irsp->ulpBdeCount; i++) {
3417 		struct lpfc_hbq_entry *hbqe = NULL;
3418 
3419 		if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3420 			if (i == 0) {
3421 				hbqe = (struct lpfc_hbq_entry *)
3422 					&irsp->un.ulpWord[0];
3423 				saveq->wqe.gen_req.bde.tus.f.bdeSize =
3424 					hbqe->bde.tus.f.bdeSize;
3425 			} else if (i == 1) {
3426 				hbqe = (struct lpfc_hbq_entry *)
3427 					&irsp->unsli3.sli3Words[4];
3428 				saveq->unsol_rcv_len = hbqe->bde.tus.f.bdeSize;
3429 			}
3430 		}
3431 	}
3432 }
3433 
3434 /**
3435  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
3436  * @phba: Pointer to HBA context object.
3437  * @pring: Pointer to driver SLI ring object.
3438  * @saveq: Pointer to the unsolicited iocb.
3439  *
3440  * This function is called with no lock held by the ring event handler
3441  * when there is an unsolicited iocb posted to the response ring by the
3442  * firmware. This function gets the buffer associated with the iocbs
3443  * and calls the event handler for the ring. This function handles both
3444  * qring buffers and hbq buffers.
3445  * When the function returns 1 the caller can free the iocb object otherwise
3446  * upper layer functions will free the iocb objects.
3447  **/
3448 static int
3449 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3450 			    struct lpfc_iocbq *saveq)
3451 {
3452 	IOCB_t           * irsp;
3453 	WORD5            * w5p;
3454 	dma_addr_t	 paddr;
3455 	uint32_t           Rctl, Type;
3456 	struct lpfc_iocbq *iocbq;
3457 	struct lpfc_dmabuf *dmzbuf;
3458 
3459 	irsp = &saveq->iocb;
3460 	saveq->vport = phba->pport;
3461 
3462 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
3463 		if (pring->lpfc_sli_rcv_async_status)
3464 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
3465 		else
3466 			lpfc_printf_log(phba,
3467 					KERN_WARNING,
3468 					LOG_SLI,
3469 					"0316 Ring %d handler: unexpected "
3470 					"ASYNC_STATUS iocb received evt_code "
3471 					"0x%x\n",
3472 					pring->ringno,
3473 					irsp->un.asyncstat.evt_code);
3474 		return 1;
3475 	}
3476 
3477 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3478 	    (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3479 		if (irsp->ulpBdeCount > 0) {
3480 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3481 						   irsp->un.ulpWord[3]);
3482 			lpfc_in_buf_free(phba, dmzbuf);
3483 		}
3484 
3485 		if (irsp->ulpBdeCount > 1) {
3486 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3487 						   irsp->unsli3.sli3Words[3]);
3488 			lpfc_in_buf_free(phba, dmzbuf);
3489 		}
3490 
3491 		if (irsp->ulpBdeCount > 2) {
3492 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3493 						   irsp->unsli3.sli3Words[7]);
3494 			lpfc_in_buf_free(phba, dmzbuf);
3495 		}
3496 
3497 		return 1;
3498 	}
3499 
3500 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3501 		if (irsp->ulpBdeCount != 0) {
3502 			saveq->cmd_dmabuf = lpfc_sli_get_buff(phba, pring,
3503 						irsp->un.ulpWord[3]);
3504 			if (!saveq->cmd_dmabuf)
3505 				lpfc_printf_log(phba,
3506 					KERN_ERR,
3507 					LOG_SLI,
3508 					"0341 Ring %d Cannot find buffer for "
3509 					"an unsolicited iocb. tag 0x%x\n",
3510 					pring->ringno,
3511 					irsp->un.ulpWord[3]);
3512 		}
3513 		if (irsp->ulpBdeCount == 2) {
3514 			saveq->bpl_dmabuf = lpfc_sli_get_buff(phba, pring,
3515 						irsp->unsli3.sli3Words[7]);
3516 			if (!saveq->bpl_dmabuf)
3517 				lpfc_printf_log(phba,
3518 					KERN_ERR,
3519 					LOG_SLI,
3520 					"0342 Ring %d Cannot find buffer for an"
3521 					" unsolicited iocb. tag 0x%x\n",
3522 					pring->ringno,
3523 					irsp->unsli3.sli3Words[7]);
3524 		}
3525 		list_for_each_entry(iocbq, &saveq->list, list) {
3526 			irsp = &iocbq->iocb;
3527 			if (irsp->ulpBdeCount != 0) {
3528 				iocbq->cmd_dmabuf = lpfc_sli_get_buff(phba,
3529 							pring,
3530 							irsp->un.ulpWord[3]);
3531 				if (!iocbq->cmd_dmabuf)
3532 					lpfc_printf_log(phba,
3533 						KERN_ERR,
3534 						LOG_SLI,
3535 						"0343 Ring %d Cannot find "
3536 						"buffer for an unsolicited iocb"
3537 						". tag 0x%x\n", pring->ringno,
3538 						irsp->un.ulpWord[3]);
3539 			}
3540 			if (irsp->ulpBdeCount == 2) {
3541 				iocbq->bpl_dmabuf = lpfc_sli_get_buff(phba,
3542 						pring,
3543 						irsp->unsli3.sli3Words[7]);
3544 				if (!iocbq->bpl_dmabuf)
3545 					lpfc_printf_log(phba,
3546 						KERN_ERR,
3547 						LOG_SLI,
3548 						"0344 Ring %d Cannot find "
3549 						"buffer for an unsolicited "
3550 						"iocb. tag 0x%x\n",
3551 						pring->ringno,
3552 						irsp->unsli3.sli3Words[7]);
3553 			}
3554 		}
3555 	} else {
3556 		paddr = getPaddr(irsp->un.cont64[0].addrHigh,
3557 				 irsp->un.cont64[0].addrLow);
3558 		saveq->cmd_dmabuf = lpfc_sli_ringpostbuf_get(phba, pring,
3559 							     paddr);
3560 		if (irsp->ulpBdeCount == 2) {
3561 			paddr = getPaddr(irsp->un.cont64[1].addrHigh,
3562 					 irsp->un.cont64[1].addrLow);
3563 			saveq->bpl_dmabuf = lpfc_sli_ringpostbuf_get(phba,
3564 								   pring,
3565 								   paddr);
3566 		}
3567 	}
3568 
3569 	if (irsp->ulpBdeCount != 0 &&
3570 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3571 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3572 		int found = 0;
3573 
3574 		/* search continue save q for same XRI */
3575 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3576 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3577 				saveq->iocb.unsli3.rcvsli3.ox_id) {
3578 				list_add_tail(&saveq->list, &iocbq->list);
3579 				found = 1;
3580 				break;
3581 			}
3582 		}
3583 		if (!found)
3584 			list_add_tail(&saveq->clist,
3585 				      &pring->iocb_continue_saveq);
3586 
3587 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3588 			list_del_init(&iocbq->clist);
3589 			saveq = iocbq;
3590 			irsp = &saveq->iocb;
3591 		} else {
3592 			return 0;
3593 		}
3594 	}
3595 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3596 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3597 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3598 		Rctl = FC_RCTL_ELS_REQ;
3599 		Type = FC_TYPE_ELS;
3600 	} else {
3601 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3602 		Rctl = w5p->hcsw.Rctl;
3603 		Type = w5p->hcsw.Type;
3604 
3605 		/* Firmware Workaround */
3606 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3607 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3608 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3609 			Rctl = FC_RCTL_ELS_REQ;
3610 			Type = FC_TYPE_ELS;
3611 			w5p->hcsw.Rctl = Rctl;
3612 			w5p->hcsw.Type = Type;
3613 		}
3614 	}
3615 
3616 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) &&
3617 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX ||
3618 	    irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3619 		if (irsp->unsli3.rcvsli3.vpi == 0xffff)
3620 			saveq->vport = phba->pport;
3621 		else
3622 			saveq->vport = lpfc_find_vport_by_vpid(phba,
3623 					       irsp->unsli3.rcvsli3.vpi);
3624 	}
3625 
3626 	/* Prepare WQE with Unsol frame */
3627 	lpfc_sli_prep_unsol_wqe(phba, saveq);
3628 
3629 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3630 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3631 				"0313 Ring %d handler: unexpected Rctl x%x "
3632 				"Type x%x received\n",
3633 				pring->ringno, Rctl, Type);
3634 
3635 	return 1;
3636 }
3637 
3638 /**
3639  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3640  * @phba: Pointer to HBA context object.
3641  * @pring: Pointer to driver SLI ring object.
3642  * @prspiocb: Pointer to response iocb object.
3643  *
3644  * This function looks up the iocb_lookup table to get the command iocb
3645  * corresponding to the given response iocb using the iotag of the
3646  * response iocb. The driver calls this function with the hbalock held
3647  * for SLI3 ports or the ring lock held for SLI4 ports.
3648  * This function returns the command iocb object if it finds the command
3649  * iocb else returns NULL.
3650  **/
3651 static struct lpfc_iocbq *
3652 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3653 		      struct lpfc_sli_ring *pring,
3654 		      struct lpfc_iocbq *prspiocb)
3655 {
3656 	struct lpfc_iocbq *cmd_iocb = NULL;
3657 	u16 iotag;
3658 
3659 	if (phba->sli_rev == LPFC_SLI_REV4)
3660 		iotag = get_wqe_reqtag(prspiocb);
3661 	else
3662 		iotag = prspiocb->iocb.ulpIoTag;
3663 
3664 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3665 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3666 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3667 			/* remove from txcmpl queue list */
3668 			list_del_init(&cmd_iocb->list);
3669 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3670 			pring->txcmplq_cnt--;
3671 			return cmd_iocb;
3672 		}
3673 	}
3674 
3675 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3676 			"0317 iotag x%x is out of "
3677 			"range: max iotag x%x\n",
3678 			iotag, phba->sli.last_iotag);
3679 	return NULL;
3680 }
3681 
3682 /**
3683  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3684  * @phba: Pointer to HBA context object.
3685  * @pring: Pointer to driver SLI ring object.
3686  * @iotag: IOCB tag.
3687  *
3688  * This function looks up the iocb_lookup table to get the command iocb
3689  * corresponding to the given iotag. The driver calls this function with
3690  * the ring lock held because this function is an SLI4 port only helper.
3691  * This function returns the command iocb object if it finds the command
3692  * iocb else returns NULL.
3693  **/
3694 static struct lpfc_iocbq *
3695 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3696 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3697 {
3698 	struct lpfc_iocbq *cmd_iocb = NULL;
3699 
3700 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3701 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3702 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3703 			/* remove from txcmpl queue list */
3704 			list_del_init(&cmd_iocb->list);
3705 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3706 			pring->txcmplq_cnt--;
3707 			return cmd_iocb;
3708 		}
3709 	}
3710 
3711 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3712 			"0372 iotag x%x lookup error: max iotag (x%x) "
3713 			"cmd_flag x%x\n",
3714 			iotag, phba->sli.last_iotag,
3715 			cmd_iocb ? cmd_iocb->cmd_flag : 0xffff);
3716 	return NULL;
3717 }
3718 
3719 /**
3720  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3721  * @phba: Pointer to HBA context object.
3722  * @pring: Pointer to driver SLI ring object.
3723  * @saveq: Pointer to the response iocb to be processed.
3724  *
3725  * This function is called by the ring event handler for non-fcp
3726  * rings when there is a new response iocb in the response ring.
3727  * The caller is not required to hold any locks. This function
3728  * gets the command iocb associated with the response iocb and
3729  * calls the completion handler for the command iocb. If there
3730  * is no completion handler, the function will free the resources
3731  * associated with command iocb. If the response iocb is for
3732  * an already aborted command iocb, the status of the completion
3733  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3734  * This function always returns 1.
3735  **/
3736 static int
3737 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3738 			  struct lpfc_iocbq *saveq)
3739 {
3740 	struct lpfc_iocbq *cmdiocbp;
3741 	unsigned long iflag;
3742 	u32 ulp_command, ulp_status, ulp_word4, ulp_context, iotag;
3743 
3744 	if (phba->sli_rev == LPFC_SLI_REV4)
3745 		spin_lock_irqsave(&pring->ring_lock, iflag);
3746 	else
3747 		spin_lock_irqsave(&phba->hbalock, iflag);
3748 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3749 	if (phba->sli_rev == LPFC_SLI_REV4)
3750 		spin_unlock_irqrestore(&pring->ring_lock, iflag);
3751 	else
3752 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3753 
3754 	ulp_command = get_job_cmnd(phba, saveq);
3755 	ulp_status = get_job_ulpstatus(phba, saveq);
3756 	ulp_word4 = get_job_word4(phba, saveq);
3757 	ulp_context = get_job_ulpcontext(phba, saveq);
3758 	if (phba->sli_rev == LPFC_SLI_REV4)
3759 		iotag = get_wqe_reqtag(saveq);
3760 	else
3761 		iotag = saveq->iocb.ulpIoTag;
3762 
3763 	if (cmdiocbp) {
3764 		ulp_command = get_job_cmnd(phba, cmdiocbp);
3765 		if (cmdiocbp->cmd_cmpl) {
3766 			/*
3767 			 * If an ELS command failed send an event to mgmt
3768 			 * application.
3769 			 */
3770 			if (ulp_status &&
3771 			     (pring->ringno == LPFC_ELS_RING) &&
3772 			     (ulp_command == CMD_ELS_REQUEST64_CR))
3773 				lpfc_send_els_failure_event(phba,
3774 					cmdiocbp, saveq);
3775 
3776 			/*
3777 			 * Post all ELS completions to the worker thread.
3778 			 * All other are passed to the completion callback.
3779 			 */
3780 			if (pring->ringno == LPFC_ELS_RING) {
3781 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3782 				    (cmdiocbp->cmd_flag &
3783 							LPFC_DRIVER_ABORTED)) {
3784 					spin_lock_irqsave(&phba->hbalock,
3785 							  iflag);
3786 					cmdiocbp->cmd_flag &=
3787 						~LPFC_DRIVER_ABORTED;
3788 					spin_unlock_irqrestore(&phba->hbalock,
3789 							       iflag);
3790 					saveq->iocb.ulpStatus =
3791 						IOSTAT_LOCAL_REJECT;
3792 					saveq->iocb.un.ulpWord[4] =
3793 						IOERR_SLI_ABORTED;
3794 
3795 					/* Firmware could still be in progress
3796 					 * of DMAing payload, so don't free data
3797 					 * buffer till after a hbeat.
3798 					 */
3799 					spin_lock_irqsave(&phba->hbalock,
3800 							  iflag);
3801 					saveq->cmd_flag |= LPFC_DELAY_MEM_FREE;
3802 					spin_unlock_irqrestore(&phba->hbalock,
3803 							       iflag);
3804 				}
3805 				if (phba->sli_rev == LPFC_SLI_REV4) {
3806 					if (saveq->cmd_flag &
3807 					    LPFC_EXCHANGE_BUSY) {
3808 						/* Set cmdiocb flag for the
3809 						 * exchange busy so sgl (xri)
3810 						 * will not be released until
3811 						 * the abort xri is received
3812 						 * from hba.
3813 						 */
3814 						spin_lock_irqsave(
3815 							&phba->hbalock, iflag);
3816 						cmdiocbp->cmd_flag |=
3817 							LPFC_EXCHANGE_BUSY;
3818 						spin_unlock_irqrestore(
3819 							&phba->hbalock, iflag);
3820 					}
3821 					if (cmdiocbp->cmd_flag &
3822 					    LPFC_DRIVER_ABORTED) {
3823 						/*
3824 						 * Clear LPFC_DRIVER_ABORTED
3825 						 * bit in case it was driver
3826 						 * initiated abort.
3827 						 */
3828 						spin_lock_irqsave(
3829 							&phba->hbalock, iflag);
3830 						cmdiocbp->cmd_flag &=
3831 							~LPFC_DRIVER_ABORTED;
3832 						spin_unlock_irqrestore(
3833 							&phba->hbalock, iflag);
3834 						set_job_ulpstatus(cmdiocbp,
3835 								  IOSTAT_LOCAL_REJECT);
3836 						set_job_ulpword4(cmdiocbp,
3837 								 IOERR_ABORT_REQUESTED);
3838 						/*
3839 						 * For SLI4, irspiocb contains
3840 						 * NO_XRI in sli_xritag, it
3841 						 * shall not affect releasing
3842 						 * sgl (xri) process.
3843 						 */
3844 						set_job_ulpstatus(saveq,
3845 								  IOSTAT_LOCAL_REJECT);
3846 						set_job_ulpword4(saveq,
3847 								 IOERR_SLI_ABORTED);
3848 						spin_lock_irqsave(
3849 							&phba->hbalock, iflag);
3850 						saveq->cmd_flag |=
3851 							LPFC_DELAY_MEM_FREE;
3852 						spin_unlock_irqrestore(
3853 							&phba->hbalock, iflag);
3854 					}
3855 				}
3856 			}
3857 			cmdiocbp->cmd_cmpl(phba, cmdiocbp, saveq);
3858 		} else
3859 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3860 	} else {
3861 		/*
3862 		 * Unknown initiating command based on the response iotag.
3863 		 * This could be the case on the ELS ring because of
3864 		 * lpfc_els_abort().
3865 		 */
3866 		if (pring->ringno != LPFC_ELS_RING) {
3867 			/*
3868 			 * Ring <ringno> handler: unexpected completion IoTag
3869 			 * <IoTag>
3870 			 */
3871 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3872 					 "0322 Ring %d handler: "
3873 					 "unexpected completion IoTag x%x "
3874 					 "Data: x%x x%x x%x x%x\n",
3875 					 pring->ringno, iotag, ulp_status,
3876 					 ulp_word4, ulp_command, ulp_context);
3877 		}
3878 	}
3879 
3880 	return 1;
3881 }
3882 
3883 /**
3884  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3885  * @phba: Pointer to HBA context object.
3886  * @pring: Pointer to driver SLI ring object.
3887  *
3888  * This function is called from the iocb ring event handlers when
3889  * put pointer is ahead of the get pointer for a ring. This function signal
3890  * an error attention condition to the worker thread and the worker
3891  * thread will transition the HBA to offline state.
3892  **/
3893 static void
3894 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3895 {
3896 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3897 	/*
3898 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3899 	 * rsp ring <portRspMax>
3900 	 */
3901 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3902 			"0312 Ring %d handler: portRspPut %d "
3903 			"is bigger than rsp ring %d\n",
3904 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3905 			pring->sli.sli3.numRiocb);
3906 
3907 	phba->link_state = LPFC_HBA_ERROR;
3908 
3909 	/*
3910 	 * All error attention handlers are posted to
3911 	 * worker thread
3912 	 */
3913 	phba->work_ha |= HA_ERATT;
3914 	phba->work_hs = HS_FFER3;
3915 
3916 	lpfc_worker_wake_up(phba);
3917 
3918 	return;
3919 }
3920 
3921 /**
3922  * lpfc_poll_eratt - Error attention polling timer timeout handler
3923  * @t: Context to fetch pointer to address of HBA context object from.
3924  *
3925  * This function is invoked by the Error Attention polling timer when the
3926  * timer times out. It will check the SLI Error Attention register for
3927  * possible attention events. If so, it will post an Error Attention event
3928  * and wake up worker thread to process it. Otherwise, it will set up the
3929  * Error Attention polling timer for the next poll.
3930  **/
3931 void lpfc_poll_eratt(struct timer_list *t)
3932 {
3933 	struct lpfc_hba *phba;
3934 	uint32_t eratt = 0;
3935 	uint64_t sli_intr, cnt;
3936 
3937 	phba = from_timer(phba, t, eratt_poll);
3938 
3939 	/* Here we will also keep track of interrupts per sec of the hba */
3940 	sli_intr = phba->sli.slistat.sli_intr;
3941 
3942 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3943 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3944 			sli_intr);
3945 	else
3946 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3947 
3948 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3949 	do_div(cnt, phba->eratt_poll_interval);
3950 	phba->sli.slistat.sli_ips = cnt;
3951 
3952 	phba->sli.slistat.sli_prev_intr = sli_intr;
3953 
3954 	/* Check chip HA register for error event */
3955 	eratt = lpfc_sli_check_eratt(phba);
3956 
3957 	if (eratt)
3958 		/* Tell the worker thread there is work to do */
3959 		lpfc_worker_wake_up(phba);
3960 	else
3961 		/* Restart the timer for next eratt poll */
3962 		mod_timer(&phba->eratt_poll,
3963 			  jiffies +
3964 			  msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3965 	return;
3966 }
3967 
3968 
3969 /**
3970  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3971  * @phba: Pointer to HBA context object.
3972  * @pring: Pointer to driver SLI ring object.
3973  * @mask: Host attention register mask for this ring.
3974  *
3975  * This function is called from the interrupt context when there is a ring
3976  * event for the fcp ring. The caller does not hold any lock.
3977  * The function processes each response iocb in the response ring until it
3978  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3979  * LE bit set. The function will call the completion handler of the command iocb
3980  * if the response iocb indicates a completion for a command iocb or it is
3981  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3982  * function if this is an unsolicited iocb.
3983  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3984  * to check it explicitly.
3985  */
3986 int
3987 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3988 				struct lpfc_sli_ring *pring, uint32_t mask)
3989 {
3990 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3991 	IOCB_t *irsp = NULL;
3992 	IOCB_t *entry = NULL;
3993 	struct lpfc_iocbq *cmdiocbq = NULL;
3994 	struct lpfc_iocbq rspiocbq;
3995 	uint32_t status;
3996 	uint32_t portRspPut, portRspMax;
3997 	int rc = 1;
3998 	lpfc_iocb_type type;
3999 	unsigned long iflag;
4000 	uint32_t rsp_cmpl = 0;
4001 
4002 	spin_lock_irqsave(&phba->hbalock, iflag);
4003 	pring->stats.iocb_event++;
4004 
4005 	/*
4006 	 * The next available response entry should never exceed the maximum
4007 	 * entries.  If it does, treat it as an adapter hardware error.
4008 	 */
4009 	portRspMax = pring->sli.sli3.numRiocb;
4010 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4011 	if (unlikely(portRspPut >= portRspMax)) {
4012 		lpfc_sli_rsp_pointers_error(phba, pring);
4013 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4014 		return 1;
4015 	}
4016 	if (phba->fcp_ring_in_use) {
4017 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4018 		return 1;
4019 	} else
4020 		phba->fcp_ring_in_use = 1;
4021 
4022 	rmb();
4023 	while (pring->sli.sli3.rspidx != portRspPut) {
4024 		/*
4025 		 * Fetch an entry off the ring and copy it into a local data
4026 		 * structure.  The copy involves a byte-swap since the
4027 		 * network byte order and pci byte orders are different.
4028 		 */
4029 		entry = lpfc_resp_iocb(phba, pring);
4030 		phba->last_completion_time = jiffies;
4031 
4032 		if (++pring->sli.sli3.rspidx >= portRspMax)
4033 			pring->sli.sli3.rspidx = 0;
4034 
4035 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
4036 				      (uint32_t *) &rspiocbq.iocb,
4037 				      phba->iocb_rsp_size);
4038 		INIT_LIST_HEAD(&(rspiocbq.list));
4039 		irsp = &rspiocbq.iocb;
4040 
4041 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
4042 		pring->stats.iocb_rsp++;
4043 		rsp_cmpl++;
4044 
4045 		if (unlikely(irsp->ulpStatus)) {
4046 			/*
4047 			 * If resource errors reported from HBA, reduce
4048 			 * queuedepths of the SCSI device.
4049 			 */
4050 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
4051 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
4052 			     IOERR_NO_RESOURCES)) {
4053 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4054 				phba->lpfc_rampdown_queue_depth(phba);
4055 				spin_lock_irqsave(&phba->hbalock, iflag);
4056 			}
4057 
4058 			/* Rsp ring <ringno> error: IOCB */
4059 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4060 					"0336 Rsp Ring %d error: IOCB Data: "
4061 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
4062 					pring->ringno,
4063 					irsp->un.ulpWord[0],
4064 					irsp->un.ulpWord[1],
4065 					irsp->un.ulpWord[2],
4066 					irsp->un.ulpWord[3],
4067 					irsp->un.ulpWord[4],
4068 					irsp->un.ulpWord[5],
4069 					*(uint32_t *)&irsp->un1,
4070 					*((uint32_t *)&irsp->un1 + 1));
4071 		}
4072 
4073 		switch (type) {
4074 		case LPFC_ABORT_IOCB:
4075 		case LPFC_SOL_IOCB:
4076 			/*
4077 			 * Idle exchange closed via ABTS from port.  No iocb
4078 			 * resources need to be recovered.
4079 			 */
4080 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
4081 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4082 						"0333 IOCB cmd 0x%x"
4083 						" processed. Skipping"
4084 						" completion\n",
4085 						irsp->ulpCommand);
4086 				break;
4087 			}
4088 
4089 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
4090 							 &rspiocbq);
4091 			if (unlikely(!cmdiocbq))
4092 				break;
4093 			if (cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED)
4094 				cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
4095 			if (cmdiocbq->cmd_cmpl) {
4096 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4097 				cmdiocbq->cmd_cmpl(phba, cmdiocbq, &rspiocbq);
4098 				spin_lock_irqsave(&phba->hbalock, iflag);
4099 			}
4100 			break;
4101 		case LPFC_UNSOL_IOCB:
4102 			spin_unlock_irqrestore(&phba->hbalock, iflag);
4103 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
4104 			spin_lock_irqsave(&phba->hbalock, iflag);
4105 			break;
4106 		default:
4107 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
4108 				char adaptermsg[LPFC_MAX_ADPTMSG];
4109 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4110 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
4111 				       MAX_MSG_DATA);
4112 				dev_warn(&((phba->pcidev)->dev),
4113 					 "lpfc%d: %s\n",
4114 					 phba->brd_no, adaptermsg);
4115 			} else {
4116 				/* Unknown IOCB command */
4117 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4118 						"0334 Unknown IOCB command "
4119 						"Data: x%x, x%x x%x x%x x%x\n",
4120 						type, irsp->ulpCommand,
4121 						irsp->ulpStatus,
4122 						irsp->ulpIoTag,
4123 						irsp->ulpContext);
4124 			}
4125 			break;
4126 		}
4127 
4128 		/*
4129 		 * The response IOCB has been processed.  Update the ring
4130 		 * pointer in SLIM.  If the port response put pointer has not
4131 		 * been updated, sync the pgp->rspPutInx and fetch the new port
4132 		 * response put pointer.
4133 		 */
4134 		writel(pring->sli.sli3.rspidx,
4135 			&phba->host_gp[pring->ringno].rspGetInx);
4136 
4137 		if (pring->sli.sli3.rspidx == portRspPut)
4138 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4139 	}
4140 
4141 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
4142 		pring->stats.iocb_rsp_full++;
4143 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4144 		writel(status, phba->CAregaddr);
4145 		readl(phba->CAregaddr);
4146 	}
4147 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4148 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4149 		pring->stats.iocb_cmd_empty++;
4150 
4151 		/* Force update of the local copy of cmdGetInx */
4152 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4153 		lpfc_sli_resume_iocb(phba, pring);
4154 
4155 		if ((pring->lpfc_sli_cmd_available))
4156 			(pring->lpfc_sli_cmd_available) (phba, pring);
4157 
4158 	}
4159 
4160 	phba->fcp_ring_in_use = 0;
4161 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4162 	return rc;
4163 }
4164 
4165 /**
4166  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
4167  * @phba: Pointer to HBA context object.
4168  * @pring: Pointer to driver SLI ring object.
4169  * @rspiocbp: Pointer to driver response IOCB object.
4170  *
4171  * This function is called from the worker thread when there is a slow-path
4172  * response IOCB to process. This function chains all the response iocbs until
4173  * seeing the iocb with the LE bit set. The function will call
4174  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
4175  * completion of a command iocb. The function will call the
4176  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
4177  * The function frees the resources or calls the completion handler if this
4178  * iocb is an abort completion. The function returns NULL when the response
4179  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
4180  * this function shall chain the iocb on to the iocb_continueq and return the
4181  * response iocb passed in.
4182  **/
4183 static struct lpfc_iocbq *
4184 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
4185 			struct lpfc_iocbq *rspiocbp)
4186 {
4187 	struct lpfc_iocbq *saveq;
4188 	struct lpfc_iocbq *cmdiocb;
4189 	struct lpfc_iocbq *next_iocb;
4190 	IOCB_t *irsp;
4191 	uint32_t free_saveq;
4192 	u8 cmd_type;
4193 	lpfc_iocb_type type;
4194 	unsigned long iflag;
4195 	u32 ulp_status = get_job_ulpstatus(phba, rspiocbp);
4196 	u32 ulp_word4 = get_job_word4(phba, rspiocbp);
4197 	u32 ulp_command = get_job_cmnd(phba, rspiocbp);
4198 	int rc;
4199 
4200 	spin_lock_irqsave(&phba->hbalock, iflag);
4201 	/* First add the response iocb to the countinueq list */
4202 	list_add_tail(&rspiocbp->list, &pring->iocb_continueq);
4203 	pring->iocb_continueq_cnt++;
4204 
4205 	/*
4206 	 * By default, the driver expects to free all resources
4207 	 * associated with this iocb completion.
4208 	 */
4209 	free_saveq = 1;
4210 	saveq = list_get_first(&pring->iocb_continueq,
4211 			       struct lpfc_iocbq, list);
4212 	list_del_init(&pring->iocb_continueq);
4213 	pring->iocb_continueq_cnt = 0;
4214 
4215 	pring->stats.iocb_rsp++;
4216 
4217 	/*
4218 	 * If resource errors reported from HBA, reduce
4219 	 * queuedepths of the SCSI device.
4220 	 */
4221 	if (ulp_status == IOSTAT_LOCAL_REJECT &&
4222 	    ((ulp_word4 & IOERR_PARAM_MASK) ==
4223 	     IOERR_NO_RESOURCES)) {
4224 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4225 		phba->lpfc_rampdown_queue_depth(phba);
4226 		spin_lock_irqsave(&phba->hbalock, iflag);
4227 	}
4228 
4229 	if (ulp_status) {
4230 		/* Rsp ring <ringno> error: IOCB */
4231 		if (phba->sli_rev < LPFC_SLI_REV4) {
4232 			irsp = &rspiocbp->iocb;
4233 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4234 					"0328 Rsp Ring %d error: ulp_status x%x "
4235 					"IOCB Data: "
4236 					"x%08x x%08x x%08x x%08x "
4237 					"x%08x x%08x x%08x x%08x "
4238 					"x%08x x%08x x%08x x%08x "
4239 					"x%08x x%08x x%08x x%08x\n",
4240 					pring->ringno, ulp_status,
4241 					get_job_ulpword(rspiocbp, 0),
4242 					get_job_ulpword(rspiocbp, 1),
4243 					get_job_ulpword(rspiocbp, 2),
4244 					get_job_ulpword(rspiocbp, 3),
4245 					get_job_ulpword(rspiocbp, 4),
4246 					get_job_ulpword(rspiocbp, 5),
4247 					*(((uint32_t *)irsp) + 6),
4248 					*(((uint32_t *)irsp) + 7),
4249 					*(((uint32_t *)irsp) + 8),
4250 					*(((uint32_t *)irsp) + 9),
4251 					*(((uint32_t *)irsp) + 10),
4252 					*(((uint32_t *)irsp) + 11),
4253 					*(((uint32_t *)irsp) + 12),
4254 					*(((uint32_t *)irsp) + 13),
4255 					*(((uint32_t *)irsp) + 14),
4256 					*(((uint32_t *)irsp) + 15));
4257 		} else {
4258 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4259 					"0321 Rsp Ring %d error: "
4260 					"IOCB Data: "
4261 					"x%x x%x x%x x%x\n",
4262 					pring->ringno,
4263 					rspiocbp->wcqe_cmpl.word0,
4264 					rspiocbp->wcqe_cmpl.total_data_placed,
4265 					rspiocbp->wcqe_cmpl.parameter,
4266 					rspiocbp->wcqe_cmpl.word3);
4267 		}
4268 	}
4269 
4270 
4271 	/*
4272 	 * Fetch the iocb command type and call the correct completion
4273 	 * routine. Solicited and Unsolicited IOCBs on the ELS ring
4274 	 * get freed back to the lpfc_iocb_list by the discovery
4275 	 * kernel thread.
4276 	 */
4277 	cmd_type = ulp_command & CMD_IOCB_MASK;
4278 	type = lpfc_sli_iocb_cmd_type(cmd_type);
4279 	switch (type) {
4280 	case LPFC_SOL_IOCB:
4281 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4282 		rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
4283 		spin_lock_irqsave(&phba->hbalock, iflag);
4284 		break;
4285 	case LPFC_UNSOL_IOCB:
4286 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4287 		rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
4288 		spin_lock_irqsave(&phba->hbalock, iflag);
4289 		if (!rc)
4290 			free_saveq = 0;
4291 		break;
4292 	case LPFC_ABORT_IOCB:
4293 		cmdiocb = NULL;
4294 		if (ulp_command != CMD_XRI_ABORTED_CX)
4295 			cmdiocb = lpfc_sli_iocbq_lookup(phba, pring,
4296 							saveq);
4297 		if (cmdiocb) {
4298 			/* Call the specified completion routine */
4299 			if (cmdiocb->cmd_cmpl) {
4300 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4301 				cmdiocb->cmd_cmpl(phba, cmdiocb, saveq);
4302 				spin_lock_irqsave(&phba->hbalock, iflag);
4303 			} else {
4304 				__lpfc_sli_release_iocbq(phba, cmdiocb);
4305 			}
4306 		}
4307 		break;
4308 	case LPFC_UNKNOWN_IOCB:
4309 		if (ulp_command == CMD_ADAPTER_MSG) {
4310 			char adaptermsg[LPFC_MAX_ADPTMSG];
4311 
4312 			memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4313 			memcpy(&adaptermsg[0], (uint8_t *)&rspiocbp->wqe,
4314 			       MAX_MSG_DATA);
4315 			dev_warn(&((phba->pcidev)->dev),
4316 				 "lpfc%d: %s\n",
4317 				 phba->brd_no, adaptermsg);
4318 		} else {
4319 			/* Unknown command */
4320 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4321 					"0335 Unknown IOCB "
4322 					"command Data: x%x "
4323 					"x%x x%x x%x\n",
4324 					ulp_command,
4325 					ulp_status,
4326 					get_wqe_reqtag(rspiocbp),
4327 					get_job_ulpcontext(phba, rspiocbp));
4328 		}
4329 		break;
4330 	}
4331 
4332 	if (free_saveq) {
4333 		list_for_each_entry_safe(rspiocbp, next_iocb,
4334 					 &saveq->list, list) {
4335 			list_del_init(&rspiocbp->list);
4336 			__lpfc_sli_release_iocbq(phba, rspiocbp);
4337 		}
4338 		__lpfc_sli_release_iocbq(phba, saveq);
4339 	}
4340 	rspiocbp = NULL;
4341 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4342 	return rspiocbp;
4343 }
4344 
4345 /**
4346  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
4347  * @phba: Pointer to HBA context object.
4348  * @pring: Pointer to driver SLI ring object.
4349  * @mask: Host attention register mask for this ring.
4350  *
4351  * This routine wraps the actual slow_ring event process routine from the
4352  * API jump table function pointer from the lpfc_hba struct.
4353  **/
4354 void
4355 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
4356 				struct lpfc_sli_ring *pring, uint32_t mask)
4357 {
4358 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
4359 }
4360 
4361 /**
4362  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
4363  * @phba: Pointer to HBA context object.
4364  * @pring: Pointer to driver SLI ring object.
4365  * @mask: Host attention register mask for this ring.
4366  *
4367  * This function is called from the worker thread when there is a ring event
4368  * for non-fcp rings. The caller does not hold any lock. The function will
4369  * remove each response iocb in the response ring and calls the handle
4370  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4371  **/
4372 static void
4373 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
4374 				   struct lpfc_sli_ring *pring, uint32_t mask)
4375 {
4376 	struct lpfc_pgp *pgp;
4377 	IOCB_t *entry;
4378 	IOCB_t *irsp = NULL;
4379 	struct lpfc_iocbq *rspiocbp = NULL;
4380 	uint32_t portRspPut, portRspMax;
4381 	unsigned long iflag;
4382 	uint32_t status;
4383 
4384 	pgp = &phba->port_gp[pring->ringno];
4385 	spin_lock_irqsave(&phba->hbalock, iflag);
4386 	pring->stats.iocb_event++;
4387 
4388 	/*
4389 	 * The next available response entry should never exceed the maximum
4390 	 * entries.  If it does, treat it as an adapter hardware error.
4391 	 */
4392 	portRspMax = pring->sli.sli3.numRiocb;
4393 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4394 	if (portRspPut >= portRspMax) {
4395 		/*
4396 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
4397 		 * rsp ring <portRspMax>
4398 		 */
4399 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4400 				"0303 Ring %d handler: portRspPut %d "
4401 				"is bigger than rsp ring %d\n",
4402 				pring->ringno, portRspPut, portRspMax);
4403 
4404 		phba->link_state = LPFC_HBA_ERROR;
4405 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4406 
4407 		phba->work_hs = HS_FFER3;
4408 		lpfc_handle_eratt(phba);
4409 
4410 		return;
4411 	}
4412 
4413 	rmb();
4414 	while (pring->sli.sli3.rspidx != portRspPut) {
4415 		/*
4416 		 * Build a completion list and call the appropriate handler.
4417 		 * The process is to get the next available response iocb, get
4418 		 * a free iocb from the list, copy the response data into the
4419 		 * free iocb, insert to the continuation list, and update the
4420 		 * next response index to slim.  This process makes response
4421 		 * iocb's in the ring available to DMA as fast as possible but
4422 		 * pays a penalty for a copy operation.  Since the iocb is
4423 		 * only 32 bytes, this penalty is considered small relative to
4424 		 * the PCI reads for register values and a slim write.  When
4425 		 * the ulpLe field is set, the entire Command has been
4426 		 * received.
4427 		 */
4428 		entry = lpfc_resp_iocb(phba, pring);
4429 
4430 		phba->last_completion_time = jiffies;
4431 		rspiocbp = __lpfc_sli_get_iocbq(phba);
4432 		if (rspiocbp == NULL) {
4433 			printk(KERN_ERR "%s: out of buffers! Failing "
4434 			       "completion.\n", __func__);
4435 			break;
4436 		}
4437 
4438 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
4439 				      phba->iocb_rsp_size);
4440 		irsp = &rspiocbp->iocb;
4441 
4442 		if (++pring->sli.sli3.rspidx >= portRspMax)
4443 			pring->sli.sli3.rspidx = 0;
4444 
4445 		if (pring->ringno == LPFC_ELS_RING) {
4446 			lpfc_debugfs_slow_ring_trc(phba,
4447 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
4448 				*(((uint32_t *) irsp) + 4),
4449 				*(((uint32_t *) irsp) + 6),
4450 				*(((uint32_t *) irsp) + 7));
4451 		}
4452 
4453 		writel(pring->sli.sli3.rspidx,
4454 			&phba->host_gp[pring->ringno].rspGetInx);
4455 
4456 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4457 		/* Handle the response IOCB */
4458 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
4459 		spin_lock_irqsave(&phba->hbalock, iflag);
4460 
4461 		/*
4462 		 * If the port response put pointer has not been updated, sync
4463 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
4464 		 * response put pointer.
4465 		 */
4466 		if (pring->sli.sli3.rspidx == portRspPut) {
4467 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4468 		}
4469 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
4470 
4471 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
4472 		/* At least one response entry has been freed */
4473 		pring->stats.iocb_rsp_full++;
4474 		/* SET RxRE_RSP in Chip Att register */
4475 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4476 		writel(status, phba->CAregaddr);
4477 		readl(phba->CAregaddr); /* flush */
4478 	}
4479 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4480 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4481 		pring->stats.iocb_cmd_empty++;
4482 
4483 		/* Force update of the local copy of cmdGetInx */
4484 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4485 		lpfc_sli_resume_iocb(phba, pring);
4486 
4487 		if ((pring->lpfc_sli_cmd_available))
4488 			(pring->lpfc_sli_cmd_available) (phba, pring);
4489 
4490 	}
4491 
4492 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4493 	return;
4494 }
4495 
4496 /**
4497  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
4498  * @phba: Pointer to HBA context object.
4499  * @pring: Pointer to driver SLI ring object.
4500  * @mask: Host attention register mask for this ring.
4501  *
4502  * This function is called from the worker thread when there is a pending
4503  * ELS response iocb on the driver internal slow-path response iocb worker
4504  * queue. The caller does not hold any lock. The function will remove each
4505  * response iocb from the response worker queue and calls the handle
4506  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4507  **/
4508 static void
4509 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4510 				   struct lpfc_sli_ring *pring, uint32_t mask)
4511 {
4512 	struct lpfc_iocbq *irspiocbq;
4513 	struct hbq_dmabuf *dmabuf;
4514 	struct lpfc_cq_event *cq_event;
4515 	unsigned long iflag;
4516 	int count = 0;
4517 
4518 	spin_lock_irqsave(&phba->hbalock, iflag);
4519 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
4520 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4521 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4522 		/* Get the response iocb from the head of work queue */
4523 		spin_lock_irqsave(&phba->hbalock, iflag);
4524 		list_remove_head(&phba->sli4_hba.sp_queue_event,
4525 				 cq_event, struct lpfc_cq_event, list);
4526 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4527 
4528 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4529 		case CQE_CODE_COMPL_WQE:
4530 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4531 						 cq_event);
4532 			/* Translate ELS WCQE to response IOCBQ */
4533 			irspiocbq = lpfc_sli4_els_preprocess_rspiocbq(phba,
4534 								      irspiocbq);
4535 			if (irspiocbq)
4536 				lpfc_sli_sp_handle_rspiocb(phba, pring,
4537 							   irspiocbq);
4538 			count++;
4539 			break;
4540 		case CQE_CODE_RECEIVE:
4541 		case CQE_CODE_RECEIVE_V1:
4542 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
4543 					      cq_event);
4544 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
4545 			count++;
4546 			break;
4547 		default:
4548 			break;
4549 		}
4550 
4551 		/* Limit the number of events to 64 to avoid soft lockups */
4552 		if (count == 64)
4553 			break;
4554 	}
4555 }
4556 
4557 /**
4558  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4559  * @phba: Pointer to HBA context object.
4560  * @pring: Pointer to driver SLI ring object.
4561  *
4562  * This function aborts all iocbs in the given ring and frees all the iocb
4563  * objects in txq. This function issues an abort iocb for all the iocb commands
4564  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4565  * the return of this function. The caller is not required to hold any locks.
4566  **/
4567 void
4568 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4569 {
4570 	LIST_HEAD(tx_completions);
4571 	LIST_HEAD(txcmplq_completions);
4572 	struct lpfc_iocbq *iocb, *next_iocb;
4573 	int offline;
4574 
4575 	if (pring->ringno == LPFC_ELS_RING) {
4576 		lpfc_fabric_abort_hba(phba);
4577 	}
4578 	offline = pci_channel_offline(phba->pcidev);
4579 
4580 	/* Error everything on txq and txcmplq
4581 	 * First do the txq.
4582 	 */
4583 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4584 		spin_lock_irq(&pring->ring_lock);
4585 		list_splice_init(&pring->txq, &tx_completions);
4586 		pring->txq_cnt = 0;
4587 
4588 		if (offline) {
4589 			list_splice_init(&pring->txcmplq,
4590 					 &txcmplq_completions);
4591 		} else {
4592 			/* Next issue ABTS for everything on the txcmplq */
4593 			list_for_each_entry_safe(iocb, next_iocb,
4594 						 &pring->txcmplq, list)
4595 				lpfc_sli_issue_abort_iotag(phba, pring,
4596 							   iocb, NULL);
4597 		}
4598 		spin_unlock_irq(&pring->ring_lock);
4599 	} else {
4600 		spin_lock_irq(&phba->hbalock);
4601 		list_splice_init(&pring->txq, &tx_completions);
4602 		pring->txq_cnt = 0;
4603 
4604 		if (offline) {
4605 			list_splice_init(&pring->txcmplq, &txcmplq_completions);
4606 		} else {
4607 			/* Next issue ABTS for everything on the txcmplq */
4608 			list_for_each_entry_safe(iocb, next_iocb,
4609 						 &pring->txcmplq, list)
4610 				lpfc_sli_issue_abort_iotag(phba, pring,
4611 							   iocb, NULL);
4612 		}
4613 		spin_unlock_irq(&phba->hbalock);
4614 	}
4615 
4616 	if (offline) {
4617 		/* Cancel all the IOCBs from the completions list */
4618 		lpfc_sli_cancel_iocbs(phba, &txcmplq_completions,
4619 				      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
4620 	} else {
4621 		/* Make sure HBA is alive */
4622 		lpfc_issue_hb_tmo(phba);
4623 	}
4624 	/* Cancel all the IOCBs from the completions list */
4625 	lpfc_sli_cancel_iocbs(phba, &tx_completions, IOSTAT_LOCAL_REJECT,
4626 			      IOERR_SLI_ABORTED);
4627 }
4628 
4629 /**
4630  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4631  * @phba: Pointer to HBA context object.
4632  *
4633  * This function aborts all iocbs in FCP rings and frees all the iocb
4634  * objects in txq. This function issues an abort iocb for all the iocb commands
4635  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4636  * the return of this function. The caller is not required to hold any locks.
4637  **/
4638 void
4639 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4640 {
4641 	struct lpfc_sli *psli = &phba->sli;
4642 	struct lpfc_sli_ring  *pring;
4643 	uint32_t i;
4644 
4645 	/* Look on all the FCP Rings for the iotag */
4646 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4647 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4648 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4649 			lpfc_sli_abort_iocb_ring(phba, pring);
4650 		}
4651 	} else {
4652 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4653 		lpfc_sli_abort_iocb_ring(phba, pring);
4654 	}
4655 }
4656 
4657 /**
4658  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4659  * @phba: Pointer to HBA context object.
4660  *
4661  * This function flushes all iocbs in the IO ring and frees all the iocb
4662  * objects in txq and txcmplq. This function will not issue abort iocbs
4663  * for all the iocb commands in txcmplq, they will just be returned with
4664  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4665  * slot has been permanently disabled.
4666  **/
4667 void
4668 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4669 {
4670 	LIST_HEAD(txq);
4671 	LIST_HEAD(txcmplq);
4672 	struct lpfc_sli *psli = &phba->sli;
4673 	struct lpfc_sli_ring  *pring;
4674 	uint32_t i;
4675 	struct lpfc_iocbq *piocb, *next_iocb;
4676 
4677 	spin_lock_irq(&phba->hbalock);
4678 	/* Indicate the I/O queues are flushed */
4679 	phba->hba_flag |= HBA_IOQ_FLUSH;
4680 	spin_unlock_irq(&phba->hbalock);
4681 
4682 	/* Look on all the FCP Rings for the iotag */
4683 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4684 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4685 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4686 
4687 			spin_lock_irq(&pring->ring_lock);
4688 			/* Retrieve everything on txq */
4689 			list_splice_init(&pring->txq, &txq);
4690 			list_for_each_entry_safe(piocb, next_iocb,
4691 						 &pring->txcmplq, list)
4692 				piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4693 			/* Retrieve everything on the txcmplq */
4694 			list_splice_init(&pring->txcmplq, &txcmplq);
4695 			pring->txq_cnt = 0;
4696 			pring->txcmplq_cnt = 0;
4697 			spin_unlock_irq(&pring->ring_lock);
4698 
4699 			/* Flush the txq */
4700 			lpfc_sli_cancel_iocbs(phba, &txq,
4701 					      IOSTAT_LOCAL_REJECT,
4702 					      IOERR_SLI_DOWN);
4703 			/* Flush the txcmplq */
4704 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4705 					      IOSTAT_LOCAL_REJECT,
4706 					      IOERR_SLI_DOWN);
4707 			if (unlikely(pci_channel_offline(phba->pcidev)))
4708 				lpfc_sli4_io_xri_aborted(phba, NULL, 0);
4709 		}
4710 	} else {
4711 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4712 
4713 		spin_lock_irq(&phba->hbalock);
4714 		/* Retrieve everything on txq */
4715 		list_splice_init(&pring->txq, &txq);
4716 		list_for_each_entry_safe(piocb, next_iocb,
4717 					 &pring->txcmplq, list)
4718 			piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4719 		/* Retrieve everything on the txcmplq */
4720 		list_splice_init(&pring->txcmplq, &txcmplq);
4721 		pring->txq_cnt = 0;
4722 		pring->txcmplq_cnt = 0;
4723 		spin_unlock_irq(&phba->hbalock);
4724 
4725 		/* Flush the txq */
4726 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4727 				      IOERR_SLI_DOWN);
4728 		/* Flush the txcmpq */
4729 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4730 				      IOERR_SLI_DOWN);
4731 	}
4732 }
4733 
4734 /**
4735  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4736  * @phba: Pointer to HBA context object.
4737  * @mask: Bit mask to be checked.
4738  *
4739  * This function reads the host status register and compares
4740  * with the provided bit mask to check if HBA completed
4741  * the restart. This function will wait in a loop for the
4742  * HBA to complete restart. If the HBA does not restart within
4743  * 15 iterations, the function will reset the HBA again. The
4744  * function returns 1 when HBA fail to restart otherwise returns
4745  * zero.
4746  **/
4747 static int
4748 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4749 {
4750 	uint32_t status;
4751 	int i = 0;
4752 	int retval = 0;
4753 
4754 	/* Read the HBA Host Status Register */
4755 	if (lpfc_readl(phba->HSregaddr, &status))
4756 		return 1;
4757 
4758 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4759 
4760 	/*
4761 	 * Check status register every 100ms for 5 retries, then every
4762 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4763 	 * every 2.5 sec for 4.
4764 	 * Break our of the loop if errors occurred during init.
4765 	 */
4766 	while (((status & mask) != mask) &&
4767 	       !(status & HS_FFERM) &&
4768 	       i++ < 20) {
4769 
4770 		if (i <= 5)
4771 			msleep(10);
4772 		else if (i <= 10)
4773 			msleep(500);
4774 		else
4775 			msleep(2500);
4776 
4777 		if (i == 15) {
4778 				/* Do post */
4779 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4780 			lpfc_sli_brdrestart(phba);
4781 		}
4782 		/* Read the HBA Host Status Register */
4783 		if (lpfc_readl(phba->HSregaddr, &status)) {
4784 			retval = 1;
4785 			break;
4786 		}
4787 	}
4788 
4789 	/* Check to see if any errors occurred during init */
4790 	if ((status & HS_FFERM) || (i >= 20)) {
4791 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4792 				"2751 Adapter failed to restart, "
4793 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4794 				status,
4795 				readl(phba->MBslimaddr + 0xa8),
4796 				readl(phba->MBslimaddr + 0xac));
4797 		phba->link_state = LPFC_HBA_ERROR;
4798 		retval = 1;
4799 	}
4800 
4801 	return retval;
4802 }
4803 
4804 /**
4805  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4806  * @phba: Pointer to HBA context object.
4807  * @mask: Bit mask to be checked.
4808  *
4809  * This function checks the host status register to check if HBA is
4810  * ready. This function will wait in a loop for the HBA to be ready
4811  * If the HBA is not ready , the function will will reset the HBA PCI
4812  * function again. The function returns 1 when HBA fail to be ready
4813  * otherwise returns zero.
4814  **/
4815 static int
4816 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4817 {
4818 	uint32_t status;
4819 	int retval = 0;
4820 
4821 	/* Read the HBA Host Status Register */
4822 	status = lpfc_sli4_post_status_check(phba);
4823 
4824 	if (status) {
4825 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4826 		lpfc_sli_brdrestart(phba);
4827 		status = lpfc_sli4_post_status_check(phba);
4828 	}
4829 
4830 	/* Check to see if any errors occurred during init */
4831 	if (status) {
4832 		phba->link_state = LPFC_HBA_ERROR;
4833 		retval = 1;
4834 	} else
4835 		phba->sli4_hba.intr_enable = 0;
4836 
4837 	phba->hba_flag &= ~HBA_SETUP;
4838 	return retval;
4839 }
4840 
4841 /**
4842  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4843  * @phba: Pointer to HBA context object.
4844  * @mask: Bit mask to be checked.
4845  *
4846  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4847  * from the API jump table function pointer from the lpfc_hba struct.
4848  **/
4849 int
4850 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4851 {
4852 	return phba->lpfc_sli_brdready(phba, mask);
4853 }
4854 
4855 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4856 
4857 /**
4858  * lpfc_reset_barrier - Make HBA ready for HBA reset
4859  * @phba: Pointer to HBA context object.
4860  *
4861  * This function is called before resetting an HBA. This function is called
4862  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4863  **/
4864 void lpfc_reset_barrier(struct lpfc_hba *phba)
4865 {
4866 	uint32_t __iomem *resp_buf;
4867 	uint32_t __iomem *mbox_buf;
4868 	volatile struct MAILBOX_word0 mbox;
4869 	uint32_t hc_copy, ha_copy, resp_data;
4870 	int  i;
4871 	uint8_t hdrtype;
4872 
4873 	lockdep_assert_held(&phba->hbalock);
4874 
4875 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4876 	if (hdrtype != 0x80 ||
4877 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4878 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4879 		return;
4880 
4881 	/*
4882 	 * Tell the other part of the chip to suspend temporarily all
4883 	 * its DMA activity.
4884 	 */
4885 	resp_buf = phba->MBslimaddr;
4886 
4887 	/* Disable the error attention */
4888 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4889 		return;
4890 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4891 	readl(phba->HCregaddr); /* flush */
4892 	phba->link_flag |= LS_IGNORE_ERATT;
4893 
4894 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4895 		return;
4896 	if (ha_copy & HA_ERATT) {
4897 		/* Clear Chip error bit */
4898 		writel(HA_ERATT, phba->HAregaddr);
4899 		phba->pport->stopped = 1;
4900 	}
4901 
4902 	mbox.word0 = 0;
4903 	mbox.mbxCommand = MBX_KILL_BOARD;
4904 	mbox.mbxOwner = OWN_CHIP;
4905 
4906 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4907 	mbox_buf = phba->MBslimaddr;
4908 	writel(mbox.word0, mbox_buf);
4909 
4910 	for (i = 0; i < 50; i++) {
4911 		if (lpfc_readl((resp_buf + 1), &resp_data))
4912 			return;
4913 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4914 			mdelay(1);
4915 		else
4916 			break;
4917 	}
4918 	resp_data = 0;
4919 	if (lpfc_readl((resp_buf + 1), &resp_data))
4920 		return;
4921 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4922 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4923 		    phba->pport->stopped)
4924 			goto restore_hc;
4925 		else
4926 			goto clear_errat;
4927 	}
4928 
4929 	mbox.mbxOwner = OWN_HOST;
4930 	resp_data = 0;
4931 	for (i = 0; i < 500; i++) {
4932 		if (lpfc_readl(resp_buf, &resp_data))
4933 			return;
4934 		if (resp_data != mbox.word0)
4935 			mdelay(1);
4936 		else
4937 			break;
4938 	}
4939 
4940 clear_errat:
4941 
4942 	while (++i < 500) {
4943 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4944 			return;
4945 		if (!(ha_copy & HA_ERATT))
4946 			mdelay(1);
4947 		else
4948 			break;
4949 	}
4950 
4951 	if (readl(phba->HAregaddr) & HA_ERATT) {
4952 		writel(HA_ERATT, phba->HAregaddr);
4953 		phba->pport->stopped = 1;
4954 	}
4955 
4956 restore_hc:
4957 	phba->link_flag &= ~LS_IGNORE_ERATT;
4958 	writel(hc_copy, phba->HCregaddr);
4959 	readl(phba->HCregaddr); /* flush */
4960 }
4961 
4962 /**
4963  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4964  * @phba: Pointer to HBA context object.
4965  *
4966  * This function issues a kill_board mailbox command and waits for
4967  * the error attention interrupt. This function is called for stopping
4968  * the firmware processing. The caller is not required to hold any
4969  * locks. This function calls lpfc_hba_down_post function to free
4970  * any pending commands after the kill. The function will return 1 when it
4971  * fails to kill the board else will return 0.
4972  **/
4973 int
4974 lpfc_sli_brdkill(struct lpfc_hba *phba)
4975 {
4976 	struct lpfc_sli *psli;
4977 	LPFC_MBOXQ_t *pmb;
4978 	uint32_t status;
4979 	uint32_t ha_copy;
4980 	int retval;
4981 	int i = 0;
4982 
4983 	psli = &phba->sli;
4984 
4985 	/* Kill HBA */
4986 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4987 			"0329 Kill HBA Data: x%x x%x\n",
4988 			phba->pport->port_state, psli->sli_flag);
4989 
4990 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4991 	if (!pmb)
4992 		return 1;
4993 
4994 	/* Disable the error attention */
4995 	spin_lock_irq(&phba->hbalock);
4996 	if (lpfc_readl(phba->HCregaddr, &status)) {
4997 		spin_unlock_irq(&phba->hbalock);
4998 		mempool_free(pmb, phba->mbox_mem_pool);
4999 		return 1;
5000 	}
5001 	status &= ~HC_ERINT_ENA;
5002 	writel(status, phba->HCregaddr);
5003 	readl(phba->HCregaddr); /* flush */
5004 	phba->link_flag |= LS_IGNORE_ERATT;
5005 	spin_unlock_irq(&phba->hbalock);
5006 
5007 	lpfc_kill_board(phba, pmb);
5008 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
5009 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5010 
5011 	if (retval != MBX_SUCCESS) {
5012 		if (retval != MBX_BUSY)
5013 			mempool_free(pmb, phba->mbox_mem_pool);
5014 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5015 				"2752 KILL_BOARD command failed retval %d\n",
5016 				retval);
5017 		spin_lock_irq(&phba->hbalock);
5018 		phba->link_flag &= ~LS_IGNORE_ERATT;
5019 		spin_unlock_irq(&phba->hbalock);
5020 		return 1;
5021 	}
5022 
5023 	spin_lock_irq(&phba->hbalock);
5024 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
5025 	spin_unlock_irq(&phba->hbalock);
5026 
5027 	mempool_free(pmb, phba->mbox_mem_pool);
5028 
5029 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
5030 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
5031 	 * 3 seconds we still set HBA_ERROR state because the status of the
5032 	 * board is now undefined.
5033 	 */
5034 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
5035 		return 1;
5036 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
5037 		mdelay(100);
5038 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
5039 			return 1;
5040 	}
5041 
5042 	del_timer_sync(&psli->mbox_tmo);
5043 	if (ha_copy & HA_ERATT) {
5044 		writel(HA_ERATT, phba->HAregaddr);
5045 		phba->pport->stopped = 1;
5046 	}
5047 	spin_lock_irq(&phba->hbalock);
5048 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5049 	psli->mbox_active = NULL;
5050 	phba->link_flag &= ~LS_IGNORE_ERATT;
5051 	spin_unlock_irq(&phba->hbalock);
5052 
5053 	lpfc_hba_down_post(phba);
5054 	phba->link_state = LPFC_HBA_ERROR;
5055 
5056 	return ha_copy & HA_ERATT ? 0 : 1;
5057 }
5058 
5059 /**
5060  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
5061  * @phba: Pointer to HBA context object.
5062  *
5063  * This function resets the HBA by writing HC_INITFF to the control
5064  * register. After the HBA resets, this function resets all the iocb ring
5065  * indices. This function disables PCI layer parity checking during
5066  * the reset.
5067  * This function returns 0 always.
5068  * The caller is not required to hold any locks.
5069  **/
5070 int
5071 lpfc_sli_brdreset(struct lpfc_hba *phba)
5072 {
5073 	struct lpfc_sli *psli;
5074 	struct lpfc_sli_ring *pring;
5075 	uint16_t cfg_value;
5076 	int i;
5077 
5078 	psli = &phba->sli;
5079 
5080 	/* Reset HBA */
5081 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5082 			"0325 Reset HBA Data: x%x x%x\n",
5083 			(phba->pport) ? phba->pport->port_state : 0,
5084 			psli->sli_flag);
5085 
5086 	/* perform board reset */
5087 	phba->fc_eventTag = 0;
5088 	phba->link_events = 0;
5089 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5090 	if (phba->pport) {
5091 		phba->pport->fc_myDID = 0;
5092 		phba->pport->fc_prevDID = 0;
5093 	}
5094 
5095 	/* Turn off parity checking and serr during the physical reset */
5096 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
5097 		return -EIO;
5098 
5099 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
5100 			      (cfg_value &
5101 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5102 
5103 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
5104 
5105 	/* Now toggle INITFF bit in the Host Control Register */
5106 	writel(HC_INITFF, phba->HCregaddr);
5107 	mdelay(1);
5108 	readl(phba->HCregaddr); /* flush */
5109 	writel(0, phba->HCregaddr);
5110 	readl(phba->HCregaddr); /* flush */
5111 
5112 	/* Restore PCI cmd register */
5113 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5114 
5115 	/* Initialize relevant SLI info */
5116 	for (i = 0; i < psli->num_rings; i++) {
5117 		pring = &psli->sli3_ring[i];
5118 		pring->flag = 0;
5119 		pring->sli.sli3.rspidx = 0;
5120 		pring->sli.sli3.next_cmdidx  = 0;
5121 		pring->sli.sli3.local_getidx = 0;
5122 		pring->sli.sli3.cmdidx = 0;
5123 		pring->missbufcnt = 0;
5124 	}
5125 
5126 	phba->link_state = LPFC_WARM_START;
5127 	return 0;
5128 }
5129 
5130 /**
5131  * lpfc_sli4_brdreset - Reset a sli-4 HBA
5132  * @phba: Pointer to HBA context object.
5133  *
5134  * This function resets a SLI4 HBA. This function disables PCI layer parity
5135  * checking during resets the device. The caller is not required to hold
5136  * any locks.
5137  *
5138  * This function returns 0 on success else returns negative error code.
5139  **/
5140 int
5141 lpfc_sli4_brdreset(struct lpfc_hba *phba)
5142 {
5143 	struct lpfc_sli *psli = &phba->sli;
5144 	uint16_t cfg_value;
5145 	int rc = 0;
5146 
5147 	/* Reset HBA */
5148 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5149 			"0295 Reset HBA Data: x%x x%x x%x\n",
5150 			phba->pport->port_state, psli->sli_flag,
5151 			phba->hba_flag);
5152 
5153 	/* perform board reset */
5154 	phba->fc_eventTag = 0;
5155 	phba->link_events = 0;
5156 	phba->pport->fc_myDID = 0;
5157 	phba->pport->fc_prevDID = 0;
5158 	phba->hba_flag &= ~HBA_SETUP;
5159 
5160 	spin_lock_irq(&phba->hbalock);
5161 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
5162 	phba->fcf.fcf_flag = 0;
5163 	spin_unlock_irq(&phba->hbalock);
5164 
5165 	/* Now physically reset the device */
5166 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5167 			"0389 Performing PCI function reset!\n");
5168 
5169 	/* Turn off parity checking and serr during the physical reset */
5170 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
5171 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5172 				"3205 PCI read Config failed\n");
5173 		return -EIO;
5174 	}
5175 
5176 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
5177 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5178 
5179 	/* Perform FCoE PCI function reset before freeing queue memory */
5180 	rc = lpfc_pci_function_reset(phba);
5181 
5182 	/* Restore PCI cmd register */
5183 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5184 
5185 	return rc;
5186 }
5187 
5188 /**
5189  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
5190  * @phba: Pointer to HBA context object.
5191  *
5192  * This function is called in the SLI initialization code path to
5193  * restart the HBA. The caller is not required to hold any lock.
5194  * This function writes MBX_RESTART mailbox command to the SLIM and
5195  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
5196  * function to free any pending commands. The function enables
5197  * POST only during the first initialization. The function returns zero.
5198  * The function does not guarantee completion of MBX_RESTART mailbox
5199  * command before the return of this function.
5200  **/
5201 static int
5202 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
5203 {
5204 	volatile struct MAILBOX_word0 mb;
5205 	struct lpfc_sli *psli;
5206 	void __iomem *to_slim;
5207 	uint32_t hba_aer_enabled;
5208 
5209 	spin_lock_irq(&phba->hbalock);
5210 
5211 	/* Take PCIe device Advanced Error Reporting (AER) state */
5212 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
5213 
5214 	psli = &phba->sli;
5215 
5216 	/* Restart HBA */
5217 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5218 			"0337 Restart HBA Data: x%x x%x\n",
5219 			(phba->pport) ? phba->pport->port_state : 0,
5220 			psli->sli_flag);
5221 
5222 	mb.word0 = 0;
5223 	mb.mbxCommand = MBX_RESTART;
5224 	mb.mbxHc = 1;
5225 
5226 	lpfc_reset_barrier(phba);
5227 
5228 	to_slim = phba->MBslimaddr;
5229 	writel(mb.word0, to_slim);
5230 	readl(to_slim); /* flush */
5231 
5232 	/* Only skip post after fc_ffinit is completed */
5233 	if (phba->pport && phba->pport->port_state)
5234 		mb.word0 = 1;	/* This is really setting up word1 */
5235 	else
5236 		mb.word0 = 0;	/* This is really setting up word1 */
5237 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
5238 	writel(mb.word0, to_slim);
5239 	readl(to_slim); /* flush */
5240 
5241 	lpfc_sli_brdreset(phba);
5242 	if (phba->pport)
5243 		phba->pport->stopped = 0;
5244 	phba->link_state = LPFC_INIT_START;
5245 	phba->hba_flag = 0;
5246 	spin_unlock_irq(&phba->hbalock);
5247 
5248 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5249 	psli->stats_start = ktime_get_seconds();
5250 
5251 	/* Give the INITFF and Post time to settle. */
5252 	mdelay(100);
5253 
5254 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
5255 	if (hba_aer_enabled)
5256 		pci_disable_pcie_error_reporting(phba->pcidev);
5257 
5258 	lpfc_hba_down_post(phba);
5259 
5260 	return 0;
5261 }
5262 
5263 /**
5264  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
5265  * @phba: Pointer to HBA context object.
5266  *
5267  * This function is called in the SLI initialization code path to restart
5268  * a SLI4 HBA. The caller is not required to hold any lock.
5269  * At the end of the function, it calls lpfc_hba_down_post function to
5270  * free any pending commands.
5271  **/
5272 static int
5273 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
5274 {
5275 	struct lpfc_sli *psli = &phba->sli;
5276 	uint32_t hba_aer_enabled;
5277 	int rc;
5278 
5279 	/* Restart HBA */
5280 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5281 			"0296 Restart HBA Data: x%x x%x\n",
5282 			phba->pport->port_state, psli->sli_flag);
5283 
5284 	/* Take PCIe device Advanced Error Reporting (AER) state */
5285 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
5286 
5287 	rc = lpfc_sli4_brdreset(phba);
5288 	if (rc) {
5289 		phba->link_state = LPFC_HBA_ERROR;
5290 		goto hba_down_queue;
5291 	}
5292 
5293 	spin_lock_irq(&phba->hbalock);
5294 	phba->pport->stopped = 0;
5295 	phba->link_state = LPFC_INIT_START;
5296 	phba->hba_flag = 0;
5297 	/* Preserve FA-PWWN expectation */
5298 	phba->sli4_hba.fawwpn_flag &= LPFC_FAWWPN_FABRIC;
5299 	spin_unlock_irq(&phba->hbalock);
5300 
5301 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5302 	psli->stats_start = ktime_get_seconds();
5303 
5304 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
5305 	if (hba_aer_enabled)
5306 		pci_disable_pcie_error_reporting(phba->pcidev);
5307 
5308 hba_down_queue:
5309 	lpfc_hba_down_post(phba);
5310 	lpfc_sli4_queue_destroy(phba);
5311 
5312 	return rc;
5313 }
5314 
5315 /**
5316  * lpfc_sli_brdrestart - Wrapper func for restarting hba
5317  * @phba: Pointer to HBA context object.
5318  *
5319  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
5320  * API jump table function pointer from the lpfc_hba struct.
5321 **/
5322 int
5323 lpfc_sli_brdrestart(struct lpfc_hba *phba)
5324 {
5325 	return phba->lpfc_sli_brdrestart(phba);
5326 }
5327 
5328 /**
5329  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
5330  * @phba: Pointer to HBA context object.
5331  *
5332  * This function is called after a HBA restart to wait for successful
5333  * restart of the HBA. Successful restart of the HBA is indicated by
5334  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
5335  * iteration, the function will restart the HBA again. The function returns
5336  * zero if HBA successfully restarted else returns negative error code.
5337  **/
5338 int
5339 lpfc_sli_chipset_init(struct lpfc_hba *phba)
5340 {
5341 	uint32_t status, i = 0;
5342 
5343 	/* Read the HBA Host Status Register */
5344 	if (lpfc_readl(phba->HSregaddr, &status))
5345 		return -EIO;
5346 
5347 	/* Check status register to see what current state is */
5348 	i = 0;
5349 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
5350 
5351 		/* Check every 10ms for 10 retries, then every 100ms for 90
5352 		 * retries, then every 1 sec for 50 retires for a total of
5353 		 * ~60 seconds before reset the board again and check every
5354 		 * 1 sec for 50 retries. The up to 60 seconds before the
5355 		 * board ready is required by the Falcon FIPS zeroization
5356 		 * complete, and any reset the board in between shall cause
5357 		 * restart of zeroization, further delay the board ready.
5358 		 */
5359 		if (i++ >= 200) {
5360 			/* Adapter failed to init, timeout, status reg
5361 			   <status> */
5362 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5363 					"0436 Adapter failed to init, "
5364 					"timeout, status reg x%x, "
5365 					"FW Data: A8 x%x AC x%x\n", status,
5366 					readl(phba->MBslimaddr + 0xa8),
5367 					readl(phba->MBslimaddr + 0xac));
5368 			phba->link_state = LPFC_HBA_ERROR;
5369 			return -ETIMEDOUT;
5370 		}
5371 
5372 		/* Check to see if any errors occurred during init */
5373 		if (status & HS_FFERM) {
5374 			/* ERROR: During chipset initialization */
5375 			/* Adapter failed to init, chipset, status reg
5376 			   <status> */
5377 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5378 					"0437 Adapter failed to init, "
5379 					"chipset, status reg x%x, "
5380 					"FW Data: A8 x%x AC x%x\n", status,
5381 					readl(phba->MBslimaddr + 0xa8),
5382 					readl(phba->MBslimaddr + 0xac));
5383 			phba->link_state = LPFC_HBA_ERROR;
5384 			return -EIO;
5385 		}
5386 
5387 		if (i <= 10)
5388 			msleep(10);
5389 		else if (i <= 100)
5390 			msleep(100);
5391 		else
5392 			msleep(1000);
5393 
5394 		if (i == 150) {
5395 			/* Do post */
5396 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5397 			lpfc_sli_brdrestart(phba);
5398 		}
5399 		/* Read the HBA Host Status Register */
5400 		if (lpfc_readl(phba->HSregaddr, &status))
5401 			return -EIO;
5402 	}
5403 
5404 	/* Check to see if any errors occurred during init */
5405 	if (status & HS_FFERM) {
5406 		/* ERROR: During chipset initialization */
5407 		/* Adapter failed to init, chipset, status reg <status> */
5408 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5409 				"0438 Adapter failed to init, chipset, "
5410 				"status reg x%x, "
5411 				"FW Data: A8 x%x AC x%x\n", status,
5412 				readl(phba->MBslimaddr + 0xa8),
5413 				readl(phba->MBslimaddr + 0xac));
5414 		phba->link_state = LPFC_HBA_ERROR;
5415 		return -EIO;
5416 	}
5417 
5418 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5419 
5420 	/* Clear all interrupt enable conditions */
5421 	writel(0, phba->HCregaddr);
5422 	readl(phba->HCregaddr); /* flush */
5423 
5424 	/* setup host attn register */
5425 	writel(0xffffffff, phba->HAregaddr);
5426 	readl(phba->HAregaddr); /* flush */
5427 	return 0;
5428 }
5429 
5430 /**
5431  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5432  *
5433  * This function calculates and returns the number of HBQs required to be
5434  * configured.
5435  **/
5436 int
5437 lpfc_sli_hbq_count(void)
5438 {
5439 	return ARRAY_SIZE(lpfc_hbq_defs);
5440 }
5441 
5442 /**
5443  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5444  *
5445  * This function adds the number of hbq entries in every HBQ to get
5446  * the total number of hbq entries required for the HBA and returns
5447  * the total count.
5448  **/
5449 static int
5450 lpfc_sli_hbq_entry_count(void)
5451 {
5452 	int  hbq_count = lpfc_sli_hbq_count();
5453 	int  count = 0;
5454 	int  i;
5455 
5456 	for (i = 0; i < hbq_count; ++i)
5457 		count += lpfc_hbq_defs[i]->entry_count;
5458 	return count;
5459 }
5460 
5461 /**
5462  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5463  *
5464  * This function calculates amount of memory required for all hbq entries
5465  * to be configured and returns the total memory required.
5466  **/
5467 int
5468 lpfc_sli_hbq_size(void)
5469 {
5470 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5471 }
5472 
5473 /**
5474  * lpfc_sli_hbq_setup - configure and initialize HBQs
5475  * @phba: Pointer to HBA context object.
5476  *
5477  * This function is called during the SLI initialization to configure
5478  * all the HBQs and post buffers to the HBQ. The caller is not
5479  * required to hold any locks. This function will return zero if successful
5480  * else it will return negative error code.
5481  **/
5482 static int
5483 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5484 {
5485 	int  hbq_count = lpfc_sli_hbq_count();
5486 	LPFC_MBOXQ_t *pmb;
5487 	MAILBOX_t *pmbox;
5488 	uint32_t hbqno;
5489 	uint32_t hbq_entry_index;
5490 
5491 				/* Get a Mailbox buffer to setup mailbox
5492 				 * commands for HBA initialization
5493 				 */
5494 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5495 
5496 	if (!pmb)
5497 		return -ENOMEM;
5498 
5499 	pmbox = &pmb->u.mb;
5500 
5501 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
5502 	phba->link_state = LPFC_INIT_MBX_CMDS;
5503 	phba->hbq_in_use = 1;
5504 
5505 	hbq_entry_index = 0;
5506 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5507 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
5508 		phba->hbqs[hbqno].hbqPutIdx      = 0;
5509 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5510 		phba->hbqs[hbqno].entry_count =
5511 			lpfc_hbq_defs[hbqno]->entry_count;
5512 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5513 			hbq_entry_index, pmb);
5514 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
5515 
5516 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5517 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5518 			   mbxStatus <status>, ring <num> */
5519 
5520 			lpfc_printf_log(phba, KERN_ERR,
5521 					LOG_SLI | LOG_VPORT,
5522 					"1805 Adapter failed to init. "
5523 					"Data: x%x x%x x%x\n",
5524 					pmbox->mbxCommand,
5525 					pmbox->mbxStatus, hbqno);
5526 
5527 			phba->link_state = LPFC_HBA_ERROR;
5528 			mempool_free(pmb, phba->mbox_mem_pool);
5529 			return -ENXIO;
5530 		}
5531 	}
5532 	phba->hbq_count = hbq_count;
5533 
5534 	mempool_free(pmb, phba->mbox_mem_pool);
5535 
5536 	/* Initially populate or replenish the HBQs */
5537 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5538 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5539 	return 0;
5540 }
5541 
5542 /**
5543  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5544  * @phba: Pointer to HBA context object.
5545  *
5546  * This function is called during the SLI initialization to configure
5547  * all the HBQs and post buffers to the HBQ. The caller is not
5548  * required to hold any locks. This function will return zero if successful
5549  * else it will return negative error code.
5550  **/
5551 static int
5552 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5553 {
5554 	phba->hbq_in_use = 1;
5555 	/**
5556 	 * Specific case when the MDS diagnostics is enabled and supported.
5557 	 * The receive buffer count is truncated to manage the incoming
5558 	 * traffic.
5559 	 **/
5560 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5561 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5562 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5563 	else
5564 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5565 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5566 	phba->hbq_count = 1;
5567 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5568 	/* Initially populate or replenish the HBQs */
5569 	return 0;
5570 }
5571 
5572 /**
5573  * lpfc_sli_config_port - Issue config port mailbox command
5574  * @phba: Pointer to HBA context object.
5575  * @sli_mode: sli mode - 2/3
5576  *
5577  * This function is called by the sli initialization code path
5578  * to issue config_port mailbox command. This function restarts the
5579  * HBA firmware and issues a config_port mailbox command to configure
5580  * the SLI interface in the sli mode specified by sli_mode
5581  * variable. The caller is not required to hold any locks.
5582  * The function returns 0 if successful, else returns negative error
5583  * code.
5584  **/
5585 int
5586 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5587 {
5588 	LPFC_MBOXQ_t *pmb;
5589 	uint32_t resetcount = 0, rc = 0, done = 0;
5590 
5591 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5592 	if (!pmb) {
5593 		phba->link_state = LPFC_HBA_ERROR;
5594 		return -ENOMEM;
5595 	}
5596 
5597 	phba->sli_rev = sli_mode;
5598 	while (resetcount < 2 && !done) {
5599 		spin_lock_irq(&phba->hbalock);
5600 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5601 		spin_unlock_irq(&phba->hbalock);
5602 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5603 		lpfc_sli_brdrestart(phba);
5604 		rc = lpfc_sli_chipset_init(phba);
5605 		if (rc)
5606 			break;
5607 
5608 		spin_lock_irq(&phba->hbalock);
5609 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5610 		spin_unlock_irq(&phba->hbalock);
5611 		resetcount++;
5612 
5613 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5614 		 * value of 0 means the call was successful.  Any other
5615 		 * nonzero value is a failure, but if ERESTART is returned,
5616 		 * the driver may reset the HBA and try again.
5617 		 */
5618 		rc = lpfc_config_port_prep(phba);
5619 		if (rc == -ERESTART) {
5620 			phba->link_state = LPFC_LINK_UNKNOWN;
5621 			continue;
5622 		} else if (rc)
5623 			break;
5624 
5625 		phba->link_state = LPFC_INIT_MBX_CMDS;
5626 		lpfc_config_port(phba, pmb);
5627 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5628 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5629 					LPFC_SLI3_HBQ_ENABLED |
5630 					LPFC_SLI3_CRP_ENABLED |
5631 					LPFC_SLI3_DSS_ENABLED);
5632 		if (rc != MBX_SUCCESS) {
5633 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5634 				"0442 Adapter failed to init, mbxCmd x%x "
5635 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5636 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5637 			spin_lock_irq(&phba->hbalock);
5638 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5639 			spin_unlock_irq(&phba->hbalock);
5640 			rc = -ENXIO;
5641 		} else {
5642 			/* Allow asynchronous mailbox command to go through */
5643 			spin_lock_irq(&phba->hbalock);
5644 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5645 			spin_unlock_irq(&phba->hbalock);
5646 			done = 1;
5647 
5648 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5649 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5650 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5651 					"3110 Port did not grant ASABT\n");
5652 		}
5653 	}
5654 	if (!done) {
5655 		rc = -EINVAL;
5656 		goto do_prep_failed;
5657 	}
5658 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5659 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5660 			rc = -ENXIO;
5661 			goto do_prep_failed;
5662 		}
5663 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5664 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5665 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5666 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5667 				phba->max_vpi : phba->max_vports;
5668 
5669 		} else
5670 			phba->max_vpi = 0;
5671 		if (pmb->u.mb.un.varCfgPort.gerbm)
5672 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5673 		if (pmb->u.mb.un.varCfgPort.gcrp)
5674 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5675 
5676 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5677 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5678 
5679 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5680 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5681 				phba->cfg_enable_bg = 0;
5682 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5683 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5684 						"0443 Adapter did not grant "
5685 						"BlockGuard\n");
5686 			}
5687 		}
5688 	} else {
5689 		phba->hbq_get = NULL;
5690 		phba->port_gp = phba->mbox->us.s2.port;
5691 		phba->max_vpi = 0;
5692 	}
5693 do_prep_failed:
5694 	mempool_free(pmb, phba->mbox_mem_pool);
5695 	return rc;
5696 }
5697 
5698 
5699 /**
5700  * lpfc_sli_hba_setup - SLI initialization function
5701  * @phba: Pointer to HBA context object.
5702  *
5703  * This function is the main SLI initialization function. This function
5704  * is called by the HBA initialization code, HBA reset code and HBA
5705  * error attention handler code. Caller is not required to hold any
5706  * locks. This function issues config_port mailbox command to configure
5707  * the SLI, setup iocb rings and HBQ rings. In the end the function
5708  * calls the config_port_post function to issue init_link mailbox
5709  * command and to start the discovery. The function will return zero
5710  * if successful, else it will return negative error code.
5711  **/
5712 int
5713 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5714 {
5715 	uint32_t rc;
5716 	int  i;
5717 	int longs;
5718 
5719 	/* Enable ISR already does config_port because of config_msi mbx */
5720 	if (phba->hba_flag & HBA_NEEDS_CFG_PORT) {
5721 		rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5722 		if (rc)
5723 			return -EIO;
5724 		phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
5725 	}
5726 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5727 
5728 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
5729 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
5730 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
5731 		if (!rc) {
5732 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5733 					"2709 This device supports "
5734 					"Advanced Error Reporting (AER)\n");
5735 			spin_lock_irq(&phba->hbalock);
5736 			phba->hba_flag |= HBA_AER_ENABLED;
5737 			spin_unlock_irq(&phba->hbalock);
5738 		} else {
5739 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5740 					"2708 This device does not support "
5741 					"Advanced Error Reporting (AER): %d\n",
5742 					rc);
5743 			phba->cfg_aer_support = 0;
5744 		}
5745 	}
5746 
5747 	if (phba->sli_rev == 3) {
5748 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5749 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5750 	} else {
5751 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5752 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5753 		phba->sli3_options = 0;
5754 	}
5755 
5756 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5757 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5758 			phba->sli_rev, phba->max_vpi);
5759 	rc = lpfc_sli_ring_map(phba);
5760 
5761 	if (rc)
5762 		goto lpfc_sli_hba_setup_error;
5763 
5764 	/* Initialize VPIs. */
5765 	if (phba->sli_rev == LPFC_SLI_REV3) {
5766 		/*
5767 		 * The VPI bitmask and physical ID array are allocated
5768 		 * and initialized once only - at driver load.  A port
5769 		 * reset doesn't need to reinitialize this memory.
5770 		 */
5771 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5772 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5773 			phba->vpi_bmask = kcalloc(longs,
5774 						  sizeof(unsigned long),
5775 						  GFP_KERNEL);
5776 			if (!phba->vpi_bmask) {
5777 				rc = -ENOMEM;
5778 				goto lpfc_sli_hba_setup_error;
5779 			}
5780 
5781 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5782 						sizeof(uint16_t),
5783 						GFP_KERNEL);
5784 			if (!phba->vpi_ids) {
5785 				kfree(phba->vpi_bmask);
5786 				rc = -ENOMEM;
5787 				goto lpfc_sli_hba_setup_error;
5788 			}
5789 			for (i = 0; i < phba->max_vpi; i++)
5790 				phba->vpi_ids[i] = i;
5791 		}
5792 	}
5793 
5794 	/* Init HBQs */
5795 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5796 		rc = lpfc_sli_hbq_setup(phba);
5797 		if (rc)
5798 			goto lpfc_sli_hba_setup_error;
5799 	}
5800 	spin_lock_irq(&phba->hbalock);
5801 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5802 	spin_unlock_irq(&phba->hbalock);
5803 
5804 	rc = lpfc_config_port_post(phba);
5805 	if (rc)
5806 		goto lpfc_sli_hba_setup_error;
5807 
5808 	return rc;
5809 
5810 lpfc_sli_hba_setup_error:
5811 	phba->link_state = LPFC_HBA_ERROR;
5812 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5813 			"0445 Firmware initialization failed\n");
5814 	return rc;
5815 }
5816 
5817 /**
5818  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5819  * @phba: Pointer to HBA context object.
5820  *
5821  * This function issue a dump mailbox command to read config region
5822  * 23 and parse the records in the region and populate driver
5823  * data structure.
5824  **/
5825 static int
5826 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5827 {
5828 	LPFC_MBOXQ_t *mboxq;
5829 	struct lpfc_dmabuf *mp;
5830 	struct lpfc_mqe *mqe;
5831 	uint32_t data_length;
5832 	int rc;
5833 
5834 	/* Program the default value of vlan_id and fc_map */
5835 	phba->valid_vlan = 0;
5836 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5837 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5838 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5839 
5840 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5841 	if (!mboxq)
5842 		return -ENOMEM;
5843 
5844 	mqe = &mboxq->u.mqe;
5845 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5846 		rc = -ENOMEM;
5847 		goto out_free_mboxq;
5848 	}
5849 
5850 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5851 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5852 
5853 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5854 			"(%d):2571 Mailbox cmd x%x Status x%x "
5855 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5856 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5857 			"CQ: x%x x%x x%x x%x\n",
5858 			mboxq->vport ? mboxq->vport->vpi : 0,
5859 			bf_get(lpfc_mqe_command, mqe),
5860 			bf_get(lpfc_mqe_status, mqe),
5861 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5862 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5863 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5864 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5865 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5866 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5867 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5868 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5869 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5870 			mboxq->mcqe.word0,
5871 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5872 			mboxq->mcqe.trailer);
5873 
5874 	if (rc) {
5875 		rc = -EIO;
5876 		goto out_free_mboxq;
5877 	}
5878 	data_length = mqe->un.mb_words[5];
5879 	if (data_length > DMP_RGN23_SIZE) {
5880 		rc = -EIO;
5881 		goto out_free_mboxq;
5882 	}
5883 
5884 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5885 	rc = 0;
5886 
5887 out_free_mboxq:
5888 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
5889 	return rc;
5890 }
5891 
5892 /**
5893  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5894  * @phba: pointer to lpfc hba data structure.
5895  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5896  * @vpd: pointer to the memory to hold resulting port vpd data.
5897  * @vpd_size: On input, the number of bytes allocated to @vpd.
5898  *	      On output, the number of data bytes in @vpd.
5899  *
5900  * This routine executes a READ_REV SLI4 mailbox command.  In
5901  * addition, this routine gets the port vpd data.
5902  *
5903  * Return codes
5904  * 	0 - successful
5905  * 	-ENOMEM - could not allocated memory.
5906  **/
5907 static int
5908 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5909 		    uint8_t *vpd, uint32_t *vpd_size)
5910 {
5911 	int rc = 0;
5912 	uint32_t dma_size;
5913 	struct lpfc_dmabuf *dmabuf;
5914 	struct lpfc_mqe *mqe;
5915 
5916 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5917 	if (!dmabuf)
5918 		return -ENOMEM;
5919 
5920 	/*
5921 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5922 	 * mailbox command.
5923 	 */
5924 	dma_size = *vpd_size;
5925 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5926 					  &dmabuf->phys, GFP_KERNEL);
5927 	if (!dmabuf->virt) {
5928 		kfree(dmabuf);
5929 		return -ENOMEM;
5930 	}
5931 
5932 	/*
5933 	 * The SLI4 implementation of READ_REV conflicts at word1,
5934 	 * bits 31:16 and SLI4 adds vpd functionality not present
5935 	 * in SLI3.  This code corrects the conflicts.
5936 	 */
5937 	lpfc_read_rev(phba, mboxq);
5938 	mqe = &mboxq->u.mqe;
5939 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5940 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5941 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5942 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5943 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5944 
5945 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5946 	if (rc) {
5947 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5948 				  dmabuf->virt, dmabuf->phys);
5949 		kfree(dmabuf);
5950 		return -EIO;
5951 	}
5952 
5953 	/*
5954 	 * The available vpd length cannot be bigger than the
5955 	 * DMA buffer passed to the port.  Catch the less than
5956 	 * case and update the caller's size.
5957 	 */
5958 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5959 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5960 
5961 	memcpy(vpd, dmabuf->virt, *vpd_size);
5962 
5963 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5964 			  dmabuf->virt, dmabuf->phys);
5965 	kfree(dmabuf);
5966 	return 0;
5967 }
5968 
5969 /**
5970  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5971  * @phba: pointer to lpfc hba data structure.
5972  *
5973  * This routine retrieves SLI4 device physical port name this PCI function
5974  * is attached to.
5975  *
5976  * Return codes
5977  *      0 - successful
5978  *      otherwise - failed to retrieve controller attributes
5979  **/
5980 static int
5981 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5982 {
5983 	LPFC_MBOXQ_t *mboxq;
5984 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5985 	struct lpfc_controller_attribute *cntl_attr;
5986 	void *virtaddr = NULL;
5987 	uint32_t alloclen, reqlen;
5988 	uint32_t shdr_status, shdr_add_status;
5989 	union lpfc_sli4_cfg_shdr *shdr;
5990 	int rc;
5991 
5992 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5993 	if (!mboxq)
5994 		return -ENOMEM;
5995 
5996 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5997 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5998 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5999 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
6000 			LPFC_SLI4_MBX_NEMBED);
6001 
6002 	if (alloclen < reqlen) {
6003 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6004 				"3084 Allocated DMA memory size (%d) is "
6005 				"less than the requested DMA memory size "
6006 				"(%d)\n", alloclen, reqlen);
6007 		rc = -ENOMEM;
6008 		goto out_free_mboxq;
6009 	}
6010 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6011 	virtaddr = mboxq->sge_array->addr[0];
6012 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
6013 	shdr = &mbx_cntl_attr->cfg_shdr;
6014 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6015 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6016 	if (shdr_status || shdr_add_status || rc) {
6017 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6018 				"3085 Mailbox x%x (x%x/x%x) failed, "
6019 				"rc:x%x, status:x%x, add_status:x%x\n",
6020 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6021 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6022 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6023 				rc, shdr_status, shdr_add_status);
6024 		rc = -ENXIO;
6025 		goto out_free_mboxq;
6026 	}
6027 
6028 	cntl_attr = &mbx_cntl_attr->cntl_attr;
6029 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
6030 	phba->sli4_hba.lnk_info.lnk_tp =
6031 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
6032 	phba->sli4_hba.lnk_info.lnk_no =
6033 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
6034 	phba->sli4_hba.flash_id = bf_get(lpfc_cntl_attr_flash_id, cntl_attr);
6035 	phba->sli4_hba.asic_rev = bf_get(lpfc_cntl_attr_asic_rev, cntl_attr);
6036 
6037 	memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
6038 	strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
6039 		sizeof(phba->BIOSVersion));
6040 
6041 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6042 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s, "
6043 			"flash_id: x%02x, asic_rev: x%02x\n",
6044 			phba->sli4_hba.lnk_info.lnk_tp,
6045 			phba->sli4_hba.lnk_info.lnk_no,
6046 			phba->BIOSVersion, phba->sli4_hba.flash_id,
6047 			phba->sli4_hba.asic_rev);
6048 out_free_mboxq:
6049 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6050 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6051 	else
6052 		mempool_free(mboxq, phba->mbox_mem_pool);
6053 	return rc;
6054 }
6055 
6056 /**
6057  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
6058  * @phba: pointer to lpfc hba data structure.
6059  *
6060  * This routine retrieves SLI4 device physical port name this PCI function
6061  * is attached to.
6062  *
6063  * Return codes
6064  *      0 - successful
6065  *      otherwise - failed to retrieve physical port name
6066  **/
6067 static int
6068 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
6069 {
6070 	LPFC_MBOXQ_t *mboxq;
6071 	struct lpfc_mbx_get_port_name *get_port_name;
6072 	uint32_t shdr_status, shdr_add_status;
6073 	union lpfc_sli4_cfg_shdr *shdr;
6074 	char cport_name = 0;
6075 	int rc;
6076 
6077 	/* We assume nothing at this point */
6078 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6079 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
6080 
6081 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6082 	if (!mboxq)
6083 		return -ENOMEM;
6084 	/* obtain link type and link number via READ_CONFIG */
6085 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6086 	lpfc_sli4_read_config(phba);
6087 
6088 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG)
6089 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
6090 
6091 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
6092 		goto retrieve_ppname;
6093 
6094 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
6095 	rc = lpfc_sli4_get_ctl_attr(phba);
6096 	if (rc)
6097 		goto out_free_mboxq;
6098 
6099 retrieve_ppname:
6100 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
6101 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
6102 		sizeof(struct lpfc_mbx_get_port_name) -
6103 		sizeof(struct lpfc_sli4_cfg_mhdr),
6104 		LPFC_SLI4_MBX_EMBED);
6105 	get_port_name = &mboxq->u.mqe.un.get_port_name;
6106 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
6107 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
6108 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
6109 		phba->sli4_hba.lnk_info.lnk_tp);
6110 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6111 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6112 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6113 	if (shdr_status || shdr_add_status || rc) {
6114 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6115 				"3087 Mailbox x%x (x%x/x%x) failed: "
6116 				"rc:x%x, status:x%x, add_status:x%x\n",
6117 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6118 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6119 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6120 				rc, shdr_status, shdr_add_status);
6121 		rc = -ENXIO;
6122 		goto out_free_mboxq;
6123 	}
6124 	switch (phba->sli4_hba.lnk_info.lnk_no) {
6125 	case LPFC_LINK_NUMBER_0:
6126 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
6127 				&get_port_name->u.response);
6128 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6129 		break;
6130 	case LPFC_LINK_NUMBER_1:
6131 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
6132 				&get_port_name->u.response);
6133 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6134 		break;
6135 	case LPFC_LINK_NUMBER_2:
6136 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
6137 				&get_port_name->u.response);
6138 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6139 		break;
6140 	case LPFC_LINK_NUMBER_3:
6141 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
6142 				&get_port_name->u.response);
6143 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6144 		break;
6145 	default:
6146 		break;
6147 	}
6148 
6149 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
6150 		phba->Port[0] = cport_name;
6151 		phba->Port[1] = '\0';
6152 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6153 				"3091 SLI get port name: %s\n", phba->Port);
6154 	}
6155 
6156 out_free_mboxq:
6157 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6158 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6159 	else
6160 		mempool_free(mboxq, phba->mbox_mem_pool);
6161 	return rc;
6162 }
6163 
6164 /**
6165  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
6166  * @phba: pointer to lpfc hba data structure.
6167  *
6168  * This routine is called to explicitly arm the SLI4 device's completion and
6169  * event queues
6170  **/
6171 static void
6172 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
6173 {
6174 	int qidx;
6175 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
6176 	struct lpfc_sli4_hdw_queue *qp;
6177 	struct lpfc_queue *eq;
6178 
6179 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
6180 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
6181 	if (sli4_hba->nvmels_cq)
6182 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
6183 					   LPFC_QUEUE_REARM);
6184 
6185 	if (sli4_hba->hdwq) {
6186 		/* Loop thru all Hardware Queues */
6187 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
6188 			qp = &sli4_hba->hdwq[qidx];
6189 			/* ARM the corresponding CQ */
6190 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
6191 						LPFC_QUEUE_REARM);
6192 		}
6193 
6194 		/* Loop thru all IRQ vectors */
6195 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
6196 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
6197 			/* ARM the corresponding EQ */
6198 			sli4_hba->sli4_write_eq_db(phba, eq,
6199 						   0, LPFC_QUEUE_REARM);
6200 		}
6201 	}
6202 
6203 	if (phba->nvmet_support) {
6204 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
6205 			sli4_hba->sli4_write_cq_db(phba,
6206 				sli4_hba->nvmet_cqset[qidx], 0,
6207 				LPFC_QUEUE_REARM);
6208 		}
6209 	}
6210 }
6211 
6212 /**
6213  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
6214  * @phba: Pointer to HBA context object.
6215  * @type: The resource extent type.
6216  * @extnt_count: buffer to hold port available extent count.
6217  * @extnt_size: buffer to hold element count per extent.
6218  *
6219  * This function calls the port and retrievs the number of available
6220  * extents and their size for a particular extent type.
6221  *
6222  * Returns: 0 if successful.  Nonzero otherwise.
6223  **/
6224 int
6225 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
6226 			       uint16_t *extnt_count, uint16_t *extnt_size)
6227 {
6228 	int rc = 0;
6229 	uint32_t length;
6230 	uint32_t mbox_tmo;
6231 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
6232 	LPFC_MBOXQ_t *mbox;
6233 
6234 	*extnt_count = 0;
6235 	*extnt_size = 0;
6236 
6237 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6238 	if (!mbox)
6239 		return -ENOMEM;
6240 
6241 	/* Find out how many extents are available for this resource type */
6242 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
6243 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6244 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6245 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
6246 			 length, LPFC_SLI4_MBX_EMBED);
6247 
6248 	/* Send an extents count of 0 - the GET doesn't use it. */
6249 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6250 					LPFC_SLI4_MBX_EMBED);
6251 	if (unlikely(rc)) {
6252 		rc = -EIO;
6253 		goto err_exit;
6254 	}
6255 
6256 	if (!phba->sli4_hba.intr_enable)
6257 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6258 	else {
6259 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6260 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6261 	}
6262 	if (unlikely(rc)) {
6263 		rc = -EIO;
6264 		goto err_exit;
6265 	}
6266 
6267 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
6268 	if (bf_get(lpfc_mbox_hdr_status,
6269 		   &rsrc_info->header.cfg_shdr.response)) {
6270 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6271 				"2930 Failed to get resource extents "
6272 				"Status 0x%x Add'l Status 0x%x\n",
6273 				bf_get(lpfc_mbox_hdr_status,
6274 				       &rsrc_info->header.cfg_shdr.response),
6275 				bf_get(lpfc_mbox_hdr_add_status,
6276 				       &rsrc_info->header.cfg_shdr.response));
6277 		rc = -EIO;
6278 		goto err_exit;
6279 	}
6280 
6281 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
6282 			      &rsrc_info->u.rsp);
6283 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
6284 			     &rsrc_info->u.rsp);
6285 
6286 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6287 			"3162 Retrieved extents type-%d from port: count:%d, "
6288 			"size:%d\n", type, *extnt_count, *extnt_size);
6289 
6290 err_exit:
6291 	mempool_free(mbox, phba->mbox_mem_pool);
6292 	return rc;
6293 }
6294 
6295 /**
6296  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
6297  * @phba: Pointer to HBA context object.
6298  * @type: The extent type to check.
6299  *
6300  * This function reads the current available extents from the port and checks
6301  * if the extent count or extent size has changed since the last access.
6302  * Callers use this routine post port reset to understand if there is a
6303  * extent reprovisioning requirement.
6304  *
6305  * Returns:
6306  *   -Error: error indicates problem.
6307  *   1: Extent count or size has changed.
6308  *   0: No changes.
6309  **/
6310 static int
6311 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
6312 {
6313 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
6314 	uint16_t size_diff, rsrc_ext_size;
6315 	int rc = 0;
6316 	struct lpfc_rsrc_blks *rsrc_entry;
6317 	struct list_head *rsrc_blk_list = NULL;
6318 
6319 	size_diff = 0;
6320 	curr_ext_cnt = 0;
6321 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6322 					    &rsrc_ext_cnt,
6323 					    &rsrc_ext_size);
6324 	if (unlikely(rc))
6325 		return -EIO;
6326 
6327 	switch (type) {
6328 	case LPFC_RSC_TYPE_FCOE_RPI:
6329 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6330 		break;
6331 	case LPFC_RSC_TYPE_FCOE_VPI:
6332 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
6333 		break;
6334 	case LPFC_RSC_TYPE_FCOE_XRI:
6335 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6336 		break;
6337 	case LPFC_RSC_TYPE_FCOE_VFI:
6338 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6339 		break;
6340 	default:
6341 		break;
6342 	}
6343 
6344 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
6345 		curr_ext_cnt++;
6346 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
6347 			size_diff++;
6348 	}
6349 
6350 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
6351 		rc = 1;
6352 
6353 	return rc;
6354 }
6355 
6356 /**
6357  * lpfc_sli4_cfg_post_extnts -
6358  * @phba: Pointer to HBA context object.
6359  * @extnt_cnt: number of available extents.
6360  * @type: the extent type (rpi, xri, vfi, vpi).
6361  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
6362  * @mbox: pointer to the caller's allocated mailbox structure.
6363  *
6364  * This function executes the extents allocation request.  It also
6365  * takes care of the amount of memory needed to allocate or get the
6366  * allocated extents. It is the caller's responsibility to evaluate
6367  * the response.
6368  *
6369  * Returns:
6370  *   -Error:  Error value describes the condition found.
6371  *   0: if successful
6372  **/
6373 static int
6374 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6375 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6376 {
6377 	int rc = 0;
6378 	uint32_t req_len;
6379 	uint32_t emb_len;
6380 	uint32_t alloc_len, mbox_tmo;
6381 
6382 	/* Calculate the total requested length of the dma memory */
6383 	req_len = extnt_cnt * sizeof(uint16_t);
6384 
6385 	/*
6386 	 * Calculate the size of an embedded mailbox.  The uint32_t
6387 	 * accounts for extents-specific word.
6388 	 */
6389 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6390 		sizeof(uint32_t);
6391 
6392 	/*
6393 	 * Presume the allocation and response will fit into an embedded
6394 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6395 	 */
6396 	*emb = LPFC_SLI4_MBX_EMBED;
6397 	if (req_len > emb_len) {
6398 		req_len = extnt_cnt * sizeof(uint16_t) +
6399 			sizeof(union lpfc_sli4_cfg_shdr) +
6400 			sizeof(uint32_t);
6401 		*emb = LPFC_SLI4_MBX_NEMBED;
6402 	}
6403 
6404 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6405 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6406 				     req_len, *emb);
6407 	if (alloc_len < req_len) {
6408 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6409 			"2982 Allocated DMA memory size (x%x) is "
6410 			"less than the requested DMA memory "
6411 			"size (x%x)\n", alloc_len, req_len);
6412 		return -ENOMEM;
6413 	}
6414 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6415 	if (unlikely(rc))
6416 		return -EIO;
6417 
6418 	if (!phba->sli4_hba.intr_enable)
6419 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6420 	else {
6421 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6422 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6423 	}
6424 
6425 	if (unlikely(rc))
6426 		rc = -EIO;
6427 	return rc;
6428 }
6429 
6430 /**
6431  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6432  * @phba: Pointer to HBA context object.
6433  * @type:  The resource extent type to allocate.
6434  *
6435  * This function allocates the number of elements for the specified
6436  * resource type.
6437  **/
6438 static int
6439 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6440 {
6441 	bool emb = false;
6442 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6443 	uint16_t rsrc_id, rsrc_start, j, k;
6444 	uint16_t *ids;
6445 	int i, rc;
6446 	unsigned long longs;
6447 	unsigned long *bmask;
6448 	struct lpfc_rsrc_blks *rsrc_blks;
6449 	LPFC_MBOXQ_t *mbox;
6450 	uint32_t length;
6451 	struct lpfc_id_range *id_array = NULL;
6452 	void *virtaddr = NULL;
6453 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6454 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6455 	struct list_head *ext_blk_list;
6456 
6457 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6458 					    &rsrc_cnt,
6459 					    &rsrc_size);
6460 	if (unlikely(rc))
6461 		return -EIO;
6462 
6463 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6464 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6465 			"3009 No available Resource Extents "
6466 			"for resource type 0x%x: Count: 0x%x, "
6467 			"Size 0x%x\n", type, rsrc_cnt,
6468 			rsrc_size);
6469 		return -ENOMEM;
6470 	}
6471 
6472 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6473 			"2903 Post resource extents type-0x%x: "
6474 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6475 
6476 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6477 	if (!mbox)
6478 		return -ENOMEM;
6479 
6480 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6481 	if (unlikely(rc)) {
6482 		rc = -EIO;
6483 		goto err_exit;
6484 	}
6485 
6486 	/*
6487 	 * Figure out where the response is located.  Then get local pointers
6488 	 * to the response data.  The port does not guarantee to respond to
6489 	 * all extents counts request so update the local variable with the
6490 	 * allocated count from the port.
6491 	 */
6492 	if (emb == LPFC_SLI4_MBX_EMBED) {
6493 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6494 		id_array = &rsrc_ext->u.rsp.id[0];
6495 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6496 	} else {
6497 		virtaddr = mbox->sge_array->addr[0];
6498 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6499 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6500 		id_array = &n_rsrc->id;
6501 	}
6502 
6503 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6504 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6505 
6506 	/*
6507 	 * Based on the resource size and count, correct the base and max
6508 	 * resource values.
6509 	 */
6510 	length = sizeof(struct lpfc_rsrc_blks);
6511 	switch (type) {
6512 	case LPFC_RSC_TYPE_FCOE_RPI:
6513 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6514 						   sizeof(unsigned long),
6515 						   GFP_KERNEL);
6516 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6517 			rc = -ENOMEM;
6518 			goto err_exit;
6519 		}
6520 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6521 						 sizeof(uint16_t),
6522 						 GFP_KERNEL);
6523 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6524 			kfree(phba->sli4_hba.rpi_bmask);
6525 			rc = -ENOMEM;
6526 			goto err_exit;
6527 		}
6528 
6529 		/*
6530 		 * The next_rpi was initialized with the maximum available
6531 		 * count but the port may allocate a smaller number.  Catch
6532 		 * that case and update the next_rpi.
6533 		 */
6534 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6535 
6536 		/* Initialize local ptrs for common extent processing later. */
6537 		bmask = phba->sli4_hba.rpi_bmask;
6538 		ids = phba->sli4_hba.rpi_ids;
6539 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6540 		break;
6541 	case LPFC_RSC_TYPE_FCOE_VPI:
6542 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6543 					  GFP_KERNEL);
6544 		if (unlikely(!phba->vpi_bmask)) {
6545 			rc = -ENOMEM;
6546 			goto err_exit;
6547 		}
6548 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6549 					 GFP_KERNEL);
6550 		if (unlikely(!phba->vpi_ids)) {
6551 			kfree(phba->vpi_bmask);
6552 			rc = -ENOMEM;
6553 			goto err_exit;
6554 		}
6555 
6556 		/* Initialize local ptrs for common extent processing later. */
6557 		bmask = phba->vpi_bmask;
6558 		ids = phba->vpi_ids;
6559 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6560 		break;
6561 	case LPFC_RSC_TYPE_FCOE_XRI:
6562 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6563 						   sizeof(unsigned long),
6564 						   GFP_KERNEL);
6565 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6566 			rc = -ENOMEM;
6567 			goto err_exit;
6568 		}
6569 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6570 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6571 						 sizeof(uint16_t),
6572 						 GFP_KERNEL);
6573 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6574 			kfree(phba->sli4_hba.xri_bmask);
6575 			rc = -ENOMEM;
6576 			goto err_exit;
6577 		}
6578 
6579 		/* Initialize local ptrs for common extent processing later. */
6580 		bmask = phba->sli4_hba.xri_bmask;
6581 		ids = phba->sli4_hba.xri_ids;
6582 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6583 		break;
6584 	case LPFC_RSC_TYPE_FCOE_VFI:
6585 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6586 						   sizeof(unsigned long),
6587 						   GFP_KERNEL);
6588 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6589 			rc = -ENOMEM;
6590 			goto err_exit;
6591 		}
6592 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6593 						 sizeof(uint16_t),
6594 						 GFP_KERNEL);
6595 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6596 			kfree(phba->sli4_hba.vfi_bmask);
6597 			rc = -ENOMEM;
6598 			goto err_exit;
6599 		}
6600 
6601 		/* Initialize local ptrs for common extent processing later. */
6602 		bmask = phba->sli4_hba.vfi_bmask;
6603 		ids = phba->sli4_hba.vfi_ids;
6604 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6605 		break;
6606 	default:
6607 		/* Unsupported Opcode.  Fail call. */
6608 		id_array = NULL;
6609 		bmask = NULL;
6610 		ids = NULL;
6611 		ext_blk_list = NULL;
6612 		goto err_exit;
6613 	}
6614 
6615 	/*
6616 	 * Complete initializing the extent configuration with the
6617 	 * allocated ids assigned to this function.  The bitmask serves
6618 	 * as an index into the array and manages the available ids.  The
6619 	 * array just stores the ids communicated to the port via the wqes.
6620 	 */
6621 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6622 		if ((i % 2) == 0)
6623 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6624 					 &id_array[k]);
6625 		else
6626 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6627 					 &id_array[k]);
6628 
6629 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6630 		if (unlikely(!rsrc_blks)) {
6631 			rc = -ENOMEM;
6632 			kfree(bmask);
6633 			kfree(ids);
6634 			goto err_exit;
6635 		}
6636 		rsrc_blks->rsrc_start = rsrc_id;
6637 		rsrc_blks->rsrc_size = rsrc_size;
6638 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6639 		rsrc_start = rsrc_id;
6640 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6641 			phba->sli4_hba.io_xri_start = rsrc_start +
6642 				lpfc_sli4_get_iocb_cnt(phba);
6643 		}
6644 
6645 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6646 			ids[j] = rsrc_id;
6647 			rsrc_id++;
6648 			j++;
6649 		}
6650 		/* Entire word processed.  Get next word.*/
6651 		if ((i % 2) == 1)
6652 			k++;
6653 	}
6654  err_exit:
6655 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6656 	return rc;
6657 }
6658 
6659 
6660 
6661 /**
6662  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6663  * @phba: Pointer to HBA context object.
6664  * @type: the extent's type.
6665  *
6666  * This function deallocates all extents of a particular resource type.
6667  * SLI4 does not allow for deallocating a particular extent range.  It
6668  * is the caller's responsibility to release all kernel memory resources.
6669  **/
6670 static int
6671 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6672 {
6673 	int rc;
6674 	uint32_t length, mbox_tmo = 0;
6675 	LPFC_MBOXQ_t *mbox;
6676 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6677 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6678 
6679 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6680 	if (!mbox)
6681 		return -ENOMEM;
6682 
6683 	/*
6684 	 * This function sends an embedded mailbox because it only sends the
6685 	 * the resource type.  All extents of this type are released by the
6686 	 * port.
6687 	 */
6688 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6689 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6690 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6691 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6692 			 length, LPFC_SLI4_MBX_EMBED);
6693 
6694 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6695 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6696 					LPFC_SLI4_MBX_EMBED);
6697 	if (unlikely(rc)) {
6698 		rc = -EIO;
6699 		goto out_free_mbox;
6700 	}
6701 	if (!phba->sli4_hba.intr_enable)
6702 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6703 	else {
6704 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6705 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6706 	}
6707 	if (unlikely(rc)) {
6708 		rc = -EIO;
6709 		goto out_free_mbox;
6710 	}
6711 
6712 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6713 	if (bf_get(lpfc_mbox_hdr_status,
6714 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6715 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6716 				"2919 Failed to release resource extents "
6717 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6718 				"Resource memory not released.\n",
6719 				type,
6720 				bf_get(lpfc_mbox_hdr_status,
6721 				    &dealloc_rsrc->header.cfg_shdr.response),
6722 				bf_get(lpfc_mbox_hdr_add_status,
6723 				    &dealloc_rsrc->header.cfg_shdr.response));
6724 		rc = -EIO;
6725 		goto out_free_mbox;
6726 	}
6727 
6728 	/* Release kernel memory resources for the specific type. */
6729 	switch (type) {
6730 	case LPFC_RSC_TYPE_FCOE_VPI:
6731 		kfree(phba->vpi_bmask);
6732 		kfree(phba->vpi_ids);
6733 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6734 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6735 				    &phba->lpfc_vpi_blk_list, list) {
6736 			list_del_init(&rsrc_blk->list);
6737 			kfree(rsrc_blk);
6738 		}
6739 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6740 		break;
6741 	case LPFC_RSC_TYPE_FCOE_XRI:
6742 		kfree(phba->sli4_hba.xri_bmask);
6743 		kfree(phba->sli4_hba.xri_ids);
6744 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6745 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6746 			list_del_init(&rsrc_blk->list);
6747 			kfree(rsrc_blk);
6748 		}
6749 		break;
6750 	case LPFC_RSC_TYPE_FCOE_VFI:
6751 		kfree(phba->sli4_hba.vfi_bmask);
6752 		kfree(phba->sli4_hba.vfi_ids);
6753 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6754 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6755 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6756 			list_del_init(&rsrc_blk->list);
6757 			kfree(rsrc_blk);
6758 		}
6759 		break;
6760 	case LPFC_RSC_TYPE_FCOE_RPI:
6761 		/* RPI bitmask and physical id array are cleaned up earlier. */
6762 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6763 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6764 			list_del_init(&rsrc_blk->list);
6765 			kfree(rsrc_blk);
6766 		}
6767 		break;
6768 	default:
6769 		break;
6770 	}
6771 
6772 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6773 
6774  out_free_mbox:
6775 	mempool_free(mbox, phba->mbox_mem_pool);
6776 	return rc;
6777 }
6778 
6779 static void
6780 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6781 		  uint32_t feature)
6782 {
6783 	uint32_t len;
6784 	u32 sig_freq = 0;
6785 
6786 	len = sizeof(struct lpfc_mbx_set_feature) -
6787 		sizeof(struct lpfc_sli4_cfg_mhdr);
6788 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6789 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6790 			 LPFC_SLI4_MBX_EMBED);
6791 
6792 	switch (feature) {
6793 	case LPFC_SET_UE_RECOVERY:
6794 		bf_set(lpfc_mbx_set_feature_UER,
6795 		       &mbox->u.mqe.un.set_feature, 1);
6796 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6797 		mbox->u.mqe.un.set_feature.param_len = 8;
6798 		break;
6799 	case LPFC_SET_MDS_DIAGS:
6800 		bf_set(lpfc_mbx_set_feature_mds,
6801 		       &mbox->u.mqe.un.set_feature, 1);
6802 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6803 		       &mbox->u.mqe.un.set_feature, 1);
6804 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6805 		mbox->u.mqe.un.set_feature.param_len = 8;
6806 		break;
6807 	case LPFC_SET_CGN_SIGNAL:
6808 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6809 			sig_freq = 0;
6810 		else
6811 			sig_freq = phba->cgn_sig_freq;
6812 
6813 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6814 			bf_set(lpfc_mbx_set_feature_CGN_alarm_freq,
6815 			       &mbox->u.mqe.un.set_feature, sig_freq);
6816 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6817 			       &mbox->u.mqe.un.set_feature, sig_freq);
6818 		}
6819 
6820 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY)
6821 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6822 			       &mbox->u.mqe.un.set_feature, sig_freq);
6823 
6824 		if (phba->cmf_active_mode == LPFC_CFG_OFF ||
6825 		    phba->cgn_reg_signal == EDC_CG_SIG_NOTSUPPORTED)
6826 			sig_freq = 0;
6827 		else
6828 			sig_freq = lpfc_acqe_cgn_frequency;
6829 
6830 		bf_set(lpfc_mbx_set_feature_CGN_acqe_freq,
6831 		       &mbox->u.mqe.un.set_feature, sig_freq);
6832 
6833 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_CGN_SIGNAL;
6834 		mbox->u.mqe.un.set_feature.param_len = 12;
6835 		break;
6836 	case LPFC_SET_DUAL_DUMP:
6837 		bf_set(lpfc_mbx_set_feature_dd,
6838 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6839 		bf_set(lpfc_mbx_set_feature_ddquery,
6840 		       &mbox->u.mqe.un.set_feature, 0);
6841 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6842 		mbox->u.mqe.un.set_feature.param_len = 4;
6843 		break;
6844 	case LPFC_SET_ENABLE_MI:
6845 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_MI;
6846 		mbox->u.mqe.un.set_feature.param_len = 4;
6847 		bf_set(lpfc_mbx_set_feature_milunq, &mbox->u.mqe.un.set_feature,
6848 		       phba->pport->cfg_lun_queue_depth);
6849 		bf_set(lpfc_mbx_set_feature_mi, &mbox->u.mqe.un.set_feature,
6850 		       phba->sli4_hba.pc_sli4_params.mi_ver);
6851 		break;
6852 	case LPFC_SET_LD_SIGNAL:
6853 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_LD_SIGNAL;
6854 		mbox->u.mqe.un.set_feature.param_len = 16;
6855 		bf_set(lpfc_mbx_set_feature_lds_qry,
6856 		       &mbox->u.mqe.un.set_feature, LPFC_QUERY_LDS_OP);
6857 		break;
6858 	case LPFC_SET_ENABLE_CMF:
6859 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_CMF;
6860 		mbox->u.mqe.un.set_feature.param_len = 4;
6861 		bf_set(lpfc_mbx_set_feature_cmf,
6862 		       &mbox->u.mqe.un.set_feature, 1);
6863 		break;
6864 	}
6865 	return;
6866 }
6867 
6868 /**
6869  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6870  * @phba: Pointer to HBA context object.
6871  *
6872  * Disable FW logging into host memory on the adapter. To
6873  * be done before reading logs from the host memory.
6874  **/
6875 void
6876 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6877 {
6878 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6879 
6880 	spin_lock_irq(&phba->hbalock);
6881 	ras_fwlog->state = INACTIVE;
6882 	spin_unlock_irq(&phba->hbalock);
6883 
6884 	/* Disable FW logging to host memory */
6885 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6886 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6887 
6888 	/* Wait 10ms for firmware to stop using DMA buffer */
6889 	usleep_range(10 * 1000, 20 * 1000);
6890 }
6891 
6892 /**
6893  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6894  * @phba: Pointer to HBA context object.
6895  *
6896  * This function is called to free memory allocated for RAS FW logging
6897  * support in the driver.
6898  **/
6899 void
6900 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6901 {
6902 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6903 	struct lpfc_dmabuf *dmabuf, *next;
6904 
6905 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6906 		list_for_each_entry_safe(dmabuf, next,
6907 				    &ras_fwlog->fwlog_buff_list,
6908 				    list) {
6909 			list_del(&dmabuf->list);
6910 			dma_free_coherent(&phba->pcidev->dev,
6911 					  LPFC_RAS_MAX_ENTRY_SIZE,
6912 					  dmabuf->virt, dmabuf->phys);
6913 			kfree(dmabuf);
6914 		}
6915 	}
6916 
6917 	if (ras_fwlog->lwpd.virt) {
6918 		dma_free_coherent(&phba->pcidev->dev,
6919 				  sizeof(uint32_t) * 2,
6920 				  ras_fwlog->lwpd.virt,
6921 				  ras_fwlog->lwpd.phys);
6922 		ras_fwlog->lwpd.virt = NULL;
6923 	}
6924 
6925 	spin_lock_irq(&phba->hbalock);
6926 	ras_fwlog->state = INACTIVE;
6927 	spin_unlock_irq(&phba->hbalock);
6928 }
6929 
6930 /**
6931  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6932  * @phba: Pointer to HBA context object.
6933  * @fwlog_buff_count: Count of buffers to be created.
6934  *
6935  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6936  * to update FW log is posted to the adapter.
6937  * Buffer count is calculated based on module param ras_fwlog_buffsize
6938  * Size of each buffer posted to FW is 64K.
6939  **/
6940 
6941 static int
6942 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6943 			uint32_t fwlog_buff_count)
6944 {
6945 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6946 	struct lpfc_dmabuf *dmabuf;
6947 	int rc = 0, i = 0;
6948 
6949 	/* Initialize List */
6950 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6951 
6952 	/* Allocate memory for the LWPD */
6953 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6954 					    sizeof(uint32_t) * 2,
6955 					    &ras_fwlog->lwpd.phys,
6956 					    GFP_KERNEL);
6957 	if (!ras_fwlog->lwpd.virt) {
6958 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6959 				"6185 LWPD Memory Alloc Failed\n");
6960 
6961 		return -ENOMEM;
6962 	}
6963 
6964 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6965 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6966 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6967 				 GFP_KERNEL);
6968 		if (!dmabuf) {
6969 			rc = -ENOMEM;
6970 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6971 					"6186 Memory Alloc failed FW logging");
6972 			goto free_mem;
6973 		}
6974 
6975 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6976 						  LPFC_RAS_MAX_ENTRY_SIZE,
6977 						  &dmabuf->phys, GFP_KERNEL);
6978 		if (!dmabuf->virt) {
6979 			kfree(dmabuf);
6980 			rc = -ENOMEM;
6981 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6982 					"6187 DMA Alloc Failed FW logging");
6983 			goto free_mem;
6984 		}
6985 		dmabuf->buffer_tag = i;
6986 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6987 	}
6988 
6989 free_mem:
6990 	if (rc)
6991 		lpfc_sli4_ras_dma_free(phba);
6992 
6993 	return rc;
6994 }
6995 
6996 /**
6997  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6998  * @phba: pointer to lpfc hba data structure.
6999  * @pmb: pointer to the driver internal queue element for mailbox command.
7000  *
7001  * Completion handler for driver's RAS MBX command to the device.
7002  **/
7003 static void
7004 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7005 {
7006 	MAILBOX_t *mb;
7007 	union lpfc_sli4_cfg_shdr *shdr;
7008 	uint32_t shdr_status, shdr_add_status;
7009 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
7010 
7011 	mb = &pmb->u.mb;
7012 
7013 	shdr = (union lpfc_sli4_cfg_shdr *)
7014 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
7015 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7016 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7017 
7018 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
7019 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7020 				"6188 FW LOG mailbox "
7021 				"completed with status x%x add_status x%x,"
7022 				" mbx status x%x\n",
7023 				shdr_status, shdr_add_status, mb->mbxStatus);
7024 
7025 		ras_fwlog->ras_hwsupport = false;
7026 		goto disable_ras;
7027 	}
7028 
7029 	spin_lock_irq(&phba->hbalock);
7030 	ras_fwlog->state = ACTIVE;
7031 	spin_unlock_irq(&phba->hbalock);
7032 	mempool_free(pmb, phba->mbox_mem_pool);
7033 
7034 	return;
7035 
7036 disable_ras:
7037 	/* Free RAS DMA memory */
7038 	lpfc_sli4_ras_dma_free(phba);
7039 	mempool_free(pmb, phba->mbox_mem_pool);
7040 }
7041 
7042 /**
7043  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
7044  * @phba: pointer to lpfc hba data structure.
7045  * @fwlog_level: Logging verbosity level.
7046  * @fwlog_enable: Enable/Disable logging.
7047  *
7048  * Initialize memory and post mailbox command to enable FW logging in host
7049  * memory.
7050  **/
7051 int
7052 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
7053 			 uint32_t fwlog_level,
7054 			 uint32_t fwlog_enable)
7055 {
7056 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
7057 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
7058 	struct lpfc_dmabuf *dmabuf;
7059 	LPFC_MBOXQ_t *mbox;
7060 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
7061 	int rc = 0;
7062 
7063 	spin_lock_irq(&phba->hbalock);
7064 	ras_fwlog->state = INACTIVE;
7065 	spin_unlock_irq(&phba->hbalock);
7066 
7067 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
7068 			  phba->cfg_ras_fwlog_buffsize);
7069 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
7070 
7071 	/*
7072 	 * If re-enabling FW logging support use earlier allocated
7073 	 * DMA buffers while posting MBX command.
7074 	 **/
7075 	if (!ras_fwlog->lwpd.virt) {
7076 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
7077 		if (rc) {
7078 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7079 					"6189 FW Log Memory Allocation Failed");
7080 			return rc;
7081 		}
7082 	}
7083 
7084 	/* Setup Mailbox command */
7085 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7086 	if (!mbox) {
7087 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7088 				"6190 RAS MBX Alloc Failed");
7089 		rc = -ENOMEM;
7090 		goto mem_free;
7091 	}
7092 
7093 	ras_fwlog->fw_loglevel = fwlog_level;
7094 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
7095 		sizeof(struct lpfc_sli4_cfg_mhdr));
7096 
7097 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
7098 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
7099 			 len, LPFC_SLI4_MBX_EMBED);
7100 
7101 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
7102 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
7103 	       fwlog_enable);
7104 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
7105 	       ras_fwlog->fw_loglevel);
7106 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
7107 	       ras_fwlog->fw_buffcount);
7108 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
7109 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
7110 
7111 	/* Update DMA buffer address */
7112 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
7113 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
7114 
7115 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
7116 			putPaddrLow(dmabuf->phys);
7117 
7118 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
7119 			putPaddrHigh(dmabuf->phys);
7120 	}
7121 
7122 	/* Update LPWD address */
7123 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
7124 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
7125 
7126 	spin_lock_irq(&phba->hbalock);
7127 	ras_fwlog->state = REG_INPROGRESS;
7128 	spin_unlock_irq(&phba->hbalock);
7129 	mbox->vport = phba->pport;
7130 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
7131 
7132 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
7133 
7134 	if (rc == MBX_NOT_FINISHED) {
7135 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7136 				"6191 FW-Log Mailbox failed. "
7137 				"status %d mbxStatus : x%x", rc,
7138 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
7139 		mempool_free(mbox, phba->mbox_mem_pool);
7140 		rc = -EIO;
7141 		goto mem_free;
7142 	} else
7143 		rc = 0;
7144 mem_free:
7145 	if (rc)
7146 		lpfc_sli4_ras_dma_free(phba);
7147 
7148 	return rc;
7149 }
7150 
7151 /**
7152  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
7153  * @phba: Pointer to HBA context object.
7154  *
7155  * Check if RAS is supported on the adapter and initialize it.
7156  **/
7157 void
7158 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
7159 {
7160 	/* Check RAS FW Log needs to be enabled or not */
7161 	if (lpfc_check_fwlog_support(phba))
7162 		return;
7163 
7164 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
7165 				 LPFC_RAS_ENABLE_LOGGING);
7166 }
7167 
7168 /**
7169  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
7170  * @phba: Pointer to HBA context object.
7171  *
7172  * This function allocates all SLI4 resource identifiers.
7173  **/
7174 int
7175 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
7176 {
7177 	int i, rc, error = 0;
7178 	uint16_t count, base;
7179 	unsigned long longs;
7180 
7181 	if (!phba->sli4_hba.rpi_hdrs_in_use)
7182 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
7183 	if (phba->sli4_hba.extents_in_use) {
7184 		/*
7185 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
7186 		 * resource extent count must be read and allocated before
7187 		 * provisioning the resource id arrays.
7188 		 */
7189 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7190 		    LPFC_IDX_RSRC_RDY) {
7191 			/*
7192 			 * Extent-based resources are set - the driver could
7193 			 * be in a port reset. Figure out if any corrective
7194 			 * actions need to be taken.
7195 			 */
7196 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7197 						 LPFC_RSC_TYPE_FCOE_VFI);
7198 			if (rc != 0)
7199 				error++;
7200 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7201 						 LPFC_RSC_TYPE_FCOE_VPI);
7202 			if (rc != 0)
7203 				error++;
7204 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7205 						 LPFC_RSC_TYPE_FCOE_XRI);
7206 			if (rc != 0)
7207 				error++;
7208 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7209 						 LPFC_RSC_TYPE_FCOE_RPI);
7210 			if (rc != 0)
7211 				error++;
7212 
7213 			/*
7214 			 * It's possible that the number of resources
7215 			 * provided to this port instance changed between
7216 			 * resets.  Detect this condition and reallocate
7217 			 * resources.  Otherwise, there is no action.
7218 			 */
7219 			if (error) {
7220 				lpfc_printf_log(phba, KERN_INFO,
7221 						LOG_MBOX | LOG_INIT,
7222 						"2931 Detected extent resource "
7223 						"change.  Reallocating all "
7224 						"extents.\n");
7225 				rc = lpfc_sli4_dealloc_extent(phba,
7226 						 LPFC_RSC_TYPE_FCOE_VFI);
7227 				rc = lpfc_sli4_dealloc_extent(phba,
7228 						 LPFC_RSC_TYPE_FCOE_VPI);
7229 				rc = lpfc_sli4_dealloc_extent(phba,
7230 						 LPFC_RSC_TYPE_FCOE_XRI);
7231 				rc = lpfc_sli4_dealloc_extent(phba,
7232 						 LPFC_RSC_TYPE_FCOE_RPI);
7233 			} else
7234 				return 0;
7235 		}
7236 
7237 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7238 		if (unlikely(rc))
7239 			goto err_exit;
7240 
7241 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7242 		if (unlikely(rc))
7243 			goto err_exit;
7244 
7245 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7246 		if (unlikely(rc))
7247 			goto err_exit;
7248 
7249 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7250 		if (unlikely(rc))
7251 			goto err_exit;
7252 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7253 		       LPFC_IDX_RSRC_RDY);
7254 		return rc;
7255 	} else {
7256 		/*
7257 		 * The port does not support resource extents.  The XRI, VPI,
7258 		 * VFI, RPI resource ids were determined from READ_CONFIG.
7259 		 * Just allocate the bitmasks and provision the resource id
7260 		 * arrays.  If a port reset is active, the resources don't
7261 		 * need any action - just exit.
7262 		 */
7263 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7264 		    LPFC_IDX_RSRC_RDY) {
7265 			lpfc_sli4_dealloc_resource_identifiers(phba);
7266 			lpfc_sli4_remove_rpis(phba);
7267 		}
7268 		/* RPIs. */
7269 		count = phba->sli4_hba.max_cfg_param.max_rpi;
7270 		if (count <= 0) {
7271 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7272 					"3279 Invalid provisioning of "
7273 					"rpi:%d\n", count);
7274 			rc = -EINVAL;
7275 			goto err_exit;
7276 		}
7277 		base = phba->sli4_hba.max_cfg_param.rpi_base;
7278 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7279 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
7280 						   sizeof(unsigned long),
7281 						   GFP_KERNEL);
7282 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
7283 			rc = -ENOMEM;
7284 			goto err_exit;
7285 		}
7286 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
7287 						 GFP_KERNEL);
7288 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
7289 			rc = -ENOMEM;
7290 			goto free_rpi_bmask;
7291 		}
7292 
7293 		for (i = 0; i < count; i++)
7294 			phba->sli4_hba.rpi_ids[i] = base + i;
7295 
7296 		/* VPIs. */
7297 		count = phba->sli4_hba.max_cfg_param.max_vpi;
7298 		if (count <= 0) {
7299 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7300 					"3280 Invalid provisioning of "
7301 					"vpi:%d\n", count);
7302 			rc = -EINVAL;
7303 			goto free_rpi_ids;
7304 		}
7305 		base = phba->sli4_hba.max_cfg_param.vpi_base;
7306 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7307 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
7308 					  GFP_KERNEL);
7309 		if (unlikely(!phba->vpi_bmask)) {
7310 			rc = -ENOMEM;
7311 			goto free_rpi_ids;
7312 		}
7313 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
7314 					GFP_KERNEL);
7315 		if (unlikely(!phba->vpi_ids)) {
7316 			rc = -ENOMEM;
7317 			goto free_vpi_bmask;
7318 		}
7319 
7320 		for (i = 0; i < count; i++)
7321 			phba->vpi_ids[i] = base + i;
7322 
7323 		/* XRIs. */
7324 		count = phba->sli4_hba.max_cfg_param.max_xri;
7325 		if (count <= 0) {
7326 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7327 					"3281 Invalid provisioning of "
7328 					"xri:%d\n", count);
7329 			rc = -EINVAL;
7330 			goto free_vpi_ids;
7331 		}
7332 		base = phba->sli4_hba.max_cfg_param.xri_base;
7333 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7334 		phba->sli4_hba.xri_bmask = kcalloc(longs,
7335 						   sizeof(unsigned long),
7336 						   GFP_KERNEL);
7337 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
7338 			rc = -ENOMEM;
7339 			goto free_vpi_ids;
7340 		}
7341 		phba->sli4_hba.max_cfg_param.xri_used = 0;
7342 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
7343 						 GFP_KERNEL);
7344 		if (unlikely(!phba->sli4_hba.xri_ids)) {
7345 			rc = -ENOMEM;
7346 			goto free_xri_bmask;
7347 		}
7348 
7349 		for (i = 0; i < count; i++)
7350 			phba->sli4_hba.xri_ids[i] = base + i;
7351 
7352 		/* VFIs. */
7353 		count = phba->sli4_hba.max_cfg_param.max_vfi;
7354 		if (count <= 0) {
7355 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7356 					"3282 Invalid provisioning of "
7357 					"vfi:%d\n", count);
7358 			rc = -EINVAL;
7359 			goto free_xri_ids;
7360 		}
7361 		base = phba->sli4_hba.max_cfg_param.vfi_base;
7362 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7363 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
7364 						   sizeof(unsigned long),
7365 						   GFP_KERNEL);
7366 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
7367 			rc = -ENOMEM;
7368 			goto free_xri_ids;
7369 		}
7370 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
7371 						 GFP_KERNEL);
7372 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
7373 			rc = -ENOMEM;
7374 			goto free_vfi_bmask;
7375 		}
7376 
7377 		for (i = 0; i < count; i++)
7378 			phba->sli4_hba.vfi_ids[i] = base + i;
7379 
7380 		/*
7381 		 * Mark all resources ready.  An HBA reset doesn't need
7382 		 * to reset the initialization.
7383 		 */
7384 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7385 		       LPFC_IDX_RSRC_RDY);
7386 		return 0;
7387 	}
7388 
7389  free_vfi_bmask:
7390 	kfree(phba->sli4_hba.vfi_bmask);
7391 	phba->sli4_hba.vfi_bmask = NULL;
7392  free_xri_ids:
7393 	kfree(phba->sli4_hba.xri_ids);
7394 	phba->sli4_hba.xri_ids = NULL;
7395  free_xri_bmask:
7396 	kfree(phba->sli4_hba.xri_bmask);
7397 	phba->sli4_hba.xri_bmask = NULL;
7398  free_vpi_ids:
7399 	kfree(phba->vpi_ids);
7400 	phba->vpi_ids = NULL;
7401  free_vpi_bmask:
7402 	kfree(phba->vpi_bmask);
7403 	phba->vpi_bmask = NULL;
7404  free_rpi_ids:
7405 	kfree(phba->sli4_hba.rpi_ids);
7406 	phba->sli4_hba.rpi_ids = NULL;
7407  free_rpi_bmask:
7408 	kfree(phba->sli4_hba.rpi_bmask);
7409 	phba->sli4_hba.rpi_bmask = NULL;
7410  err_exit:
7411 	return rc;
7412 }
7413 
7414 /**
7415  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
7416  * @phba: Pointer to HBA context object.
7417  *
7418  * This function allocates the number of elements for the specified
7419  * resource type.
7420  **/
7421 int
7422 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7423 {
7424 	if (phba->sli4_hba.extents_in_use) {
7425 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7426 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7427 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7428 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7429 	} else {
7430 		kfree(phba->vpi_bmask);
7431 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
7432 		kfree(phba->vpi_ids);
7433 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7434 		kfree(phba->sli4_hba.xri_bmask);
7435 		kfree(phba->sli4_hba.xri_ids);
7436 		kfree(phba->sli4_hba.vfi_bmask);
7437 		kfree(phba->sli4_hba.vfi_ids);
7438 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7439 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7440 	}
7441 
7442 	return 0;
7443 }
7444 
7445 /**
7446  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7447  * @phba: Pointer to HBA context object.
7448  * @type: The resource extent type.
7449  * @extnt_cnt: buffer to hold port extent count response
7450  * @extnt_size: buffer to hold port extent size response.
7451  *
7452  * This function calls the port to read the host allocated extents
7453  * for a particular type.
7454  **/
7455 int
7456 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7457 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
7458 {
7459 	bool emb;
7460 	int rc = 0;
7461 	uint16_t curr_blks = 0;
7462 	uint32_t req_len, emb_len;
7463 	uint32_t alloc_len, mbox_tmo;
7464 	struct list_head *blk_list_head;
7465 	struct lpfc_rsrc_blks *rsrc_blk;
7466 	LPFC_MBOXQ_t *mbox;
7467 	void *virtaddr = NULL;
7468 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7469 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7470 	union  lpfc_sli4_cfg_shdr *shdr;
7471 
7472 	switch (type) {
7473 	case LPFC_RSC_TYPE_FCOE_VPI:
7474 		blk_list_head = &phba->lpfc_vpi_blk_list;
7475 		break;
7476 	case LPFC_RSC_TYPE_FCOE_XRI:
7477 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7478 		break;
7479 	case LPFC_RSC_TYPE_FCOE_VFI:
7480 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7481 		break;
7482 	case LPFC_RSC_TYPE_FCOE_RPI:
7483 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7484 		break;
7485 	default:
7486 		return -EIO;
7487 	}
7488 
7489 	/* Count the number of extents currently allocatd for this type. */
7490 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
7491 		if (curr_blks == 0) {
7492 			/*
7493 			 * The GET_ALLOCATED mailbox does not return the size,
7494 			 * just the count.  The size should be just the size
7495 			 * stored in the current allocated block and all sizes
7496 			 * for an extent type are the same so set the return
7497 			 * value now.
7498 			 */
7499 			*extnt_size = rsrc_blk->rsrc_size;
7500 		}
7501 		curr_blks++;
7502 	}
7503 
7504 	/*
7505 	 * Calculate the size of an embedded mailbox.  The uint32_t
7506 	 * accounts for extents-specific word.
7507 	 */
7508 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7509 		sizeof(uint32_t);
7510 
7511 	/*
7512 	 * Presume the allocation and response will fit into an embedded
7513 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7514 	 */
7515 	emb = LPFC_SLI4_MBX_EMBED;
7516 	req_len = emb_len;
7517 	if (req_len > emb_len) {
7518 		req_len = curr_blks * sizeof(uint16_t) +
7519 			sizeof(union lpfc_sli4_cfg_shdr) +
7520 			sizeof(uint32_t);
7521 		emb = LPFC_SLI4_MBX_NEMBED;
7522 	}
7523 
7524 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7525 	if (!mbox)
7526 		return -ENOMEM;
7527 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7528 
7529 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7530 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7531 				     req_len, emb);
7532 	if (alloc_len < req_len) {
7533 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7534 			"2983 Allocated DMA memory size (x%x) is "
7535 			"less than the requested DMA memory "
7536 			"size (x%x)\n", alloc_len, req_len);
7537 		rc = -ENOMEM;
7538 		goto err_exit;
7539 	}
7540 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7541 	if (unlikely(rc)) {
7542 		rc = -EIO;
7543 		goto err_exit;
7544 	}
7545 
7546 	if (!phba->sli4_hba.intr_enable)
7547 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7548 	else {
7549 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7550 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7551 	}
7552 
7553 	if (unlikely(rc)) {
7554 		rc = -EIO;
7555 		goto err_exit;
7556 	}
7557 
7558 	/*
7559 	 * Figure out where the response is located.  Then get local pointers
7560 	 * to the response data.  The port does not guarantee to respond to
7561 	 * all extents counts request so update the local variable with the
7562 	 * allocated count from the port.
7563 	 */
7564 	if (emb == LPFC_SLI4_MBX_EMBED) {
7565 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7566 		shdr = &rsrc_ext->header.cfg_shdr;
7567 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7568 	} else {
7569 		virtaddr = mbox->sge_array->addr[0];
7570 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7571 		shdr = &n_rsrc->cfg_shdr;
7572 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7573 	}
7574 
7575 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7576 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7577 			"2984 Failed to read allocated resources "
7578 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7579 			type,
7580 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7581 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7582 		rc = -EIO;
7583 		goto err_exit;
7584 	}
7585  err_exit:
7586 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7587 	return rc;
7588 }
7589 
7590 /**
7591  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7592  * @phba: pointer to lpfc hba data structure.
7593  * @sgl_list: linked link of sgl buffers to post
7594  * @cnt: number of linked list buffers
7595  *
7596  * This routine walks the list of buffers that have been allocated and
7597  * repost them to the port by using SGL block post. This is needed after a
7598  * pci_function_reset/warm_start or start. It attempts to construct blocks
7599  * of buffer sgls which contains contiguous xris and uses the non-embedded
7600  * SGL block post mailbox commands to post them to the port. For single
7601  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7602  * mailbox command for posting.
7603  *
7604  * Returns: 0 = success, non-zero failure.
7605  **/
7606 static int
7607 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7608 			  struct list_head *sgl_list, int cnt)
7609 {
7610 	struct lpfc_sglq *sglq_entry = NULL;
7611 	struct lpfc_sglq *sglq_entry_next = NULL;
7612 	struct lpfc_sglq *sglq_entry_first = NULL;
7613 	int status, total_cnt;
7614 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7615 	int last_xritag = NO_XRI;
7616 	LIST_HEAD(prep_sgl_list);
7617 	LIST_HEAD(blck_sgl_list);
7618 	LIST_HEAD(allc_sgl_list);
7619 	LIST_HEAD(post_sgl_list);
7620 	LIST_HEAD(free_sgl_list);
7621 
7622 	spin_lock_irq(&phba->hbalock);
7623 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7624 	list_splice_init(sgl_list, &allc_sgl_list);
7625 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7626 	spin_unlock_irq(&phba->hbalock);
7627 
7628 	total_cnt = cnt;
7629 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7630 				 &allc_sgl_list, list) {
7631 		list_del_init(&sglq_entry->list);
7632 		block_cnt++;
7633 		if ((last_xritag != NO_XRI) &&
7634 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7635 			/* a hole in xri block, form a sgl posting block */
7636 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7637 			post_cnt = block_cnt - 1;
7638 			/* prepare list for next posting block */
7639 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7640 			block_cnt = 1;
7641 		} else {
7642 			/* prepare list for next posting block */
7643 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7644 			/* enough sgls for non-embed sgl mbox command */
7645 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7646 				list_splice_init(&prep_sgl_list,
7647 						 &blck_sgl_list);
7648 				post_cnt = block_cnt;
7649 				block_cnt = 0;
7650 			}
7651 		}
7652 		num_posted++;
7653 
7654 		/* keep track of last sgl's xritag */
7655 		last_xritag = sglq_entry->sli4_xritag;
7656 
7657 		/* end of repost sgl list condition for buffers */
7658 		if (num_posted == total_cnt) {
7659 			if (post_cnt == 0) {
7660 				list_splice_init(&prep_sgl_list,
7661 						 &blck_sgl_list);
7662 				post_cnt = block_cnt;
7663 			} else if (block_cnt == 1) {
7664 				status = lpfc_sli4_post_sgl(phba,
7665 						sglq_entry->phys, 0,
7666 						sglq_entry->sli4_xritag);
7667 				if (!status) {
7668 					/* successful, put sgl to posted list */
7669 					list_add_tail(&sglq_entry->list,
7670 						      &post_sgl_list);
7671 				} else {
7672 					/* Failure, put sgl to free list */
7673 					lpfc_printf_log(phba, KERN_WARNING,
7674 						LOG_SLI,
7675 						"3159 Failed to post "
7676 						"sgl, xritag:x%x\n",
7677 						sglq_entry->sli4_xritag);
7678 					list_add_tail(&sglq_entry->list,
7679 						      &free_sgl_list);
7680 					total_cnt--;
7681 				}
7682 			}
7683 		}
7684 
7685 		/* continue until a nembed page worth of sgls */
7686 		if (post_cnt == 0)
7687 			continue;
7688 
7689 		/* post the buffer list sgls as a block */
7690 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7691 						 post_cnt);
7692 
7693 		if (!status) {
7694 			/* success, put sgl list to posted sgl list */
7695 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7696 		} else {
7697 			/* Failure, put sgl list to free sgl list */
7698 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7699 							    struct lpfc_sglq,
7700 							    list);
7701 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7702 					"3160 Failed to post sgl-list, "
7703 					"xritag:x%x-x%x\n",
7704 					sglq_entry_first->sli4_xritag,
7705 					(sglq_entry_first->sli4_xritag +
7706 					 post_cnt - 1));
7707 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7708 			total_cnt -= post_cnt;
7709 		}
7710 
7711 		/* don't reset xirtag due to hole in xri block */
7712 		if (block_cnt == 0)
7713 			last_xritag = NO_XRI;
7714 
7715 		/* reset sgl post count for next round of posting */
7716 		post_cnt = 0;
7717 	}
7718 
7719 	/* free the sgls failed to post */
7720 	lpfc_free_sgl_list(phba, &free_sgl_list);
7721 
7722 	/* push sgls posted to the available list */
7723 	if (!list_empty(&post_sgl_list)) {
7724 		spin_lock_irq(&phba->hbalock);
7725 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7726 		list_splice_init(&post_sgl_list, sgl_list);
7727 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7728 		spin_unlock_irq(&phba->hbalock);
7729 	} else {
7730 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7731 				"3161 Failure to post sgl to port.\n");
7732 		return -EIO;
7733 	}
7734 
7735 	/* return the number of XRIs actually posted */
7736 	return total_cnt;
7737 }
7738 
7739 /**
7740  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7741  * @phba: pointer to lpfc hba data structure.
7742  *
7743  * This routine walks the list of nvme buffers that have been allocated and
7744  * repost them to the port by using SGL block post. This is needed after a
7745  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7746  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7747  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7748  *
7749  * Returns: 0 = success, non-zero failure.
7750  **/
7751 static int
7752 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7753 {
7754 	LIST_HEAD(post_nblist);
7755 	int num_posted, rc = 0;
7756 
7757 	/* get all NVME buffers need to repost to a local list */
7758 	lpfc_io_buf_flush(phba, &post_nblist);
7759 
7760 	/* post the list of nvme buffer sgls to port if available */
7761 	if (!list_empty(&post_nblist)) {
7762 		num_posted = lpfc_sli4_post_io_sgl_list(
7763 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7764 		/* failed to post any nvme buffer, return error */
7765 		if (num_posted == 0)
7766 			rc = -EIO;
7767 	}
7768 	return rc;
7769 }
7770 
7771 static void
7772 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7773 {
7774 	uint32_t len;
7775 
7776 	len = sizeof(struct lpfc_mbx_set_host_data) -
7777 		sizeof(struct lpfc_sli4_cfg_mhdr);
7778 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7779 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7780 			 LPFC_SLI4_MBX_EMBED);
7781 
7782 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7783 	mbox->u.mqe.un.set_host_data.param_len =
7784 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7785 	snprintf(mbox->u.mqe.un.set_host_data.un.data,
7786 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7787 		 "Linux %s v"LPFC_DRIVER_VERSION,
7788 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7789 }
7790 
7791 int
7792 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7793 		    struct lpfc_queue *drq, int count, int idx)
7794 {
7795 	int rc, i;
7796 	struct lpfc_rqe hrqe;
7797 	struct lpfc_rqe drqe;
7798 	struct lpfc_rqb *rqbp;
7799 	unsigned long flags;
7800 	struct rqb_dmabuf *rqb_buffer;
7801 	LIST_HEAD(rqb_buf_list);
7802 
7803 	rqbp = hrq->rqbp;
7804 	for (i = 0; i < count; i++) {
7805 		spin_lock_irqsave(&phba->hbalock, flags);
7806 		/* IF RQ is already full, don't bother */
7807 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7808 			spin_unlock_irqrestore(&phba->hbalock, flags);
7809 			break;
7810 		}
7811 		spin_unlock_irqrestore(&phba->hbalock, flags);
7812 
7813 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7814 		if (!rqb_buffer)
7815 			break;
7816 		rqb_buffer->hrq = hrq;
7817 		rqb_buffer->drq = drq;
7818 		rqb_buffer->idx = idx;
7819 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7820 	}
7821 
7822 	spin_lock_irqsave(&phba->hbalock, flags);
7823 	while (!list_empty(&rqb_buf_list)) {
7824 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7825 				 hbuf.list);
7826 
7827 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7828 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7829 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7830 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7831 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7832 		if (rc < 0) {
7833 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7834 					"6421 Cannot post to HRQ %d: %x %x %x "
7835 					"DRQ %x %x\n",
7836 					hrq->queue_id,
7837 					hrq->host_index,
7838 					hrq->hba_index,
7839 					hrq->entry_count,
7840 					drq->host_index,
7841 					drq->hba_index);
7842 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7843 		} else {
7844 			list_add_tail(&rqb_buffer->hbuf.list,
7845 				      &rqbp->rqb_buffer_list);
7846 			rqbp->buffer_count++;
7847 		}
7848 	}
7849 	spin_unlock_irqrestore(&phba->hbalock, flags);
7850 	return 1;
7851 }
7852 
7853 static void
7854 lpfc_mbx_cmpl_read_lds_params(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7855 {
7856 	union lpfc_sli4_cfg_shdr *shdr;
7857 	u32 shdr_status, shdr_add_status;
7858 
7859 	shdr = (union lpfc_sli4_cfg_shdr *)
7860 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7861 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7862 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7863 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7864 		lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT | LOG_MBOX,
7865 				"4622 SET_FEATURE (x%x) mbox failed, "
7866 				"status x%x add_status x%x, mbx status x%x\n",
7867 				LPFC_SET_LD_SIGNAL, shdr_status,
7868 				shdr_add_status, pmb->u.mb.mbxStatus);
7869 		phba->degrade_activate_threshold = 0;
7870 		phba->degrade_deactivate_threshold = 0;
7871 		phba->fec_degrade_interval = 0;
7872 		goto out;
7873 	}
7874 
7875 	phba->degrade_activate_threshold = pmb->u.mqe.un.set_feature.word7;
7876 	phba->degrade_deactivate_threshold = pmb->u.mqe.un.set_feature.word8;
7877 	phba->fec_degrade_interval = pmb->u.mqe.un.set_feature.word10;
7878 
7879 	lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT,
7880 			"4624 Success: da x%x dd x%x interval x%x\n",
7881 			phba->degrade_activate_threshold,
7882 			phba->degrade_deactivate_threshold,
7883 			phba->fec_degrade_interval);
7884 out:
7885 	mempool_free(pmb, phba->mbox_mem_pool);
7886 }
7887 
7888 int
7889 lpfc_read_lds_params(struct lpfc_hba *phba)
7890 {
7891 	LPFC_MBOXQ_t *mboxq;
7892 	int rc;
7893 
7894 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7895 	if (!mboxq)
7896 		return -ENOMEM;
7897 
7898 	lpfc_set_features(phba, mboxq, LPFC_SET_LD_SIGNAL);
7899 	mboxq->vport = phba->pport;
7900 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_lds_params;
7901 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7902 	if (rc == MBX_NOT_FINISHED) {
7903 		mempool_free(mboxq, phba->mbox_mem_pool);
7904 		return -EIO;
7905 	}
7906 	return 0;
7907 }
7908 
7909 static void
7910 lpfc_mbx_cmpl_cgn_set_ftrs(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7911 {
7912 	struct lpfc_vport *vport = pmb->vport;
7913 	union lpfc_sli4_cfg_shdr *shdr;
7914 	u32 shdr_status, shdr_add_status;
7915 	u32 sig, acqe;
7916 
7917 	/* Two outcomes. (1) Set featurs was successul and EDC negotiation
7918 	 * is done. (2) Mailbox failed and send FPIN support only.
7919 	 */
7920 	shdr = (union lpfc_sli4_cfg_shdr *)
7921 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7922 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7923 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7924 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7925 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
7926 				"2516 CGN SET_FEATURE mbox failed with "
7927 				"status x%x add_status x%x, mbx status x%x "
7928 				"Reset Congestion to FPINs only\n",
7929 				shdr_status, shdr_add_status,
7930 				pmb->u.mb.mbxStatus);
7931 		/* If there is a mbox error, move on to RDF */
7932 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7933 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7934 		goto out;
7935 	}
7936 
7937 	/* Zero out Congestion Signal ACQE counter */
7938 	phba->cgn_acqe_cnt = 0;
7939 
7940 	acqe = bf_get(lpfc_mbx_set_feature_CGN_acqe_freq,
7941 		      &pmb->u.mqe.un.set_feature);
7942 	sig = bf_get(lpfc_mbx_set_feature_CGN_warn_freq,
7943 		     &pmb->u.mqe.un.set_feature);
7944 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7945 			"4620 SET_FEATURES Success: Freq: %ds %dms "
7946 			" Reg: x%x x%x\n", acqe, sig,
7947 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7948 out:
7949 	mempool_free(pmb, phba->mbox_mem_pool);
7950 
7951 	/* Register for FPIN events from the fabric now that the
7952 	 * EDC common_set_features has completed.
7953 	 */
7954 	lpfc_issue_els_rdf(vport, 0);
7955 }
7956 
7957 int
7958 lpfc_config_cgn_signal(struct lpfc_hba *phba)
7959 {
7960 	LPFC_MBOXQ_t *mboxq;
7961 	u32 rc;
7962 
7963 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7964 	if (!mboxq)
7965 		goto out_rdf;
7966 
7967 	lpfc_set_features(phba, mboxq, LPFC_SET_CGN_SIGNAL);
7968 	mboxq->vport = phba->pport;
7969 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_cgn_set_ftrs;
7970 
7971 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7972 			"4621 SET_FEATURES: FREQ sig x%x acqe x%x: "
7973 			"Reg: x%x x%x\n",
7974 			phba->cgn_sig_freq, lpfc_acqe_cgn_frequency,
7975 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7976 
7977 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7978 	if (rc == MBX_NOT_FINISHED)
7979 		goto out;
7980 	return 0;
7981 
7982 out:
7983 	mempool_free(mboxq, phba->mbox_mem_pool);
7984 out_rdf:
7985 	/* If there is a mbox error, move on to RDF */
7986 	phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7987 	phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7988 	lpfc_issue_els_rdf(phba->pport, 0);
7989 	return -EIO;
7990 }
7991 
7992 /**
7993  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7994  * @phba: pointer to lpfc hba data structure.
7995  *
7996  * This routine initializes the per-cq idle_stat to dynamically dictate
7997  * polling decisions.
7998  *
7999  * Return codes:
8000  *   None
8001  **/
8002 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
8003 {
8004 	int i;
8005 	struct lpfc_sli4_hdw_queue *hdwq;
8006 	struct lpfc_queue *cq;
8007 	struct lpfc_idle_stat *idle_stat;
8008 	u64 wall;
8009 
8010 	for_each_present_cpu(i) {
8011 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
8012 		cq = hdwq->io_cq;
8013 
8014 		/* Skip if we've already handled this cq's primary CPU */
8015 		if (cq->chann != i)
8016 			continue;
8017 
8018 		idle_stat = &phba->sli4_hba.idle_stat[i];
8019 
8020 		idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
8021 		idle_stat->prev_wall = wall;
8022 
8023 		if (phba->nvmet_support ||
8024 		    phba->cmf_active_mode != LPFC_CFG_OFF)
8025 			cq->poll_mode = LPFC_QUEUE_WORK;
8026 		else
8027 			cq->poll_mode = LPFC_IRQ_POLL;
8028 	}
8029 
8030 	if (!phba->nvmet_support)
8031 		schedule_delayed_work(&phba->idle_stat_delay_work,
8032 				      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
8033 }
8034 
8035 static void lpfc_sli4_dip(struct lpfc_hba *phba)
8036 {
8037 	uint32_t if_type;
8038 
8039 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
8040 	if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
8041 	    if_type == LPFC_SLI_INTF_IF_TYPE_6) {
8042 		struct lpfc_register reg_data;
8043 
8044 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
8045 			       &reg_data.word0))
8046 			return;
8047 
8048 		if (bf_get(lpfc_sliport_status_dip, &reg_data))
8049 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8050 					"2904 Firmware Dump Image Present"
8051 					" on Adapter");
8052 	}
8053 }
8054 
8055 /**
8056  * lpfc_rx_monitor_create_ring - Initialize ring buffer for rx_monitor
8057  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8058  * @entries: Number of rx_info_entry objects to allocate in ring
8059  *
8060  * Return:
8061  * 0 - Success
8062  * ENOMEM - Failure to kmalloc
8063  **/
8064 int lpfc_rx_monitor_create_ring(struct lpfc_rx_info_monitor *rx_monitor,
8065 				u32 entries)
8066 {
8067 	rx_monitor->ring = kmalloc_array(entries, sizeof(struct rx_info_entry),
8068 					 GFP_KERNEL);
8069 	if (!rx_monitor->ring)
8070 		return -ENOMEM;
8071 
8072 	rx_monitor->head_idx = 0;
8073 	rx_monitor->tail_idx = 0;
8074 	spin_lock_init(&rx_monitor->lock);
8075 	rx_monitor->entries = entries;
8076 
8077 	return 0;
8078 }
8079 
8080 /**
8081  * lpfc_rx_monitor_destroy_ring - Free ring buffer for rx_monitor
8082  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8083  **/
8084 void lpfc_rx_monitor_destroy_ring(struct lpfc_rx_info_monitor *rx_monitor)
8085 {
8086 	spin_lock(&rx_monitor->lock);
8087 	kfree(rx_monitor->ring);
8088 	rx_monitor->ring = NULL;
8089 	rx_monitor->entries = 0;
8090 	rx_monitor->head_idx = 0;
8091 	rx_monitor->tail_idx = 0;
8092 	spin_unlock(&rx_monitor->lock);
8093 }
8094 
8095 /**
8096  * lpfc_rx_monitor_record - Insert an entry into rx_monitor's ring
8097  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8098  * @entry: Pointer to rx_info_entry
8099  *
8100  * Used to insert an rx_info_entry into rx_monitor's ring.  Note that this is a
8101  * deep copy of rx_info_entry not a shallow copy of the rx_info_entry ptr.
8102  *
8103  * This is called from lpfc_cmf_timer, which is in timer/softirq context.
8104  *
8105  * In cases of old data overflow, we do a best effort of FIFO order.
8106  **/
8107 void lpfc_rx_monitor_record(struct lpfc_rx_info_monitor *rx_monitor,
8108 			    struct rx_info_entry *entry)
8109 {
8110 	struct rx_info_entry *ring = rx_monitor->ring;
8111 	u32 *head_idx = &rx_monitor->head_idx;
8112 	u32 *tail_idx = &rx_monitor->tail_idx;
8113 	spinlock_t *ring_lock = &rx_monitor->lock;
8114 	u32 ring_size = rx_monitor->entries;
8115 
8116 	spin_lock(ring_lock);
8117 	memcpy(&ring[*tail_idx], entry, sizeof(*entry));
8118 	*tail_idx = (*tail_idx + 1) % ring_size;
8119 
8120 	/* Best effort of FIFO saved data */
8121 	if (*tail_idx == *head_idx)
8122 		*head_idx = (*head_idx + 1) % ring_size;
8123 
8124 	spin_unlock(ring_lock);
8125 }
8126 
8127 /**
8128  * lpfc_rx_monitor_report - Read out rx_monitor's ring
8129  * @phba: Pointer to lpfc_hba object
8130  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8131  * @buf: Pointer to char buffer that will contain rx monitor info data
8132  * @buf_len: Length buf including null char
8133  * @max_read_entries: Maximum number of entries to read out of ring
8134  *
8135  * Used to dump/read what's in rx_monitor's ring buffer.
8136  *
8137  * If buf is NULL || buf_len == 0, then it is implied that we want to log the
8138  * information to kmsg instead of filling out buf.
8139  *
8140  * Return:
8141  * Number of entries read out of the ring
8142  **/
8143 u32 lpfc_rx_monitor_report(struct lpfc_hba *phba,
8144 			   struct lpfc_rx_info_monitor *rx_monitor, char *buf,
8145 			   u32 buf_len, u32 max_read_entries)
8146 {
8147 	struct rx_info_entry *ring = rx_monitor->ring;
8148 	struct rx_info_entry *entry;
8149 	u32 *head_idx = &rx_monitor->head_idx;
8150 	u32 *tail_idx = &rx_monitor->tail_idx;
8151 	spinlock_t *ring_lock = &rx_monitor->lock;
8152 	u32 ring_size = rx_monitor->entries;
8153 	u32 cnt = 0;
8154 	char tmp[DBG_LOG_STR_SZ] = {0};
8155 	bool log_to_kmsg = (!buf || !buf_len) ? true : false;
8156 
8157 	if (!log_to_kmsg) {
8158 		/* clear the buffer to be sure */
8159 		memset(buf, 0, buf_len);
8160 
8161 		scnprintf(buf, buf_len, "\t%-16s%-16s%-16s%-16s%-8s%-8s%-8s"
8162 					"%-8s%-8s%-8s%-16s\n",
8163 					"MaxBPI", "Tot_Data_CMF",
8164 					"Tot_Data_Cmd", "Tot_Data_Cmpl",
8165 					"Lat(us)", "Avg_IO", "Max_IO", "Bsy",
8166 					"IO_cnt", "Info", "BWutil(ms)");
8167 	}
8168 
8169 	/* Needs to be _irq because record is called from timer interrupt
8170 	 * context
8171 	 */
8172 	spin_lock_irq(ring_lock);
8173 	while (*head_idx != *tail_idx) {
8174 		entry = &ring[*head_idx];
8175 
8176 		/* Read out this entry's data. */
8177 		if (!log_to_kmsg) {
8178 			/* If !log_to_kmsg, then store to buf. */
8179 			scnprintf(tmp, sizeof(tmp),
8180 				  "%03d:\t%-16llu%-16llu%-16llu%-16llu%-8llu"
8181 				  "%-8llu%-8llu%-8u%-8u%-8u%u(%u)\n",
8182 				  *head_idx, entry->max_bytes_per_interval,
8183 				  entry->cmf_bytes, entry->total_bytes,
8184 				  entry->rcv_bytes, entry->avg_io_latency,
8185 				  entry->avg_io_size, entry->max_read_cnt,
8186 				  entry->cmf_busy, entry->io_cnt,
8187 				  entry->cmf_info, entry->timer_utilization,
8188 				  entry->timer_interval);
8189 
8190 			/* Check for buffer overflow */
8191 			if ((strlen(buf) + strlen(tmp)) >= buf_len)
8192 				break;
8193 
8194 			/* Append entry's data to buffer */
8195 			strlcat(buf, tmp, buf_len);
8196 		} else {
8197 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
8198 					"4410 %02u: MBPI %llu Xmit %llu "
8199 					"Cmpl %llu Lat %llu ASz %llu Info %02u "
8200 					"BWUtil %u Int %u slot %u\n",
8201 					cnt, entry->max_bytes_per_interval,
8202 					entry->total_bytes, entry->rcv_bytes,
8203 					entry->avg_io_latency,
8204 					entry->avg_io_size, entry->cmf_info,
8205 					entry->timer_utilization,
8206 					entry->timer_interval, *head_idx);
8207 		}
8208 
8209 		*head_idx = (*head_idx + 1) % ring_size;
8210 
8211 		/* Don't feed more than max_read_entries */
8212 		cnt++;
8213 		if (cnt >= max_read_entries)
8214 			break;
8215 	}
8216 	spin_unlock_irq(ring_lock);
8217 
8218 	return cnt;
8219 }
8220 
8221 /**
8222  * lpfc_cmf_setup - Initialize idle_stat tracking
8223  * @phba: Pointer to HBA context object.
8224  *
8225  * This is called from HBA setup during driver load or when the HBA
8226  * comes online. this does all the initialization to support CMF and MI.
8227  **/
8228 static int
8229 lpfc_cmf_setup(struct lpfc_hba *phba)
8230 {
8231 	LPFC_MBOXQ_t *mboxq;
8232 	struct lpfc_dmabuf *mp;
8233 	struct lpfc_pc_sli4_params *sli4_params;
8234 	int rc, cmf, mi_ver;
8235 
8236 	rc = lpfc_sli4_refresh_params(phba);
8237 	if (unlikely(rc))
8238 		return rc;
8239 
8240 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8241 	if (!mboxq)
8242 		return -ENOMEM;
8243 
8244 	sli4_params = &phba->sli4_hba.pc_sli4_params;
8245 
8246 	/* Always try to enable MI feature if we can */
8247 	if (sli4_params->mi_ver) {
8248 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_MI);
8249 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8250 		mi_ver = bf_get(lpfc_mbx_set_feature_mi,
8251 				 &mboxq->u.mqe.un.set_feature);
8252 
8253 		if (rc == MBX_SUCCESS) {
8254 			if (mi_ver) {
8255 				lpfc_printf_log(phba,
8256 						KERN_WARNING, LOG_CGN_MGMT,
8257 						"6215 MI is enabled\n");
8258 				sli4_params->mi_ver = mi_ver;
8259 			} else {
8260 				lpfc_printf_log(phba,
8261 						KERN_WARNING, LOG_CGN_MGMT,
8262 						"6338 MI is disabled\n");
8263 				sli4_params->mi_ver = 0;
8264 			}
8265 		} else {
8266 			/* mi_ver is already set from GET_SLI4_PARAMETERS */
8267 			lpfc_printf_log(phba, KERN_INFO,
8268 					LOG_CGN_MGMT | LOG_INIT,
8269 					"6245 Enable MI Mailbox x%x (x%x/x%x) "
8270 					"failed, rc:x%x mi:x%x\n",
8271 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8272 					lpfc_sli_config_mbox_subsys_get
8273 						(phba, mboxq),
8274 					lpfc_sli_config_mbox_opcode_get
8275 						(phba, mboxq),
8276 					rc, sli4_params->mi_ver);
8277 		}
8278 	} else {
8279 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8280 				"6217 MI is disabled\n");
8281 	}
8282 
8283 	/* Ensure FDMI is enabled for MI if enable_mi is set */
8284 	if (sli4_params->mi_ver)
8285 		phba->cfg_fdmi_on = LPFC_FDMI_SUPPORT;
8286 
8287 	/* Always try to enable CMF feature if we can */
8288 	if (sli4_params->cmf) {
8289 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_CMF);
8290 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8291 		cmf = bf_get(lpfc_mbx_set_feature_cmf,
8292 			     &mboxq->u.mqe.un.set_feature);
8293 		if (rc == MBX_SUCCESS && cmf) {
8294 			lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8295 					"6218 CMF is enabled: mode %d\n",
8296 					phba->cmf_active_mode);
8297 		} else {
8298 			lpfc_printf_log(phba, KERN_WARNING,
8299 					LOG_CGN_MGMT | LOG_INIT,
8300 					"6219 Enable CMF Mailbox x%x (x%x/x%x) "
8301 					"failed, rc:x%x dd:x%x\n",
8302 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8303 					lpfc_sli_config_mbox_subsys_get
8304 						(phba, mboxq),
8305 					lpfc_sli_config_mbox_opcode_get
8306 						(phba, mboxq),
8307 					rc, cmf);
8308 			sli4_params->cmf = 0;
8309 			phba->cmf_active_mode = LPFC_CFG_OFF;
8310 			goto no_cmf;
8311 		}
8312 
8313 		/* Allocate Congestion Information Buffer */
8314 		if (!phba->cgn_i) {
8315 			mp = kmalloc(sizeof(*mp), GFP_KERNEL);
8316 			if (mp)
8317 				mp->virt = dma_alloc_coherent
8318 						(&phba->pcidev->dev,
8319 						sizeof(struct lpfc_cgn_info),
8320 						&mp->phys, GFP_KERNEL);
8321 			if (!mp || !mp->virt) {
8322 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8323 						"2640 Failed to alloc memory "
8324 						"for Congestion Info\n");
8325 				kfree(mp);
8326 				sli4_params->cmf = 0;
8327 				phba->cmf_active_mode = LPFC_CFG_OFF;
8328 				goto no_cmf;
8329 			}
8330 			phba->cgn_i = mp;
8331 
8332 			/* initialize congestion buffer info */
8333 			lpfc_init_congestion_buf(phba);
8334 			lpfc_init_congestion_stat(phba);
8335 
8336 			/* Zero out Congestion Signal counters */
8337 			atomic64_set(&phba->cgn_acqe_stat.alarm, 0);
8338 			atomic64_set(&phba->cgn_acqe_stat.warn, 0);
8339 		}
8340 
8341 		rc = lpfc_sli4_cgn_params_read(phba);
8342 		if (rc < 0) {
8343 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8344 					"6242 Error reading Cgn Params (%d)\n",
8345 					rc);
8346 			/* Ensure CGN Mode is off */
8347 			sli4_params->cmf = 0;
8348 		} else if (!rc) {
8349 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8350 					"6243 CGN Event empty object.\n");
8351 			/* Ensure CGN Mode is off */
8352 			sli4_params->cmf = 0;
8353 		}
8354 	} else {
8355 no_cmf:
8356 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8357 				"6220 CMF is disabled\n");
8358 	}
8359 
8360 	/* Only register congestion buffer with firmware if BOTH
8361 	 * CMF and E2E are enabled.
8362 	 */
8363 	if (sli4_params->cmf && sli4_params->mi_ver) {
8364 		rc = lpfc_reg_congestion_buf(phba);
8365 		if (rc) {
8366 			dma_free_coherent(&phba->pcidev->dev,
8367 					  sizeof(struct lpfc_cgn_info),
8368 					  phba->cgn_i->virt, phba->cgn_i->phys);
8369 			kfree(phba->cgn_i);
8370 			phba->cgn_i = NULL;
8371 			/* Ensure CGN Mode is off */
8372 			phba->cmf_active_mode = LPFC_CFG_OFF;
8373 			sli4_params->cmf = 0;
8374 			return 0;
8375 		}
8376 	}
8377 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8378 			"6470 Setup MI version %d CMF %d mode %d\n",
8379 			sli4_params->mi_ver, sli4_params->cmf,
8380 			phba->cmf_active_mode);
8381 
8382 	mempool_free(mboxq, phba->mbox_mem_pool);
8383 
8384 	/* Initialize atomic counters */
8385 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
8386 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
8387 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
8388 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
8389 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
8390 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
8391 	atomic64_set(&phba->cgn_latency_evt, 0);
8392 
8393 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
8394 
8395 	/* Allocate RX Monitor Buffer */
8396 	if (!phba->rx_monitor) {
8397 		phba->rx_monitor = kzalloc(sizeof(*phba->rx_monitor),
8398 					   GFP_KERNEL);
8399 
8400 		if (!phba->rx_monitor) {
8401 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8402 					"2644 Failed to alloc memory "
8403 					"for RX Monitor Buffer\n");
8404 			return -ENOMEM;
8405 		}
8406 
8407 		/* Instruct the rx_monitor object to instantiate its ring */
8408 		if (lpfc_rx_monitor_create_ring(phba->rx_monitor,
8409 						LPFC_MAX_RXMONITOR_ENTRY)) {
8410 			kfree(phba->rx_monitor);
8411 			phba->rx_monitor = NULL;
8412 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8413 					"2645 Failed to alloc memory "
8414 					"for RX Monitor's Ring\n");
8415 			return -ENOMEM;
8416 		}
8417 	}
8418 
8419 	return 0;
8420 }
8421 
8422 static int
8423 lpfc_set_host_tm(struct lpfc_hba *phba)
8424 {
8425 	LPFC_MBOXQ_t *mboxq;
8426 	uint32_t len, rc;
8427 	struct timespec64 cur_time;
8428 	struct tm broken;
8429 	uint32_t month, day, year;
8430 	uint32_t hour, minute, second;
8431 	struct lpfc_mbx_set_host_date_time *tm;
8432 
8433 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8434 	if (!mboxq)
8435 		return -ENOMEM;
8436 
8437 	len = sizeof(struct lpfc_mbx_set_host_data) -
8438 		sizeof(struct lpfc_sli4_cfg_mhdr);
8439 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
8440 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
8441 			 LPFC_SLI4_MBX_EMBED);
8442 
8443 	mboxq->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_DATE_TIME;
8444 	mboxq->u.mqe.un.set_host_data.param_len =
8445 			sizeof(struct lpfc_mbx_set_host_date_time);
8446 	tm = &mboxq->u.mqe.un.set_host_data.un.tm;
8447 	ktime_get_real_ts64(&cur_time);
8448 	time64_to_tm(cur_time.tv_sec, 0, &broken);
8449 	month = broken.tm_mon + 1;
8450 	day = broken.tm_mday;
8451 	year = broken.tm_year - 100;
8452 	hour = broken.tm_hour;
8453 	minute = broken.tm_min;
8454 	second = broken.tm_sec;
8455 	bf_set(lpfc_mbx_set_host_month, tm, month);
8456 	bf_set(lpfc_mbx_set_host_day, tm, day);
8457 	bf_set(lpfc_mbx_set_host_year, tm, year);
8458 	bf_set(lpfc_mbx_set_host_hour, tm, hour);
8459 	bf_set(lpfc_mbx_set_host_min, tm, minute);
8460 	bf_set(lpfc_mbx_set_host_sec, tm, second);
8461 
8462 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8463 	mempool_free(mboxq, phba->mbox_mem_pool);
8464 	return rc;
8465 }
8466 
8467 /**
8468  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
8469  * @phba: Pointer to HBA context object.
8470  *
8471  * This function is the main SLI4 device initialization PCI function. This
8472  * function is called by the HBA initialization code, HBA reset code and
8473  * HBA error attention handler code. Caller is not required to hold any
8474  * locks.
8475  **/
8476 int
8477 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
8478 {
8479 	int rc, i, cnt, len, dd;
8480 	LPFC_MBOXQ_t *mboxq;
8481 	struct lpfc_mqe *mqe;
8482 	uint8_t *vpd;
8483 	uint32_t vpd_size;
8484 	uint32_t ftr_rsp = 0;
8485 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
8486 	struct lpfc_vport *vport = phba->pport;
8487 	struct lpfc_dmabuf *mp;
8488 	struct lpfc_rqb *rqbp;
8489 	u32 flg;
8490 
8491 	/* Perform a PCI function reset to start from clean */
8492 	rc = lpfc_pci_function_reset(phba);
8493 	if (unlikely(rc))
8494 		return -ENODEV;
8495 
8496 	/* Check the HBA Host Status Register for readyness */
8497 	rc = lpfc_sli4_post_status_check(phba);
8498 	if (unlikely(rc))
8499 		return -ENODEV;
8500 	else {
8501 		spin_lock_irq(&phba->hbalock);
8502 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
8503 		flg = phba->sli.sli_flag;
8504 		spin_unlock_irq(&phba->hbalock);
8505 		/* Allow a little time after setting SLI_ACTIVE for any polled
8506 		 * MBX commands to complete via BSG.
8507 		 */
8508 		for (i = 0; i < 50 && (flg & LPFC_SLI_MBOX_ACTIVE); i++) {
8509 			msleep(20);
8510 			spin_lock_irq(&phba->hbalock);
8511 			flg = phba->sli.sli_flag;
8512 			spin_unlock_irq(&phba->hbalock);
8513 		}
8514 	}
8515 
8516 	lpfc_sli4_dip(phba);
8517 
8518 	/*
8519 	 * Allocate a single mailbox container for initializing the
8520 	 * port.
8521 	 */
8522 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8523 	if (!mboxq)
8524 		return -ENOMEM;
8525 
8526 	/* Issue READ_REV to collect vpd and FW information. */
8527 	vpd_size = SLI4_PAGE_SIZE;
8528 	vpd = kzalloc(vpd_size, GFP_KERNEL);
8529 	if (!vpd) {
8530 		rc = -ENOMEM;
8531 		goto out_free_mbox;
8532 	}
8533 
8534 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
8535 	if (unlikely(rc)) {
8536 		kfree(vpd);
8537 		goto out_free_mbox;
8538 	}
8539 
8540 	mqe = &mboxq->u.mqe;
8541 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
8542 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
8543 		phba->hba_flag |= HBA_FCOE_MODE;
8544 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
8545 	} else {
8546 		phba->hba_flag &= ~HBA_FCOE_MODE;
8547 	}
8548 
8549 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
8550 		LPFC_DCBX_CEE_MODE)
8551 		phba->hba_flag |= HBA_FIP_SUPPORT;
8552 	else
8553 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
8554 
8555 	phba->hba_flag &= ~HBA_IOQ_FLUSH;
8556 
8557 	if (phba->sli_rev != LPFC_SLI_REV4) {
8558 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8559 			"0376 READ_REV Error. SLI Level %d "
8560 			"FCoE enabled %d\n",
8561 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
8562 		rc = -EIO;
8563 		kfree(vpd);
8564 		goto out_free_mbox;
8565 	}
8566 
8567 	rc = lpfc_set_host_tm(phba);
8568 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
8569 			"6468 Set host date / time: Status x%x:\n", rc);
8570 
8571 	/*
8572 	 * Continue initialization with default values even if driver failed
8573 	 * to read FCoE param config regions, only read parameters if the
8574 	 * board is FCoE
8575 	 */
8576 	if (phba->hba_flag & HBA_FCOE_MODE &&
8577 	    lpfc_sli4_read_fcoe_params(phba))
8578 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
8579 			"2570 Failed to read FCoE parameters\n");
8580 
8581 	/*
8582 	 * Retrieve sli4 device physical port name, failure of doing it
8583 	 * is considered as non-fatal.
8584 	 */
8585 	rc = lpfc_sli4_retrieve_pport_name(phba);
8586 	if (!rc)
8587 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8588 				"3080 Successful retrieving SLI4 device "
8589 				"physical port name: %s.\n", phba->Port);
8590 
8591 	rc = lpfc_sli4_get_ctl_attr(phba);
8592 	if (!rc)
8593 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8594 				"8351 Successful retrieving SLI4 device "
8595 				"CTL ATTR\n");
8596 
8597 	/*
8598 	 * Evaluate the read rev and vpd data. Populate the driver
8599 	 * state with the results. If this routine fails, the failure
8600 	 * is not fatal as the driver will use generic values.
8601 	 */
8602 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
8603 	if (unlikely(!rc)) {
8604 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8605 				"0377 Error %d parsing vpd. "
8606 				"Using defaults.\n", rc);
8607 		rc = 0;
8608 	}
8609 	kfree(vpd);
8610 
8611 	/* Save information as VPD data */
8612 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
8613 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
8614 
8615 	/*
8616 	 * This is because first G7 ASIC doesn't support the standard
8617 	 * 0x5a NVME cmd descriptor type/subtype
8618 	 */
8619 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8620 			LPFC_SLI_INTF_IF_TYPE_6) &&
8621 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
8622 	    (phba->vpd.rev.smRev == 0) &&
8623 	    (phba->cfg_nvme_embed_cmd == 1))
8624 		phba->cfg_nvme_embed_cmd = 0;
8625 
8626 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
8627 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
8628 					 &mqe->un.read_rev);
8629 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
8630 				       &mqe->un.read_rev);
8631 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
8632 					    &mqe->un.read_rev);
8633 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
8634 					   &mqe->un.read_rev);
8635 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
8636 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
8637 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
8638 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
8639 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
8640 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
8641 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8642 			"(%d):0380 READ_REV Status x%x "
8643 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
8644 			mboxq->vport ? mboxq->vport->vpi : 0,
8645 			bf_get(lpfc_mqe_status, mqe),
8646 			phba->vpd.rev.opFwName,
8647 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
8648 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
8649 
8650 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8651 	    LPFC_SLI_INTF_IF_TYPE_0) {
8652 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
8653 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8654 		if (rc == MBX_SUCCESS) {
8655 			phba->hba_flag |= HBA_RECOVERABLE_UE;
8656 			/* Set 1Sec interval to detect UE */
8657 			phba->eratt_poll_interval = 1;
8658 			phba->sli4_hba.ue_to_sr = bf_get(
8659 					lpfc_mbx_set_feature_UESR,
8660 					&mboxq->u.mqe.un.set_feature);
8661 			phba->sli4_hba.ue_to_rp = bf_get(
8662 					lpfc_mbx_set_feature_UERP,
8663 					&mboxq->u.mqe.un.set_feature);
8664 		}
8665 	}
8666 
8667 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
8668 		/* Enable MDS Diagnostics only if the SLI Port supports it */
8669 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
8670 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8671 		if (rc != MBX_SUCCESS)
8672 			phba->mds_diags_support = 0;
8673 	}
8674 
8675 	/*
8676 	 * Discover the port's supported feature set and match it against the
8677 	 * hosts requests.
8678 	 */
8679 	lpfc_request_features(phba, mboxq);
8680 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8681 	if (unlikely(rc)) {
8682 		rc = -EIO;
8683 		goto out_free_mbox;
8684 	}
8685 
8686 	/* Disable VMID if app header is not supported */
8687 	if (phba->cfg_vmid_app_header && !(bf_get(lpfc_mbx_rq_ftr_rsp_ashdr,
8688 						  &mqe->un.req_ftrs))) {
8689 		bf_set(lpfc_ftr_ashdr, &phba->sli4_hba.sli4_flags, 0);
8690 		phba->cfg_vmid_app_header = 0;
8691 		lpfc_printf_log(phba, KERN_DEBUG, LOG_SLI,
8692 				"1242 vmid feature not supported\n");
8693 	}
8694 
8695 	/*
8696 	 * The port must support FCP initiator mode as this is the
8697 	 * only mode running in the host.
8698 	 */
8699 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
8700 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8701 				"0378 No support for fcpi mode.\n");
8702 		ftr_rsp++;
8703 	}
8704 
8705 	/* Performance Hints are ONLY for FCoE */
8706 	if (phba->hba_flag & HBA_FCOE_MODE) {
8707 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
8708 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
8709 		else
8710 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
8711 	}
8712 
8713 	/*
8714 	 * If the port cannot support the host's requested features
8715 	 * then turn off the global config parameters to disable the
8716 	 * feature in the driver.  This is not a fatal error.
8717 	 */
8718 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8719 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
8720 			phba->cfg_enable_bg = 0;
8721 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
8722 			ftr_rsp++;
8723 		}
8724 	}
8725 
8726 	if (phba->max_vpi && phba->cfg_enable_npiv &&
8727 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8728 		ftr_rsp++;
8729 
8730 	if (ftr_rsp) {
8731 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8732 				"0379 Feature Mismatch Data: x%08x %08x "
8733 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
8734 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
8735 				phba->cfg_enable_npiv, phba->max_vpi);
8736 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
8737 			phba->cfg_enable_bg = 0;
8738 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8739 			phba->cfg_enable_npiv = 0;
8740 	}
8741 
8742 	/* These SLI3 features are assumed in SLI4 */
8743 	spin_lock_irq(&phba->hbalock);
8744 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
8745 	spin_unlock_irq(&phba->hbalock);
8746 
8747 	/* Always try to enable dual dump feature if we can */
8748 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
8749 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8750 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
8751 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
8752 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8753 				"6448 Dual Dump is enabled\n");
8754 	else
8755 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
8756 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
8757 				"rc:x%x dd:x%x\n",
8758 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8759 				lpfc_sli_config_mbox_subsys_get(
8760 					phba, mboxq),
8761 				lpfc_sli_config_mbox_opcode_get(
8762 					phba, mboxq),
8763 				rc, dd);
8764 	/*
8765 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
8766 	 * calls depends on these resources to complete port setup.
8767 	 */
8768 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
8769 	if (rc) {
8770 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8771 				"2920 Failed to alloc Resource IDs "
8772 				"rc = x%x\n", rc);
8773 		goto out_free_mbox;
8774 	}
8775 
8776 	lpfc_set_host_data(phba, mboxq);
8777 
8778 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8779 	if (rc) {
8780 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8781 				"2134 Failed to set host os driver version %x",
8782 				rc);
8783 	}
8784 
8785 	/* Read the port's service parameters. */
8786 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
8787 	if (rc) {
8788 		phba->link_state = LPFC_HBA_ERROR;
8789 		rc = -ENOMEM;
8790 		goto out_free_mbox;
8791 	}
8792 
8793 	mboxq->vport = vport;
8794 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8795 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
8796 	if (rc == MBX_SUCCESS) {
8797 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
8798 		rc = 0;
8799 	}
8800 
8801 	/*
8802 	 * This memory was allocated by the lpfc_read_sparam routine but is
8803 	 * no longer needed.  It is released and ctx_buf NULLed to prevent
8804 	 * unintended pointer access as the mbox is reused.
8805 	 */
8806 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
8807 	kfree(mp);
8808 	mboxq->ctx_buf = NULL;
8809 	if (unlikely(rc)) {
8810 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8811 				"0382 READ_SPARAM command failed "
8812 				"status %d, mbxStatus x%x\n",
8813 				rc, bf_get(lpfc_mqe_status, mqe));
8814 		phba->link_state = LPFC_HBA_ERROR;
8815 		rc = -EIO;
8816 		goto out_free_mbox;
8817 	}
8818 
8819 	lpfc_update_vport_wwn(vport);
8820 
8821 	/* Update the fc_host data structures with new wwn. */
8822 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
8823 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
8824 
8825 	/* Create all the SLI4 queues */
8826 	rc = lpfc_sli4_queue_create(phba);
8827 	if (rc) {
8828 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8829 				"3089 Failed to allocate queues\n");
8830 		rc = -ENODEV;
8831 		goto out_free_mbox;
8832 	}
8833 	/* Set up all the queues to the device */
8834 	rc = lpfc_sli4_queue_setup(phba);
8835 	if (unlikely(rc)) {
8836 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8837 				"0381 Error %d during queue setup.\n ", rc);
8838 		goto out_stop_timers;
8839 	}
8840 	/* Initialize the driver internal SLI layer lists. */
8841 	lpfc_sli4_setup(phba);
8842 	lpfc_sli4_queue_init(phba);
8843 
8844 	/* update host els xri-sgl sizes and mappings */
8845 	rc = lpfc_sli4_els_sgl_update(phba);
8846 	if (unlikely(rc)) {
8847 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8848 				"1400 Failed to update xri-sgl size and "
8849 				"mapping: %d\n", rc);
8850 		goto out_destroy_queue;
8851 	}
8852 
8853 	/* register the els sgl pool to the port */
8854 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
8855 				       phba->sli4_hba.els_xri_cnt);
8856 	if (unlikely(rc < 0)) {
8857 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8858 				"0582 Error %d during els sgl post "
8859 				"operation\n", rc);
8860 		rc = -ENODEV;
8861 		goto out_destroy_queue;
8862 	}
8863 	phba->sli4_hba.els_xri_cnt = rc;
8864 
8865 	if (phba->nvmet_support) {
8866 		/* update host nvmet xri-sgl sizes and mappings */
8867 		rc = lpfc_sli4_nvmet_sgl_update(phba);
8868 		if (unlikely(rc)) {
8869 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8870 					"6308 Failed to update nvmet-sgl size "
8871 					"and mapping: %d\n", rc);
8872 			goto out_destroy_queue;
8873 		}
8874 
8875 		/* register the nvmet sgl pool to the port */
8876 		rc = lpfc_sli4_repost_sgl_list(
8877 			phba,
8878 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
8879 			phba->sli4_hba.nvmet_xri_cnt);
8880 		if (unlikely(rc < 0)) {
8881 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8882 					"3117 Error %d during nvmet "
8883 					"sgl post\n", rc);
8884 			rc = -ENODEV;
8885 			goto out_destroy_queue;
8886 		}
8887 		phba->sli4_hba.nvmet_xri_cnt = rc;
8888 
8889 		/* We allocate an iocbq for every receive context SGL.
8890 		 * The additional allocation is for abort and ls handling.
8891 		 */
8892 		cnt = phba->sli4_hba.nvmet_xri_cnt +
8893 			phba->sli4_hba.max_cfg_param.max_xri;
8894 	} else {
8895 		/* update host common xri-sgl sizes and mappings */
8896 		rc = lpfc_sli4_io_sgl_update(phba);
8897 		if (unlikely(rc)) {
8898 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8899 					"6082 Failed to update nvme-sgl size "
8900 					"and mapping: %d\n", rc);
8901 			goto out_destroy_queue;
8902 		}
8903 
8904 		/* register the allocated common sgl pool to the port */
8905 		rc = lpfc_sli4_repost_io_sgl_list(phba);
8906 		if (unlikely(rc)) {
8907 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8908 					"6116 Error %d during nvme sgl post "
8909 					"operation\n", rc);
8910 			/* Some NVME buffers were moved to abort nvme list */
8911 			/* A pci function reset will repost them */
8912 			rc = -ENODEV;
8913 			goto out_destroy_queue;
8914 		}
8915 		/* Each lpfc_io_buf job structure has an iocbq element.
8916 		 * This cnt provides for abort, els, ct and ls requests.
8917 		 */
8918 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
8919 	}
8920 
8921 	if (!phba->sli.iocbq_lookup) {
8922 		/* Initialize and populate the iocb list per host */
8923 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8924 				"2821 initialize iocb list with %d entries\n",
8925 				cnt);
8926 		rc = lpfc_init_iocb_list(phba, cnt);
8927 		if (rc) {
8928 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8929 					"1413 Failed to init iocb list.\n");
8930 			goto out_destroy_queue;
8931 		}
8932 	}
8933 
8934 	if (phba->nvmet_support)
8935 		lpfc_nvmet_create_targetport(phba);
8936 
8937 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
8938 		/* Post initial buffers to all RQs created */
8939 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
8940 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
8941 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
8942 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
8943 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
8944 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
8945 			rqbp->buffer_count = 0;
8946 
8947 			lpfc_post_rq_buffer(
8948 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
8949 				phba->sli4_hba.nvmet_mrq_data[i],
8950 				phba->cfg_nvmet_mrq_post, i);
8951 		}
8952 	}
8953 
8954 	/* Post the rpi header region to the device. */
8955 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
8956 	if (unlikely(rc)) {
8957 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8958 				"0393 Error %d during rpi post operation\n",
8959 				rc);
8960 		rc = -ENODEV;
8961 		goto out_free_iocblist;
8962 	}
8963 	lpfc_sli4_node_prep(phba);
8964 
8965 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
8966 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
8967 			/*
8968 			 * The FC Port needs to register FCFI (index 0)
8969 			 */
8970 			lpfc_reg_fcfi(phba, mboxq);
8971 			mboxq->vport = phba->pport;
8972 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8973 			if (rc != MBX_SUCCESS)
8974 				goto out_unset_queue;
8975 			rc = 0;
8976 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
8977 						&mboxq->u.mqe.un.reg_fcfi);
8978 		} else {
8979 			/* We are a NVME Target mode with MRQ > 1 */
8980 
8981 			/* First register the FCFI */
8982 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
8983 			mboxq->vport = phba->pport;
8984 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8985 			if (rc != MBX_SUCCESS)
8986 				goto out_unset_queue;
8987 			rc = 0;
8988 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
8989 						&mboxq->u.mqe.un.reg_fcfi_mrq);
8990 
8991 			/* Next register the MRQs */
8992 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
8993 			mboxq->vport = phba->pport;
8994 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8995 			if (rc != MBX_SUCCESS)
8996 				goto out_unset_queue;
8997 			rc = 0;
8998 		}
8999 		/* Check if the port is configured to be disabled */
9000 		lpfc_sli_read_link_ste(phba);
9001 	}
9002 
9003 	/* Don't post more new bufs if repost already recovered
9004 	 * the nvme sgls.
9005 	 */
9006 	if (phba->nvmet_support == 0) {
9007 		if (phba->sli4_hba.io_xri_cnt == 0) {
9008 			len = lpfc_new_io_buf(
9009 					      phba, phba->sli4_hba.io_xri_max);
9010 			if (len == 0) {
9011 				rc = -ENOMEM;
9012 				goto out_unset_queue;
9013 			}
9014 
9015 			if (phba->cfg_xri_rebalancing)
9016 				lpfc_create_multixri_pools(phba);
9017 		}
9018 	} else {
9019 		phba->cfg_xri_rebalancing = 0;
9020 	}
9021 
9022 	/* Allow asynchronous mailbox command to go through */
9023 	spin_lock_irq(&phba->hbalock);
9024 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9025 	spin_unlock_irq(&phba->hbalock);
9026 
9027 	/* Post receive buffers to the device */
9028 	lpfc_sli4_rb_setup(phba);
9029 
9030 	/* Reset HBA FCF states after HBA reset */
9031 	phba->fcf.fcf_flag = 0;
9032 	phba->fcf.current_rec.flag = 0;
9033 
9034 	/* Start the ELS watchdog timer */
9035 	mod_timer(&vport->els_tmofunc,
9036 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
9037 
9038 	/* Start heart beat timer */
9039 	mod_timer(&phba->hb_tmofunc,
9040 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
9041 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
9042 	phba->last_completion_time = jiffies;
9043 
9044 	/* start eq_delay heartbeat */
9045 	if (phba->cfg_auto_imax)
9046 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
9047 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
9048 
9049 	/* start per phba idle_stat_delay heartbeat */
9050 	lpfc_init_idle_stat_hb(phba);
9051 
9052 	/* Start error attention (ERATT) polling timer */
9053 	mod_timer(&phba->eratt_poll,
9054 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
9055 
9056 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
9057 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
9058 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
9059 		if (!rc) {
9060 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9061 					"2829 This device supports "
9062 					"Advanced Error Reporting (AER)\n");
9063 			spin_lock_irq(&phba->hbalock);
9064 			phba->hba_flag |= HBA_AER_ENABLED;
9065 			spin_unlock_irq(&phba->hbalock);
9066 		} else {
9067 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9068 					"2830 This device does not support "
9069 					"Advanced Error Reporting (AER)\n");
9070 			phba->cfg_aer_support = 0;
9071 		}
9072 		rc = 0;
9073 	}
9074 
9075 	/*
9076 	 * The port is ready, set the host's link state to LINK_DOWN
9077 	 * in preparation for link interrupts.
9078 	 */
9079 	spin_lock_irq(&phba->hbalock);
9080 	phba->link_state = LPFC_LINK_DOWN;
9081 
9082 	/* Check if physical ports are trunked */
9083 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
9084 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
9085 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
9086 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
9087 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
9088 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
9089 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
9090 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
9091 	spin_unlock_irq(&phba->hbalock);
9092 
9093 	/* Arm the CQs and then EQs on device */
9094 	lpfc_sli4_arm_cqeq_intr(phba);
9095 
9096 	/* Indicate device interrupt mode */
9097 	phba->sli4_hba.intr_enable = 1;
9098 
9099 	/* Setup CMF after HBA is initialized */
9100 	lpfc_cmf_setup(phba);
9101 
9102 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
9103 	    (phba->hba_flag & LINK_DISABLED)) {
9104 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9105 				"3103 Adapter Link is disabled.\n");
9106 		lpfc_down_link(phba, mboxq);
9107 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9108 		if (rc != MBX_SUCCESS) {
9109 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9110 					"3104 Adapter failed to issue "
9111 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
9112 			goto out_io_buff_free;
9113 		}
9114 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
9115 		/* don't perform init_link on SLI4 FC port loopback test */
9116 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
9117 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
9118 			if (rc)
9119 				goto out_io_buff_free;
9120 		}
9121 	}
9122 	mempool_free(mboxq, phba->mbox_mem_pool);
9123 
9124 	/* Enable RAS FW log support */
9125 	lpfc_sli4_ras_setup(phba);
9126 
9127 	phba->hba_flag |= HBA_SETUP;
9128 	return rc;
9129 
9130 out_io_buff_free:
9131 	/* Free allocated IO Buffers */
9132 	lpfc_io_free(phba);
9133 out_unset_queue:
9134 	/* Unset all the queues set up in this routine when error out */
9135 	lpfc_sli4_queue_unset(phba);
9136 out_free_iocblist:
9137 	lpfc_free_iocb_list(phba);
9138 out_destroy_queue:
9139 	lpfc_sli4_queue_destroy(phba);
9140 out_stop_timers:
9141 	lpfc_stop_hba_timers(phba);
9142 out_free_mbox:
9143 	mempool_free(mboxq, phba->mbox_mem_pool);
9144 	return rc;
9145 }
9146 
9147 /**
9148  * lpfc_mbox_timeout - Timeout call back function for mbox timer
9149  * @t: Context to fetch pointer to hba structure from.
9150  *
9151  * This is the callback function for mailbox timer. The mailbox
9152  * timer is armed when a new mailbox command is issued and the timer
9153  * is deleted when the mailbox complete. The function is called by
9154  * the kernel timer code when a mailbox does not complete within
9155  * expected time. This function wakes up the worker thread to
9156  * process the mailbox timeout and returns. All the processing is
9157  * done by the worker thread function lpfc_mbox_timeout_handler.
9158  **/
9159 void
9160 lpfc_mbox_timeout(struct timer_list *t)
9161 {
9162 	struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
9163 	unsigned long iflag;
9164 	uint32_t tmo_posted;
9165 
9166 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
9167 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
9168 	if (!tmo_posted)
9169 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
9170 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
9171 
9172 	if (!tmo_posted)
9173 		lpfc_worker_wake_up(phba);
9174 	return;
9175 }
9176 
9177 /**
9178  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
9179  *                                    are pending
9180  * @phba: Pointer to HBA context object.
9181  *
9182  * This function checks if any mailbox completions are present on the mailbox
9183  * completion queue.
9184  **/
9185 static bool
9186 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
9187 {
9188 
9189 	uint32_t idx;
9190 	struct lpfc_queue *mcq;
9191 	struct lpfc_mcqe *mcqe;
9192 	bool pending_completions = false;
9193 	uint8_t	qe_valid;
9194 
9195 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9196 		return false;
9197 
9198 	/* Check for completions on mailbox completion queue */
9199 
9200 	mcq = phba->sli4_hba.mbx_cq;
9201 	idx = mcq->hba_index;
9202 	qe_valid = mcq->qe_valid;
9203 	while (bf_get_le32(lpfc_cqe_valid,
9204 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
9205 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
9206 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
9207 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
9208 			pending_completions = true;
9209 			break;
9210 		}
9211 		idx = (idx + 1) % mcq->entry_count;
9212 		if (mcq->hba_index == idx)
9213 			break;
9214 
9215 		/* if the index wrapped around, toggle the valid bit */
9216 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
9217 			qe_valid = (qe_valid) ? 0 : 1;
9218 	}
9219 	return pending_completions;
9220 
9221 }
9222 
9223 /**
9224  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
9225  *					      that were missed.
9226  * @phba: Pointer to HBA context object.
9227  *
9228  * For sli4, it is possible to miss an interrupt. As such mbox completions
9229  * maybe missed causing erroneous mailbox timeouts to occur. This function
9230  * checks to see if mbox completions are on the mailbox completion queue
9231  * and will process all the completions associated with the eq for the
9232  * mailbox completion queue.
9233  **/
9234 static bool
9235 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
9236 {
9237 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
9238 	uint32_t eqidx;
9239 	struct lpfc_queue *fpeq = NULL;
9240 	struct lpfc_queue *eq;
9241 	bool mbox_pending;
9242 
9243 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9244 		return false;
9245 
9246 	/* Find the EQ associated with the mbox CQ */
9247 	if (sli4_hba->hdwq) {
9248 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
9249 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
9250 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
9251 				fpeq = eq;
9252 				break;
9253 			}
9254 		}
9255 	}
9256 	if (!fpeq)
9257 		return false;
9258 
9259 	/* Turn off interrupts from this EQ */
9260 
9261 	sli4_hba->sli4_eq_clr_intr(fpeq);
9262 
9263 	/* Check to see if a mbox completion is pending */
9264 
9265 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
9266 
9267 	/*
9268 	 * If a mbox completion is pending, process all the events on EQ
9269 	 * associated with the mbox completion queue (this could include
9270 	 * mailbox commands, async events, els commands, receive queue data
9271 	 * and fcp commands)
9272 	 */
9273 
9274 	if (mbox_pending)
9275 		/* process and rearm the EQ */
9276 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
9277 	else
9278 		/* Always clear and re-arm the EQ */
9279 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
9280 
9281 	return mbox_pending;
9282 
9283 }
9284 
9285 /**
9286  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
9287  * @phba: Pointer to HBA context object.
9288  *
9289  * This function is called from worker thread when a mailbox command times out.
9290  * The caller is not required to hold any locks. This function will reset the
9291  * HBA and recover all the pending commands.
9292  **/
9293 void
9294 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
9295 {
9296 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
9297 	MAILBOX_t *mb = NULL;
9298 
9299 	struct lpfc_sli *psli = &phba->sli;
9300 
9301 	/* If the mailbox completed, process the completion */
9302 	lpfc_sli4_process_missed_mbox_completions(phba);
9303 
9304 	if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
9305 		return;
9306 
9307 	if (pmbox != NULL)
9308 		mb = &pmbox->u.mb;
9309 	/* Check the pmbox pointer first.  There is a race condition
9310 	 * between the mbox timeout handler getting executed in the
9311 	 * worklist and the mailbox actually completing. When this
9312 	 * race condition occurs, the mbox_active will be NULL.
9313 	 */
9314 	spin_lock_irq(&phba->hbalock);
9315 	if (pmbox == NULL) {
9316 		lpfc_printf_log(phba, KERN_WARNING,
9317 				LOG_MBOX | LOG_SLI,
9318 				"0353 Active Mailbox cleared - mailbox timeout "
9319 				"exiting\n");
9320 		spin_unlock_irq(&phba->hbalock);
9321 		return;
9322 	}
9323 
9324 	/* Mbox cmd <mbxCommand> timeout */
9325 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9326 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
9327 			mb->mbxCommand,
9328 			phba->pport->port_state,
9329 			phba->sli.sli_flag,
9330 			phba->sli.mbox_active);
9331 	spin_unlock_irq(&phba->hbalock);
9332 
9333 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
9334 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
9335 	 * it to fail all outstanding SCSI IO.
9336 	 */
9337 	spin_lock_irq(&phba->pport->work_port_lock);
9338 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9339 	spin_unlock_irq(&phba->pport->work_port_lock);
9340 	spin_lock_irq(&phba->hbalock);
9341 	phba->link_state = LPFC_LINK_UNKNOWN;
9342 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
9343 	spin_unlock_irq(&phba->hbalock);
9344 
9345 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9346 			"0345 Resetting board due to mailbox timeout\n");
9347 
9348 	/* Reset the HBA device */
9349 	lpfc_reset_hba(phba);
9350 }
9351 
9352 /**
9353  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
9354  * @phba: Pointer to HBA context object.
9355  * @pmbox: Pointer to mailbox object.
9356  * @flag: Flag indicating how the mailbox need to be processed.
9357  *
9358  * This function is called by discovery code and HBA management code
9359  * to submit a mailbox command to firmware with SLI-3 interface spec. This
9360  * function gets the hbalock to protect the data structures.
9361  * The mailbox command can be submitted in polling mode, in which case
9362  * this function will wait in a polling loop for the completion of the
9363  * mailbox.
9364  * If the mailbox is submitted in no_wait mode (not polling) the
9365  * function will submit the command and returns immediately without waiting
9366  * for the mailbox completion. The no_wait is supported only when HBA
9367  * is in SLI2/SLI3 mode - interrupts are enabled.
9368  * The SLI interface allows only one mailbox pending at a time. If the
9369  * mailbox is issued in polling mode and there is already a mailbox
9370  * pending, then the function will return an error. If the mailbox is issued
9371  * in NO_WAIT mode and there is a mailbox pending already, the function
9372  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
9373  * The sli layer owns the mailbox object until the completion of mailbox
9374  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
9375  * return codes the caller owns the mailbox command after the return of
9376  * the function.
9377  **/
9378 static int
9379 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
9380 		       uint32_t flag)
9381 {
9382 	MAILBOX_t *mbx;
9383 	struct lpfc_sli *psli = &phba->sli;
9384 	uint32_t status, evtctr;
9385 	uint32_t ha_copy, hc_copy;
9386 	int i;
9387 	unsigned long timeout;
9388 	unsigned long drvr_flag = 0;
9389 	uint32_t word0, ldata;
9390 	void __iomem *to_slim;
9391 	int processing_queue = 0;
9392 
9393 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
9394 	if (!pmbox) {
9395 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9396 		/* processing mbox queue from intr_handler */
9397 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9398 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9399 			return MBX_SUCCESS;
9400 		}
9401 		processing_queue = 1;
9402 		pmbox = lpfc_mbox_get(phba);
9403 		if (!pmbox) {
9404 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9405 			return MBX_SUCCESS;
9406 		}
9407 	}
9408 
9409 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
9410 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
9411 		if(!pmbox->vport) {
9412 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9413 			lpfc_printf_log(phba, KERN_ERR,
9414 					LOG_MBOX | LOG_VPORT,
9415 					"1806 Mbox x%x failed. No vport\n",
9416 					pmbox->u.mb.mbxCommand);
9417 			dump_stack();
9418 			goto out_not_finished;
9419 		}
9420 	}
9421 
9422 	/* If the PCI channel is in offline state, do not post mbox. */
9423 	if (unlikely(pci_channel_offline(phba->pcidev))) {
9424 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9425 		goto out_not_finished;
9426 	}
9427 
9428 	/* If HBA has a deferred error attention, fail the iocb. */
9429 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
9430 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9431 		goto out_not_finished;
9432 	}
9433 
9434 	psli = &phba->sli;
9435 
9436 	mbx = &pmbox->u.mb;
9437 	status = MBX_SUCCESS;
9438 
9439 	if (phba->link_state == LPFC_HBA_ERROR) {
9440 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9441 
9442 		/* Mbox command <mbxCommand> cannot issue */
9443 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9444 				"(%d):0311 Mailbox command x%x cannot "
9445 				"issue Data: x%x x%x\n",
9446 				pmbox->vport ? pmbox->vport->vpi : 0,
9447 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9448 		goto out_not_finished;
9449 	}
9450 
9451 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
9452 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
9453 			!(hc_copy & HC_MBINT_ENA)) {
9454 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9455 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9456 				"(%d):2528 Mailbox command x%x cannot "
9457 				"issue Data: x%x x%x\n",
9458 				pmbox->vport ? pmbox->vport->vpi : 0,
9459 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9460 			goto out_not_finished;
9461 		}
9462 	}
9463 
9464 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9465 		/* Polling for a mbox command when another one is already active
9466 		 * is not allowed in SLI. Also, the driver must have established
9467 		 * SLI2 mode to queue and process multiple mbox commands.
9468 		 */
9469 
9470 		if (flag & MBX_POLL) {
9471 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9472 
9473 			/* Mbox command <mbxCommand> cannot issue */
9474 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9475 					"(%d):2529 Mailbox command x%x "
9476 					"cannot issue Data: x%x x%x\n",
9477 					pmbox->vport ? pmbox->vport->vpi : 0,
9478 					pmbox->u.mb.mbxCommand,
9479 					psli->sli_flag, flag);
9480 			goto out_not_finished;
9481 		}
9482 
9483 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
9484 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9485 			/* Mbox command <mbxCommand> cannot issue */
9486 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9487 					"(%d):2530 Mailbox command x%x "
9488 					"cannot issue Data: x%x x%x\n",
9489 					pmbox->vport ? pmbox->vport->vpi : 0,
9490 					pmbox->u.mb.mbxCommand,
9491 					psli->sli_flag, flag);
9492 			goto out_not_finished;
9493 		}
9494 
9495 		/* Another mailbox command is still being processed, queue this
9496 		 * command to be processed later.
9497 		 */
9498 		lpfc_mbox_put(phba, pmbox);
9499 
9500 		/* Mbox cmd issue - BUSY */
9501 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9502 				"(%d):0308 Mbox cmd issue - BUSY Data: "
9503 				"x%x x%x x%x x%x\n",
9504 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
9505 				mbx->mbxCommand,
9506 				phba->pport ? phba->pport->port_state : 0xff,
9507 				psli->sli_flag, flag);
9508 
9509 		psli->slistat.mbox_busy++;
9510 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9511 
9512 		if (pmbox->vport) {
9513 			lpfc_debugfs_disc_trc(pmbox->vport,
9514 				LPFC_DISC_TRC_MBOX_VPORT,
9515 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
9516 				(uint32_t)mbx->mbxCommand,
9517 				mbx->un.varWords[0], mbx->un.varWords[1]);
9518 		}
9519 		else {
9520 			lpfc_debugfs_disc_trc(phba->pport,
9521 				LPFC_DISC_TRC_MBOX,
9522 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
9523 				(uint32_t)mbx->mbxCommand,
9524 				mbx->un.varWords[0], mbx->un.varWords[1]);
9525 		}
9526 
9527 		return MBX_BUSY;
9528 	}
9529 
9530 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9531 
9532 	/* If we are not polling, we MUST be in SLI2 mode */
9533 	if (flag != MBX_POLL) {
9534 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
9535 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
9536 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9537 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9538 			/* Mbox command <mbxCommand> cannot issue */
9539 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9540 					"(%d):2531 Mailbox command x%x "
9541 					"cannot issue Data: x%x x%x\n",
9542 					pmbox->vport ? pmbox->vport->vpi : 0,
9543 					pmbox->u.mb.mbxCommand,
9544 					psli->sli_flag, flag);
9545 			goto out_not_finished;
9546 		}
9547 		/* timeout active mbox command */
9548 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9549 					   1000);
9550 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
9551 	}
9552 
9553 	/* Mailbox cmd <cmd> issue */
9554 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9555 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
9556 			"x%x\n",
9557 			pmbox->vport ? pmbox->vport->vpi : 0,
9558 			mbx->mbxCommand,
9559 			phba->pport ? phba->pport->port_state : 0xff,
9560 			psli->sli_flag, flag);
9561 
9562 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
9563 		if (pmbox->vport) {
9564 			lpfc_debugfs_disc_trc(pmbox->vport,
9565 				LPFC_DISC_TRC_MBOX_VPORT,
9566 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9567 				(uint32_t)mbx->mbxCommand,
9568 				mbx->un.varWords[0], mbx->un.varWords[1]);
9569 		}
9570 		else {
9571 			lpfc_debugfs_disc_trc(phba->pport,
9572 				LPFC_DISC_TRC_MBOX,
9573 				"MBOX Send:       cmd:x%x mb:x%x x%x",
9574 				(uint32_t)mbx->mbxCommand,
9575 				mbx->un.varWords[0], mbx->un.varWords[1]);
9576 		}
9577 	}
9578 
9579 	psli->slistat.mbox_cmd++;
9580 	evtctr = psli->slistat.mbox_event;
9581 
9582 	/* next set own bit for the adapter and copy over command word */
9583 	mbx->mbxOwner = OWN_CHIP;
9584 
9585 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9586 		/* Populate mbox extension offset word. */
9587 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
9588 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9589 				= (uint8_t *)phba->mbox_ext
9590 				  - (uint8_t *)phba->mbox;
9591 		}
9592 
9593 		/* Copy the mailbox extension data */
9594 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
9595 			lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
9596 					      (uint8_t *)phba->mbox_ext,
9597 					      pmbox->in_ext_byte_len);
9598 		}
9599 		/* Copy command data to host SLIM area */
9600 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
9601 	} else {
9602 		/* Populate mbox extension offset word. */
9603 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
9604 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9605 				= MAILBOX_HBA_EXT_OFFSET;
9606 
9607 		/* Copy the mailbox extension data */
9608 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
9609 			lpfc_memcpy_to_slim(phba->MBslimaddr +
9610 				MAILBOX_HBA_EXT_OFFSET,
9611 				pmbox->ctx_buf, pmbox->in_ext_byte_len);
9612 
9613 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9614 			/* copy command data into host mbox for cmpl */
9615 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
9616 					      MAILBOX_CMD_SIZE);
9617 
9618 		/* First copy mbox command data to HBA SLIM, skip past first
9619 		   word */
9620 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
9621 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
9622 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
9623 
9624 		/* Next copy over first word, with mbxOwner set */
9625 		ldata = *((uint32_t *)mbx);
9626 		to_slim = phba->MBslimaddr;
9627 		writel(ldata, to_slim);
9628 		readl(to_slim); /* flush */
9629 
9630 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9631 			/* switch over to host mailbox */
9632 			psli->sli_flag |= LPFC_SLI_ACTIVE;
9633 	}
9634 
9635 	wmb();
9636 
9637 	switch (flag) {
9638 	case MBX_NOWAIT:
9639 		/* Set up reference to mailbox command */
9640 		psli->mbox_active = pmbox;
9641 		/* Interrupt board to do it */
9642 		writel(CA_MBATT, phba->CAregaddr);
9643 		readl(phba->CAregaddr); /* flush */
9644 		/* Don't wait for it to finish, just return */
9645 		break;
9646 
9647 	case MBX_POLL:
9648 		/* Set up null reference to mailbox command */
9649 		psli->mbox_active = NULL;
9650 		/* Interrupt board to do it */
9651 		writel(CA_MBATT, phba->CAregaddr);
9652 		readl(phba->CAregaddr); /* flush */
9653 
9654 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9655 			/* First read mbox status word */
9656 			word0 = *((uint32_t *)phba->mbox);
9657 			word0 = le32_to_cpu(word0);
9658 		} else {
9659 			/* First read mbox status word */
9660 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
9661 				spin_unlock_irqrestore(&phba->hbalock,
9662 						       drvr_flag);
9663 				goto out_not_finished;
9664 			}
9665 		}
9666 
9667 		/* Read the HBA Host Attention Register */
9668 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9669 			spin_unlock_irqrestore(&phba->hbalock,
9670 						       drvr_flag);
9671 			goto out_not_finished;
9672 		}
9673 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9674 							1000) + jiffies;
9675 		i = 0;
9676 		/* Wait for command to complete */
9677 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
9678 		       (!(ha_copy & HA_MBATT) &&
9679 			(phba->link_state > LPFC_WARM_START))) {
9680 			if (time_after(jiffies, timeout)) {
9681 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9682 				spin_unlock_irqrestore(&phba->hbalock,
9683 						       drvr_flag);
9684 				goto out_not_finished;
9685 			}
9686 
9687 			/* Check if we took a mbox interrupt while we were
9688 			   polling */
9689 			if (((word0 & OWN_CHIP) != OWN_CHIP)
9690 			    && (evtctr != psli->slistat.mbox_event))
9691 				break;
9692 
9693 			if (i++ > 10) {
9694 				spin_unlock_irqrestore(&phba->hbalock,
9695 						       drvr_flag);
9696 				msleep(1);
9697 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
9698 			}
9699 
9700 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9701 				/* First copy command data */
9702 				word0 = *((uint32_t *)phba->mbox);
9703 				word0 = le32_to_cpu(word0);
9704 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
9705 					MAILBOX_t *slimmb;
9706 					uint32_t slimword0;
9707 					/* Check real SLIM for any errors */
9708 					slimword0 = readl(phba->MBslimaddr);
9709 					slimmb = (MAILBOX_t *) & slimword0;
9710 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
9711 					    && slimmb->mbxStatus) {
9712 						psli->sli_flag &=
9713 						    ~LPFC_SLI_ACTIVE;
9714 						word0 = slimword0;
9715 					}
9716 				}
9717 			} else {
9718 				/* First copy command data */
9719 				word0 = readl(phba->MBslimaddr);
9720 			}
9721 			/* Read the HBA Host Attention Register */
9722 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9723 				spin_unlock_irqrestore(&phba->hbalock,
9724 						       drvr_flag);
9725 				goto out_not_finished;
9726 			}
9727 		}
9728 
9729 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9730 			/* copy results back to user */
9731 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
9732 						MAILBOX_CMD_SIZE);
9733 			/* Copy the mailbox extension data */
9734 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9735 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
9736 						      pmbox->ctx_buf,
9737 						      pmbox->out_ext_byte_len);
9738 			}
9739 		} else {
9740 			/* First copy command data */
9741 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
9742 						MAILBOX_CMD_SIZE);
9743 			/* Copy the mailbox extension data */
9744 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9745 				lpfc_memcpy_from_slim(
9746 					pmbox->ctx_buf,
9747 					phba->MBslimaddr +
9748 					MAILBOX_HBA_EXT_OFFSET,
9749 					pmbox->out_ext_byte_len);
9750 			}
9751 		}
9752 
9753 		writel(HA_MBATT, phba->HAregaddr);
9754 		readl(phba->HAregaddr); /* flush */
9755 
9756 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9757 		status = mbx->mbxStatus;
9758 	}
9759 
9760 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9761 	return status;
9762 
9763 out_not_finished:
9764 	if (processing_queue) {
9765 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
9766 		lpfc_mbox_cmpl_put(phba, pmbox);
9767 	}
9768 	return MBX_NOT_FINISHED;
9769 }
9770 
9771 /**
9772  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
9773  * @phba: Pointer to HBA context object.
9774  *
9775  * The function blocks the posting of SLI4 asynchronous mailbox commands from
9776  * the driver internal pending mailbox queue. It will then try to wait out the
9777  * possible outstanding mailbox command before return.
9778  *
9779  * Returns:
9780  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
9781  * 	the outstanding mailbox command timed out.
9782  **/
9783 static int
9784 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
9785 {
9786 	struct lpfc_sli *psli = &phba->sli;
9787 	LPFC_MBOXQ_t *mboxq;
9788 	int rc = 0;
9789 	unsigned long timeout = 0;
9790 	u32 sli_flag;
9791 	u8 cmd, subsys, opcode;
9792 
9793 	/* Mark the asynchronous mailbox command posting as blocked */
9794 	spin_lock_irq(&phba->hbalock);
9795 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
9796 	/* Determine how long we might wait for the active mailbox
9797 	 * command to be gracefully completed by firmware.
9798 	 */
9799 	if (phba->sli.mbox_active)
9800 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
9801 						phba->sli.mbox_active) *
9802 						1000) + jiffies;
9803 	spin_unlock_irq(&phba->hbalock);
9804 
9805 	/* Make sure the mailbox is really active */
9806 	if (timeout)
9807 		lpfc_sli4_process_missed_mbox_completions(phba);
9808 
9809 	/* Wait for the outstanding mailbox command to complete */
9810 	while (phba->sli.mbox_active) {
9811 		/* Check active mailbox complete status every 2ms */
9812 		msleep(2);
9813 		if (time_after(jiffies, timeout)) {
9814 			/* Timeout, mark the outstanding cmd not complete */
9815 
9816 			/* Sanity check sli.mbox_active has not completed or
9817 			 * cancelled from another context during last 2ms sleep,
9818 			 * so take hbalock to be sure before logging.
9819 			 */
9820 			spin_lock_irq(&phba->hbalock);
9821 			if (phba->sli.mbox_active) {
9822 				mboxq = phba->sli.mbox_active;
9823 				cmd = mboxq->u.mb.mbxCommand;
9824 				subsys = lpfc_sli_config_mbox_subsys_get(phba,
9825 									 mboxq);
9826 				opcode = lpfc_sli_config_mbox_opcode_get(phba,
9827 									 mboxq);
9828 				sli_flag = psli->sli_flag;
9829 				spin_unlock_irq(&phba->hbalock);
9830 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9831 						"2352 Mailbox command x%x "
9832 						"(x%x/x%x) sli_flag x%x could "
9833 						"not complete\n",
9834 						cmd, subsys, opcode,
9835 						sli_flag);
9836 			} else {
9837 				spin_unlock_irq(&phba->hbalock);
9838 			}
9839 
9840 			rc = 1;
9841 			break;
9842 		}
9843 	}
9844 
9845 	/* Can not cleanly block async mailbox command, fails it */
9846 	if (rc) {
9847 		spin_lock_irq(&phba->hbalock);
9848 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9849 		spin_unlock_irq(&phba->hbalock);
9850 	}
9851 	return rc;
9852 }
9853 
9854 /**
9855  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
9856  * @phba: Pointer to HBA context object.
9857  *
9858  * The function unblocks and resume posting of SLI4 asynchronous mailbox
9859  * commands from the driver internal pending mailbox queue. It makes sure
9860  * that there is no outstanding mailbox command before resuming posting
9861  * asynchronous mailbox commands. If, for any reason, there is outstanding
9862  * mailbox command, it will try to wait it out before resuming asynchronous
9863  * mailbox command posting.
9864  **/
9865 static void
9866 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
9867 {
9868 	struct lpfc_sli *psli = &phba->sli;
9869 
9870 	spin_lock_irq(&phba->hbalock);
9871 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9872 		/* Asynchronous mailbox posting is not blocked, do nothing */
9873 		spin_unlock_irq(&phba->hbalock);
9874 		return;
9875 	}
9876 
9877 	/* Outstanding synchronous mailbox command is guaranteed to be done,
9878 	 * successful or timeout, after timing-out the outstanding mailbox
9879 	 * command shall always be removed, so just unblock posting async
9880 	 * mailbox command and resume
9881 	 */
9882 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9883 	spin_unlock_irq(&phba->hbalock);
9884 
9885 	/* wake up worker thread to post asynchronous mailbox command */
9886 	lpfc_worker_wake_up(phba);
9887 }
9888 
9889 /**
9890  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
9891  * @phba: Pointer to HBA context object.
9892  * @mboxq: Pointer to mailbox object.
9893  *
9894  * The function waits for the bootstrap mailbox register ready bit from
9895  * port for twice the regular mailbox command timeout value.
9896  *
9897  *      0 - no timeout on waiting for bootstrap mailbox register ready.
9898  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
9899  **/
9900 static int
9901 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9902 {
9903 	uint32_t db_ready;
9904 	unsigned long timeout;
9905 	struct lpfc_register bmbx_reg;
9906 
9907 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
9908 				   * 1000) + jiffies;
9909 
9910 	do {
9911 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
9912 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
9913 		if (!db_ready)
9914 			mdelay(2);
9915 
9916 		if (time_after(jiffies, timeout))
9917 			return MBXERR_ERROR;
9918 	} while (!db_ready);
9919 
9920 	return 0;
9921 }
9922 
9923 /**
9924  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
9925  * @phba: Pointer to HBA context object.
9926  * @mboxq: Pointer to mailbox object.
9927  *
9928  * The function posts a mailbox to the port.  The mailbox is expected
9929  * to be comletely filled in and ready for the port to operate on it.
9930  * This routine executes a synchronous completion operation on the
9931  * mailbox by polling for its completion.
9932  *
9933  * The caller must not be holding any locks when calling this routine.
9934  *
9935  * Returns:
9936  *	MBX_SUCCESS - mailbox posted successfully
9937  *	Any of the MBX error values.
9938  **/
9939 static int
9940 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9941 {
9942 	int rc = MBX_SUCCESS;
9943 	unsigned long iflag;
9944 	uint32_t mcqe_status;
9945 	uint32_t mbx_cmnd;
9946 	struct lpfc_sli *psli = &phba->sli;
9947 	struct lpfc_mqe *mb = &mboxq->u.mqe;
9948 	struct lpfc_bmbx_create *mbox_rgn;
9949 	struct dma_address *dma_address;
9950 
9951 	/*
9952 	 * Only one mailbox can be active to the bootstrap mailbox region
9953 	 * at a time and there is no queueing provided.
9954 	 */
9955 	spin_lock_irqsave(&phba->hbalock, iflag);
9956 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9957 		spin_unlock_irqrestore(&phba->hbalock, iflag);
9958 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9959 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
9960 				"cannot issue Data: x%x x%x\n",
9961 				mboxq->vport ? mboxq->vport->vpi : 0,
9962 				mboxq->u.mb.mbxCommand,
9963 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9964 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9965 				psli->sli_flag, MBX_POLL);
9966 		return MBXERR_ERROR;
9967 	}
9968 	/* The server grabs the token and owns it until release */
9969 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9970 	phba->sli.mbox_active = mboxq;
9971 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9972 
9973 	/* wait for bootstrap mbox register for readyness */
9974 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9975 	if (rc)
9976 		goto exit;
9977 	/*
9978 	 * Initialize the bootstrap memory region to avoid stale data areas
9979 	 * in the mailbox post.  Then copy the caller's mailbox contents to
9980 	 * the bmbx mailbox region.
9981 	 */
9982 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
9983 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
9984 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
9985 			       sizeof(struct lpfc_mqe));
9986 
9987 	/* Post the high mailbox dma address to the port and wait for ready. */
9988 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9989 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
9990 
9991 	/* wait for bootstrap mbox register for hi-address write done */
9992 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9993 	if (rc)
9994 		goto exit;
9995 
9996 	/* Post the low mailbox dma address to the port. */
9997 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
9998 
9999 	/* wait for bootstrap mbox register for low address write done */
10000 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
10001 	if (rc)
10002 		goto exit;
10003 
10004 	/*
10005 	 * Read the CQ to ensure the mailbox has completed.
10006 	 * If so, update the mailbox status so that the upper layers
10007 	 * can complete the request normally.
10008 	 */
10009 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
10010 			       sizeof(struct lpfc_mqe));
10011 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
10012 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
10013 			       sizeof(struct lpfc_mcqe));
10014 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
10015 	/*
10016 	 * When the CQE status indicates a failure and the mailbox status
10017 	 * indicates success then copy the CQE status into the mailbox status
10018 	 * (and prefix it with x4000).
10019 	 */
10020 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
10021 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
10022 			bf_set(lpfc_mqe_status, mb,
10023 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
10024 		rc = MBXERR_ERROR;
10025 	} else
10026 		lpfc_sli4_swap_str(phba, mboxq);
10027 
10028 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10029 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
10030 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
10031 			" x%x x%x CQ: x%x x%x x%x x%x\n",
10032 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10033 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10034 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10035 			bf_get(lpfc_mqe_status, mb),
10036 			mb->un.mb_words[0], mb->un.mb_words[1],
10037 			mb->un.mb_words[2], mb->un.mb_words[3],
10038 			mb->un.mb_words[4], mb->un.mb_words[5],
10039 			mb->un.mb_words[6], mb->un.mb_words[7],
10040 			mb->un.mb_words[8], mb->un.mb_words[9],
10041 			mb->un.mb_words[10], mb->un.mb_words[11],
10042 			mb->un.mb_words[12], mboxq->mcqe.word0,
10043 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
10044 			mboxq->mcqe.trailer);
10045 exit:
10046 	/* We are holding the token, no needed for lock when release */
10047 	spin_lock_irqsave(&phba->hbalock, iflag);
10048 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10049 	phba->sli.mbox_active = NULL;
10050 	spin_unlock_irqrestore(&phba->hbalock, iflag);
10051 	return rc;
10052 }
10053 
10054 /**
10055  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
10056  * @phba: Pointer to HBA context object.
10057  * @mboxq: Pointer to mailbox object.
10058  * @flag: Flag indicating how the mailbox need to be processed.
10059  *
10060  * This function is called by discovery code and HBA management code to submit
10061  * a mailbox command to firmware with SLI-4 interface spec.
10062  *
10063  * Return codes the caller owns the mailbox command after the return of the
10064  * function.
10065  **/
10066 static int
10067 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
10068 		       uint32_t flag)
10069 {
10070 	struct lpfc_sli *psli = &phba->sli;
10071 	unsigned long iflags;
10072 	int rc;
10073 
10074 	/* dump from issue mailbox command if setup */
10075 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
10076 
10077 	rc = lpfc_mbox_dev_check(phba);
10078 	if (unlikely(rc)) {
10079 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10080 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
10081 				"cannot issue Data: x%x x%x\n",
10082 				mboxq->vport ? mboxq->vport->vpi : 0,
10083 				mboxq->u.mb.mbxCommand,
10084 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10085 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10086 				psli->sli_flag, flag);
10087 		goto out_not_finished;
10088 	}
10089 
10090 	/* Detect polling mode and jump to a handler */
10091 	if (!phba->sli4_hba.intr_enable) {
10092 		if (flag == MBX_POLL)
10093 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10094 		else
10095 			rc = -EIO;
10096 		if (rc != MBX_SUCCESS)
10097 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10098 					"(%d):2541 Mailbox command x%x "
10099 					"(x%x/x%x) failure: "
10100 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
10101 					"Data: x%x x%x\n",
10102 					mboxq->vport ? mboxq->vport->vpi : 0,
10103 					mboxq->u.mb.mbxCommand,
10104 					lpfc_sli_config_mbox_subsys_get(phba,
10105 									mboxq),
10106 					lpfc_sli_config_mbox_opcode_get(phba,
10107 									mboxq),
10108 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10109 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10110 					bf_get(lpfc_mcqe_ext_status,
10111 					       &mboxq->mcqe),
10112 					psli->sli_flag, flag);
10113 		return rc;
10114 	} else if (flag == MBX_POLL) {
10115 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10116 				"(%d):2542 Try to issue mailbox command "
10117 				"x%x (x%x/x%x) synchronously ahead of async "
10118 				"mailbox command queue: x%x x%x\n",
10119 				mboxq->vport ? mboxq->vport->vpi : 0,
10120 				mboxq->u.mb.mbxCommand,
10121 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10122 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10123 				psli->sli_flag, flag);
10124 		/* Try to block the asynchronous mailbox posting */
10125 		rc = lpfc_sli4_async_mbox_block(phba);
10126 		if (!rc) {
10127 			/* Successfully blocked, now issue sync mbox cmd */
10128 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10129 			if (rc != MBX_SUCCESS)
10130 				lpfc_printf_log(phba, KERN_WARNING,
10131 					LOG_MBOX | LOG_SLI,
10132 					"(%d):2597 Sync Mailbox command "
10133 					"x%x (x%x/x%x) failure: "
10134 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
10135 					"Data: x%x x%x\n",
10136 					mboxq->vport ? mboxq->vport->vpi : 0,
10137 					mboxq->u.mb.mbxCommand,
10138 					lpfc_sli_config_mbox_subsys_get(phba,
10139 									mboxq),
10140 					lpfc_sli_config_mbox_opcode_get(phba,
10141 									mboxq),
10142 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10143 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10144 					bf_get(lpfc_mcqe_ext_status,
10145 					       &mboxq->mcqe),
10146 					psli->sli_flag, flag);
10147 			/* Unblock the async mailbox posting afterward */
10148 			lpfc_sli4_async_mbox_unblock(phba);
10149 		}
10150 		return rc;
10151 	}
10152 
10153 	/* Now, interrupt mode asynchronous mailbox command */
10154 	rc = lpfc_mbox_cmd_check(phba, mboxq);
10155 	if (rc) {
10156 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10157 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
10158 				"cannot issue Data: x%x x%x\n",
10159 				mboxq->vport ? mboxq->vport->vpi : 0,
10160 				mboxq->u.mb.mbxCommand,
10161 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10162 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10163 				psli->sli_flag, flag);
10164 		goto out_not_finished;
10165 	}
10166 
10167 	/* Put the mailbox command to the driver internal FIFO */
10168 	psli->slistat.mbox_busy++;
10169 	spin_lock_irqsave(&phba->hbalock, iflags);
10170 	lpfc_mbox_put(phba, mboxq);
10171 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10172 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10173 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
10174 			"x%x (x%x/x%x) x%x x%x x%x\n",
10175 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
10176 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
10177 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10178 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10179 			phba->pport->port_state,
10180 			psli->sli_flag, MBX_NOWAIT);
10181 	/* Wake up worker thread to transport mailbox command from head */
10182 	lpfc_worker_wake_up(phba);
10183 
10184 	return MBX_BUSY;
10185 
10186 out_not_finished:
10187 	return MBX_NOT_FINISHED;
10188 }
10189 
10190 /**
10191  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
10192  * @phba: Pointer to HBA context object.
10193  *
10194  * This function is called by worker thread to send a mailbox command to
10195  * SLI4 HBA firmware.
10196  *
10197  **/
10198 int
10199 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
10200 {
10201 	struct lpfc_sli *psli = &phba->sli;
10202 	LPFC_MBOXQ_t *mboxq;
10203 	int rc = MBX_SUCCESS;
10204 	unsigned long iflags;
10205 	struct lpfc_mqe *mqe;
10206 	uint32_t mbx_cmnd;
10207 
10208 	/* Check interrupt mode before post async mailbox command */
10209 	if (unlikely(!phba->sli4_hba.intr_enable))
10210 		return MBX_NOT_FINISHED;
10211 
10212 	/* Check for mailbox command service token */
10213 	spin_lock_irqsave(&phba->hbalock, iflags);
10214 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
10215 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10216 		return MBX_NOT_FINISHED;
10217 	}
10218 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
10219 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10220 		return MBX_NOT_FINISHED;
10221 	}
10222 	if (unlikely(phba->sli.mbox_active)) {
10223 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10224 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10225 				"0384 There is pending active mailbox cmd\n");
10226 		return MBX_NOT_FINISHED;
10227 	}
10228 	/* Take the mailbox command service token */
10229 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
10230 
10231 	/* Get the next mailbox command from head of queue */
10232 	mboxq = lpfc_mbox_get(phba);
10233 
10234 	/* If no more mailbox command waiting for post, we're done */
10235 	if (!mboxq) {
10236 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10237 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10238 		return MBX_SUCCESS;
10239 	}
10240 	phba->sli.mbox_active = mboxq;
10241 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10242 
10243 	/* Check device readiness for posting mailbox command */
10244 	rc = lpfc_mbox_dev_check(phba);
10245 	if (unlikely(rc))
10246 		/* Driver clean routine will clean up pending mailbox */
10247 		goto out_not_finished;
10248 
10249 	/* Prepare the mbox command to be posted */
10250 	mqe = &mboxq->u.mqe;
10251 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
10252 
10253 	/* Start timer for the mbox_tmo and log some mailbox post messages */
10254 	mod_timer(&psli->mbox_tmo, (jiffies +
10255 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
10256 
10257 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10258 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
10259 			"x%x x%x\n",
10260 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10261 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10262 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10263 			phba->pport->port_state, psli->sli_flag);
10264 
10265 	if (mbx_cmnd != MBX_HEARTBEAT) {
10266 		if (mboxq->vport) {
10267 			lpfc_debugfs_disc_trc(mboxq->vport,
10268 				LPFC_DISC_TRC_MBOX_VPORT,
10269 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
10270 				mbx_cmnd, mqe->un.mb_words[0],
10271 				mqe->un.mb_words[1]);
10272 		} else {
10273 			lpfc_debugfs_disc_trc(phba->pport,
10274 				LPFC_DISC_TRC_MBOX,
10275 				"MBOX Send: cmd:x%x mb:x%x x%x",
10276 				mbx_cmnd, mqe->un.mb_words[0],
10277 				mqe->un.mb_words[1]);
10278 		}
10279 	}
10280 	psli->slistat.mbox_cmd++;
10281 
10282 	/* Post the mailbox command to the port */
10283 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
10284 	if (rc != MBX_SUCCESS) {
10285 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10286 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
10287 				"cannot issue Data: x%x x%x\n",
10288 				mboxq->vport ? mboxq->vport->vpi : 0,
10289 				mboxq->u.mb.mbxCommand,
10290 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10291 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10292 				psli->sli_flag, MBX_NOWAIT);
10293 		goto out_not_finished;
10294 	}
10295 
10296 	return rc;
10297 
10298 out_not_finished:
10299 	spin_lock_irqsave(&phba->hbalock, iflags);
10300 	if (phba->sli.mbox_active) {
10301 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
10302 		__lpfc_mbox_cmpl_put(phba, mboxq);
10303 		/* Release the token */
10304 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10305 		phba->sli.mbox_active = NULL;
10306 	}
10307 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10308 
10309 	return MBX_NOT_FINISHED;
10310 }
10311 
10312 /**
10313  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
10314  * @phba: Pointer to HBA context object.
10315  * @pmbox: Pointer to mailbox object.
10316  * @flag: Flag indicating how the mailbox need to be processed.
10317  *
10318  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
10319  * the API jump table function pointer from the lpfc_hba struct.
10320  *
10321  * Return codes the caller owns the mailbox command after the return of the
10322  * function.
10323  **/
10324 int
10325 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
10326 {
10327 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
10328 }
10329 
10330 /**
10331  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
10332  * @phba: The hba struct for which this call is being executed.
10333  * @dev_grp: The HBA PCI-Device group number.
10334  *
10335  * This routine sets up the mbox interface API function jump table in @phba
10336  * struct.
10337  * Returns: 0 - success, -ENODEV - failure.
10338  **/
10339 int
10340 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10341 {
10342 
10343 	switch (dev_grp) {
10344 	case LPFC_PCI_DEV_LP:
10345 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
10346 		phba->lpfc_sli_handle_slow_ring_event =
10347 				lpfc_sli_handle_slow_ring_event_s3;
10348 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
10349 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
10350 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
10351 		break;
10352 	case LPFC_PCI_DEV_OC:
10353 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
10354 		phba->lpfc_sli_handle_slow_ring_event =
10355 				lpfc_sli_handle_slow_ring_event_s4;
10356 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
10357 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
10358 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
10359 		break;
10360 	default:
10361 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10362 				"1420 Invalid HBA PCI-device group: 0x%x\n",
10363 				dev_grp);
10364 		return -ENODEV;
10365 	}
10366 	return 0;
10367 }
10368 
10369 /**
10370  * __lpfc_sli_ringtx_put - Add an iocb to the txq
10371  * @phba: Pointer to HBA context object.
10372  * @pring: Pointer to driver SLI ring object.
10373  * @piocb: Pointer to address of newly added command iocb.
10374  *
10375  * This function is called with hbalock held for SLI3 ports or
10376  * the ring lock held for SLI4 ports to add a command
10377  * iocb to the txq when SLI layer cannot submit the command iocb
10378  * to the ring.
10379  **/
10380 void
10381 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10382 		    struct lpfc_iocbq *piocb)
10383 {
10384 	if (phba->sli_rev == LPFC_SLI_REV4)
10385 		lockdep_assert_held(&pring->ring_lock);
10386 	else
10387 		lockdep_assert_held(&phba->hbalock);
10388 	/* Insert the caller's iocb in the txq tail for later processing. */
10389 	list_add_tail(&piocb->list, &pring->txq);
10390 }
10391 
10392 /**
10393  * lpfc_sli_next_iocb - Get the next iocb in the txq
10394  * @phba: Pointer to HBA context object.
10395  * @pring: Pointer to driver SLI ring object.
10396  * @piocb: Pointer to address of newly added command iocb.
10397  *
10398  * This function is called with hbalock held before a new
10399  * iocb is submitted to the firmware. This function checks
10400  * txq to flush the iocbs in txq to Firmware before
10401  * submitting new iocbs to the Firmware.
10402  * If there are iocbs in the txq which need to be submitted
10403  * to firmware, lpfc_sli_next_iocb returns the first element
10404  * of the txq after dequeuing it from txq.
10405  * If there is no iocb in the txq then the function will return
10406  * *piocb and *piocb is set to NULL. Caller needs to check
10407  * *piocb to find if there are more commands in the txq.
10408  **/
10409 static struct lpfc_iocbq *
10410 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10411 		   struct lpfc_iocbq **piocb)
10412 {
10413 	struct lpfc_iocbq * nextiocb;
10414 
10415 	lockdep_assert_held(&phba->hbalock);
10416 
10417 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
10418 	if (!nextiocb) {
10419 		nextiocb = *piocb;
10420 		*piocb = NULL;
10421 	}
10422 
10423 	return nextiocb;
10424 }
10425 
10426 /**
10427  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
10428  * @phba: Pointer to HBA context object.
10429  * @ring_number: SLI ring number to issue iocb on.
10430  * @piocb: Pointer to command iocb.
10431  * @flag: Flag indicating if this command can be put into txq.
10432  *
10433  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
10434  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
10435  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
10436  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
10437  * this function allows only iocbs for posting buffers. This function finds
10438  * next available slot in the command ring and posts the command to the
10439  * available slot and writes the port attention register to request HBA start
10440  * processing new iocb. If there is no slot available in the ring and
10441  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
10442  * the function returns IOCB_BUSY.
10443  *
10444  * This function is called with hbalock held. The function will return success
10445  * after it successfully submit the iocb to firmware or after adding to the
10446  * txq.
10447  **/
10448 static int
10449 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
10450 		    struct lpfc_iocbq *piocb, uint32_t flag)
10451 {
10452 	struct lpfc_iocbq *nextiocb;
10453 	IOCB_t *iocb;
10454 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
10455 
10456 	lockdep_assert_held(&phba->hbalock);
10457 
10458 	if (piocb->cmd_cmpl && (!piocb->vport) &&
10459 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
10460 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
10461 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10462 				"1807 IOCB x%x failed. No vport\n",
10463 				piocb->iocb.ulpCommand);
10464 		dump_stack();
10465 		return IOCB_ERROR;
10466 	}
10467 
10468 
10469 	/* If the PCI channel is in offline state, do not post iocbs. */
10470 	if (unlikely(pci_channel_offline(phba->pcidev)))
10471 		return IOCB_ERROR;
10472 
10473 	/* If HBA has a deferred error attention, fail the iocb. */
10474 	if (unlikely(phba->hba_flag & DEFER_ERATT))
10475 		return IOCB_ERROR;
10476 
10477 	/*
10478 	 * We should never get an IOCB if we are in a < LINK_DOWN state
10479 	 */
10480 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
10481 		return IOCB_ERROR;
10482 
10483 	/*
10484 	 * Check to see if we are blocking IOCB processing because of a
10485 	 * outstanding event.
10486 	 */
10487 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
10488 		goto iocb_busy;
10489 
10490 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
10491 		/*
10492 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
10493 		 * can be issued if the link is not up.
10494 		 */
10495 		switch (piocb->iocb.ulpCommand) {
10496 		case CMD_QUE_RING_BUF_CN:
10497 		case CMD_QUE_RING_BUF64_CN:
10498 			/*
10499 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
10500 			 * completion, cmd_cmpl MUST be 0.
10501 			 */
10502 			if (piocb->cmd_cmpl)
10503 				piocb->cmd_cmpl = NULL;
10504 			fallthrough;
10505 		case CMD_CREATE_XRI_CR:
10506 		case CMD_CLOSE_XRI_CN:
10507 		case CMD_CLOSE_XRI_CX:
10508 			break;
10509 		default:
10510 			goto iocb_busy;
10511 		}
10512 
10513 	/*
10514 	 * For FCP commands, we must be in a state where we can process link
10515 	 * attention events.
10516 	 */
10517 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
10518 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
10519 		goto iocb_busy;
10520 	}
10521 
10522 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
10523 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
10524 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
10525 
10526 	if (iocb)
10527 		lpfc_sli_update_ring(phba, pring);
10528 	else
10529 		lpfc_sli_update_full_ring(phba, pring);
10530 
10531 	if (!piocb)
10532 		return IOCB_SUCCESS;
10533 
10534 	goto out_busy;
10535 
10536  iocb_busy:
10537 	pring->stats.iocb_cmd_delay++;
10538 
10539  out_busy:
10540 
10541 	if (!(flag & SLI_IOCB_RET_IOCB)) {
10542 		__lpfc_sli_ringtx_put(phba, pring, piocb);
10543 		return IOCB_SUCCESS;
10544 	}
10545 
10546 	return IOCB_BUSY;
10547 }
10548 
10549 /**
10550  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10551  * @phba: Pointer to HBA context object.
10552  * @ring_number: SLI ring number to issue wqe on.
10553  * @piocb: Pointer to command iocb.
10554  * @flag: Flag indicating if this command can be put into txq.
10555  *
10556  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10557  * send  an iocb command to an HBA with SLI-3 interface spec.
10558  *
10559  * This function takes the hbalock before invoking the lockless version.
10560  * The function will return success after it successfully submit the wqe to
10561  * firmware or after adding to the txq.
10562  **/
10563 static int
10564 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10565 			   struct lpfc_iocbq *piocb, uint32_t flag)
10566 {
10567 	unsigned long iflags;
10568 	int rc;
10569 
10570 	spin_lock_irqsave(&phba->hbalock, iflags);
10571 	rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10572 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10573 
10574 	return rc;
10575 }
10576 
10577 /**
10578  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10579  * @phba: Pointer to HBA context object.
10580  * @ring_number: SLI ring number to issue wqe on.
10581  * @piocb: Pointer to command iocb.
10582  * @flag: Flag indicating if this command can be put into txq.
10583  *
10584  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10585  * an wqe command to an HBA with SLI-4 interface spec.
10586  *
10587  * This function is a lockless version. The function will return success
10588  * after it successfully submit the wqe to firmware or after adding to the
10589  * txq.
10590  **/
10591 static int
10592 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10593 			   struct lpfc_iocbq *piocb, uint32_t flag)
10594 {
10595 	struct lpfc_io_buf *lpfc_cmd = piocb->io_buf;
10596 
10597 	lpfc_prep_embed_io(phba, lpfc_cmd);
10598 	return lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
10599 }
10600 
10601 void
10602 lpfc_prep_embed_io(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
10603 {
10604 	struct lpfc_iocbq *piocb = &lpfc_cmd->cur_iocbq;
10605 	union lpfc_wqe128 *wqe = &lpfc_cmd->cur_iocbq.wqe;
10606 	struct sli4_sge *sgl;
10607 
10608 	/* 128 byte wqe support here */
10609 	sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10610 
10611 	if (phba->fcp_embed_io) {
10612 		struct fcp_cmnd *fcp_cmnd;
10613 		u32 *ptr;
10614 
10615 		fcp_cmnd = lpfc_cmd->fcp_cmnd;
10616 
10617 		/* Word 0-2 - FCP_CMND */
10618 		wqe->generic.bde.tus.f.bdeFlags =
10619 			BUFF_TYPE_BDE_IMMED;
10620 		wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10621 		wqe->generic.bde.addrHigh = 0;
10622 		wqe->generic.bde.addrLow =  88;  /* Word 22 */
10623 
10624 		bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10625 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10626 
10627 		/* Word 22-29  FCP CMND Payload */
10628 		ptr = &wqe->words[22];
10629 		memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10630 	} else {
10631 		/* Word 0-2 - Inline BDE */
10632 		wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
10633 		wqe->generic.bde.tus.f.bdeSize = sizeof(struct fcp_cmnd);
10634 		wqe->generic.bde.addrHigh = sgl->addr_hi;
10635 		wqe->generic.bde.addrLow =  sgl->addr_lo;
10636 
10637 		/* Word 10 */
10638 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10639 		bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
10640 	}
10641 
10642 	/* add the VMID tags as per switch response */
10643 	if (unlikely(piocb->cmd_flag & LPFC_IO_VMID)) {
10644 		if (phba->pport->vmid_flag & LPFC_VMID_TYPE_PRIO) {
10645 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
10646 			bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10647 					(piocb->vmid_tag.cs_ctl_vmid));
10648 		} else if (phba->cfg_vmid_app_header) {
10649 			bf_set(wqe_appid, &wqe->fcp_iwrite.wqe_com, 1);
10650 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10651 			wqe->words[31] = piocb->vmid_tag.app_id;
10652 		}
10653 	}
10654 }
10655 
10656 /**
10657  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10658  * @phba: Pointer to HBA context object.
10659  * @ring_number: SLI ring number to issue iocb on.
10660  * @piocb: Pointer to command iocb.
10661  * @flag: Flag indicating if this command can be put into txq.
10662  *
10663  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10664  * an iocb command to an HBA with SLI-4 interface spec.
10665  *
10666  * This function is called with ringlock held. The function will return success
10667  * after it successfully submit the iocb to firmware or after adding to the
10668  * txq.
10669  **/
10670 static int
10671 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10672 			 struct lpfc_iocbq *piocb, uint32_t flag)
10673 {
10674 	struct lpfc_sglq *sglq;
10675 	union lpfc_wqe128 *wqe;
10676 	struct lpfc_queue *wq;
10677 	struct lpfc_sli_ring *pring;
10678 	u32 ulp_command = get_job_cmnd(phba, piocb);
10679 
10680 	/* Get the WQ */
10681 	if ((piocb->cmd_flag & LPFC_IO_FCP) ||
10682 	    (piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
10683 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10684 	} else {
10685 		wq = phba->sli4_hba.els_wq;
10686 	}
10687 
10688 	/* Get corresponding ring */
10689 	pring = wq->pring;
10690 
10691 	/*
10692 	 * The WQE can be either 64 or 128 bytes,
10693 	 */
10694 
10695 	lockdep_assert_held(&pring->ring_lock);
10696 	wqe = &piocb->wqe;
10697 	if (piocb->sli4_xritag == NO_XRI) {
10698 		if (ulp_command == CMD_ABORT_XRI_CX)
10699 			sglq = NULL;
10700 		else {
10701 			sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10702 			if (!sglq) {
10703 				if (!(flag & SLI_IOCB_RET_IOCB)) {
10704 					__lpfc_sli_ringtx_put(phba,
10705 							pring,
10706 							piocb);
10707 					return IOCB_SUCCESS;
10708 				} else {
10709 					return IOCB_BUSY;
10710 				}
10711 			}
10712 		}
10713 	} else if (piocb->cmd_flag &  LPFC_IO_FCP) {
10714 		/* These IO's already have an XRI and a mapped sgl. */
10715 		sglq = NULL;
10716 	}
10717 	else {
10718 		/*
10719 		 * This is a continuation of a commandi,(CX) so this
10720 		 * sglq is on the active list
10721 		 */
10722 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10723 		if (!sglq)
10724 			return IOCB_ERROR;
10725 	}
10726 
10727 	if (sglq) {
10728 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10729 		piocb->sli4_xritag = sglq->sli4_xritag;
10730 
10731 		/* ABTS sent by initiator to CT exchange, the
10732 		 * RX_ID field will be filled with the newly
10733 		 * allocated responder XRI.
10734 		 */
10735 		if (ulp_command == CMD_XMIT_BLS_RSP64_CX &&
10736 		    piocb->abort_bls == LPFC_ABTS_UNSOL_INT)
10737 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10738 			       piocb->sli4_xritag);
10739 
10740 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com,
10741 		       piocb->sli4_xritag);
10742 
10743 		if (lpfc_wqe_bpl2sgl(phba, piocb, sglq) == NO_XRI)
10744 			return IOCB_ERROR;
10745 	}
10746 
10747 	if (lpfc_sli4_wq_put(wq, wqe))
10748 		return IOCB_ERROR;
10749 
10750 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10751 
10752 	return 0;
10753 }
10754 
10755 /*
10756  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
10757  *
10758  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
10759  * or IOCB for sli-3  function.
10760  * pointer from the lpfc_hba struct.
10761  *
10762  * Return codes:
10763  * IOCB_ERROR - Error
10764  * IOCB_SUCCESS - Success
10765  * IOCB_BUSY - Busy
10766  **/
10767 int
10768 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
10769 		      struct lpfc_iocbq *piocb, uint32_t flag)
10770 {
10771 	return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
10772 }
10773 
10774 /*
10775  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10776  *
10777  * This routine wraps the actual lockless version for issusing IOCB function
10778  * pointer from the lpfc_hba struct.
10779  *
10780  * Return codes:
10781  * IOCB_ERROR - Error
10782  * IOCB_SUCCESS - Success
10783  * IOCB_BUSY - Busy
10784  **/
10785 int
10786 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10787 		struct lpfc_iocbq *piocb, uint32_t flag)
10788 {
10789 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10790 }
10791 
10792 static void
10793 __lpfc_sli_prep_els_req_rsp_s3(struct lpfc_iocbq *cmdiocbq,
10794 			       struct lpfc_vport *vport,
10795 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10796 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10797 {
10798 	struct lpfc_hba *phba = vport->phba;
10799 	IOCB_t *cmd;
10800 
10801 	cmd = &cmdiocbq->iocb;
10802 	memset(cmd, 0, sizeof(*cmd));
10803 
10804 	cmd->un.elsreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10805 	cmd->un.elsreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10806 	cmd->un.elsreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10807 
10808 	if (expect_rsp) {
10809 		cmd->un.elsreq64.bdl.bdeSize = (2 * sizeof(struct ulp_bde64));
10810 		cmd->un.elsreq64.remoteID = did; /* DID */
10811 		cmd->ulpCommand = CMD_ELS_REQUEST64_CR;
10812 		cmd->ulpTimeout = tmo;
10813 	} else {
10814 		cmd->un.elsreq64.bdl.bdeSize = sizeof(struct ulp_bde64);
10815 		cmd->un.genreq64.xmit_els_remoteID = did; /* DID */
10816 		cmd->ulpCommand = CMD_XMIT_ELS_RSP64_CX;
10817 		cmd->ulpPU = PARM_NPIV_DID;
10818 	}
10819 	cmd->ulpBdeCount = 1;
10820 	cmd->ulpLe = 1;
10821 	cmd->ulpClass = CLASS3;
10822 
10823 	/* If we have NPIV enabled, we want to send ELS traffic by VPI. */
10824 	if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) {
10825 		if (expect_rsp) {
10826 			cmd->un.elsreq64.myID = vport->fc_myDID;
10827 
10828 			/* For ELS_REQUEST64_CR, use the VPI by default */
10829 			cmd->ulpContext = phba->vpi_ids[vport->vpi];
10830 		}
10831 
10832 		cmd->ulpCt_h = 0;
10833 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10834 		if (elscmd == ELS_CMD_ECHO)
10835 			cmd->ulpCt_l = 0; /* context = invalid RPI */
10836 		else
10837 			cmd->ulpCt_l = 1; /* context = VPI */
10838 	}
10839 }
10840 
10841 static void
10842 __lpfc_sli_prep_els_req_rsp_s4(struct lpfc_iocbq *cmdiocbq,
10843 			       struct lpfc_vport *vport,
10844 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10845 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10846 {
10847 	struct lpfc_hba  *phba = vport->phba;
10848 	union lpfc_wqe128 *wqe;
10849 	struct ulp_bde64_le *bde;
10850 	u8 els_id;
10851 
10852 	wqe = &cmdiocbq->wqe;
10853 	memset(wqe, 0, sizeof(*wqe));
10854 
10855 	/* Word 0 - 2 BDE */
10856 	bde = (struct ulp_bde64_le *)&wqe->generic.bde;
10857 	bde->addr_low = cpu_to_le32(putPaddrLow(bmp->phys));
10858 	bde->addr_high = cpu_to_le32(putPaddrHigh(bmp->phys));
10859 	bde->type_size = cpu_to_le32(cmd_size);
10860 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10861 
10862 	if (expect_rsp) {
10863 		bf_set(wqe_cmnd, &wqe->els_req.wqe_com, CMD_ELS_REQUEST64_WQE);
10864 
10865 		/* Transfer length */
10866 		wqe->els_req.payload_len = cmd_size;
10867 		wqe->els_req.max_response_payload_len = FCELSSIZE;
10868 
10869 		/* DID */
10870 		bf_set(wqe_els_did, &wqe->els_req.wqe_dest, did);
10871 
10872 		/* Word 11 - ELS_ID */
10873 		switch (elscmd) {
10874 		case ELS_CMD_PLOGI:
10875 			els_id = LPFC_ELS_ID_PLOGI;
10876 			break;
10877 		case ELS_CMD_FLOGI:
10878 			els_id = LPFC_ELS_ID_FLOGI;
10879 			break;
10880 		case ELS_CMD_LOGO:
10881 			els_id = LPFC_ELS_ID_LOGO;
10882 			break;
10883 		case ELS_CMD_FDISC:
10884 			if (!vport->fc_myDID) {
10885 				els_id = LPFC_ELS_ID_FDISC;
10886 				break;
10887 			}
10888 			fallthrough;
10889 		default:
10890 			els_id = LPFC_ELS_ID_DEFAULT;
10891 			break;
10892 		}
10893 
10894 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
10895 	} else {
10896 		/* DID */
10897 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest, did);
10898 
10899 		/* Transfer length */
10900 		wqe->xmit_els_rsp.response_payload_len = cmd_size;
10901 
10902 		bf_set(wqe_cmnd, &wqe->xmit_els_rsp.wqe_com,
10903 		       CMD_XMIT_ELS_RSP64_WQE);
10904 	}
10905 
10906 	bf_set(wqe_tmo, &wqe->generic.wqe_com, tmo);
10907 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, cmdiocbq->iotag);
10908 	bf_set(wqe_class, &wqe->generic.wqe_com, CLASS3);
10909 
10910 	/* If we have NPIV enabled, we want to send ELS traffic by VPI.
10911 	 * For SLI4, since the driver controls VPIs we also want to include
10912 	 * all ELS pt2pt protocol traffic as well.
10913 	 */
10914 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) ||
10915 	    (vport->fc_flag & FC_PT2PT)) {
10916 		if (expect_rsp) {
10917 			bf_set(els_req64_sid, &wqe->els_req, vport->fc_myDID);
10918 
10919 			/* For ELS_REQUEST64_WQE, use the VPI by default */
10920 			bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10921 			       phba->vpi_ids[vport->vpi]);
10922 		}
10923 
10924 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10925 		if (elscmd == ELS_CMD_ECHO)
10926 			bf_set(wqe_ct, &wqe->generic.wqe_com, 0);
10927 		else
10928 			bf_set(wqe_ct, &wqe->generic.wqe_com, 1);
10929 	}
10930 }
10931 
10932 void
10933 lpfc_sli_prep_els_req_rsp(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
10934 			  struct lpfc_vport *vport, struct lpfc_dmabuf *bmp,
10935 			  u16 cmd_size, u32 did, u32 elscmd, u8 tmo,
10936 			  u8 expect_rsp)
10937 {
10938 	phba->__lpfc_sli_prep_els_req_rsp(cmdiocbq, vport, bmp, cmd_size, did,
10939 					  elscmd, tmo, expect_rsp);
10940 }
10941 
10942 static void
10943 __lpfc_sli_prep_gen_req_s3(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10944 			   u16 rpi, u32 num_entry, u8 tmo)
10945 {
10946 	IOCB_t *cmd;
10947 
10948 	cmd = &cmdiocbq->iocb;
10949 	memset(cmd, 0, sizeof(*cmd));
10950 
10951 	cmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10952 	cmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10953 	cmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10954 	cmd->un.genreq64.bdl.bdeSize = num_entry * sizeof(struct ulp_bde64);
10955 
10956 	cmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
10957 	cmd->un.genreq64.w5.hcsw.Type = FC_TYPE_CT;
10958 	cmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
10959 
10960 	cmd->ulpContext = rpi;
10961 	cmd->ulpClass = CLASS3;
10962 	cmd->ulpCommand = CMD_GEN_REQUEST64_CR;
10963 	cmd->ulpBdeCount = 1;
10964 	cmd->ulpLe = 1;
10965 	cmd->ulpOwner = OWN_CHIP;
10966 	cmd->ulpTimeout = tmo;
10967 }
10968 
10969 static void
10970 __lpfc_sli_prep_gen_req_s4(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10971 			   u16 rpi, u32 num_entry, u8 tmo)
10972 {
10973 	union lpfc_wqe128 *cmdwqe;
10974 	struct ulp_bde64_le *bde, *bpl;
10975 	u32 xmit_len = 0, total_len = 0, size, type, i;
10976 
10977 	cmdwqe = &cmdiocbq->wqe;
10978 	memset(cmdwqe, 0, sizeof(*cmdwqe));
10979 
10980 	/* Calculate total_len and xmit_len */
10981 	bpl = (struct ulp_bde64_le *)bmp->virt;
10982 	for (i = 0; i < num_entry; i++) {
10983 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10984 		total_len += size;
10985 	}
10986 	for (i = 0; i < num_entry; i++) {
10987 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10988 		type = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_TYPE_MASK;
10989 		if (type != ULP_BDE64_TYPE_BDE_64)
10990 			break;
10991 		xmit_len += size;
10992 	}
10993 
10994 	/* Words 0 - 2 */
10995 	bde = (struct ulp_bde64_le *)&cmdwqe->generic.bde;
10996 	bde->addr_low = bpl->addr_low;
10997 	bde->addr_high = bpl->addr_high;
10998 	bde->type_size = cpu_to_le32(xmit_len);
10999 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
11000 
11001 	/* Word 3 */
11002 	cmdwqe->gen_req.request_payload_len = xmit_len;
11003 
11004 	/* Word 5 */
11005 	bf_set(wqe_type, &cmdwqe->gen_req.wge_ctl, FC_TYPE_CT);
11006 	bf_set(wqe_rctl, &cmdwqe->gen_req.wge_ctl, FC_RCTL_DD_UNSOL_CTL);
11007 	bf_set(wqe_si, &cmdwqe->gen_req.wge_ctl, 1);
11008 	bf_set(wqe_la, &cmdwqe->gen_req.wge_ctl, 1);
11009 
11010 	/* Word 6 */
11011 	bf_set(wqe_ctxt_tag, &cmdwqe->gen_req.wqe_com, rpi);
11012 
11013 	/* Word 7 */
11014 	bf_set(wqe_tmo, &cmdwqe->gen_req.wqe_com, tmo);
11015 	bf_set(wqe_class, &cmdwqe->gen_req.wqe_com, CLASS3);
11016 	bf_set(wqe_cmnd, &cmdwqe->gen_req.wqe_com, CMD_GEN_REQUEST64_CR);
11017 	bf_set(wqe_ct, &cmdwqe->gen_req.wqe_com, SLI4_CT_RPI);
11018 
11019 	/* Word 12 */
11020 	cmdwqe->gen_req.max_response_payload_len = total_len - xmit_len;
11021 }
11022 
11023 void
11024 lpfc_sli_prep_gen_req(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11025 		      struct lpfc_dmabuf *bmp, u16 rpi, u32 num_entry, u8 tmo)
11026 {
11027 	phba->__lpfc_sli_prep_gen_req(cmdiocbq, bmp, rpi, num_entry, tmo);
11028 }
11029 
11030 static void
11031 __lpfc_sli_prep_xmit_seq64_s3(struct lpfc_iocbq *cmdiocbq,
11032 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11033 			      u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11034 {
11035 	IOCB_t *icmd;
11036 
11037 	icmd = &cmdiocbq->iocb;
11038 	memset(icmd, 0, sizeof(*icmd));
11039 
11040 	icmd->un.xseq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
11041 	icmd->un.xseq64.bdl.addrLow = putPaddrLow(bmp->phys);
11042 	icmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
11043 	icmd->un.xseq64.bdl.bdeSize = (num_entry * sizeof(struct ulp_bde64));
11044 	icmd->un.xseq64.w5.hcsw.Fctl = LA;
11045 	if (last_seq)
11046 		icmd->un.xseq64.w5.hcsw.Fctl |= LS;
11047 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
11048 	icmd->un.xseq64.w5.hcsw.Rctl = rctl;
11049 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
11050 
11051 	icmd->ulpBdeCount = 1;
11052 	icmd->ulpLe = 1;
11053 	icmd->ulpClass = CLASS3;
11054 
11055 	switch (cr_cx_cmd) {
11056 	case CMD_XMIT_SEQUENCE64_CR:
11057 		icmd->ulpContext = rpi;
11058 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CR;
11059 		break;
11060 	case CMD_XMIT_SEQUENCE64_CX:
11061 		icmd->ulpContext = ox_id;
11062 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CX;
11063 		break;
11064 	default:
11065 		break;
11066 	}
11067 }
11068 
11069 static void
11070 __lpfc_sli_prep_xmit_seq64_s4(struct lpfc_iocbq *cmdiocbq,
11071 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11072 			      u32 full_size, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11073 {
11074 	union lpfc_wqe128 *wqe;
11075 	struct ulp_bde64 *bpl;
11076 
11077 	wqe = &cmdiocbq->wqe;
11078 	memset(wqe, 0, sizeof(*wqe));
11079 
11080 	/* Words 0 - 2 */
11081 	bpl = (struct ulp_bde64 *)bmp->virt;
11082 	wqe->xmit_sequence.bde.addrHigh = bpl->addrHigh;
11083 	wqe->xmit_sequence.bde.addrLow = bpl->addrLow;
11084 	wqe->xmit_sequence.bde.tus.w = bpl->tus.w;
11085 
11086 	/* Word 5 */
11087 	bf_set(wqe_ls, &wqe->xmit_sequence.wge_ctl, last_seq);
11088 	bf_set(wqe_la, &wqe->xmit_sequence.wge_ctl, 1);
11089 	bf_set(wqe_dfctl, &wqe->xmit_sequence.wge_ctl, 0);
11090 	bf_set(wqe_rctl, &wqe->xmit_sequence.wge_ctl, rctl);
11091 	bf_set(wqe_type, &wqe->xmit_sequence.wge_ctl, FC_TYPE_CT);
11092 
11093 	/* Word 6 */
11094 	bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com, rpi);
11095 
11096 	bf_set(wqe_cmnd, &wqe->xmit_sequence.wqe_com,
11097 	       CMD_XMIT_SEQUENCE64_WQE);
11098 
11099 	/* Word 7 */
11100 	bf_set(wqe_class, &wqe->xmit_sequence.wqe_com, CLASS3);
11101 
11102 	/* Word 9 */
11103 	bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com, ox_id);
11104 
11105 	/* Word 12 */
11106 	if (cmdiocbq->cmd_flag & (LPFC_IO_LIBDFC | LPFC_IO_LOOPBACK))
11107 		wqe->xmit_sequence.xmit_len = full_size;
11108 	else
11109 		wqe->xmit_sequence.xmit_len =
11110 			wqe->xmit_sequence.bde.tus.f.bdeSize;
11111 }
11112 
11113 void
11114 lpfc_sli_prep_xmit_seq64(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11115 			 struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11116 			 u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11117 {
11118 	phba->__lpfc_sli_prep_xmit_seq64(cmdiocbq, bmp, rpi, ox_id, num_entry,
11119 					 rctl, last_seq, cr_cx_cmd);
11120 }
11121 
11122 static void
11123 __lpfc_sli_prep_abort_xri_s3(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11124 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11125 			     bool wqec)
11126 {
11127 	IOCB_t *icmd = NULL;
11128 
11129 	icmd = &cmdiocbq->iocb;
11130 	memset(icmd, 0, sizeof(*icmd));
11131 
11132 	/* Word 5 */
11133 	icmd->un.acxri.abortContextTag = ulp_context;
11134 	icmd->un.acxri.abortIoTag = iotag;
11135 
11136 	if (ia) {
11137 		/* Word 7 */
11138 		icmd->ulpCommand = CMD_CLOSE_XRI_CN;
11139 	} else {
11140 		/* Word 3 */
11141 		icmd->un.acxri.abortType = ABORT_TYPE_ABTS;
11142 
11143 		/* Word 7 */
11144 		icmd->ulpClass = ulp_class;
11145 		icmd->ulpCommand = CMD_ABORT_XRI_CN;
11146 	}
11147 
11148 	/* Word 7 */
11149 	icmd->ulpLe = 1;
11150 }
11151 
11152 static void
11153 __lpfc_sli_prep_abort_xri_s4(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11154 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11155 			     bool wqec)
11156 {
11157 	union lpfc_wqe128 *wqe;
11158 
11159 	wqe = &cmdiocbq->wqe;
11160 	memset(wqe, 0, sizeof(*wqe));
11161 
11162 	/* Word 3 */
11163 	bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
11164 	if (ia)
11165 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
11166 	else
11167 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
11168 
11169 	/* Word 7 */
11170 	bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_WQE);
11171 
11172 	/* Word 8 */
11173 	wqe->abort_cmd.wqe_com.abort_tag = ulp_context;
11174 
11175 	/* Word 9 */
11176 	bf_set(wqe_reqtag, &wqe->abort_cmd.wqe_com, iotag);
11177 
11178 	/* Word 10 */
11179 	bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
11180 
11181 	/* Word 11 */
11182 	if (wqec)
11183 		bf_set(wqe_wqec, &wqe->abort_cmd.wqe_com, 1);
11184 	bf_set(wqe_cqid, &wqe->abort_cmd.wqe_com, cqid);
11185 	bf_set(wqe_cmd_type, &wqe->abort_cmd.wqe_com, OTHER_COMMAND);
11186 }
11187 
11188 void
11189 lpfc_sli_prep_abort_xri(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11190 			u16 ulp_context, u16 iotag, u8 ulp_class, u16 cqid,
11191 			bool ia, bool wqec)
11192 {
11193 	phba->__lpfc_sli_prep_abort_xri(cmdiocbq, ulp_context, iotag, ulp_class,
11194 					cqid, ia, wqec);
11195 }
11196 
11197 /**
11198  * lpfc_sli_api_table_setup - Set up sli api function jump table
11199  * @phba: The hba struct for which this call is being executed.
11200  * @dev_grp: The HBA PCI-Device group number.
11201  *
11202  * This routine sets up the SLI interface API function jump table in @phba
11203  * struct.
11204  * Returns: 0 - success, -ENODEV - failure.
11205  **/
11206 int
11207 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
11208 {
11209 
11210 	switch (dev_grp) {
11211 	case LPFC_PCI_DEV_LP:
11212 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
11213 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
11214 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
11215 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s3;
11216 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s3;
11217 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s3;
11218 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s3;
11219 		break;
11220 	case LPFC_PCI_DEV_OC:
11221 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
11222 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
11223 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
11224 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s4;
11225 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s4;
11226 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s4;
11227 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s4;
11228 		break;
11229 	default:
11230 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11231 				"1419 Invalid HBA PCI-device group: 0x%x\n",
11232 				dev_grp);
11233 		return -ENODEV;
11234 	}
11235 	return 0;
11236 }
11237 
11238 /**
11239  * lpfc_sli4_calc_ring - Calculates which ring to use
11240  * @phba: Pointer to HBA context object.
11241  * @piocb: Pointer to command iocb.
11242  *
11243  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
11244  * hba_wqidx, thus we need to calculate the corresponding ring.
11245  * Since ABORTS must go on the same WQ of the command they are
11246  * aborting, we use command's hba_wqidx.
11247  */
11248 struct lpfc_sli_ring *
11249 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
11250 {
11251 	struct lpfc_io_buf *lpfc_cmd;
11252 
11253 	if (piocb->cmd_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
11254 		if (unlikely(!phba->sli4_hba.hdwq))
11255 			return NULL;
11256 		/*
11257 		 * for abort iocb hba_wqidx should already
11258 		 * be setup based on what work queue we used.
11259 		 */
11260 		if (!(piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
11261 			lpfc_cmd = piocb->io_buf;
11262 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
11263 		}
11264 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
11265 	} else {
11266 		if (unlikely(!phba->sli4_hba.els_wq))
11267 			return NULL;
11268 		piocb->hba_wqidx = 0;
11269 		return phba->sli4_hba.els_wq->pring;
11270 	}
11271 }
11272 
11273 inline void lpfc_sli4_poll_eq(struct lpfc_queue *eq)
11274 {
11275 	struct lpfc_hba *phba = eq->phba;
11276 
11277 	/*
11278 	 * Unlocking an irq is one of the entry point to check
11279 	 * for re-schedule, but we are good for io submission
11280 	 * path as midlayer does a get_cpu to glue us in. Flush
11281 	 * out the invalidate queue so we can see the updated
11282 	 * value for flag.
11283 	 */
11284 	smp_rmb();
11285 
11286 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
11287 		/* We will not likely get the completion for the caller
11288 		 * during this iteration but i guess that's fine.
11289 		 * Future io's coming on this eq should be able to
11290 		 * pick it up.  As for the case of single io's, they
11291 		 * will be handled through a sched from polling timer
11292 		 * function which is currently triggered every 1msec.
11293 		 */
11294 		lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM);
11295 }
11296 
11297 /**
11298  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
11299  * @phba: Pointer to HBA context object.
11300  * @ring_number: Ring number
11301  * @piocb: Pointer to command iocb.
11302  * @flag: Flag indicating if this command can be put into txq.
11303  *
11304  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
11305  * function. This function gets the hbalock and calls
11306  * __lpfc_sli_issue_iocb function and will return the error returned
11307  * by __lpfc_sli_issue_iocb function. This wrapper is used by
11308  * functions which do not hold hbalock.
11309  **/
11310 int
11311 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
11312 		    struct lpfc_iocbq *piocb, uint32_t flag)
11313 {
11314 	struct lpfc_sli_ring *pring;
11315 	struct lpfc_queue *eq;
11316 	unsigned long iflags;
11317 	int rc;
11318 
11319 	/* If the PCI channel is in offline state, do not post iocbs. */
11320 	if (unlikely(pci_channel_offline(phba->pcidev)))
11321 		return IOCB_ERROR;
11322 
11323 	if (phba->sli_rev == LPFC_SLI_REV4) {
11324 		lpfc_sli_prep_wqe(phba, piocb);
11325 
11326 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
11327 
11328 		pring = lpfc_sli4_calc_ring(phba, piocb);
11329 		if (unlikely(pring == NULL))
11330 			return IOCB_ERROR;
11331 
11332 		spin_lock_irqsave(&pring->ring_lock, iflags);
11333 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11334 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11335 
11336 		lpfc_sli4_poll_eq(eq);
11337 	} else {
11338 		/* For now, SLI2/3 will still use hbalock */
11339 		spin_lock_irqsave(&phba->hbalock, iflags);
11340 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11341 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11342 	}
11343 	return rc;
11344 }
11345 
11346 /**
11347  * lpfc_extra_ring_setup - Extra ring setup function
11348  * @phba: Pointer to HBA context object.
11349  *
11350  * This function is called while driver attaches with the
11351  * HBA to setup the extra ring. The extra ring is used
11352  * only when driver needs to support target mode functionality
11353  * or IP over FC functionalities.
11354  *
11355  * This function is called with no lock held. SLI3 only.
11356  **/
11357 static int
11358 lpfc_extra_ring_setup( struct lpfc_hba *phba)
11359 {
11360 	struct lpfc_sli *psli;
11361 	struct lpfc_sli_ring *pring;
11362 
11363 	psli = &phba->sli;
11364 
11365 	/* Adjust cmd/rsp ring iocb entries more evenly */
11366 
11367 	/* Take some away from the FCP ring */
11368 	pring = &psli->sli3_ring[LPFC_FCP_RING];
11369 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11370 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11371 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11372 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11373 
11374 	/* and give them to the extra ring */
11375 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
11376 
11377 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11378 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11379 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11380 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11381 
11382 	/* Setup default profile for this ring */
11383 	pring->iotag_max = 4096;
11384 	pring->num_mask = 1;
11385 	pring->prt[0].profile = 0;      /* Mask 0 */
11386 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
11387 	pring->prt[0].type = phba->cfg_multi_ring_type;
11388 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
11389 	return 0;
11390 }
11391 
11392 static void
11393 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
11394 			     struct lpfc_nodelist *ndlp)
11395 {
11396 	unsigned long iflags;
11397 	struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
11398 
11399 	spin_lock_irqsave(&phba->hbalock, iflags);
11400 	if (!list_empty(&evtp->evt_listp)) {
11401 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11402 		return;
11403 	}
11404 
11405 	/* Incrementing the reference count until the queued work is done. */
11406 	evtp->evt_arg1  = lpfc_nlp_get(ndlp);
11407 	if (!evtp->evt_arg1) {
11408 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11409 		return;
11410 	}
11411 	evtp->evt = LPFC_EVT_RECOVER_PORT;
11412 	list_add_tail(&evtp->evt_listp, &phba->work_list);
11413 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11414 
11415 	lpfc_worker_wake_up(phba);
11416 }
11417 
11418 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
11419  * @phba: Pointer to HBA context object.
11420  * @iocbq: Pointer to iocb object.
11421  *
11422  * The async_event handler calls this routine when it receives
11423  * an ASYNC_STATUS_CN event from the port.  The port generates
11424  * this event when an Abort Sequence request to an rport fails
11425  * twice in succession.  The abort could be originated by the
11426  * driver or by the port.  The ABTS could have been for an ELS
11427  * or FCP IO.  The port only generates this event when an ABTS
11428  * fails to complete after one retry.
11429  */
11430 static void
11431 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
11432 			  struct lpfc_iocbq *iocbq)
11433 {
11434 	struct lpfc_nodelist *ndlp = NULL;
11435 	uint16_t rpi = 0, vpi = 0;
11436 	struct lpfc_vport *vport = NULL;
11437 
11438 	/* The rpi in the ulpContext is vport-sensitive. */
11439 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
11440 	rpi = iocbq->iocb.ulpContext;
11441 
11442 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11443 			"3092 Port generated ABTS async event "
11444 			"on vpi %d rpi %d status 0x%x\n",
11445 			vpi, rpi, iocbq->iocb.ulpStatus);
11446 
11447 	vport = lpfc_find_vport_by_vpid(phba, vpi);
11448 	if (!vport)
11449 		goto err_exit;
11450 	ndlp = lpfc_findnode_rpi(vport, rpi);
11451 	if (!ndlp)
11452 		goto err_exit;
11453 
11454 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
11455 		lpfc_sli_abts_recover_port(vport, ndlp);
11456 	return;
11457 
11458  err_exit:
11459 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11460 			"3095 Event Context not found, no "
11461 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
11462 			vpi, rpi, iocbq->iocb.ulpStatus,
11463 			iocbq->iocb.ulpContext);
11464 }
11465 
11466 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
11467  * @phba: pointer to HBA context object.
11468  * @ndlp: nodelist pointer for the impacted rport.
11469  * @axri: pointer to the wcqe containing the failed exchange.
11470  *
11471  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
11472  * port.  The port generates this event when an abort exchange request to an
11473  * rport fails twice in succession with no reply.  The abort could be originated
11474  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
11475  */
11476 void
11477 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
11478 			   struct lpfc_nodelist *ndlp,
11479 			   struct sli4_wcqe_xri_aborted *axri)
11480 {
11481 	uint32_t ext_status = 0;
11482 
11483 	if (!ndlp) {
11484 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11485 				"3115 Node Context not found, driver "
11486 				"ignoring abts err event\n");
11487 		return;
11488 	}
11489 
11490 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11491 			"3116 Port generated FCP XRI ABORT event on "
11492 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
11493 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
11494 			bf_get(lpfc_wcqe_xa_xri, axri),
11495 			bf_get(lpfc_wcqe_xa_status, axri),
11496 			axri->parameter);
11497 
11498 	/*
11499 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
11500 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
11501 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
11502 	 */
11503 	ext_status = axri->parameter & IOERR_PARAM_MASK;
11504 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
11505 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
11506 		lpfc_sli_post_recovery_event(phba, ndlp);
11507 }
11508 
11509 /**
11510  * lpfc_sli_async_event_handler - ASYNC iocb handler function
11511  * @phba: Pointer to HBA context object.
11512  * @pring: Pointer to driver SLI ring object.
11513  * @iocbq: Pointer to iocb object.
11514  *
11515  * This function is called by the slow ring event handler
11516  * function when there is an ASYNC event iocb in the ring.
11517  * This function is called with no lock held.
11518  * Currently this function handles only temperature related
11519  * ASYNC events. The function decodes the temperature sensor
11520  * event message and posts events for the management applications.
11521  **/
11522 static void
11523 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
11524 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
11525 {
11526 	IOCB_t *icmd;
11527 	uint16_t evt_code;
11528 	struct temp_event temp_event_data;
11529 	struct Scsi_Host *shost;
11530 	uint32_t *iocb_w;
11531 
11532 	icmd = &iocbq->iocb;
11533 	evt_code = icmd->un.asyncstat.evt_code;
11534 
11535 	switch (evt_code) {
11536 	case ASYNC_TEMP_WARN:
11537 	case ASYNC_TEMP_SAFE:
11538 		temp_event_data.data = (uint32_t) icmd->ulpContext;
11539 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
11540 		if (evt_code == ASYNC_TEMP_WARN) {
11541 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
11542 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11543 				"0347 Adapter is very hot, please take "
11544 				"corrective action. temperature : %d Celsius\n",
11545 				(uint32_t) icmd->ulpContext);
11546 		} else {
11547 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
11548 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11549 				"0340 Adapter temperature is OK now. "
11550 				"temperature : %d Celsius\n",
11551 				(uint32_t) icmd->ulpContext);
11552 		}
11553 
11554 		/* Send temperature change event to applications */
11555 		shost = lpfc_shost_from_vport(phba->pport);
11556 		fc_host_post_vendor_event(shost, fc_get_event_number(),
11557 			sizeof(temp_event_data), (char *) &temp_event_data,
11558 			LPFC_NL_VENDOR_ID);
11559 		break;
11560 	case ASYNC_STATUS_CN:
11561 		lpfc_sli_abts_err_handler(phba, iocbq);
11562 		break;
11563 	default:
11564 		iocb_w = (uint32_t *) icmd;
11565 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11566 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
11567 			" evt_code 0x%x\n"
11568 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
11569 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
11570 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
11571 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
11572 			pring->ringno, icmd->un.asyncstat.evt_code,
11573 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
11574 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
11575 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
11576 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
11577 
11578 		break;
11579 	}
11580 }
11581 
11582 
11583 /**
11584  * lpfc_sli4_setup - SLI ring setup function
11585  * @phba: Pointer to HBA context object.
11586  *
11587  * lpfc_sli_setup sets up rings of the SLI interface with
11588  * number of iocbs per ring and iotags. This function is
11589  * called while driver attach to the HBA and before the
11590  * interrupts are enabled. So there is no need for locking.
11591  *
11592  * This function always returns 0.
11593  **/
11594 int
11595 lpfc_sli4_setup(struct lpfc_hba *phba)
11596 {
11597 	struct lpfc_sli_ring *pring;
11598 
11599 	pring = phba->sli4_hba.els_wq->pring;
11600 	pring->num_mask = LPFC_MAX_RING_MASK;
11601 	pring->prt[0].profile = 0;	/* Mask 0 */
11602 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11603 	pring->prt[0].type = FC_TYPE_ELS;
11604 	pring->prt[0].lpfc_sli_rcv_unsol_event =
11605 	    lpfc_els_unsol_event;
11606 	pring->prt[1].profile = 0;	/* Mask 1 */
11607 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
11608 	pring->prt[1].type = FC_TYPE_ELS;
11609 	pring->prt[1].lpfc_sli_rcv_unsol_event =
11610 	    lpfc_els_unsol_event;
11611 	pring->prt[2].profile = 0;	/* Mask 2 */
11612 	/* NameServer Inquiry */
11613 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11614 	/* NameServer */
11615 	pring->prt[2].type = FC_TYPE_CT;
11616 	pring->prt[2].lpfc_sli_rcv_unsol_event =
11617 	    lpfc_ct_unsol_event;
11618 	pring->prt[3].profile = 0;	/* Mask 3 */
11619 	/* NameServer response */
11620 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11621 	/* NameServer */
11622 	pring->prt[3].type = FC_TYPE_CT;
11623 	pring->prt[3].lpfc_sli_rcv_unsol_event =
11624 	    lpfc_ct_unsol_event;
11625 	return 0;
11626 }
11627 
11628 /**
11629  * lpfc_sli_setup - SLI ring setup function
11630  * @phba: Pointer to HBA context object.
11631  *
11632  * lpfc_sli_setup sets up rings of the SLI interface with
11633  * number of iocbs per ring and iotags. This function is
11634  * called while driver attach to the HBA and before the
11635  * interrupts are enabled. So there is no need for locking.
11636  *
11637  * This function always returns 0. SLI3 only.
11638  **/
11639 int
11640 lpfc_sli_setup(struct lpfc_hba *phba)
11641 {
11642 	int i, totiocbsize = 0;
11643 	struct lpfc_sli *psli = &phba->sli;
11644 	struct lpfc_sli_ring *pring;
11645 
11646 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
11647 	psli->sli_flag = 0;
11648 
11649 	psli->iocbq_lookup = NULL;
11650 	psli->iocbq_lookup_len = 0;
11651 	psli->last_iotag = 0;
11652 
11653 	for (i = 0; i < psli->num_rings; i++) {
11654 		pring = &psli->sli3_ring[i];
11655 		switch (i) {
11656 		case LPFC_FCP_RING:	/* ring 0 - FCP */
11657 			/* numCiocb and numRiocb are used in config_port */
11658 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
11659 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
11660 			pring->sli.sli3.numCiocb +=
11661 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11662 			pring->sli.sli3.numRiocb +=
11663 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11664 			pring->sli.sli3.numCiocb +=
11665 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11666 			pring->sli.sli3.numRiocb +=
11667 				SLI2_IOCB_RSP_R3XTRA_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_ctr = 0;
11675 			pring->iotag_max =
11676 			    (phba->cfg_hba_queue_depth * 2);
11677 			pring->fast_iotag = pring->iotag_max;
11678 			pring->num_mask = 0;
11679 			break;
11680 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
11681 			/* numCiocb and numRiocb are used in config_port */
11682 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
11683 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
11684 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11685 							SLI3_IOCB_CMD_SIZE :
11686 							SLI2_IOCB_CMD_SIZE;
11687 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11688 							SLI3_IOCB_RSP_SIZE :
11689 							SLI2_IOCB_RSP_SIZE;
11690 			pring->iotag_max = phba->cfg_hba_queue_depth;
11691 			pring->num_mask = 0;
11692 			break;
11693 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
11694 			/* numCiocb and numRiocb are used in config_port */
11695 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
11696 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
11697 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11698 							SLI3_IOCB_CMD_SIZE :
11699 							SLI2_IOCB_CMD_SIZE;
11700 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11701 							SLI3_IOCB_RSP_SIZE :
11702 							SLI2_IOCB_RSP_SIZE;
11703 			pring->fast_iotag = 0;
11704 			pring->iotag_ctr = 0;
11705 			pring->iotag_max = 4096;
11706 			pring->lpfc_sli_rcv_async_status =
11707 				lpfc_sli_async_event_handler;
11708 			pring->num_mask = LPFC_MAX_RING_MASK;
11709 			pring->prt[0].profile = 0;	/* Mask 0 */
11710 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11711 			pring->prt[0].type = FC_TYPE_ELS;
11712 			pring->prt[0].lpfc_sli_rcv_unsol_event =
11713 			    lpfc_els_unsol_event;
11714 			pring->prt[1].profile = 0;	/* Mask 1 */
11715 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
11716 			pring->prt[1].type = FC_TYPE_ELS;
11717 			pring->prt[1].lpfc_sli_rcv_unsol_event =
11718 			    lpfc_els_unsol_event;
11719 			pring->prt[2].profile = 0;	/* Mask 2 */
11720 			/* NameServer Inquiry */
11721 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11722 			/* NameServer */
11723 			pring->prt[2].type = FC_TYPE_CT;
11724 			pring->prt[2].lpfc_sli_rcv_unsol_event =
11725 			    lpfc_ct_unsol_event;
11726 			pring->prt[3].profile = 0;	/* Mask 3 */
11727 			/* NameServer response */
11728 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11729 			/* NameServer */
11730 			pring->prt[3].type = FC_TYPE_CT;
11731 			pring->prt[3].lpfc_sli_rcv_unsol_event =
11732 			    lpfc_ct_unsol_event;
11733 			break;
11734 		}
11735 		totiocbsize += (pring->sli.sli3.numCiocb *
11736 			pring->sli.sli3.sizeCiocb) +
11737 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
11738 	}
11739 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
11740 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
11741 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
11742 		       "SLI2 SLIM Data: x%x x%lx\n",
11743 		       phba->brd_no, totiocbsize,
11744 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
11745 	}
11746 	if (phba->cfg_multi_ring_support == 2)
11747 		lpfc_extra_ring_setup(phba);
11748 
11749 	return 0;
11750 }
11751 
11752 /**
11753  * lpfc_sli4_queue_init - Queue initialization function
11754  * @phba: Pointer to HBA context object.
11755  *
11756  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
11757  * ring. This function also initializes ring indices of each ring.
11758  * This function is called during the initialization of the SLI
11759  * interface of an HBA.
11760  * This function is called with no lock held and always returns
11761  * 1.
11762  **/
11763 void
11764 lpfc_sli4_queue_init(struct lpfc_hba *phba)
11765 {
11766 	struct lpfc_sli *psli;
11767 	struct lpfc_sli_ring *pring;
11768 	int i;
11769 
11770 	psli = &phba->sli;
11771 	spin_lock_irq(&phba->hbalock);
11772 	INIT_LIST_HEAD(&psli->mboxq);
11773 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11774 	/* Initialize list headers for txq and txcmplq as double linked lists */
11775 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
11776 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
11777 		pring->flag = 0;
11778 		pring->ringno = LPFC_FCP_RING;
11779 		pring->txcmplq_cnt = 0;
11780 		INIT_LIST_HEAD(&pring->txq);
11781 		INIT_LIST_HEAD(&pring->txcmplq);
11782 		INIT_LIST_HEAD(&pring->iocb_continueq);
11783 		spin_lock_init(&pring->ring_lock);
11784 	}
11785 	pring = phba->sli4_hba.els_wq->pring;
11786 	pring->flag = 0;
11787 	pring->ringno = LPFC_ELS_RING;
11788 	pring->txcmplq_cnt = 0;
11789 	INIT_LIST_HEAD(&pring->txq);
11790 	INIT_LIST_HEAD(&pring->txcmplq);
11791 	INIT_LIST_HEAD(&pring->iocb_continueq);
11792 	spin_lock_init(&pring->ring_lock);
11793 
11794 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11795 		pring = phba->sli4_hba.nvmels_wq->pring;
11796 		pring->flag = 0;
11797 		pring->ringno = LPFC_ELS_RING;
11798 		pring->txcmplq_cnt = 0;
11799 		INIT_LIST_HEAD(&pring->txq);
11800 		INIT_LIST_HEAD(&pring->txcmplq);
11801 		INIT_LIST_HEAD(&pring->iocb_continueq);
11802 		spin_lock_init(&pring->ring_lock);
11803 	}
11804 
11805 	spin_unlock_irq(&phba->hbalock);
11806 }
11807 
11808 /**
11809  * lpfc_sli_queue_init - Queue initialization function
11810  * @phba: Pointer to HBA context object.
11811  *
11812  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11813  * ring. This function also initializes ring indices of each ring.
11814  * This function is called during the initialization of the SLI
11815  * interface of an HBA.
11816  * This function is called with no lock held and always returns
11817  * 1.
11818  **/
11819 void
11820 lpfc_sli_queue_init(struct lpfc_hba *phba)
11821 {
11822 	struct lpfc_sli *psli;
11823 	struct lpfc_sli_ring *pring;
11824 	int i;
11825 
11826 	psli = &phba->sli;
11827 	spin_lock_irq(&phba->hbalock);
11828 	INIT_LIST_HEAD(&psli->mboxq);
11829 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11830 	/* Initialize list headers for txq and txcmplq as double linked lists */
11831 	for (i = 0; i < psli->num_rings; i++) {
11832 		pring = &psli->sli3_ring[i];
11833 		pring->ringno = i;
11834 		pring->sli.sli3.next_cmdidx  = 0;
11835 		pring->sli.sli3.local_getidx = 0;
11836 		pring->sli.sli3.cmdidx = 0;
11837 		INIT_LIST_HEAD(&pring->iocb_continueq);
11838 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11839 		INIT_LIST_HEAD(&pring->postbufq);
11840 		pring->flag = 0;
11841 		INIT_LIST_HEAD(&pring->txq);
11842 		INIT_LIST_HEAD(&pring->txcmplq);
11843 		spin_lock_init(&pring->ring_lock);
11844 	}
11845 	spin_unlock_irq(&phba->hbalock);
11846 }
11847 
11848 /**
11849  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11850  * @phba: Pointer to HBA context object.
11851  *
11852  * This routine flushes the mailbox command subsystem. It will unconditionally
11853  * flush all the mailbox commands in the three possible stages in the mailbox
11854  * command sub-system: pending mailbox command queue; the outstanding mailbox
11855  * command; and completed mailbox command queue. It is caller's responsibility
11856  * to make sure that the driver is in the proper state to flush the mailbox
11857  * command sub-system. Namely, the posting of mailbox commands into the
11858  * pending mailbox command queue from the various clients must be stopped;
11859  * either the HBA is in a state that it will never works on the outstanding
11860  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11861  * mailbox command has been completed.
11862  **/
11863 static void
11864 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11865 {
11866 	LIST_HEAD(completions);
11867 	struct lpfc_sli *psli = &phba->sli;
11868 	LPFC_MBOXQ_t *pmb;
11869 	unsigned long iflag;
11870 
11871 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11872 	local_bh_disable();
11873 
11874 	/* Flush all the mailbox commands in the mbox system */
11875 	spin_lock_irqsave(&phba->hbalock, iflag);
11876 
11877 	/* The pending mailbox command queue */
11878 	list_splice_init(&phba->sli.mboxq, &completions);
11879 	/* The outstanding active mailbox command */
11880 	if (psli->mbox_active) {
11881 		list_add_tail(&psli->mbox_active->list, &completions);
11882 		psli->mbox_active = NULL;
11883 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11884 	}
11885 	/* The completed mailbox command queue */
11886 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11887 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11888 
11889 	/* Enable softirqs again, done with phba->hbalock */
11890 	local_bh_enable();
11891 
11892 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11893 	while (!list_empty(&completions)) {
11894 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11895 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11896 		if (pmb->mbox_cmpl)
11897 			pmb->mbox_cmpl(phba, pmb);
11898 	}
11899 }
11900 
11901 /**
11902  * lpfc_sli_host_down - Vport cleanup function
11903  * @vport: Pointer to virtual port object.
11904  *
11905  * lpfc_sli_host_down is called to clean up the resources
11906  * associated with a vport before destroying virtual
11907  * port data structures.
11908  * This function does following operations:
11909  * - Free discovery resources associated with this virtual
11910  *   port.
11911  * - Free iocbs associated with this virtual port in
11912  *   the txq.
11913  * - Send abort for all iocb commands associated with this
11914  *   vport in txcmplq.
11915  *
11916  * This function is called with no lock held and always returns 1.
11917  **/
11918 int
11919 lpfc_sli_host_down(struct lpfc_vport *vport)
11920 {
11921 	LIST_HEAD(completions);
11922 	struct lpfc_hba *phba = vport->phba;
11923 	struct lpfc_sli *psli = &phba->sli;
11924 	struct lpfc_queue *qp = NULL;
11925 	struct lpfc_sli_ring *pring;
11926 	struct lpfc_iocbq *iocb, *next_iocb;
11927 	int i;
11928 	unsigned long flags = 0;
11929 	uint16_t prev_pring_flag;
11930 
11931 	lpfc_cleanup_discovery_resources(vport);
11932 
11933 	spin_lock_irqsave(&phba->hbalock, flags);
11934 
11935 	/*
11936 	 * Error everything on the txq since these iocbs
11937 	 * have not been given to the FW yet.
11938 	 * Also issue ABTS for everything on the txcmplq
11939 	 */
11940 	if (phba->sli_rev != LPFC_SLI_REV4) {
11941 		for (i = 0; i < psli->num_rings; i++) {
11942 			pring = &psli->sli3_ring[i];
11943 			prev_pring_flag = pring->flag;
11944 			/* Only slow rings */
11945 			if (pring->ringno == LPFC_ELS_RING) {
11946 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11947 				/* Set the lpfc data pending flag */
11948 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11949 			}
11950 			list_for_each_entry_safe(iocb, next_iocb,
11951 						 &pring->txq, list) {
11952 				if (iocb->vport != vport)
11953 					continue;
11954 				list_move_tail(&iocb->list, &completions);
11955 			}
11956 			list_for_each_entry_safe(iocb, next_iocb,
11957 						 &pring->txcmplq, list) {
11958 				if (iocb->vport != vport)
11959 					continue;
11960 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11961 							   NULL);
11962 			}
11963 			pring->flag = prev_pring_flag;
11964 		}
11965 	} else {
11966 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11967 			pring = qp->pring;
11968 			if (!pring)
11969 				continue;
11970 			if (pring == phba->sli4_hba.els_wq->pring) {
11971 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11972 				/* Set the lpfc data pending flag */
11973 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11974 			}
11975 			prev_pring_flag = pring->flag;
11976 			spin_lock(&pring->ring_lock);
11977 			list_for_each_entry_safe(iocb, next_iocb,
11978 						 &pring->txq, list) {
11979 				if (iocb->vport != vport)
11980 					continue;
11981 				list_move_tail(&iocb->list, &completions);
11982 			}
11983 			spin_unlock(&pring->ring_lock);
11984 			list_for_each_entry_safe(iocb, next_iocb,
11985 						 &pring->txcmplq, list) {
11986 				if (iocb->vport != vport)
11987 					continue;
11988 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11989 							   NULL);
11990 			}
11991 			pring->flag = prev_pring_flag;
11992 		}
11993 	}
11994 	spin_unlock_irqrestore(&phba->hbalock, flags);
11995 
11996 	/* Make sure HBA is alive */
11997 	lpfc_issue_hb_tmo(phba);
11998 
11999 	/* Cancel all the IOCBs from the completions list */
12000 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
12001 			      IOERR_SLI_DOWN);
12002 	return 1;
12003 }
12004 
12005 /**
12006  * lpfc_sli_hba_down - Resource cleanup function for the HBA
12007  * @phba: Pointer to HBA context object.
12008  *
12009  * This function cleans up all iocb, buffers, mailbox commands
12010  * while shutting down the HBA. This function is called with no
12011  * lock held and always returns 1.
12012  * This function does the following to cleanup driver resources:
12013  * - Free discovery resources for each virtual port
12014  * - Cleanup any pending fabric iocbs
12015  * - Iterate through the iocb txq and free each entry
12016  *   in the list.
12017  * - Free up any buffer posted to the HBA
12018  * - Free mailbox commands in the mailbox queue.
12019  **/
12020 int
12021 lpfc_sli_hba_down(struct lpfc_hba *phba)
12022 {
12023 	LIST_HEAD(completions);
12024 	struct lpfc_sli *psli = &phba->sli;
12025 	struct lpfc_queue *qp = NULL;
12026 	struct lpfc_sli_ring *pring;
12027 	struct lpfc_dmabuf *buf_ptr;
12028 	unsigned long flags = 0;
12029 	int i;
12030 
12031 	/* Shutdown the mailbox command sub-system */
12032 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
12033 
12034 	lpfc_hba_down_prep(phba);
12035 
12036 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12037 	local_bh_disable();
12038 
12039 	lpfc_fabric_abort_hba(phba);
12040 
12041 	spin_lock_irqsave(&phba->hbalock, flags);
12042 
12043 	/*
12044 	 * Error everything on the txq since these iocbs
12045 	 * have not been given to the FW yet.
12046 	 */
12047 	if (phba->sli_rev != LPFC_SLI_REV4) {
12048 		for (i = 0; i < psli->num_rings; i++) {
12049 			pring = &psli->sli3_ring[i];
12050 			/* Only slow rings */
12051 			if (pring->ringno == LPFC_ELS_RING) {
12052 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12053 				/* Set the lpfc data pending flag */
12054 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12055 			}
12056 			list_splice_init(&pring->txq, &completions);
12057 		}
12058 	} else {
12059 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12060 			pring = qp->pring;
12061 			if (!pring)
12062 				continue;
12063 			spin_lock(&pring->ring_lock);
12064 			list_splice_init(&pring->txq, &completions);
12065 			spin_unlock(&pring->ring_lock);
12066 			if (pring == phba->sli4_hba.els_wq->pring) {
12067 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12068 				/* Set the lpfc data pending flag */
12069 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12070 			}
12071 		}
12072 	}
12073 	spin_unlock_irqrestore(&phba->hbalock, flags);
12074 
12075 	/* Cancel all the IOCBs from the completions list */
12076 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
12077 			      IOERR_SLI_DOWN);
12078 
12079 	spin_lock_irqsave(&phba->hbalock, flags);
12080 	list_splice_init(&phba->elsbuf, &completions);
12081 	phba->elsbuf_cnt = 0;
12082 	phba->elsbuf_prev_cnt = 0;
12083 	spin_unlock_irqrestore(&phba->hbalock, flags);
12084 
12085 	while (!list_empty(&completions)) {
12086 		list_remove_head(&completions, buf_ptr,
12087 			struct lpfc_dmabuf, list);
12088 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
12089 		kfree(buf_ptr);
12090 	}
12091 
12092 	/* Enable softirqs again, done with phba->hbalock */
12093 	local_bh_enable();
12094 
12095 	/* Return any active mbox cmds */
12096 	del_timer_sync(&psli->mbox_tmo);
12097 
12098 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
12099 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
12100 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
12101 
12102 	return 1;
12103 }
12104 
12105 /**
12106  * lpfc_sli_pcimem_bcopy - SLI memory copy function
12107  * @srcp: Source memory pointer.
12108  * @destp: Destination memory pointer.
12109  * @cnt: Number of words required to be copied.
12110  *
12111  * This function is used for copying data between driver memory
12112  * and the SLI memory. This function also changes the endianness
12113  * of each word if native endianness is different from SLI
12114  * endianness. This function can be called with or without
12115  * lock.
12116  **/
12117 void
12118 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
12119 {
12120 	uint32_t *src = srcp;
12121 	uint32_t *dest = destp;
12122 	uint32_t ldata;
12123 	int i;
12124 
12125 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
12126 		ldata = *src;
12127 		ldata = le32_to_cpu(ldata);
12128 		*dest = ldata;
12129 		src++;
12130 		dest++;
12131 	}
12132 }
12133 
12134 
12135 /**
12136  * lpfc_sli_bemem_bcopy - SLI memory copy function
12137  * @srcp: Source memory pointer.
12138  * @destp: Destination memory pointer.
12139  * @cnt: Number of words required to be copied.
12140  *
12141  * This function is used for copying data between a data structure
12142  * with big endian representation to local endianness.
12143  * This function can be called with or without lock.
12144  **/
12145 void
12146 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
12147 {
12148 	uint32_t *src = srcp;
12149 	uint32_t *dest = destp;
12150 	uint32_t ldata;
12151 	int i;
12152 
12153 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
12154 		ldata = *src;
12155 		ldata = be32_to_cpu(ldata);
12156 		*dest = ldata;
12157 		src++;
12158 		dest++;
12159 	}
12160 }
12161 
12162 /**
12163  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
12164  * @phba: Pointer to HBA context object.
12165  * @pring: Pointer to driver SLI ring object.
12166  * @mp: Pointer to driver buffer object.
12167  *
12168  * This function is called with no lock held.
12169  * It always return zero after adding the buffer to the postbufq
12170  * buffer list.
12171  **/
12172 int
12173 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12174 			 struct lpfc_dmabuf *mp)
12175 {
12176 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
12177 	   later */
12178 	spin_lock_irq(&phba->hbalock);
12179 	list_add_tail(&mp->list, &pring->postbufq);
12180 	pring->postbufq_cnt++;
12181 	spin_unlock_irq(&phba->hbalock);
12182 	return 0;
12183 }
12184 
12185 /**
12186  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
12187  * @phba: Pointer to HBA context object.
12188  *
12189  * When HBQ is enabled, buffers are searched based on tags. This function
12190  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
12191  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
12192  * does not conflict with tags of buffer posted for unsolicited events.
12193  * The function returns the allocated tag. The function is called with
12194  * no locks held.
12195  **/
12196 uint32_t
12197 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
12198 {
12199 	spin_lock_irq(&phba->hbalock);
12200 	phba->buffer_tag_count++;
12201 	/*
12202 	 * Always set the QUE_BUFTAG_BIT to distiguish between
12203 	 * a tag assigned by HBQ.
12204 	 */
12205 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
12206 	spin_unlock_irq(&phba->hbalock);
12207 	return phba->buffer_tag_count;
12208 }
12209 
12210 /**
12211  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
12212  * @phba: Pointer to HBA context object.
12213  * @pring: Pointer to driver SLI ring object.
12214  * @tag: Buffer tag.
12215  *
12216  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
12217  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
12218  * iocb is posted to the response ring with the tag of the buffer.
12219  * This function searches the pring->postbufq list using the tag
12220  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
12221  * iocb. If the buffer is found then lpfc_dmabuf object of the
12222  * buffer is returned to the caller else NULL is returned.
12223  * This function is called with no lock held.
12224  **/
12225 struct lpfc_dmabuf *
12226 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12227 			uint32_t tag)
12228 {
12229 	struct lpfc_dmabuf *mp, *next_mp;
12230 	struct list_head *slp = &pring->postbufq;
12231 
12232 	/* Search postbufq, from the beginning, looking for a match on tag */
12233 	spin_lock_irq(&phba->hbalock);
12234 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12235 		if (mp->buffer_tag == tag) {
12236 			list_del_init(&mp->list);
12237 			pring->postbufq_cnt--;
12238 			spin_unlock_irq(&phba->hbalock);
12239 			return mp;
12240 		}
12241 	}
12242 
12243 	spin_unlock_irq(&phba->hbalock);
12244 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12245 			"0402 Cannot find virtual addr for buffer tag on "
12246 			"ring %d Data x%lx x%px x%px x%x\n",
12247 			pring->ringno, (unsigned long) tag,
12248 			slp->next, slp->prev, pring->postbufq_cnt);
12249 
12250 	return NULL;
12251 }
12252 
12253 /**
12254  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
12255  * @phba: Pointer to HBA context object.
12256  * @pring: Pointer to driver SLI ring object.
12257  * @phys: DMA address of the buffer.
12258  *
12259  * This function searches the buffer list using the dma_address
12260  * of unsolicited event to find the driver's lpfc_dmabuf object
12261  * corresponding to the dma_address. The function returns the
12262  * lpfc_dmabuf object if a buffer is found else it returns NULL.
12263  * This function is called by the ct and els unsolicited event
12264  * handlers to get the buffer associated with the unsolicited
12265  * event.
12266  *
12267  * This function is called with no lock held.
12268  **/
12269 struct lpfc_dmabuf *
12270 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12271 			 dma_addr_t phys)
12272 {
12273 	struct lpfc_dmabuf *mp, *next_mp;
12274 	struct list_head *slp = &pring->postbufq;
12275 
12276 	/* Search postbufq, from the beginning, looking for a match on phys */
12277 	spin_lock_irq(&phba->hbalock);
12278 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12279 		if (mp->phys == phys) {
12280 			list_del_init(&mp->list);
12281 			pring->postbufq_cnt--;
12282 			spin_unlock_irq(&phba->hbalock);
12283 			return mp;
12284 		}
12285 	}
12286 
12287 	spin_unlock_irq(&phba->hbalock);
12288 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12289 			"0410 Cannot find virtual addr for mapped buf on "
12290 			"ring %d Data x%llx x%px x%px x%x\n",
12291 			pring->ringno, (unsigned long long)phys,
12292 			slp->next, slp->prev, pring->postbufq_cnt);
12293 	return NULL;
12294 }
12295 
12296 /**
12297  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
12298  * @phba: Pointer to HBA context object.
12299  * @cmdiocb: Pointer to driver command iocb object.
12300  * @rspiocb: Pointer to driver response iocb object.
12301  *
12302  * This function is the completion handler for the abort iocbs for
12303  * ELS commands. This function is called from the ELS ring event
12304  * handler with no lock held. This function frees memory resources
12305  * associated with the abort iocb.
12306  **/
12307 static void
12308 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12309 			struct lpfc_iocbq *rspiocb)
12310 {
12311 	u32 ulp_status = get_job_ulpstatus(phba, rspiocb);
12312 	u32 ulp_word4 = get_job_word4(phba, rspiocb);
12313 	u8 cmnd = get_job_cmnd(phba, cmdiocb);
12314 
12315 	if (ulp_status) {
12316 		/*
12317 		 * Assume that the port already completed and returned, or
12318 		 * will return the iocb. Just Log the message.
12319 		 */
12320 		if (phba->sli_rev < LPFC_SLI_REV4) {
12321 			if (cmnd == CMD_ABORT_XRI_CX &&
12322 			    ulp_status == IOSTAT_LOCAL_REJECT &&
12323 			    ulp_word4 == IOERR_ABORT_REQUESTED) {
12324 				goto release_iocb;
12325 			}
12326 		}
12327 
12328 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
12329 				"0327 Cannot abort els iocb x%px "
12330 				"with io cmd xri %x abort tag : x%x, "
12331 				"abort status %x abort code %x\n",
12332 				cmdiocb, get_job_abtsiotag(phba, cmdiocb),
12333 				(phba->sli_rev == LPFC_SLI_REV4) ?
12334 				get_wqe_reqtag(cmdiocb) :
12335 				cmdiocb->iocb.un.acxri.abortContextTag,
12336 				ulp_status, ulp_word4);
12337 
12338 	}
12339 release_iocb:
12340 	lpfc_sli_release_iocbq(phba, cmdiocb);
12341 	return;
12342 }
12343 
12344 /**
12345  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
12346  * @phba: Pointer to HBA context object.
12347  * @cmdiocb: Pointer to driver command iocb object.
12348  * @rspiocb: Pointer to driver response iocb object.
12349  *
12350  * The function is called from SLI ring event handler with no
12351  * lock held. This function is the completion handler for ELS commands
12352  * which are aborted. The function frees memory resources used for
12353  * the aborted ELS commands.
12354  **/
12355 void
12356 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12357 		     struct lpfc_iocbq *rspiocb)
12358 {
12359 	struct lpfc_nodelist *ndlp = cmdiocb->ndlp;
12360 	IOCB_t *irsp;
12361 	LPFC_MBOXQ_t *mbox;
12362 	u32 ulp_command, ulp_status, ulp_word4, iotag;
12363 
12364 	ulp_command = get_job_cmnd(phba, cmdiocb);
12365 	ulp_status = get_job_ulpstatus(phba, rspiocb);
12366 	ulp_word4 = get_job_word4(phba, rspiocb);
12367 
12368 	if (phba->sli_rev == LPFC_SLI_REV4) {
12369 		iotag = get_wqe_reqtag(cmdiocb);
12370 	} else {
12371 		irsp = &rspiocb->iocb;
12372 		iotag = irsp->ulpIoTag;
12373 
12374 		/* It is possible a PLOGI_RJT for NPIV ports to get aborted.
12375 		 * The MBX_REG_LOGIN64 mbox command is freed back to the
12376 		 * mbox_mem_pool here.
12377 		 */
12378 		if (cmdiocb->context_un.mbox) {
12379 			mbox = cmdiocb->context_un.mbox;
12380 			lpfc_mbox_rsrc_cleanup(phba, mbox, MBOX_THD_UNLOCKED);
12381 			cmdiocb->context_un.mbox = NULL;
12382 		}
12383 	}
12384 
12385 	/* ELS cmd tag <ulpIoTag> completes */
12386 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
12387 			"0139 Ignoring ELS cmd code x%x completion Data: "
12388 			"x%x x%x x%x x%px\n",
12389 			ulp_command, ulp_status, ulp_word4, iotag,
12390 			cmdiocb->ndlp);
12391 	/*
12392 	 * Deref the ndlp after free_iocb. sli_release_iocb will access the ndlp
12393 	 * if exchange is busy.
12394 	 */
12395 	if (ulp_command == CMD_GEN_REQUEST64_CR)
12396 		lpfc_ct_free_iocb(phba, cmdiocb);
12397 	else
12398 		lpfc_els_free_iocb(phba, cmdiocb);
12399 
12400 	lpfc_nlp_put(ndlp);
12401 }
12402 
12403 /**
12404  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
12405  * @phba: Pointer to HBA context object.
12406  * @pring: Pointer to driver SLI ring object.
12407  * @cmdiocb: Pointer to driver command iocb object.
12408  * @cmpl: completion function.
12409  *
12410  * This function issues an abort iocb for the provided command iocb. In case
12411  * of unloading, the abort iocb will not be issued to commands on the ELS
12412  * ring. Instead, the callback function shall be changed to those commands
12413  * so that nothing happens when them finishes. This function is called with
12414  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
12415  * when the command iocb is an abort request.
12416  *
12417  **/
12418 int
12419 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12420 			   struct lpfc_iocbq *cmdiocb, void *cmpl)
12421 {
12422 	struct lpfc_vport *vport = cmdiocb->vport;
12423 	struct lpfc_iocbq *abtsiocbp;
12424 	int retval = IOCB_ERROR;
12425 	unsigned long iflags;
12426 	struct lpfc_nodelist *ndlp = NULL;
12427 	u32 ulp_command = get_job_cmnd(phba, cmdiocb);
12428 	u16 ulp_context, iotag;
12429 	bool ia;
12430 
12431 	/*
12432 	 * There are certain command types we don't want to abort.  And we
12433 	 * don't want to abort commands that are already in the process of
12434 	 * being aborted.
12435 	 */
12436 	if (ulp_command == CMD_ABORT_XRI_WQE ||
12437 	    ulp_command == CMD_ABORT_XRI_CN ||
12438 	    ulp_command == CMD_CLOSE_XRI_CN ||
12439 	    cmdiocb->cmd_flag & LPFC_DRIVER_ABORTED)
12440 		return IOCB_ABORTING;
12441 
12442 	if (!pring) {
12443 		if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12444 			cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12445 		else
12446 			cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12447 		return retval;
12448 	}
12449 
12450 	/*
12451 	 * If we're unloading, don't abort iocb on the ELS ring, but change
12452 	 * the callback so that nothing happens when it finishes.
12453 	 */
12454 	if ((vport->load_flag & FC_UNLOADING) &&
12455 	    pring->ringno == LPFC_ELS_RING) {
12456 		if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12457 			cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12458 		else
12459 			cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12460 		return retval;
12461 	}
12462 
12463 	/* issue ABTS for this IOCB based on iotag */
12464 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
12465 	if (abtsiocbp == NULL)
12466 		return IOCB_NORESOURCE;
12467 
12468 	/* This signals the response to set the correct status
12469 	 * before calling the completion handler
12470 	 */
12471 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
12472 
12473 	if (phba->sli_rev == LPFC_SLI_REV4) {
12474 		ulp_context = cmdiocb->sli4_xritag;
12475 		iotag = abtsiocbp->iotag;
12476 	} else {
12477 		iotag = cmdiocb->iocb.ulpIoTag;
12478 		if (pring->ringno == LPFC_ELS_RING) {
12479 			ndlp = cmdiocb->ndlp;
12480 			ulp_context = ndlp->nlp_rpi;
12481 		} else {
12482 			ulp_context = cmdiocb->iocb.ulpContext;
12483 		}
12484 	}
12485 
12486 	if (phba->link_state < LPFC_LINK_UP ||
12487 	    (phba->sli_rev == LPFC_SLI_REV4 &&
12488 	     phba->sli4_hba.link_state.status == LPFC_FC_LA_TYPE_LINK_DOWN) ||
12489 	    (phba->link_flag & LS_EXTERNAL_LOOPBACK))
12490 		ia = true;
12491 	else
12492 		ia = false;
12493 
12494 	lpfc_sli_prep_abort_xri(phba, abtsiocbp, ulp_context, iotag,
12495 				cmdiocb->iocb.ulpClass,
12496 				LPFC_WQE_CQ_ID_DEFAULT, ia, false);
12497 
12498 	abtsiocbp->vport = vport;
12499 
12500 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12501 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
12502 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
12503 		abtsiocbp->cmd_flag |= (LPFC_IO_FCP | LPFC_USE_FCPWQIDX);
12504 
12505 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
12506 		abtsiocbp->cmd_flag |= LPFC_IO_FOF;
12507 
12508 	if (cmpl)
12509 		abtsiocbp->cmd_cmpl = cmpl;
12510 	else
12511 		abtsiocbp->cmd_cmpl = lpfc_sli_abort_els_cmpl;
12512 	abtsiocbp->vport = vport;
12513 
12514 	if (phba->sli_rev == LPFC_SLI_REV4) {
12515 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
12516 		if (unlikely(pring == NULL))
12517 			goto abort_iotag_exit;
12518 		/* Note: both hbalock and ring_lock need to be set here */
12519 		spin_lock_irqsave(&pring->ring_lock, iflags);
12520 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12521 			abtsiocbp, 0);
12522 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
12523 	} else {
12524 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12525 			abtsiocbp, 0);
12526 	}
12527 
12528 abort_iotag_exit:
12529 
12530 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
12531 			 "0339 Abort IO XRI x%x, Original iotag x%x, "
12532 			 "abort tag x%x Cmdjob : x%px Abortjob : x%px "
12533 			 "retval x%x\n",
12534 			 ulp_context, (phba->sli_rev == LPFC_SLI_REV4) ?
12535 			 cmdiocb->iotag : iotag, iotag, cmdiocb, abtsiocbp,
12536 			 retval);
12537 	if (retval) {
12538 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
12539 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
12540 	}
12541 
12542 	/*
12543 	 * Caller to this routine should check for IOCB_ERROR
12544 	 * and handle it properly.  This routine no longer removes
12545 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
12546 	 */
12547 	return retval;
12548 }
12549 
12550 /**
12551  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
12552  * @phba: pointer to lpfc HBA data structure.
12553  *
12554  * This routine will abort all pending and outstanding iocbs to an HBA.
12555  **/
12556 void
12557 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
12558 {
12559 	struct lpfc_sli *psli = &phba->sli;
12560 	struct lpfc_sli_ring *pring;
12561 	struct lpfc_queue *qp = NULL;
12562 	int i;
12563 
12564 	if (phba->sli_rev != LPFC_SLI_REV4) {
12565 		for (i = 0; i < psli->num_rings; i++) {
12566 			pring = &psli->sli3_ring[i];
12567 			lpfc_sli_abort_iocb_ring(phba, pring);
12568 		}
12569 		return;
12570 	}
12571 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12572 		pring = qp->pring;
12573 		if (!pring)
12574 			continue;
12575 		lpfc_sli_abort_iocb_ring(phba, pring);
12576 	}
12577 }
12578 
12579 /**
12580  * lpfc_sli_validate_fcp_iocb_for_abort - filter iocbs appropriate for FCP aborts
12581  * @iocbq: Pointer to iocb object.
12582  * @vport: Pointer to driver virtual port object.
12583  *
12584  * This function acts as an iocb filter for functions which abort FCP iocbs.
12585  *
12586  * Return values
12587  * -ENODEV, if a null iocb or vport ptr is encountered
12588  * -EINVAL, if the iocb is not an FCP I/O, not on the TX cmpl queue, premarked as
12589  *          driver already started the abort process, or is an abort iocb itself
12590  * 0, passes criteria for aborting the FCP I/O iocb
12591  **/
12592 static int
12593 lpfc_sli_validate_fcp_iocb_for_abort(struct lpfc_iocbq *iocbq,
12594 				     struct lpfc_vport *vport)
12595 {
12596 	u8 ulp_command;
12597 
12598 	/* No null ptr vports */
12599 	if (!iocbq || iocbq->vport != vport)
12600 		return -ENODEV;
12601 
12602 	/* iocb must be for FCP IO, already exists on the TX cmpl queue,
12603 	 * can't be premarked as driver aborted, nor be an ABORT iocb itself
12604 	 */
12605 	ulp_command = get_job_cmnd(vport->phba, iocbq);
12606 	if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12607 	    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ) ||
12608 	    (iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12609 	    (ulp_command == CMD_ABORT_XRI_CN ||
12610 	     ulp_command == CMD_CLOSE_XRI_CN ||
12611 	     ulp_command == CMD_ABORT_XRI_WQE))
12612 		return -EINVAL;
12613 
12614 	return 0;
12615 }
12616 
12617 /**
12618  * lpfc_sli_validate_fcp_iocb - validate commands associated with a SCSI target
12619  * @iocbq: Pointer to driver iocb object.
12620  * @vport: Pointer to driver virtual port object.
12621  * @tgt_id: SCSI ID of the target.
12622  * @lun_id: LUN ID of the scsi device.
12623  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
12624  *
12625  * This function acts as an iocb filter for validating a lun/SCSI target/SCSI
12626  * host.
12627  *
12628  * It will return
12629  * 0 if the filtering criteria is met for the given iocb and will return
12630  * 1 if the filtering criteria is not met.
12631  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
12632  * given iocb is for the SCSI device specified by vport, tgt_id and
12633  * lun_id parameter.
12634  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
12635  * given iocb is for the SCSI target specified by vport and tgt_id
12636  * parameters.
12637  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
12638  * given iocb is for the SCSI host associated with the given vport.
12639  * This function is called with no locks held.
12640  **/
12641 static int
12642 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
12643 			   uint16_t tgt_id, uint64_t lun_id,
12644 			   lpfc_ctx_cmd ctx_cmd)
12645 {
12646 	struct lpfc_io_buf *lpfc_cmd;
12647 	int rc = 1;
12648 
12649 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12650 
12651 	if (lpfc_cmd->pCmd == NULL)
12652 		return rc;
12653 
12654 	switch (ctx_cmd) {
12655 	case LPFC_CTX_LUN:
12656 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12657 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
12658 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
12659 			rc = 0;
12660 		break;
12661 	case LPFC_CTX_TGT:
12662 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12663 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
12664 			rc = 0;
12665 		break;
12666 	case LPFC_CTX_HOST:
12667 		rc = 0;
12668 		break;
12669 	default:
12670 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
12671 			__func__, ctx_cmd);
12672 		break;
12673 	}
12674 
12675 	return rc;
12676 }
12677 
12678 /**
12679  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
12680  * @vport: Pointer to virtual port.
12681  * @tgt_id: SCSI ID of the target.
12682  * @lun_id: LUN ID of the scsi device.
12683  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12684  *
12685  * This function returns number of FCP commands pending for the vport.
12686  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
12687  * commands pending on the vport associated with SCSI device specified
12688  * by tgt_id and lun_id parameters.
12689  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
12690  * commands pending on the vport associated with SCSI target specified
12691  * by tgt_id parameter.
12692  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
12693  * commands pending on the vport.
12694  * This function returns the number of iocbs which satisfy the filter.
12695  * This function is called without any lock held.
12696  **/
12697 int
12698 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
12699 		  lpfc_ctx_cmd ctx_cmd)
12700 {
12701 	struct lpfc_hba *phba = vport->phba;
12702 	struct lpfc_iocbq *iocbq;
12703 	int sum, i;
12704 	unsigned long iflags;
12705 	u8 ulp_command;
12706 
12707 	spin_lock_irqsave(&phba->hbalock, iflags);
12708 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
12709 		iocbq = phba->sli.iocbq_lookup[i];
12710 
12711 		if (!iocbq || iocbq->vport != vport)
12712 			continue;
12713 		if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12714 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ))
12715 			continue;
12716 
12717 		/* Include counting outstanding aborts */
12718 		ulp_command = get_job_cmnd(phba, iocbq);
12719 		if (ulp_command == CMD_ABORT_XRI_CN ||
12720 		    ulp_command == CMD_CLOSE_XRI_CN ||
12721 		    ulp_command == CMD_ABORT_XRI_WQE) {
12722 			sum++;
12723 			continue;
12724 		}
12725 
12726 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12727 					       ctx_cmd) == 0)
12728 			sum++;
12729 	}
12730 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12731 
12732 	return sum;
12733 }
12734 
12735 /**
12736  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
12737  * @phba: Pointer to HBA context object
12738  * @cmdiocb: Pointer to command iocb object.
12739  * @rspiocb: Pointer to response iocb object.
12740  *
12741  * This function is called when an aborted FCP iocb completes. This
12742  * function is called by the ring event handler with no lock held.
12743  * This function frees the iocb.
12744  **/
12745 void
12746 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12747 			struct lpfc_iocbq *rspiocb)
12748 {
12749 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12750 			"3096 ABORT_XRI_CX completing on rpi x%x "
12751 			"original iotag x%x, abort cmd iotag x%x "
12752 			"status 0x%x, reason 0x%x\n",
12753 			(phba->sli_rev == LPFC_SLI_REV4) ?
12754 			cmdiocb->sli4_xritag :
12755 			cmdiocb->iocb.un.acxri.abortContextTag,
12756 			get_job_abtsiotag(phba, cmdiocb),
12757 			cmdiocb->iotag, get_job_ulpstatus(phba, rspiocb),
12758 			get_job_word4(phba, rspiocb));
12759 	lpfc_sli_release_iocbq(phba, cmdiocb);
12760 	return;
12761 }
12762 
12763 /**
12764  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
12765  * @vport: Pointer to virtual port.
12766  * @tgt_id: SCSI ID of the target.
12767  * @lun_id: LUN ID of the scsi device.
12768  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12769  *
12770  * This function sends an abort command for every SCSI command
12771  * associated with the given virtual port pending on the ring
12772  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12773  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12774  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12775  * followed by lpfc_sli_validate_fcp_iocb.
12776  *
12777  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
12778  * FCP iocbs associated with lun specified by tgt_id and lun_id
12779  * parameters
12780  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
12781  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12782  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
12783  * FCP iocbs associated with virtual port.
12784  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
12785  * lpfc_sli4_calc_ring is used.
12786  * This function returns number of iocbs it failed to abort.
12787  * This function is called with no locks held.
12788  **/
12789 int
12790 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
12791 		    lpfc_ctx_cmd abort_cmd)
12792 {
12793 	struct lpfc_hba *phba = vport->phba;
12794 	struct lpfc_sli_ring *pring = NULL;
12795 	struct lpfc_iocbq *iocbq;
12796 	int errcnt = 0, ret_val = 0;
12797 	unsigned long iflags;
12798 	int i;
12799 
12800 	/* all I/Os are in process of being flushed */
12801 	if (phba->hba_flag & HBA_IOQ_FLUSH)
12802 		return errcnt;
12803 
12804 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12805 		iocbq = phba->sli.iocbq_lookup[i];
12806 
12807 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12808 			continue;
12809 
12810 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12811 					       abort_cmd) != 0)
12812 			continue;
12813 
12814 		spin_lock_irqsave(&phba->hbalock, iflags);
12815 		if (phba->sli_rev == LPFC_SLI_REV3) {
12816 			pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12817 		} else if (phba->sli_rev == LPFC_SLI_REV4) {
12818 			pring = lpfc_sli4_calc_ring(phba, iocbq);
12819 		}
12820 		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
12821 						     lpfc_sli_abort_fcp_cmpl);
12822 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12823 		if (ret_val != IOCB_SUCCESS)
12824 			errcnt++;
12825 	}
12826 
12827 	return errcnt;
12828 }
12829 
12830 /**
12831  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12832  * @vport: Pointer to virtual port.
12833  * @pring: Pointer to driver SLI ring object.
12834  * @tgt_id: SCSI ID of the target.
12835  * @lun_id: LUN ID of the scsi device.
12836  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12837  *
12838  * This function sends an abort command for every SCSI command
12839  * associated with the given virtual port pending on the ring
12840  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12841  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12842  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12843  * followed by lpfc_sli_validate_fcp_iocb.
12844  *
12845  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12846  * FCP iocbs associated with lun specified by tgt_id and lun_id
12847  * parameters
12848  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12849  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12850  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12851  * FCP iocbs associated with virtual port.
12852  * This function returns number of iocbs it aborted .
12853  * This function is called with no locks held right after a taskmgmt
12854  * command is sent.
12855  **/
12856 int
12857 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12858 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12859 {
12860 	struct lpfc_hba *phba = vport->phba;
12861 	struct lpfc_io_buf *lpfc_cmd;
12862 	struct lpfc_iocbq *abtsiocbq;
12863 	struct lpfc_nodelist *ndlp = NULL;
12864 	struct lpfc_iocbq *iocbq;
12865 	int sum, i, ret_val;
12866 	unsigned long iflags;
12867 	struct lpfc_sli_ring *pring_s4 = NULL;
12868 	u16 ulp_context, iotag, cqid = LPFC_WQE_CQ_ID_DEFAULT;
12869 	bool ia;
12870 
12871 	spin_lock_irqsave(&phba->hbalock, iflags);
12872 
12873 	/* all I/Os are in process of being flushed */
12874 	if (phba->hba_flag & HBA_IOQ_FLUSH) {
12875 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12876 		return 0;
12877 	}
12878 	sum = 0;
12879 
12880 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12881 		iocbq = phba->sli.iocbq_lookup[i];
12882 
12883 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12884 			continue;
12885 
12886 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12887 					       cmd) != 0)
12888 			continue;
12889 
12890 		/* Guard against IO completion being called at same time */
12891 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12892 		spin_lock(&lpfc_cmd->buf_lock);
12893 
12894 		if (!lpfc_cmd->pCmd) {
12895 			spin_unlock(&lpfc_cmd->buf_lock);
12896 			continue;
12897 		}
12898 
12899 		if (phba->sli_rev == LPFC_SLI_REV4) {
12900 			pring_s4 =
12901 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12902 			if (!pring_s4) {
12903 				spin_unlock(&lpfc_cmd->buf_lock);
12904 				continue;
12905 			}
12906 			/* Note: both hbalock and ring_lock must be set here */
12907 			spin_lock(&pring_s4->ring_lock);
12908 		}
12909 
12910 		/*
12911 		 * If the iocbq is already being aborted, don't take a second
12912 		 * action, but do count it.
12913 		 */
12914 		if ((iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12915 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ)) {
12916 			if (phba->sli_rev == LPFC_SLI_REV4)
12917 				spin_unlock(&pring_s4->ring_lock);
12918 			spin_unlock(&lpfc_cmd->buf_lock);
12919 			continue;
12920 		}
12921 
12922 		/* issue ABTS for this IOCB based on iotag */
12923 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
12924 		if (!abtsiocbq) {
12925 			if (phba->sli_rev == LPFC_SLI_REV4)
12926 				spin_unlock(&pring_s4->ring_lock);
12927 			spin_unlock(&lpfc_cmd->buf_lock);
12928 			continue;
12929 		}
12930 
12931 		if (phba->sli_rev == LPFC_SLI_REV4) {
12932 			iotag = abtsiocbq->iotag;
12933 			ulp_context = iocbq->sli4_xritag;
12934 			cqid = lpfc_cmd->hdwq->io_cq_map;
12935 		} else {
12936 			iotag = iocbq->iocb.ulpIoTag;
12937 			if (pring->ringno == LPFC_ELS_RING) {
12938 				ndlp = iocbq->ndlp;
12939 				ulp_context = ndlp->nlp_rpi;
12940 			} else {
12941 				ulp_context = iocbq->iocb.ulpContext;
12942 			}
12943 		}
12944 
12945 		ndlp = lpfc_cmd->rdata->pnode;
12946 
12947 		if (lpfc_is_link_up(phba) &&
12948 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE) &&
12949 		    !(phba->link_flag & LS_EXTERNAL_LOOPBACK))
12950 			ia = false;
12951 		else
12952 			ia = true;
12953 
12954 		lpfc_sli_prep_abort_xri(phba, abtsiocbq, ulp_context, iotag,
12955 					iocbq->iocb.ulpClass, cqid,
12956 					ia, false);
12957 
12958 		abtsiocbq->vport = vport;
12959 
12960 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12961 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12962 		if (iocbq->cmd_flag & LPFC_IO_FCP)
12963 			abtsiocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
12964 		if (iocbq->cmd_flag & LPFC_IO_FOF)
12965 			abtsiocbq->cmd_flag |= LPFC_IO_FOF;
12966 
12967 		/* Setup callback routine and issue the command. */
12968 		abtsiocbq->cmd_cmpl = lpfc_sli_abort_fcp_cmpl;
12969 
12970 		/*
12971 		 * Indicate the IO is being aborted by the driver and set
12972 		 * the caller's flag into the aborted IO.
12973 		 */
12974 		iocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
12975 
12976 		if (phba->sli_rev == LPFC_SLI_REV4) {
12977 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
12978 							abtsiocbq, 0);
12979 			spin_unlock(&pring_s4->ring_lock);
12980 		} else {
12981 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
12982 							abtsiocbq, 0);
12983 		}
12984 
12985 		spin_unlock(&lpfc_cmd->buf_lock);
12986 
12987 		if (ret_val == IOCB_ERROR)
12988 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
12989 		else
12990 			sum++;
12991 	}
12992 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12993 	return sum;
12994 }
12995 
12996 /**
12997  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
12998  * @phba: Pointer to HBA context object.
12999  * @cmdiocbq: Pointer to command iocb.
13000  * @rspiocbq: Pointer to response iocb.
13001  *
13002  * This function is the completion handler for iocbs issued using
13003  * lpfc_sli_issue_iocb_wait function. This function is called by the
13004  * ring event handler function without any lock held. This function
13005  * can be called from both worker thread context and interrupt
13006  * context. This function also can be called from other thread which
13007  * cleans up the SLI layer objects.
13008  * This function copy the contents of the response iocb to the
13009  * response iocb memory object provided by the caller of
13010  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
13011  * sleeps for the iocb completion.
13012  **/
13013 static void
13014 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
13015 			struct lpfc_iocbq *cmdiocbq,
13016 			struct lpfc_iocbq *rspiocbq)
13017 {
13018 	wait_queue_head_t *pdone_q;
13019 	unsigned long iflags;
13020 	struct lpfc_io_buf *lpfc_cmd;
13021 	size_t offset = offsetof(struct lpfc_iocbq, wqe);
13022 
13023 	spin_lock_irqsave(&phba->hbalock, iflags);
13024 	if (cmdiocbq->cmd_flag & LPFC_IO_WAKE_TMO) {
13025 
13026 		/*
13027 		 * A time out has occurred for the iocb.  If a time out
13028 		 * completion handler has been supplied, call it.  Otherwise,
13029 		 * just free the iocbq.
13030 		 */
13031 
13032 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13033 		cmdiocbq->cmd_cmpl = cmdiocbq->wait_cmd_cmpl;
13034 		cmdiocbq->wait_cmd_cmpl = NULL;
13035 		if (cmdiocbq->cmd_cmpl)
13036 			cmdiocbq->cmd_cmpl(phba, cmdiocbq, NULL);
13037 		else
13038 			lpfc_sli_release_iocbq(phba, cmdiocbq);
13039 		return;
13040 	}
13041 
13042 	/* Copy the contents of the local rspiocb into the caller's buffer. */
13043 	cmdiocbq->cmd_flag |= LPFC_IO_WAKE;
13044 	if (cmdiocbq->rsp_iocb && rspiocbq)
13045 		memcpy((char *)cmdiocbq->rsp_iocb + offset,
13046 		       (char *)rspiocbq + offset, sizeof(*rspiocbq) - offset);
13047 
13048 	/* Set the exchange busy flag for task management commands */
13049 	if ((cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
13050 	    !(cmdiocbq->cmd_flag & LPFC_IO_LIBDFC)) {
13051 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
13052 					cur_iocbq);
13053 		if (rspiocbq && (rspiocbq->cmd_flag & LPFC_EXCHANGE_BUSY))
13054 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
13055 		else
13056 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
13057 	}
13058 
13059 	pdone_q = cmdiocbq->context_un.wait_queue;
13060 	if (pdone_q)
13061 		wake_up(pdone_q);
13062 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13063 	return;
13064 }
13065 
13066 /**
13067  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
13068  * @phba: Pointer to HBA context object..
13069  * @piocbq: Pointer to command iocb.
13070  * @flag: Flag to test.
13071  *
13072  * This routine grabs the hbalock and then test the cmd_flag to
13073  * see if the passed in flag is set.
13074  * Returns:
13075  * 1 if flag is set.
13076  * 0 if flag is not set.
13077  **/
13078 static int
13079 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
13080 		 struct lpfc_iocbq *piocbq, uint32_t flag)
13081 {
13082 	unsigned long iflags;
13083 	int ret;
13084 
13085 	spin_lock_irqsave(&phba->hbalock, iflags);
13086 	ret = piocbq->cmd_flag & flag;
13087 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13088 	return ret;
13089 
13090 }
13091 
13092 /**
13093  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
13094  * @phba: Pointer to HBA context object..
13095  * @ring_number: Ring number
13096  * @piocb: Pointer to command iocb.
13097  * @prspiocbq: Pointer to response iocb.
13098  * @timeout: Timeout in number of seconds.
13099  *
13100  * This function issues the iocb to firmware and waits for the
13101  * iocb to complete. The cmd_cmpl field of the shall be used
13102  * to handle iocbs which time out. If the field is NULL, the
13103  * function shall free the iocbq structure.  If more clean up is
13104  * needed, the caller is expected to provide a completion function
13105  * that will provide the needed clean up.  If the iocb command is
13106  * not completed within timeout seconds, the function will either
13107  * free the iocbq structure (if cmd_cmpl == NULL) or execute the
13108  * completion function set in the cmd_cmpl field and then return
13109  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
13110  * resources if this function returns IOCB_TIMEDOUT.
13111  * The function waits for the iocb completion using an
13112  * non-interruptible wait.
13113  * This function will sleep while waiting for iocb completion.
13114  * So, this function should not be called from any context which
13115  * does not allow sleeping. Due to the same reason, this function
13116  * cannot be called with interrupt disabled.
13117  * This function assumes that the iocb completions occur while
13118  * this function sleep. So, this function cannot be called from
13119  * the thread which process iocb completion for this ring.
13120  * This function clears the cmd_flag of the iocb object before
13121  * issuing the iocb and the iocb completion handler sets this
13122  * flag and wakes this thread when the iocb completes.
13123  * The contents of the response iocb will be copied to prspiocbq
13124  * by the completion handler when the command completes.
13125  * This function returns IOCB_SUCCESS when success.
13126  * This function is called with no lock held.
13127  **/
13128 int
13129 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
13130 			 uint32_t ring_number,
13131 			 struct lpfc_iocbq *piocb,
13132 			 struct lpfc_iocbq *prspiocbq,
13133 			 uint32_t timeout)
13134 {
13135 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
13136 	long timeleft, timeout_req = 0;
13137 	int retval = IOCB_SUCCESS;
13138 	uint32_t creg_val;
13139 	struct lpfc_iocbq *iocb;
13140 	int txq_cnt = 0;
13141 	int txcmplq_cnt = 0;
13142 	struct lpfc_sli_ring *pring;
13143 	unsigned long iflags;
13144 	bool iocb_completed = true;
13145 
13146 	if (phba->sli_rev >= LPFC_SLI_REV4) {
13147 		lpfc_sli_prep_wqe(phba, piocb);
13148 
13149 		pring = lpfc_sli4_calc_ring(phba, piocb);
13150 	} else
13151 		pring = &phba->sli.sli3_ring[ring_number];
13152 	/*
13153 	 * If the caller has provided a response iocbq buffer, then rsp_iocb
13154 	 * is NULL or its an error.
13155 	 */
13156 	if (prspiocbq) {
13157 		if (piocb->rsp_iocb)
13158 			return IOCB_ERROR;
13159 		piocb->rsp_iocb = prspiocbq;
13160 	}
13161 
13162 	piocb->wait_cmd_cmpl = piocb->cmd_cmpl;
13163 	piocb->cmd_cmpl = lpfc_sli_wake_iocb_wait;
13164 	piocb->context_un.wait_queue = &done_q;
13165 	piocb->cmd_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
13166 
13167 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13168 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13169 			return IOCB_ERROR;
13170 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
13171 		writel(creg_val, phba->HCregaddr);
13172 		readl(phba->HCregaddr); /* flush */
13173 	}
13174 
13175 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
13176 				     SLI_IOCB_RET_IOCB);
13177 	if (retval == IOCB_SUCCESS) {
13178 		timeout_req = msecs_to_jiffies(timeout * 1000);
13179 		timeleft = wait_event_timeout(done_q,
13180 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
13181 				timeout_req);
13182 		spin_lock_irqsave(&phba->hbalock, iflags);
13183 		if (!(piocb->cmd_flag & LPFC_IO_WAKE)) {
13184 
13185 			/*
13186 			 * IOCB timed out.  Inform the wake iocb wait
13187 			 * completion function and set local status
13188 			 */
13189 
13190 			iocb_completed = false;
13191 			piocb->cmd_flag |= LPFC_IO_WAKE_TMO;
13192 		}
13193 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13194 		if (iocb_completed) {
13195 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13196 					"0331 IOCB wake signaled\n");
13197 			/* Note: we are not indicating if the IOCB has a success
13198 			 * status or not - that's for the caller to check.
13199 			 * IOCB_SUCCESS means just that the command was sent and
13200 			 * completed. Not that it completed successfully.
13201 			 * */
13202 		} else if (timeleft == 0) {
13203 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13204 					"0338 IOCB wait timeout error - no "
13205 					"wake response Data x%x\n", timeout);
13206 			retval = IOCB_TIMEDOUT;
13207 		} else {
13208 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13209 					"0330 IOCB wake NOT set, "
13210 					"Data x%x x%lx\n",
13211 					timeout, (timeleft / jiffies));
13212 			retval = IOCB_TIMEDOUT;
13213 		}
13214 	} else if (retval == IOCB_BUSY) {
13215 		if (phba->cfg_log_verbose & LOG_SLI) {
13216 			list_for_each_entry(iocb, &pring->txq, list) {
13217 				txq_cnt++;
13218 			}
13219 			list_for_each_entry(iocb, &pring->txcmplq, list) {
13220 				txcmplq_cnt++;
13221 			}
13222 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13223 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
13224 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
13225 		}
13226 		return retval;
13227 	} else {
13228 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13229 				"0332 IOCB wait issue failed, Data x%x\n",
13230 				retval);
13231 		retval = IOCB_ERROR;
13232 	}
13233 
13234 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13235 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13236 			return IOCB_ERROR;
13237 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
13238 		writel(creg_val, phba->HCregaddr);
13239 		readl(phba->HCregaddr); /* flush */
13240 	}
13241 
13242 	if (prspiocbq)
13243 		piocb->rsp_iocb = NULL;
13244 
13245 	piocb->context_un.wait_queue = NULL;
13246 	piocb->cmd_cmpl = NULL;
13247 	return retval;
13248 }
13249 
13250 /**
13251  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
13252  * @phba: Pointer to HBA context object.
13253  * @pmboxq: Pointer to driver mailbox object.
13254  * @timeout: Timeout in number of seconds.
13255  *
13256  * This function issues the mailbox to firmware and waits for the
13257  * mailbox command to complete. If the mailbox command is not
13258  * completed within timeout seconds, it returns MBX_TIMEOUT.
13259  * The function waits for the mailbox completion using an
13260  * interruptible wait. If the thread is woken up due to a
13261  * signal, MBX_TIMEOUT error is returned to the caller. Caller
13262  * should not free the mailbox resources, if this function returns
13263  * MBX_TIMEOUT.
13264  * This function will sleep while waiting for mailbox completion.
13265  * So, this function should not be called from any context which
13266  * does not allow sleeping. Due to the same reason, this function
13267  * cannot be called with interrupt disabled.
13268  * This function assumes that the mailbox completion occurs while
13269  * this function sleep. So, this function cannot be called from
13270  * the worker thread which processes mailbox completion.
13271  * This function is called in the context of HBA management
13272  * applications.
13273  * This function returns MBX_SUCCESS when successful.
13274  * This function is called with no lock held.
13275  **/
13276 int
13277 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
13278 			 uint32_t timeout)
13279 {
13280 	struct completion mbox_done;
13281 	int retval;
13282 	unsigned long flag;
13283 
13284 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
13285 	/* setup wake call as IOCB callback */
13286 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
13287 
13288 	/* setup context3 field to pass wait_queue pointer to wake function  */
13289 	init_completion(&mbox_done);
13290 	pmboxq->context3 = &mbox_done;
13291 	/* now issue the command */
13292 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
13293 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
13294 		wait_for_completion_timeout(&mbox_done,
13295 					    msecs_to_jiffies(timeout * 1000));
13296 
13297 		spin_lock_irqsave(&phba->hbalock, flag);
13298 		pmboxq->context3 = NULL;
13299 		/*
13300 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
13301 		 * else do not free the resources.
13302 		 */
13303 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
13304 			retval = MBX_SUCCESS;
13305 		} else {
13306 			retval = MBX_TIMEOUT;
13307 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13308 		}
13309 		spin_unlock_irqrestore(&phba->hbalock, flag);
13310 	}
13311 	return retval;
13312 }
13313 
13314 /**
13315  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
13316  * @phba: Pointer to HBA context.
13317  * @mbx_action: Mailbox shutdown options.
13318  *
13319  * This function is called to shutdown the driver's mailbox sub-system.
13320  * It first marks the mailbox sub-system is in a block state to prevent
13321  * the asynchronous mailbox command from issued off the pending mailbox
13322  * command queue. If the mailbox command sub-system shutdown is due to
13323  * HBA error conditions such as EEH or ERATT, this routine shall invoke
13324  * the mailbox sub-system flush routine to forcefully bring down the
13325  * mailbox sub-system. Otherwise, if it is due to normal condition (such
13326  * as with offline or HBA function reset), this routine will wait for the
13327  * outstanding mailbox command to complete before invoking the mailbox
13328  * sub-system flush routine to gracefully bring down mailbox sub-system.
13329  **/
13330 void
13331 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
13332 {
13333 	struct lpfc_sli *psli = &phba->sli;
13334 	unsigned long timeout;
13335 
13336 	if (mbx_action == LPFC_MBX_NO_WAIT) {
13337 		/* delay 100ms for port state */
13338 		msleep(100);
13339 		lpfc_sli_mbox_sys_flush(phba);
13340 		return;
13341 	}
13342 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
13343 
13344 	/* Disable softirqs, including timers from obtaining phba->hbalock */
13345 	local_bh_disable();
13346 
13347 	spin_lock_irq(&phba->hbalock);
13348 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13349 
13350 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
13351 		/* Determine how long we might wait for the active mailbox
13352 		 * command to be gracefully completed by firmware.
13353 		 */
13354 		if (phba->sli.mbox_active)
13355 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
13356 						phba->sli.mbox_active) *
13357 						1000) + jiffies;
13358 		spin_unlock_irq(&phba->hbalock);
13359 
13360 		/* Enable softirqs again, done with phba->hbalock */
13361 		local_bh_enable();
13362 
13363 		while (phba->sli.mbox_active) {
13364 			/* Check active mailbox complete status every 2ms */
13365 			msleep(2);
13366 			if (time_after(jiffies, timeout))
13367 				/* Timeout, let the mailbox flush routine to
13368 				 * forcefully release active mailbox command
13369 				 */
13370 				break;
13371 		}
13372 	} else {
13373 		spin_unlock_irq(&phba->hbalock);
13374 
13375 		/* Enable softirqs again, done with phba->hbalock */
13376 		local_bh_enable();
13377 	}
13378 
13379 	lpfc_sli_mbox_sys_flush(phba);
13380 }
13381 
13382 /**
13383  * lpfc_sli_eratt_read - read sli-3 error attention events
13384  * @phba: Pointer to HBA context.
13385  *
13386  * This function is called to read the SLI3 device error attention registers
13387  * for possible error attention events. The caller must hold the hostlock
13388  * with spin_lock_irq().
13389  *
13390  * This function returns 1 when there is Error Attention in the Host Attention
13391  * Register and returns 0 otherwise.
13392  **/
13393 static int
13394 lpfc_sli_eratt_read(struct lpfc_hba *phba)
13395 {
13396 	uint32_t ha_copy;
13397 
13398 	/* Read chip Host Attention (HA) register */
13399 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
13400 		goto unplug_err;
13401 
13402 	if (ha_copy & HA_ERATT) {
13403 		/* Read host status register to retrieve error event */
13404 		if (lpfc_sli_read_hs(phba))
13405 			goto unplug_err;
13406 
13407 		/* Check if there is a deferred error condition is active */
13408 		if ((HS_FFER1 & phba->work_hs) &&
13409 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13410 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
13411 			phba->hba_flag |= DEFER_ERATT;
13412 			/* Clear all interrupt enable conditions */
13413 			writel(0, phba->HCregaddr);
13414 			readl(phba->HCregaddr);
13415 		}
13416 
13417 		/* Set the driver HA work bitmap */
13418 		phba->work_ha |= HA_ERATT;
13419 		/* Indicate polling handles this ERATT */
13420 		phba->hba_flag |= HBA_ERATT_HANDLED;
13421 		return 1;
13422 	}
13423 	return 0;
13424 
13425 unplug_err:
13426 	/* Set the driver HS work bitmap */
13427 	phba->work_hs |= UNPLUG_ERR;
13428 	/* Set the driver HA work bitmap */
13429 	phba->work_ha |= HA_ERATT;
13430 	/* Indicate polling handles this ERATT */
13431 	phba->hba_flag |= HBA_ERATT_HANDLED;
13432 	return 1;
13433 }
13434 
13435 /**
13436  * lpfc_sli4_eratt_read - read sli-4 error attention events
13437  * @phba: Pointer to HBA context.
13438  *
13439  * This function is called to read the SLI4 device error attention registers
13440  * for possible error attention events. The caller must hold the hostlock
13441  * with spin_lock_irq().
13442  *
13443  * This function returns 1 when there is Error Attention in the Host Attention
13444  * Register and returns 0 otherwise.
13445  **/
13446 static int
13447 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
13448 {
13449 	uint32_t uerr_sta_hi, uerr_sta_lo;
13450 	uint32_t if_type, portsmphr;
13451 	struct lpfc_register portstat_reg;
13452 	u32 logmask;
13453 
13454 	/*
13455 	 * For now, use the SLI4 device internal unrecoverable error
13456 	 * registers for error attention. This can be changed later.
13457 	 */
13458 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
13459 	switch (if_type) {
13460 	case LPFC_SLI_INTF_IF_TYPE_0:
13461 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
13462 			&uerr_sta_lo) ||
13463 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
13464 			&uerr_sta_hi)) {
13465 			phba->work_hs |= UNPLUG_ERR;
13466 			phba->work_ha |= HA_ERATT;
13467 			phba->hba_flag |= HBA_ERATT_HANDLED;
13468 			return 1;
13469 		}
13470 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
13471 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
13472 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13473 					"1423 HBA Unrecoverable error: "
13474 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
13475 					"ue_mask_lo_reg=0x%x, "
13476 					"ue_mask_hi_reg=0x%x\n",
13477 					uerr_sta_lo, uerr_sta_hi,
13478 					phba->sli4_hba.ue_mask_lo,
13479 					phba->sli4_hba.ue_mask_hi);
13480 			phba->work_status[0] = uerr_sta_lo;
13481 			phba->work_status[1] = uerr_sta_hi;
13482 			phba->work_ha |= HA_ERATT;
13483 			phba->hba_flag |= HBA_ERATT_HANDLED;
13484 			return 1;
13485 		}
13486 		break;
13487 	case LPFC_SLI_INTF_IF_TYPE_2:
13488 	case LPFC_SLI_INTF_IF_TYPE_6:
13489 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
13490 			&portstat_reg.word0) ||
13491 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
13492 			&portsmphr)){
13493 			phba->work_hs |= UNPLUG_ERR;
13494 			phba->work_ha |= HA_ERATT;
13495 			phba->hba_flag |= HBA_ERATT_HANDLED;
13496 			return 1;
13497 		}
13498 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
13499 			phba->work_status[0] =
13500 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
13501 			phba->work_status[1] =
13502 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
13503 			logmask = LOG_TRACE_EVENT;
13504 			if (phba->work_status[0] ==
13505 				SLIPORT_ERR1_REG_ERR_CODE_2 &&
13506 			    phba->work_status[1] == SLIPORT_ERR2_REG_FW_RESTART)
13507 				logmask = LOG_SLI;
13508 			lpfc_printf_log(phba, KERN_ERR, logmask,
13509 					"2885 Port Status Event: "
13510 					"port status reg 0x%x, "
13511 					"port smphr reg 0x%x, "
13512 					"error 1=0x%x, error 2=0x%x\n",
13513 					portstat_reg.word0,
13514 					portsmphr,
13515 					phba->work_status[0],
13516 					phba->work_status[1]);
13517 			phba->work_ha |= HA_ERATT;
13518 			phba->hba_flag |= HBA_ERATT_HANDLED;
13519 			return 1;
13520 		}
13521 		break;
13522 	case LPFC_SLI_INTF_IF_TYPE_1:
13523 	default:
13524 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13525 				"2886 HBA Error Attention on unsupported "
13526 				"if type %d.", if_type);
13527 		return 1;
13528 	}
13529 
13530 	return 0;
13531 }
13532 
13533 /**
13534  * lpfc_sli_check_eratt - check error attention events
13535  * @phba: Pointer to HBA context.
13536  *
13537  * This function is called from timer soft interrupt context to check HBA's
13538  * error attention register bit for error attention events.
13539  *
13540  * This function returns 1 when there is Error Attention in the Host Attention
13541  * Register and returns 0 otherwise.
13542  **/
13543 int
13544 lpfc_sli_check_eratt(struct lpfc_hba *phba)
13545 {
13546 	uint32_t ha_copy;
13547 
13548 	/* If somebody is waiting to handle an eratt, don't process it
13549 	 * here. The brdkill function will do this.
13550 	 */
13551 	if (phba->link_flag & LS_IGNORE_ERATT)
13552 		return 0;
13553 
13554 	/* Check if interrupt handler handles this ERATT */
13555 	spin_lock_irq(&phba->hbalock);
13556 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
13557 		/* Interrupt handler has handled ERATT */
13558 		spin_unlock_irq(&phba->hbalock);
13559 		return 0;
13560 	}
13561 
13562 	/*
13563 	 * If there is deferred error attention, do not check for error
13564 	 * attention
13565 	 */
13566 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13567 		spin_unlock_irq(&phba->hbalock);
13568 		return 0;
13569 	}
13570 
13571 	/* If PCI channel is offline, don't process it */
13572 	if (unlikely(pci_channel_offline(phba->pcidev))) {
13573 		spin_unlock_irq(&phba->hbalock);
13574 		return 0;
13575 	}
13576 
13577 	switch (phba->sli_rev) {
13578 	case LPFC_SLI_REV2:
13579 	case LPFC_SLI_REV3:
13580 		/* Read chip Host Attention (HA) register */
13581 		ha_copy = lpfc_sli_eratt_read(phba);
13582 		break;
13583 	case LPFC_SLI_REV4:
13584 		/* Read device Uncoverable Error (UERR) registers */
13585 		ha_copy = lpfc_sli4_eratt_read(phba);
13586 		break;
13587 	default:
13588 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13589 				"0299 Invalid SLI revision (%d)\n",
13590 				phba->sli_rev);
13591 		ha_copy = 0;
13592 		break;
13593 	}
13594 	spin_unlock_irq(&phba->hbalock);
13595 
13596 	return ha_copy;
13597 }
13598 
13599 /**
13600  * lpfc_intr_state_check - Check device state for interrupt handling
13601  * @phba: Pointer to HBA context.
13602  *
13603  * This inline routine checks whether a device or its PCI slot is in a state
13604  * that the interrupt should be handled.
13605  *
13606  * This function returns 0 if the device or the PCI slot is in a state that
13607  * interrupt should be handled, otherwise -EIO.
13608  */
13609 static inline int
13610 lpfc_intr_state_check(struct lpfc_hba *phba)
13611 {
13612 	/* If the pci channel is offline, ignore all the interrupts */
13613 	if (unlikely(pci_channel_offline(phba->pcidev)))
13614 		return -EIO;
13615 
13616 	/* Update device level interrupt statistics */
13617 	phba->sli.slistat.sli_intr++;
13618 
13619 	/* Ignore all interrupts during initialization. */
13620 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
13621 		return -EIO;
13622 
13623 	return 0;
13624 }
13625 
13626 /**
13627  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
13628  * @irq: Interrupt number.
13629  * @dev_id: The device context pointer.
13630  *
13631  * This function is directly called from the PCI layer as an interrupt
13632  * service routine when device with SLI-3 interface spec is enabled with
13633  * MSI-X multi-message interrupt mode and there are slow-path events in
13634  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
13635  * interrupt mode, this function is called as part of the device-level
13636  * interrupt handler. When the PCI slot is in error recovery or the HBA
13637  * is undergoing initialization, the interrupt handler will not process
13638  * the interrupt. The link attention and ELS ring attention events are
13639  * handled by the worker thread. The interrupt handler signals the worker
13640  * thread and returns for these events. This function is called without
13641  * any lock held. It gets the hbalock to access and update SLI data
13642  * structures.
13643  *
13644  * This function returns IRQ_HANDLED when interrupt is handled else it
13645  * returns IRQ_NONE.
13646  **/
13647 irqreturn_t
13648 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
13649 {
13650 	struct lpfc_hba  *phba;
13651 	uint32_t ha_copy, hc_copy;
13652 	uint32_t work_ha_copy;
13653 	unsigned long status;
13654 	unsigned long iflag;
13655 	uint32_t control;
13656 
13657 	MAILBOX_t *mbox, *pmbox;
13658 	struct lpfc_vport *vport;
13659 	struct lpfc_nodelist *ndlp;
13660 	struct lpfc_dmabuf *mp;
13661 	LPFC_MBOXQ_t *pmb;
13662 	int rc;
13663 
13664 	/*
13665 	 * Get the driver's phba structure from the dev_id and
13666 	 * assume the HBA is not interrupting.
13667 	 */
13668 	phba = (struct lpfc_hba *)dev_id;
13669 
13670 	if (unlikely(!phba))
13671 		return IRQ_NONE;
13672 
13673 	/*
13674 	 * Stuff needs to be attented to when this function is invoked as an
13675 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13676 	 */
13677 	if (phba->intr_type == MSIX) {
13678 		/* Check device state for handling interrupt */
13679 		if (lpfc_intr_state_check(phba))
13680 			return IRQ_NONE;
13681 		/* Need to read HA REG for slow-path events */
13682 		spin_lock_irqsave(&phba->hbalock, iflag);
13683 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13684 			goto unplug_error;
13685 		/* If somebody is waiting to handle an eratt don't process it
13686 		 * here. The brdkill function will do this.
13687 		 */
13688 		if (phba->link_flag & LS_IGNORE_ERATT)
13689 			ha_copy &= ~HA_ERATT;
13690 		/* Check the need for handling ERATT in interrupt handler */
13691 		if (ha_copy & HA_ERATT) {
13692 			if (phba->hba_flag & HBA_ERATT_HANDLED)
13693 				/* ERATT polling has handled ERATT */
13694 				ha_copy &= ~HA_ERATT;
13695 			else
13696 				/* Indicate interrupt handler handles ERATT */
13697 				phba->hba_flag |= HBA_ERATT_HANDLED;
13698 		}
13699 
13700 		/*
13701 		 * If there is deferred error attention, do not check for any
13702 		 * interrupt.
13703 		 */
13704 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13705 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13706 			return IRQ_NONE;
13707 		}
13708 
13709 		/* Clear up only attention source related to slow-path */
13710 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
13711 			goto unplug_error;
13712 
13713 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
13714 			HC_LAINT_ENA | HC_ERINT_ENA),
13715 			phba->HCregaddr);
13716 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
13717 			phba->HAregaddr);
13718 		writel(hc_copy, phba->HCregaddr);
13719 		readl(phba->HAregaddr); /* flush */
13720 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13721 	} else
13722 		ha_copy = phba->ha_copy;
13723 
13724 	work_ha_copy = ha_copy & phba->work_ha_mask;
13725 
13726 	if (work_ha_copy) {
13727 		if (work_ha_copy & HA_LATT) {
13728 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
13729 				/*
13730 				 * Turn off Link Attention interrupts
13731 				 * until CLEAR_LA done
13732 				 */
13733 				spin_lock_irqsave(&phba->hbalock, iflag);
13734 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
13735 				if (lpfc_readl(phba->HCregaddr, &control))
13736 					goto unplug_error;
13737 				control &= ~HC_LAINT_ENA;
13738 				writel(control, phba->HCregaddr);
13739 				readl(phba->HCregaddr); /* flush */
13740 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13741 			}
13742 			else
13743 				work_ha_copy &= ~HA_LATT;
13744 		}
13745 
13746 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
13747 			/*
13748 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
13749 			 * the only slow ring.
13750 			 */
13751 			status = (work_ha_copy &
13752 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
13753 			status >>= (4*LPFC_ELS_RING);
13754 			if (status & HA_RXMASK) {
13755 				spin_lock_irqsave(&phba->hbalock, iflag);
13756 				if (lpfc_readl(phba->HCregaddr, &control))
13757 					goto unplug_error;
13758 
13759 				lpfc_debugfs_slow_ring_trc(phba,
13760 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
13761 				control, status,
13762 				(uint32_t)phba->sli.slistat.sli_intr);
13763 
13764 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
13765 					lpfc_debugfs_slow_ring_trc(phba,
13766 						"ISR Disable ring:"
13767 						"pwork:x%x hawork:x%x wait:x%x",
13768 						phba->work_ha, work_ha_copy,
13769 						(uint32_t)((unsigned long)
13770 						&phba->work_waitq));
13771 
13772 					control &=
13773 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
13774 					writel(control, phba->HCregaddr);
13775 					readl(phba->HCregaddr); /* flush */
13776 				}
13777 				else {
13778 					lpfc_debugfs_slow_ring_trc(phba,
13779 						"ISR slow ring:   pwork:"
13780 						"x%x hawork:x%x wait:x%x",
13781 						phba->work_ha, work_ha_copy,
13782 						(uint32_t)((unsigned long)
13783 						&phba->work_waitq));
13784 				}
13785 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13786 			}
13787 		}
13788 		spin_lock_irqsave(&phba->hbalock, iflag);
13789 		if (work_ha_copy & HA_ERATT) {
13790 			if (lpfc_sli_read_hs(phba))
13791 				goto unplug_error;
13792 			/*
13793 			 * Check if there is a deferred error condition
13794 			 * is active
13795 			 */
13796 			if ((HS_FFER1 & phba->work_hs) &&
13797 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13798 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
13799 				  phba->work_hs)) {
13800 				phba->hba_flag |= DEFER_ERATT;
13801 				/* Clear all interrupt enable conditions */
13802 				writel(0, phba->HCregaddr);
13803 				readl(phba->HCregaddr);
13804 			}
13805 		}
13806 
13807 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
13808 			pmb = phba->sli.mbox_active;
13809 			pmbox = &pmb->u.mb;
13810 			mbox = phba->mbox;
13811 			vport = pmb->vport;
13812 
13813 			/* First check out the status word */
13814 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
13815 			if (pmbox->mbxOwner != OWN_HOST) {
13816 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13817 				/*
13818 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
13819 				 * mbxStatus <status>
13820 				 */
13821 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13822 						"(%d):0304 Stray Mailbox "
13823 						"Interrupt mbxCommand x%x "
13824 						"mbxStatus x%x\n",
13825 						(vport ? vport->vpi : 0),
13826 						pmbox->mbxCommand,
13827 						pmbox->mbxStatus);
13828 				/* clear mailbox attention bit */
13829 				work_ha_copy &= ~HA_MBATT;
13830 			} else {
13831 				phba->sli.mbox_active = NULL;
13832 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13833 				phba->last_completion_time = jiffies;
13834 				del_timer(&phba->sli.mbox_tmo);
13835 				if (pmb->mbox_cmpl) {
13836 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
13837 							MAILBOX_CMD_SIZE);
13838 					if (pmb->out_ext_byte_len &&
13839 						pmb->ctx_buf)
13840 						lpfc_sli_pcimem_bcopy(
13841 						phba->mbox_ext,
13842 						pmb->ctx_buf,
13843 						pmb->out_ext_byte_len);
13844 				}
13845 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13846 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13847 
13848 					lpfc_debugfs_disc_trc(vport,
13849 						LPFC_DISC_TRC_MBOX_VPORT,
13850 						"MBOX dflt rpi: : "
13851 						"status:x%x rpi:x%x",
13852 						(uint32_t)pmbox->mbxStatus,
13853 						pmbox->un.varWords[0], 0);
13854 
13855 					if (!pmbox->mbxStatus) {
13856 						mp = (struct lpfc_dmabuf *)
13857 							(pmb->ctx_buf);
13858 						ndlp = (struct lpfc_nodelist *)
13859 							pmb->ctx_ndlp;
13860 
13861 						/* Reg_LOGIN of dflt RPI was
13862 						 * successful. new lets get
13863 						 * rid of the RPI using the
13864 						 * same mbox buffer.
13865 						 */
13866 						lpfc_unreg_login(phba,
13867 							vport->vpi,
13868 							pmbox->un.varWords[0],
13869 							pmb);
13870 						pmb->mbox_cmpl =
13871 							lpfc_mbx_cmpl_dflt_rpi;
13872 						pmb->ctx_buf = mp;
13873 						pmb->ctx_ndlp = ndlp;
13874 						pmb->vport = vport;
13875 						rc = lpfc_sli_issue_mbox(phba,
13876 								pmb,
13877 								MBX_NOWAIT);
13878 						if (rc != MBX_BUSY)
13879 							lpfc_printf_log(phba,
13880 							KERN_ERR,
13881 							LOG_TRACE_EVENT,
13882 							"0350 rc should have"
13883 							"been MBX_BUSY\n");
13884 						if (rc != MBX_NOT_FINISHED)
13885 							goto send_current_mbox;
13886 					}
13887 				}
13888 				spin_lock_irqsave(
13889 						&phba->pport->work_port_lock,
13890 						iflag);
13891 				phba->pport->work_port_events &=
13892 					~WORKER_MBOX_TMO;
13893 				spin_unlock_irqrestore(
13894 						&phba->pport->work_port_lock,
13895 						iflag);
13896 
13897 				/* Do NOT queue MBX_HEARTBEAT to the worker
13898 				 * thread for processing.
13899 				 */
13900 				if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13901 					/* Process mbox now */
13902 					phba->sli.mbox_active = NULL;
13903 					phba->sli.sli_flag &=
13904 						~LPFC_SLI_MBOX_ACTIVE;
13905 					if (pmb->mbox_cmpl)
13906 						pmb->mbox_cmpl(phba, pmb);
13907 				} else {
13908 					/* Queue to worker thread to process */
13909 					lpfc_mbox_cmpl_put(phba, pmb);
13910 				}
13911 			}
13912 		} else
13913 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13914 
13915 		if ((work_ha_copy & HA_MBATT) &&
13916 		    (phba->sli.mbox_active == NULL)) {
13917 send_current_mbox:
13918 			/* Process next mailbox command if there is one */
13919 			do {
13920 				rc = lpfc_sli_issue_mbox(phba, NULL,
13921 							 MBX_NOWAIT);
13922 			} while (rc == MBX_NOT_FINISHED);
13923 			if (rc != MBX_SUCCESS)
13924 				lpfc_printf_log(phba, KERN_ERR,
13925 						LOG_TRACE_EVENT,
13926 						"0349 rc should be "
13927 						"MBX_SUCCESS\n");
13928 		}
13929 
13930 		spin_lock_irqsave(&phba->hbalock, iflag);
13931 		phba->work_ha |= work_ha_copy;
13932 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13933 		lpfc_worker_wake_up(phba);
13934 	}
13935 	return IRQ_HANDLED;
13936 unplug_error:
13937 	spin_unlock_irqrestore(&phba->hbalock, iflag);
13938 	return IRQ_HANDLED;
13939 
13940 } /* lpfc_sli_sp_intr_handler */
13941 
13942 /**
13943  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13944  * @irq: Interrupt number.
13945  * @dev_id: The device context pointer.
13946  *
13947  * This function is directly called from the PCI layer as an interrupt
13948  * service routine when device with SLI-3 interface spec is enabled with
13949  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13950  * ring event in the HBA. However, when the device is enabled with either
13951  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13952  * device-level interrupt handler. When the PCI slot is in error recovery
13953  * or the HBA is undergoing initialization, the interrupt handler will not
13954  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13955  * the intrrupt context. This function is called without any lock held.
13956  * It gets the hbalock to access and update SLI data structures.
13957  *
13958  * This function returns IRQ_HANDLED when interrupt is handled else it
13959  * returns IRQ_NONE.
13960  **/
13961 irqreturn_t
13962 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13963 {
13964 	struct lpfc_hba  *phba;
13965 	uint32_t ha_copy;
13966 	unsigned long status;
13967 	unsigned long iflag;
13968 	struct lpfc_sli_ring *pring;
13969 
13970 	/* Get the driver's phba structure from the dev_id and
13971 	 * assume the HBA is not interrupting.
13972 	 */
13973 	phba = (struct lpfc_hba *) dev_id;
13974 
13975 	if (unlikely(!phba))
13976 		return IRQ_NONE;
13977 
13978 	/*
13979 	 * Stuff needs to be attented to when this function is invoked as an
13980 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13981 	 */
13982 	if (phba->intr_type == MSIX) {
13983 		/* Check device state for handling interrupt */
13984 		if (lpfc_intr_state_check(phba))
13985 			return IRQ_NONE;
13986 		/* Need to read HA REG for FCP ring and other ring events */
13987 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13988 			return IRQ_HANDLED;
13989 		/* Clear up only attention source related to fast-path */
13990 		spin_lock_irqsave(&phba->hbalock, iflag);
13991 		/*
13992 		 * If there is deferred error attention, do not check for
13993 		 * any interrupt.
13994 		 */
13995 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13996 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13997 			return IRQ_NONE;
13998 		}
13999 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
14000 			phba->HAregaddr);
14001 		readl(phba->HAregaddr); /* flush */
14002 		spin_unlock_irqrestore(&phba->hbalock, iflag);
14003 	} else
14004 		ha_copy = phba->ha_copy;
14005 
14006 	/*
14007 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
14008 	 */
14009 	ha_copy &= ~(phba->work_ha_mask);
14010 
14011 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
14012 	status >>= (4*LPFC_FCP_RING);
14013 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
14014 	if (status & HA_RXMASK)
14015 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
14016 
14017 	if (phba->cfg_multi_ring_support == 2) {
14018 		/*
14019 		 * Process all events on extra ring. Take the optimized path
14020 		 * for extra ring IO.
14021 		 */
14022 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14023 		status >>= (4*LPFC_EXTRA_RING);
14024 		if (status & HA_RXMASK) {
14025 			lpfc_sli_handle_fast_ring_event(phba,
14026 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
14027 					status);
14028 		}
14029 	}
14030 	return IRQ_HANDLED;
14031 }  /* lpfc_sli_fp_intr_handler */
14032 
14033 /**
14034  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
14035  * @irq: Interrupt number.
14036  * @dev_id: The device context pointer.
14037  *
14038  * This function is the HBA device-level interrupt handler to device with
14039  * SLI-3 interface spec, called from the PCI layer when either MSI or
14040  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
14041  * requires driver attention. This function invokes the slow-path interrupt
14042  * attention handling function and fast-path interrupt attention handling
14043  * function in turn to process the relevant HBA attention events. This
14044  * function is called without any lock held. It gets the hbalock to access
14045  * and update SLI data structures.
14046  *
14047  * This function returns IRQ_HANDLED when interrupt is handled, else it
14048  * returns IRQ_NONE.
14049  **/
14050 irqreturn_t
14051 lpfc_sli_intr_handler(int irq, void *dev_id)
14052 {
14053 	struct lpfc_hba  *phba;
14054 	irqreturn_t sp_irq_rc, fp_irq_rc;
14055 	unsigned long status1, status2;
14056 	uint32_t hc_copy;
14057 
14058 	/*
14059 	 * Get the driver's phba structure from the dev_id and
14060 	 * assume the HBA is not interrupting.
14061 	 */
14062 	phba = (struct lpfc_hba *) dev_id;
14063 
14064 	if (unlikely(!phba))
14065 		return IRQ_NONE;
14066 
14067 	/* Check device state for handling interrupt */
14068 	if (lpfc_intr_state_check(phba))
14069 		return IRQ_NONE;
14070 
14071 	spin_lock(&phba->hbalock);
14072 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
14073 		spin_unlock(&phba->hbalock);
14074 		return IRQ_HANDLED;
14075 	}
14076 
14077 	if (unlikely(!phba->ha_copy)) {
14078 		spin_unlock(&phba->hbalock);
14079 		return IRQ_NONE;
14080 	} else if (phba->ha_copy & HA_ERATT) {
14081 		if (phba->hba_flag & HBA_ERATT_HANDLED)
14082 			/* ERATT polling has handled ERATT */
14083 			phba->ha_copy &= ~HA_ERATT;
14084 		else
14085 			/* Indicate interrupt handler handles ERATT */
14086 			phba->hba_flag |= HBA_ERATT_HANDLED;
14087 	}
14088 
14089 	/*
14090 	 * If there is deferred error attention, do not check for any interrupt.
14091 	 */
14092 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
14093 		spin_unlock(&phba->hbalock);
14094 		return IRQ_NONE;
14095 	}
14096 
14097 	/* Clear attention sources except link and error attentions */
14098 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
14099 		spin_unlock(&phba->hbalock);
14100 		return IRQ_HANDLED;
14101 	}
14102 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
14103 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
14104 		phba->HCregaddr);
14105 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
14106 	writel(hc_copy, phba->HCregaddr);
14107 	readl(phba->HAregaddr); /* flush */
14108 	spin_unlock(&phba->hbalock);
14109 
14110 	/*
14111 	 * Invokes slow-path host attention interrupt handling as appropriate.
14112 	 */
14113 
14114 	/* status of events with mailbox and link attention */
14115 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
14116 
14117 	/* status of events with ELS ring */
14118 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
14119 	status2 >>= (4*LPFC_ELS_RING);
14120 
14121 	if (status1 || (status2 & HA_RXMASK))
14122 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
14123 	else
14124 		sp_irq_rc = IRQ_NONE;
14125 
14126 	/*
14127 	 * Invoke fast-path host attention interrupt handling as appropriate.
14128 	 */
14129 
14130 	/* status of events with FCP ring */
14131 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
14132 	status1 >>= (4*LPFC_FCP_RING);
14133 
14134 	/* status of events with extra ring */
14135 	if (phba->cfg_multi_ring_support == 2) {
14136 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14137 		status2 >>= (4*LPFC_EXTRA_RING);
14138 	} else
14139 		status2 = 0;
14140 
14141 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
14142 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
14143 	else
14144 		fp_irq_rc = IRQ_NONE;
14145 
14146 	/* Return device-level interrupt handling status */
14147 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
14148 }  /* lpfc_sli_intr_handler */
14149 
14150 /**
14151  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
14152  * @phba: pointer to lpfc hba data structure.
14153  *
14154  * This routine is invoked by the worker thread to process all the pending
14155  * SLI4 els abort xri events.
14156  **/
14157 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
14158 {
14159 	struct lpfc_cq_event *cq_event;
14160 	unsigned long iflags;
14161 
14162 	/* First, declare the els xri abort event has been handled */
14163 	spin_lock_irqsave(&phba->hbalock, iflags);
14164 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
14165 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14166 
14167 	/* Now, handle all the els xri abort events */
14168 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14169 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
14170 		/* Get the first event from the head of the event queue */
14171 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
14172 				 cq_event, struct lpfc_cq_event, list);
14173 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14174 				       iflags);
14175 		/* Notify aborted XRI for ELS work queue */
14176 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
14177 
14178 		/* Free the event processed back to the free pool */
14179 		lpfc_sli4_cq_event_release(phba, cq_event);
14180 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14181 				  iflags);
14182 	}
14183 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14184 }
14185 
14186 /**
14187  * lpfc_sli4_els_preprocess_rspiocbq - Get response iocbq from els wcqe
14188  * @phba: Pointer to HBA context object.
14189  * @irspiocbq: Pointer to work-queue completion queue entry.
14190  *
14191  * This routine handles an ELS work-queue completion event and construct
14192  * a pseudo response ELS IOCBQ from the SLI4 ELS WCQE for the common
14193  * discovery engine to handle.
14194  *
14195  * Return: Pointer to the receive IOCBQ, NULL otherwise.
14196  **/
14197 static struct lpfc_iocbq *
14198 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
14199 				  struct lpfc_iocbq *irspiocbq)
14200 {
14201 	struct lpfc_sli_ring *pring;
14202 	struct lpfc_iocbq *cmdiocbq;
14203 	struct lpfc_wcqe_complete *wcqe;
14204 	unsigned long iflags;
14205 
14206 	pring = lpfc_phba_elsring(phba);
14207 	if (unlikely(!pring))
14208 		return NULL;
14209 
14210 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
14211 	spin_lock_irqsave(&pring->ring_lock, iflags);
14212 	pring->stats.iocb_event++;
14213 	/* Look up the ELS command IOCB and create pseudo response IOCB */
14214 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14215 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14216 	if (unlikely(!cmdiocbq)) {
14217 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
14218 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14219 				"0386 ELS complete with no corresponding "
14220 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
14221 				wcqe->word0, wcqe->total_data_placed,
14222 				wcqe->parameter, wcqe->word3);
14223 		lpfc_sli_release_iocbq(phba, irspiocbq);
14224 		return NULL;
14225 	}
14226 
14227 	memcpy(&irspiocbq->wqe, &cmdiocbq->wqe, sizeof(union lpfc_wqe128));
14228 	memcpy(&irspiocbq->wcqe_cmpl, wcqe, sizeof(*wcqe));
14229 
14230 	/* Put the iocb back on the txcmplq */
14231 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
14232 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
14233 
14234 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
14235 		spin_lock_irqsave(&phba->hbalock, iflags);
14236 		irspiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
14237 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14238 	}
14239 
14240 	return irspiocbq;
14241 }
14242 
14243 inline struct lpfc_cq_event *
14244 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
14245 {
14246 	struct lpfc_cq_event *cq_event;
14247 
14248 	/* Allocate a new internal CQ_EVENT entry */
14249 	cq_event = lpfc_sli4_cq_event_alloc(phba);
14250 	if (!cq_event) {
14251 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14252 				"0602 Failed to alloc CQ_EVENT entry\n");
14253 		return NULL;
14254 	}
14255 
14256 	/* Move the CQE into the event */
14257 	memcpy(&cq_event->cqe, entry, size);
14258 	return cq_event;
14259 }
14260 
14261 /**
14262  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
14263  * @phba: Pointer to HBA context object.
14264  * @mcqe: Pointer to mailbox completion queue entry.
14265  *
14266  * This routine process a mailbox completion queue entry with asynchronous
14267  * event.
14268  *
14269  * Return: true if work posted to worker thread, otherwise false.
14270  **/
14271 static bool
14272 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14273 {
14274 	struct lpfc_cq_event *cq_event;
14275 	unsigned long iflags;
14276 
14277 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14278 			"0392 Async Event: word0:x%x, word1:x%x, "
14279 			"word2:x%x, word3:x%x\n", mcqe->word0,
14280 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
14281 
14282 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
14283 	if (!cq_event)
14284 		return false;
14285 
14286 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
14287 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
14288 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
14289 
14290 	/* Set the async event flag */
14291 	spin_lock_irqsave(&phba->hbalock, iflags);
14292 	phba->hba_flag |= ASYNC_EVENT;
14293 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14294 
14295 	return true;
14296 }
14297 
14298 /**
14299  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
14300  * @phba: Pointer to HBA context object.
14301  * @mcqe: Pointer to mailbox completion queue entry.
14302  *
14303  * This routine process a mailbox completion queue entry with mailbox
14304  * completion event.
14305  *
14306  * Return: true if work posted to worker thread, otherwise false.
14307  **/
14308 static bool
14309 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14310 {
14311 	uint32_t mcqe_status;
14312 	MAILBOX_t *mbox, *pmbox;
14313 	struct lpfc_mqe *mqe;
14314 	struct lpfc_vport *vport;
14315 	struct lpfc_nodelist *ndlp;
14316 	struct lpfc_dmabuf *mp;
14317 	unsigned long iflags;
14318 	LPFC_MBOXQ_t *pmb;
14319 	bool workposted = false;
14320 	int rc;
14321 
14322 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
14323 	if (!bf_get(lpfc_trailer_completed, mcqe))
14324 		goto out_no_mqe_complete;
14325 
14326 	/* Get the reference to the active mbox command */
14327 	spin_lock_irqsave(&phba->hbalock, iflags);
14328 	pmb = phba->sli.mbox_active;
14329 	if (unlikely(!pmb)) {
14330 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14331 				"1832 No pending MBOX command to handle\n");
14332 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14333 		goto out_no_mqe_complete;
14334 	}
14335 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14336 	mqe = &pmb->u.mqe;
14337 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
14338 	mbox = phba->mbox;
14339 	vport = pmb->vport;
14340 
14341 	/* Reset heartbeat timer */
14342 	phba->last_completion_time = jiffies;
14343 	del_timer(&phba->sli.mbox_tmo);
14344 
14345 	/* Move mbox data to caller's mailbox region, do endian swapping */
14346 	if (pmb->mbox_cmpl && mbox)
14347 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
14348 
14349 	/*
14350 	 * For mcqe errors, conditionally move a modified error code to
14351 	 * the mbox so that the error will not be missed.
14352 	 */
14353 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
14354 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
14355 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
14356 			bf_set(lpfc_mqe_status, mqe,
14357 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
14358 	}
14359 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
14360 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
14361 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
14362 				      "MBOX dflt rpi: status:x%x rpi:x%x",
14363 				      mcqe_status,
14364 				      pmbox->un.varWords[0], 0);
14365 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
14366 			mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
14367 			ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
14368 
14369 			/* Reg_LOGIN of dflt RPI was successful. Mark the
14370 			 * node as having an UNREG_LOGIN in progress to stop
14371 			 * an unsolicited PLOGI from the same NPortId from
14372 			 * starting another mailbox transaction.
14373 			 */
14374 			spin_lock_irqsave(&ndlp->lock, iflags);
14375 			ndlp->nlp_flag |= NLP_UNREG_INP;
14376 			spin_unlock_irqrestore(&ndlp->lock, iflags);
14377 			lpfc_unreg_login(phba, vport->vpi,
14378 					 pmbox->un.varWords[0], pmb);
14379 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
14380 			pmb->ctx_buf = mp;
14381 
14382 			/* No reference taken here.  This is a default
14383 			 * RPI reg/immediate unreg cycle. The reference was
14384 			 * taken in the reg rpi path and is released when
14385 			 * this mailbox completes.
14386 			 */
14387 			pmb->ctx_ndlp = ndlp;
14388 			pmb->vport = vport;
14389 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
14390 			if (rc != MBX_BUSY)
14391 				lpfc_printf_log(phba, KERN_ERR,
14392 						LOG_TRACE_EVENT,
14393 						"0385 rc should "
14394 						"have been MBX_BUSY\n");
14395 			if (rc != MBX_NOT_FINISHED)
14396 				goto send_current_mbox;
14397 		}
14398 	}
14399 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
14400 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
14401 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
14402 
14403 	/* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
14404 	if (pmbox->mbxCommand == MBX_HEARTBEAT) {
14405 		spin_lock_irqsave(&phba->hbalock, iflags);
14406 		/* Release the mailbox command posting token */
14407 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14408 		phba->sli.mbox_active = NULL;
14409 		if (bf_get(lpfc_trailer_consumed, mcqe))
14410 			lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14411 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14412 
14413 		/* Post the next mbox command, if there is one */
14414 		lpfc_sli4_post_async_mbox(phba);
14415 
14416 		/* Process cmpl now */
14417 		if (pmb->mbox_cmpl)
14418 			pmb->mbox_cmpl(phba, pmb);
14419 		return false;
14420 	}
14421 
14422 	/* There is mailbox completion work to queue to the worker thread */
14423 	spin_lock_irqsave(&phba->hbalock, iflags);
14424 	__lpfc_mbox_cmpl_put(phba, pmb);
14425 	phba->work_ha |= HA_MBATT;
14426 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14427 	workposted = true;
14428 
14429 send_current_mbox:
14430 	spin_lock_irqsave(&phba->hbalock, iflags);
14431 	/* Release the mailbox command posting token */
14432 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14433 	/* Setting active mailbox pointer need to be in sync to flag clear */
14434 	phba->sli.mbox_active = NULL;
14435 	if (bf_get(lpfc_trailer_consumed, mcqe))
14436 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14437 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14438 	/* Wake up worker thread to post the next pending mailbox command */
14439 	lpfc_worker_wake_up(phba);
14440 	return workposted;
14441 
14442 out_no_mqe_complete:
14443 	spin_lock_irqsave(&phba->hbalock, iflags);
14444 	if (bf_get(lpfc_trailer_consumed, mcqe))
14445 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14446 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14447 	return false;
14448 }
14449 
14450 /**
14451  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
14452  * @phba: Pointer to HBA context object.
14453  * @cq: Pointer to associated CQ
14454  * @cqe: Pointer to mailbox completion queue entry.
14455  *
14456  * This routine process a mailbox completion queue entry, it invokes the
14457  * proper mailbox complete handling or asynchronous event handling routine
14458  * according to the MCQE's async bit.
14459  *
14460  * Return: true if work posted to worker thread, otherwise false.
14461  **/
14462 static bool
14463 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14464 			 struct lpfc_cqe *cqe)
14465 {
14466 	struct lpfc_mcqe mcqe;
14467 	bool workposted;
14468 
14469 	cq->CQ_mbox++;
14470 
14471 	/* Copy the mailbox MCQE and convert endian order as needed */
14472 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
14473 
14474 	/* Invoke the proper event handling routine */
14475 	if (!bf_get(lpfc_trailer_async, &mcqe))
14476 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
14477 	else
14478 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
14479 	return workposted;
14480 }
14481 
14482 /**
14483  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
14484  * @phba: Pointer to HBA context object.
14485  * @cq: Pointer to associated CQ
14486  * @wcqe: Pointer to work-queue completion queue entry.
14487  *
14488  * This routine handles an ELS work-queue completion event.
14489  *
14490  * Return: true if work posted to worker thread, otherwise false.
14491  **/
14492 static bool
14493 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14494 			     struct lpfc_wcqe_complete *wcqe)
14495 {
14496 	struct lpfc_iocbq *irspiocbq;
14497 	unsigned long iflags;
14498 	struct lpfc_sli_ring *pring = cq->pring;
14499 	int txq_cnt = 0;
14500 	int txcmplq_cnt = 0;
14501 
14502 	/* Check for response status */
14503 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14504 		/* Log the error status */
14505 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14506 				"0357 ELS CQE error: status=x%x: "
14507 				"CQE: %08x %08x %08x %08x\n",
14508 				bf_get(lpfc_wcqe_c_status, wcqe),
14509 				wcqe->word0, wcqe->total_data_placed,
14510 				wcqe->parameter, wcqe->word3);
14511 	}
14512 
14513 	/* Get an irspiocbq for later ELS response processing use */
14514 	irspiocbq = lpfc_sli_get_iocbq(phba);
14515 	if (!irspiocbq) {
14516 		if (!list_empty(&pring->txq))
14517 			txq_cnt++;
14518 		if (!list_empty(&pring->txcmplq))
14519 			txcmplq_cnt++;
14520 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14521 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
14522 			"els_txcmplq_cnt=%d\n",
14523 			txq_cnt, phba->iocb_cnt,
14524 			txcmplq_cnt);
14525 		return false;
14526 	}
14527 
14528 	/* Save off the slow-path queue event for work thread to process */
14529 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
14530 	spin_lock_irqsave(&phba->hbalock, iflags);
14531 	list_add_tail(&irspiocbq->cq_event.list,
14532 		      &phba->sli4_hba.sp_queue_event);
14533 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
14534 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14535 
14536 	return true;
14537 }
14538 
14539 /**
14540  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
14541  * @phba: Pointer to HBA context object.
14542  * @wcqe: Pointer to work-queue completion queue entry.
14543  *
14544  * This routine handles slow-path WQ entry consumed event by invoking the
14545  * proper WQ release routine to the slow-path WQ.
14546  **/
14547 static void
14548 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
14549 			     struct lpfc_wcqe_release *wcqe)
14550 {
14551 	/* sanity check on queue memory */
14552 	if (unlikely(!phba->sli4_hba.els_wq))
14553 		return;
14554 	/* Check for the slow-path ELS work queue */
14555 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
14556 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
14557 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14558 	else
14559 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14560 				"2579 Slow-path wqe consume event carries "
14561 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
14562 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
14563 				phba->sli4_hba.els_wq->queue_id);
14564 }
14565 
14566 /**
14567  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
14568  * @phba: Pointer to HBA context object.
14569  * @cq: Pointer to a WQ completion queue.
14570  * @wcqe: Pointer to work-queue completion queue entry.
14571  *
14572  * This routine handles an XRI abort event.
14573  *
14574  * Return: true if work posted to worker thread, otherwise false.
14575  **/
14576 static bool
14577 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
14578 				   struct lpfc_queue *cq,
14579 				   struct sli4_wcqe_xri_aborted *wcqe)
14580 {
14581 	bool workposted = false;
14582 	struct lpfc_cq_event *cq_event;
14583 	unsigned long iflags;
14584 
14585 	switch (cq->subtype) {
14586 	case LPFC_IO:
14587 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
14588 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14589 			/* Notify aborted XRI for NVME work queue */
14590 			if (phba->nvmet_support)
14591 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
14592 		}
14593 		workposted = false;
14594 		break;
14595 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
14596 	case LPFC_ELS:
14597 		cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
14598 		if (!cq_event) {
14599 			workposted = false;
14600 			break;
14601 		}
14602 		cq_event->hdwq = cq->hdwq;
14603 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14604 				  iflags);
14605 		list_add_tail(&cq_event->list,
14606 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
14607 		/* Set the els xri abort event flag */
14608 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
14609 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14610 				       iflags);
14611 		workposted = true;
14612 		break;
14613 	default:
14614 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14615 				"0603 Invalid CQ subtype %d: "
14616 				"%08x %08x %08x %08x\n",
14617 				cq->subtype, wcqe->word0, wcqe->parameter,
14618 				wcqe->word2, wcqe->word3);
14619 		workposted = false;
14620 		break;
14621 	}
14622 	return workposted;
14623 }
14624 
14625 #define FC_RCTL_MDS_DIAGS	0xF4
14626 
14627 /**
14628  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
14629  * @phba: Pointer to HBA context object.
14630  * @rcqe: Pointer to receive-queue completion queue entry.
14631  *
14632  * This routine process a receive-queue completion queue entry.
14633  *
14634  * Return: true if work posted to worker thread, otherwise false.
14635  **/
14636 static bool
14637 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
14638 {
14639 	bool workposted = false;
14640 	struct fc_frame_header *fc_hdr;
14641 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
14642 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
14643 	struct lpfc_nvmet_tgtport *tgtp;
14644 	struct hbq_dmabuf *dma_buf;
14645 	uint32_t status, rq_id;
14646 	unsigned long iflags;
14647 
14648 	/* sanity check on queue memory */
14649 	if (unlikely(!hrq) || unlikely(!drq))
14650 		return workposted;
14651 
14652 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14653 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14654 	else
14655 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14656 	if (rq_id != hrq->queue_id)
14657 		goto out;
14658 
14659 	status = bf_get(lpfc_rcqe_status, rcqe);
14660 	switch (status) {
14661 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14662 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14663 				"2537 Receive Frame Truncated!!\n");
14664 		fallthrough;
14665 	case FC_STATUS_RQ_SUCCESS:
14666 		spin_lock_irqsave(&phba->hbalock, iflags);
14667 		lpfc_sli4_rq_release(hrq, drq);
14668 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14669 		if (!dma_buf) {
14670 			hrq->RQ_no_buf_found++;
14671 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14672 			goto out;
14673 		}
14674 		hrq->RQ_rcv_buf++;
14675 		hrq->RQ_buf_posted--;
14676 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
14677 
14678 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14679 
14680 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
14681 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
14682 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14683 			/* Handle MDS Loopback frames */
14684 			if  (!(phba->pport->load_flag & FC_UNLOADING))
14685 				lpfc_sli4_handle_mds_loopback(phba->pport,
14686 							      dma_buf);
14687 			else
14688 				lpfc_in_buf_free(phba, &dma_buf->dbuf);
14689 			break;
14690 		}
14691 
14692 		/* save off the frame for the work thread to process */
14693 		list_add_tail(&dma_buf->cq_event.list,
14694 			      &phba->sli4_hba.sp_queue_event);
14695 		/* Frame received */
14696 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
14697 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14698 		workposted = true;
14699 		break;
14700 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14701 		if (phba->nvmet_support) {
14702 			tgtp = phba->targetport->private;
14703 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14704 					"6402 RQE Error x%x, posted %d err_cnt "
14705 					"%d: %x %x %x\n",
14706 					status, hrq->RQ_buf_posted,
14707 					hrq->RQ_no_posted_buf,
14708 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14709 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14710 					atomic_read(&tgtp->xmt_fcp_release));
14711 		}
14712 		fallthrough;
14713 
14714 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14715 		hrq->RQ_no_posted_buf++;
14716 		/* Post more buffers if possible */
14717 		spin_lock_irqsave(&phba->hbalock, iflags);
14718 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
14719 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14720 		workposted = true;
14721 		break;
14722 	}
14723 out:
14724 	return workposted;
14725 }
14726 
14727 /**
14728  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
14729  * @phba: Pointer to HBA context object.
14730  * @cq: Pointer to the completion queue.
14731  * @cqe: Pointer to a completion queue entry.
14732  *
14733  * This routine process a slow-path work-queue or receive queue completion queue
14734  * entry.
14735  *
14736  * Return: true if work posted to worker thread, otherwise false.
14737  **/
14738 static bool
14739 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14740 			 struct lpfc_cqe *cqe)
14741 {
14742 	struct lpfc_cqe cqevt;
14743 	bool workposted = false;
14744 
14745 	/* Copy the work queue CQE and convert endian order if needed */
14746 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14747 
14748 	/* Check and process for different type of WCQE and dispatch */
14749 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
14750 	case CQE_CODE_COMPL_WQE:
14751 		/* Process the WQ/RQ complete event */
14752 		phba->last_completion_time = jiffies;
14753 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14754 				(struct lpfc_wcqe_complete *)&cqevt);
14755 		break;
14756 	case CQE_CODE_RELEASE_WQE:
14757 		/* Process the WQ release event */
14758 		lpfc_sli4_sp_handle_rel_wcqe(phba,
14759 				(struct lpfc_wcqe_release *)&cqevt);
14760 		break;
14761 	case CQE_CODE_XRI_ABORTED:
14762 		/* Process the WQ XRI abort event */
14763 		phba->last_completion_time = jiffies;
14764 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14765 				(struct sli4_wcqe_xri_aborted *)&cqevt);
14766 		break;
14767 	case CQE_CODE_RECEIVE:
14768 	case CQE_CODE_RECEIVE_V1:
14769 		/* Process the RQ event */
14770 		phba->last_completion_time = jiffies;
14771 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
14772 				(struct lpfc_rcqe *)&cqevt);
14773 		break;
14774 	default:
14775 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14776 				"0388 Not a valid WCQE code: x%x\n",
14777 				bf_get(lpfc_cqe_code, &cqevt));
14778 		break;
14779 	}
14780 	return workposted;
14781 }
14782 
14783 /**
14784  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14785  * @phba: Pointer to HBA context object.
14786  * @eqe: Pointer to fast-path event queue entry.
14787  * @speq: Pointer to slow-path event queue.
14788  *
14789  * This routine process a event queue entry from the slow-path event queue.
14790  * It will check the MajorCode and MinorCode to determine this is for a
14791  * completion event on a completion queue, if not, an error shall be logged
14792  * and just return. Otherwise, it will get to the corresponding completion
14793  * queue and process all the entries on that completion queue, rearm the
14794  * completion queue, and then return.
14795  *
14796  **/
14797 static void
14798 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14799 	struct lpfc_queue *speq)
14800 {
14801 	struct lpfc_queue *cq = NULL, *childq;
14802 	uint16_t cqid;
14803 	int ret = 0;
14804 
14805 	/* Get the reference to the corresponding CQ */
14806 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14807 
14808 	list_for_each_entry(childq, &speq->child_list, list) {
14809 		if (childq->queue_id == cqid) {
14810 			cq = childq;
14811 			break;
14812 		}
14813 	}
14814 	if (unlikely(!cq)) {
14815 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14816 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14817 					"0365 Slow-path CQ identifier "
14818 					"(%d) does not exist\n", cqid);
14819 		return;
14820 	}
14821 
14822 	/* Save EQ associated with this CQ */
14823 	cq->assoc_qp = speq;
14824 
14825 	if (is_kdump_kernel())
14826 		ret = queue_work(phba->wq, &cq->spwork);
14827 	else
14828 		ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14829 
14830 	if (!ret)
14831 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14832 				"0390 Cannot schedule queue work "
14833 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14834 				cqid, cq->queue_id, raw_smp_processor_id());
14835 }
14836 
14837 /**
14838  * __lpfc_sli4_process_cq - Process elements of a CQ
14839  * @phba: Pointer to HBA context object.
14840  * @cq: Pointer to CQ to be processed
14841  * @handler: Routine to process each cqe
14842  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14843  * @poll_mode: Polling mode we were called from
14844  *
14845  * This routine processes completion queue entries in a CQ. While a valid
14846  * queue element is found, the handler is called. During processing checks
14847  * are made for periodic doorbell writes to let the hardware know of
14848  * element consumption.
14849  *
14850  * If the max limit on cqes to process is hit, or there are no more valid
14851  * entries, the loop stops. If we processed a sufficient number of elements,
14852  * meaning there is sufficient load, rather than rearming and generating
14853  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14854  * indicates no rescheduling.
14855  *
14856  * Returns True if work scheduled, False otherwise.
14857  **/
14858 static bool
14859 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14860 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14861 			struct lpfc_cqe *), unsigned long *delay,
14862 			enum lpfc_poll_mode poll_mode)
14863 {
14864 	struct lpfc_cqe *cqe;
14865 	bool workposted = false;
14866 	int count = 0, consumed = 0;
14867 	bool arm = true;
14868 
14869 	/* default - no reschedule */
14870 	*delay = 0;
14871 
14872 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14873 		goto rearm_and_exit;
14874 
14875 	/* Process all the entries to the CQ */
14876 	cq->q_flag = 0;
14877 	cqe = lpfc_sli4_cq_get(cq);
14878 	while (cqe) {
14879 		workposted |= handler(phba, cq, cqe);
14880 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
14881 
14882 		consumed++;
14883 		if (!(++count % cq->max_proc_limit))
14884 			break;
14885 
14886 		if (!(count % cq->notify_interval)) {
14887 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14888 						LPFC_QUEUE_NOARM);
14889 			consumed = 0;
14890 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14891 		}
14892 
14893 		if (count == LPFC_NVMET_CQ_NOTIFY)
14894 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14895 
14896 		cqe = lpfc_sli4_cq_get(cq);
14897 	}
14898 	if (count >= phba->cfg_cq_poll_threshold) {
14899 		*delay = 1;
14900 		arm = false;
14901 	}
14902 
14903 	/* Note: complete the irq_poll softirq before rearming CQ */
14904 	if (poll_mode == LPFC_IRQ_POLL)
14905 		irq_poll_complete(&cq->iop);
14906 
14907 	/* Track the max number of CQEs processed in 1 EQ */
14908 	if (count > cq->CQ_max_cqe)
14909 		cq->CQ_max_cqe = count;
14910 
14911 	cq->assoc_qp->EQ_cqe_cnt += count;
14912 
14913 	/* Catch the no cq entry condition */
14914 	if (unlikely(count == 0))
14915 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14916 				"0369 No entry from completion queue "
14917 				"qid=%d\n", cq->queue_id);
14918 
14919 	xchg(&cq->queue_claimed, 0);
14920 
14921 rearm_and_exit:
14922 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14923 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14924 
14925 	return workposted;
14926 }
14927 
14928 /**
14929  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14930  * @cq: pointer to CQ to process
14931  *
14932  * This routine calls the cq processing routine with a handler specific
14933  * to the type of queue bound to it.
14934  *
14935  * The CQ routine returns two values: the first is the calling status,
14936  * which indicates whether work was queued to the  background discovery
14937  * thread. If true, the routine should wakeup the discovery thread;
14938  * the second is the delay parameter. If non-zero, rather than rearming
14939  * the CQ and yet another interrupt, the CQ handler should be queued so
14940  * that it is processed in a subsequent polling action. The value of
14941  * the delay indicates when to reschedule it.
14942  **/
14943 static void
14944 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14945 {
14946 	struct lpfc_hba *phba = cq->phba;
14947 	unsigned long delay;
14948 	bool workposted = false;
14949 	int ret = 0;
14950 
14951 	/* Process and rearm the CQ */
14952 	switch (cq->type) {
14953 	case LPFC_MCQ:
14954 		workposted |= __lpfc_sli4_process_cq(phba, cq,
14955 						lpfc_sli4_sp_handle_mcqe,
14956 						&delay, LPFC_QUEUE_WORK);
14957 		break;
14958 	case LPFC_WCQ:
14959 		if (cq->subtype == LPFC_IO)
14960 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14961 						lpfc_sli4_fp_handle_cqe,
14962 						&delay, LPFC_QUEUE_WORK);
14963 		else
14964 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14965 						lpfc_sli4_sp_handle_cqe,
14966 						&delay, LPFC_QUEUE_WORK);
14967 		break;
14968 	default:
14969 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14970 				"0370 Invalid completion queue type (%d)\n",
14971 				cq->type);
14972 		return;
14973 	}
14974 
14975 	if (delay) {
14976 		if (is_kdump_kernel())
14977 			ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
14978 						delay);
14979 		else
14980 			ret = queue_delayed_work_on(cq->chann, phba->wq,
14981 						&cq->sched_spwork, delay);
14982 		if (!ret)
14983 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14984 				"0394 Cannot schedule queue work "
14985 				"for cqid=%d on CPU %d\n",
14986 				cq->queue_id, cq->chann);
14987 	}
14988 
14989 	/* wake up worker thread if there are works to be done */
14990 	if (workposted)
14991 		lpfc_worker_wake_up(phba);
14992 }
14993 
14994 /**
14995  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
14996  *   interrupt
14997  * @work: pointer to work element
14998  *
14999  * translates from the work handler and calls the slow-path handler.
15000  **/
15001 static void
15002 lpfc_sli4_sp_process_cq(struct work_struct *work)
15003 {
15004 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
15005 
15006 	__lpfc_sli4_sp_process_cq(cq);
15007 }
15008 
15009 /**
15010  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
15011  * @work: pointer to work element
15012  *
15013  * translates from the work handler and calls the slow-path handler.
15014  **/
15015 static void
15016 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
15017 {
15018 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15019 					struct lpfc_queue, sched_spwork);
15020 
15021 	__lpfc_sli4_sp_process_cq(cq);
15022 }
15023 
15024 /**
15025  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
15026  * @phba: Pointer to HBA context object.
15027  * @cq: Pointer to associated CQ
15028  * @wcqe: Pointer to work-queue completion queue entry.
15029  *
15030  * This routine process a fast-path work queue completion entry from fast-path
15031  * event queue for FCP command response completion.
15032  **/
15033 static void
15034 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15035 			     struct lpfc_wcqe_complete *wcqe)
15036 {
15037 	struct lpfc_sli_ring *pring = cq->pring;
15038 	struct lpfc_iocbq *cmdiocbq;
15039 	unsigned long iflags;
15040 
15041 	/* Check for response status */
15042 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
15043 		/* If resource errors reported from HBA, reduce queue
15044 		 * depth of the SCSI device.
15045 		 */
15046 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
15047 		     IOSTAT_LOCAL_REJECT)) &&
15048 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
15049 		     IOERR_NO_RESOURCES))
15050 			phba->lpfc_rampdown_queue_depth(phba);
15051 
15052 		/* Log the cmpl status */
15053 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15054 				"0373 FCP CQE cmpl: status=x%x: "
15055 				"CQE: %08x %08x %08x %08x\n",
15056 				bf_get(lpfc_wcqe_c_status, wcqe),
15057 				wcqe->word0, wcqe->total_data_placed,
15058 				wcqe->parameter, wcqe->word3);
15059 	}
15060 
15061 	/* Look up the FCP command IOCB and create pseudo response IOCB */
15062 	spin_lock_irqsave(&pring->ring_lock, iflags);
15063 	pring->stats.iocb_event++;
15064 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
15065 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15066 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
15067 	if (unlikely(!cmdiocbq)) {
15068 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15069 				"0374 FCP complete with no corresponding "
15070 				"cmdiocb: iotag (%d)\n",
15071 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15072 		return;
15073 	}
15074 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
15075 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
15076 #endif
15077 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
15078 		spin_lock_irqsave(&phba->hbalock, iflags);
15079 		cmdiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
15080 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15081 	}
15082 
15083 	if (cmdiocbq->cmd_cmpl) {
15084 		/* For FCP the flag is cleared in cmd_cmpl */
15085 		if (!(cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
15086 		    cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED) {
15087 			spin_lock_irqsave(&phba->hbalock, iflags);
15088 			cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
15089 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15090 		}
15091 
15092 		/* Pass the cmd_iocb and the wcqe to the upper layer */
15093 		memcpy(&cmdiocbq->wcqe_cmpl, wcqe,
15094 		       sizeof(struct lpfc_wcqe_complete));
15095 		cmdiocbq->cmd_cmpl(phba, cmdiocbq, cmdiocbq);
15096 	} else {
15097 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15098 				"0375 FCP cmdiocb not callback function "
15099 				"iotag: (%d)\n",
15100 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15101 	}
15102 }
15103 
15104 /**
15105  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
15106  * @phba: Pointer to HBA context object.
15107  * @cq: Pointer to completion queue.
15108  * @wcqe: Pointer to work-queue completion queue entry.
15109  *
15110  * This routine handles an fast-path WQ entry consumed event by invoking the
15111  * proper WQ release routine to the slow-path WQ.
15112  **/
15113 static void
15114 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15115 			     struct lpfc_wcqe_release *wcqe)
15116 {
15117 	struct lpfc_queue *childwq;
15118 	bool wqid_matched = false;
15119 	uint16_t hba_wqid;
15120 
15121 	/* Check for fast-path FCP work queue release */
15122 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
15123 	list_for_each_entry(childwq, &cq->child_list, list) {
15124 		if (childwq->queue_id == hba_wqid) {
15125 			lpfc_sli4_wq_release(childwq,
15126 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
15127 			if (childwq->q_flag & HBA_NVMET_WQFULL)
15128 				lpfc_nvmet_wqfull_process(phba, childwq);
15129 			wqid_matched = true;
15130 			break;
15131 		}
15132 	}
15133 	/* Report warning log message if no match found */
15134 	if (wqid_matched != true)
15135 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15136 				"2580 Fast-path wqe consume event carries "
15137 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
15138 }
15139 
15140 /**
15141  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
15142  * @phba: Pointer to HBA context object.
15143  * @cq: Pointer to completion queue.
15144  * @rcqe: Pointer to receive-queue completion queue entry.
15145  *
15146  * This routine process a receive-queue completion queue entry.
15147  *
15148  * Return: true if work posted to worker thread, otherwise false.
15149  **/
15150 static bool
15151 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15152 			    struct lpfc_rcqe *rcqe)
15153 {
15154 	bool workposted = false;
15155 	struct lpfc_queue *hrq;
15156 	struct lpfc_queue *drq;
15157 	struct rqb_dmabuf *dma_buf;
15158 	struct fc_frame_header *fc_hdr;
15159 	struct lpfc_nvmet_tgtport *tgtp;
15160 	uint32_t status, rq_id;
15161 	unsigned long iflags;
15162 	uint32_t fctl, idx;
15163 
15164 	if ((phba->nvmet_support == 0) ||
15165 	    (phba->sli4_hba.nvmet_cqset == NULL))
15166 		return workposted;
15167 
15168 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
15169 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
15170 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
15171 
15172 	/* sanity check on queue memory */
15173 	if (unlikely(!hrq) || unlikely(!drq))
15174 		return workposted;
15175 
15176 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
15177 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
15178 	else
15179 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
15180 
15181 	if ((phba->nvmet_support == 0) ||
15182 	    (rq_id != hrq->queue_id))
15183 		return workposted;
15184 
15185 	status = bf_get(lpfc_rcqe_status, rcqe);
15186 	switch (status) {
15187 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
15188 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15189 				"6126 Receive Frame Truncated!!\n");
15190 		fallthrough;
15191 	case FC_STATUS_RQ_SUCCESS:
15192 		spin_lock_irqsave(&phba->hbalock, iflags);
15193 		lpfc_sli4_rq_release(hrq, drq);
15194 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15195 		if (!dma_buf) {
15196 			hrq->RQ_no_buf_found++;
15197 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15198 			goto out;
15199 		}
15200 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15201 		hrq->RQ_rcv_buf++;
15202 		hrq->RQ_buf_posted--;
15203 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
15204 
15205 		/* Just some basic sanity checks on FCP Command frame */
15206 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
15207 			fc_hdr->fh_f_ctl[1] << 8 |
15208 			fc_hdr->fh_f_ctl[2]);
15209 		if (((fctl &
15210 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
15211 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
15212 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
15213 			goto drop;
15214 
15215 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
15216 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
15217 			lpfc_nvmet_unsol_fcp_event(
15218 				phba, idx, dma_buf, cq->isr_timestamp,
15219 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
15220 			return false;
15221 		}
15222 drop:
15223 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15224 		break;
15225 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
15226 		if (phba->nvmet_support) {
15227 			tgtp = phba->targetport->private;
15228 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15229 					"6401 RQE Error x%x, posted %d err_cnt "
15230 					"%d: %x %x %x\n",
15231 					status, hrq->RQ_buf_posted,
15232 					hrq->RQ_no_posted_buf,
15233 					atomic_read(&tgtp->rcv_fcp_cmd_in),
15234 					atomic_read(&tgtp->rcv_fcp_cmd_out),
15235 					atomic_read(&tgtp->xmt_fcp_release));
15236 		}
15237 		fallthrough;
15238 
15239 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
15240 		hrq->RQ_no_posted_buf++;
15241 		/* Post more buffers if possible */
15242 		break;
15243 	}
15244 out:
15245 	return workposted;
15246 }
15247 
15248 /**
15249  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
15250  * @phba: adapter with cq
15251  * @cq: Pointer to the completion queue.
15252  * @cqe: Pointer to fast-path completion queue entry.
15253  *
15254  * This routine process a fast-path work queue completion entry from fast-path
15255  * event queue for FCP command response completion.
15256  *
15257  * Return: true if work posted to worker thread, otherwise false.
15258  **/
15259 static bool
15260 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15261 			 struct lpfc_cqe *cqe)
15262 {
15263 	struct lpfc_wcqe_release wcqe;
15264 	bool workposted = false;
15265 
15266 	/* Copy the work queue CQE and convert endian order if needed */
15267 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
15268 
15269 	/* Check and process for different type of WCQE and dispatch */
15270 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
15271 	case CQE_CODE_COMPL_WQE:
15272 	case CQE_CODE_NVME_ERSP:
15273 		cq->CQ_wq++;
15274 		/* Process the WQ complete event */
15275 		phba->last_completion_time = jiffies;
15276 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
15277 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
15278 				(struct lpfc_wcqe_complete *)&wcqe);
15279 		break;
15280 	case CQE_CODE_RELEASE_WQE:
15281 		cq->CQ_release_wqe++;
15282 		/* Process the WQ release event */
15283 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
15284 				(struct lpfc_wcqe_release *)&wcqe);
15285 		break;
15286 	case CQE_CODE_XRI_ABORTED:
15287 		cq->CQ_xri_aborted++;
15288 		/* Process the WQ XRI abort event */
15289 		phba->last_completion_time = jiffies;
15290 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
15291 				(struct sli4_wcqe_xri_aborted *)&wcqe);
15292 		break;
15293 	case CQE_CODE_RECEIVE_V1:
15294 	case CQE_CODE_RECEIVE:
15295 		phba->last_completion_time = jiffies;
15296 		if (cq->subtype == LPFC_NVMET) {
15297 			workposted = lpfc_sli4_nvmet_handle_rcqe(
15298 				phba, cq, (struct lpfc_rcqe *)&wcqe);
15299 		}
15300 		break;
15301 	default:
15302 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15303 				"0144 Not a valid CQE code: x%x\n",
15304 				bf_get(lpfc_wcqe_c_code, &wcqe));
15305 		break;
15306 	}
15307 	return workposted;
15308 }
15309 
15310 /**
15311  * lpfc_sli4_sched_cq_work - Schedules cq work
15312  * @phba: Pointer to HBA context object.
15313  * @cq: Pointer to CQ
15314  * @cqid: CQ ID
15315  *
15316  * This routine checks the poll mode of the CQ corresponding to
15317  * cq->chann, then either schedules a softirq or queue_work to complete
15318  * cq work.
15319  *
15320  * queue_work path is taken if in NVMET mode, or if poll_mode is in
15321  * LPFC_QUEUE_WORK mode.  Otherwise, softirq path is taken.
15322  *
15323  **/
15324 static void lpfc_sli4_sched_cq_work(struct lpfc_hba *phba,
15325 				    struct lpfc_queue *cq, uint16_t cqid)
15326 {
15327 	int ret = 0;
15328 
15329 	switch (cq->poll_mode) {
15330 	case LPFC_IRQ_POLL:
15331 		/* CGN mgmt is mutually exclusive from softirq processing */
15332 		if (phba->cmf_active_mode == LPFC_CFG_OFF) {
15333 			irq_poll_sched(&cq->iop);
15334 			break;
15335 		}
15336 		fallthrough;
15337 	case LPFC_QUEUE_WORK:
15338 	default:
15339 		if (is_kdump_kernel())
15340 			ret = queue_work(phba->wq, &cq->irqwork);
15341 		else
15342 			ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
15343 		if (!ret)
15344 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15345 					"0383 Cannot schedule queue work "
15346 					"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
15347 					cqid, cq->queue_id,
15348 					raw_smp_processor_id());
15349 	}
15350 }
15351 
15352 /**
15353  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
15354  * @phba: Pointer to HBA context object.
15355  * @eq: Pointer to the queue structure.
15356  * @eqe: Pointer to fast-path event queue entry.
15357  *
15358  * This routine process a event queue entry from the fast-path event queue.
15359  * It will check the MajorCode and MinorCode to determine this is for a
15360  * completion event on a completion queue, if not, an error shall be logged
15361  * and just return. Otherwise, it will get to the corresponding completion
15362  * queue and process all the entries on the completion queue, rearm the
15363  * completion queue, and then return.
15364  **/
15365 static void
15366 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
15367 			 struct lpfc_eqe *eqe)
15368 {
15369 	struct lpfc_queue *cq = NULL;
15370 	uint32_t qidx = eq->hdwq;
15371 	uint16_t cqid, id;
15372 
15373 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
15374 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15375 				"0366 Not a valid completion "
15376 				"event: majorcode=x%x, minorcode=x%x\n",
15377 				bf_get_le32(lpfc_eqe_major_code, eqe),
15378 				bf_get_le32(lpfc_eqe_minor_code, eqe));
15379 		return;
15380 	}
15381 
15382 	/* Get the reference to the corresponding CQ */
15383 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
15384 
15385 	/* Use the fast lookup method first */
15386 	if (cqid <= phba->sli4_hba.cq_max) {
15387 		cq = phba->sli4_hba.cq_lookup[cqid];
15388 		if (cq)
15389 			goto  work_cq;
15390 	}
15391 
15392 	/* Next check for NVMET completion */
15393 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
15394 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
15395 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
15396 			/* Process NVMET unsol rcv */
15397 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
15398 			goto  process_cq;
15399 		}
15400 	}
15401 
15402 	if (phba->sli4_hba.nvmels_cq &&
15403 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
15404 		/* Process NVME unsol rcv */
15405 		cq = phba->sli4_hba.nvmels_cq;
15406 	}
15407 
15408 	/* Otherwise this is a Slow path event */
15409 	if (cq == NULL) {
15410 		lpfc_sli4_sp_handle_eqe(phba, eqe,
15411 					phba->sli4_hba.hdwq[qidx].hba_eq);
15412 		return;
15413 	}
15414 
15415 process_cq:
15416 	if (unlikely(cqid != cq->queue_id)) {
15417 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15418 				"0368 Miss-matched fast-path completion "
15419 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
15420 				cqid, cq->queue_id);
15421 		return;
15422 	}
15423 
15424 work_cq:
15425 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
15426 	if (phba->ktime_on)
15427 		cq->isr_timestamp = ktime_get_ns();
15428 	else
15429 		cq->isr_timestamp = 0;
15430 #endif
15431 	lpfc_sli4_sched_cq_work(phba, cq, cqid);
15432 }
15433 
15434 /**
15435  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
15436  * @cq: Pointer to CQ to be processed
15437  * @poll_mode: Enum lpfc_poll_state to determine poll mode
15438  *
15439  * This routine calls the cq processing routine with the handler for
15440  * fast path CQEs.
15441  *
15442  * The CQ routine returns two values: the first is the calling status,
15443  * which indicates whether work was queued to the  background discovery
15444  * thread. If true, the routine should wakeup the discovery thread;
15445  * the second is the delay parameter. If non-zero, rather than rearming
15446  * the CQ and yet another interrupt, the CQ handler should be queued so
15447  * that it is processed in a subsequent polling action. The value of
15448  * the delay indicates when to reschedule it.
15449  **/
15450 static void
15451 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq,
15452 			   enum lpfc_poll_mode poll_mode)
15453 {
15454 	struct lpfc_hba *phba = cq->phba;
15455 	unsigned long delay;
15456 	bool workposted = false;
15457 	int ret = 0;
15458 
15459 	/* process and rearm the CQ */
15460 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
15461 					     &delay, poll_mode);
15462 
15463 	if (delay) {
15464 		if (is_kdump_kernel())
15465 			ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
15466 						delay);
15467 		else
15468 			ret = queue_delayed_work_on(cq->chann, phba->wq,
15469 						&cq->sched_irqwork, delay);
15470 		if (!ret)
15471 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15472 					"0367 Cannot schedule queue work "
15473 					"for cqid=%d on CPU %d\n",
15474 					cq->queue_id, cq->chann);
15475 	}
15476 
15477 	/* wake up worker thread if there are works to be done */
15478 	if (workposted)
15479 		lpfc_worker_wake_up(phba);
15480 }
15481 
15482 /**
15483  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
15484  *   interrupt
15485  * @work: pointer to work element
15486  *
15487  * translates from the work handler and calls the fast-path handler.
15488  **/
15489 static void
15490 lpfc_sli4_hba_process_cq(struct work_struct *work)
15491 {
15492 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
15493 
15494 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
15495 }
15496 
15497 /**
15498  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
15499  * @work: pointer to work element
15500  *
15501  * translates from the work handler and calls the fast-path handler.
15502  **/
15503 static void
15504 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
15505 {
15506 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15507 					struct lpfc_queue, sched_irqwork);
15508 
15509 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
15510 }
15511 
15512 /**
15513  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
15514  * @irq: Interrupt number.
15515  * @dev_id: The device context pointer.
15516  *
15517  * This function is directly called from the PCI layer as an interrupt
15518  * service routine when device with SLI-4 interface spec is enabled with
15519  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
15520  * ring event in the HBA. However, when the device is enabled with either
15521  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
15522  * device-level interrupt handler. When the PCI slot is in error recovery
15523  * or the HBA is undergoing initialization, the interrupt handler will not
15524  * process the interrupt. The SCSI FCP fast-path ring event are handled in
15525  * the intrrupt context. This function is called without any lock held.
15526  * It gets the hbalock to access and update SLI data structures. Note that,
15527  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
15528  * equal to that of FCP CQ index.
15529  *
15530  * The link attention and ELS ring attention events are handled
15531  * by the worker thread. The interrupt handler signals the worker thread
15532  * and returns for these events. This function is called without any lock
15533  * held. It gets the hbalock to access and update SLI data structures.
15534  *
15535  * This function returns IRQ_HANDLED when interrupt is handled else it
15536  * returns IRQ_NONE.
15537  **/
15538 irqreturn_t
15539 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
15540 {
15541 	struct lpfc_hba *phba;
15542 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
15543 	struct lpfc_queue *fpeq;
15544 	unsigned long iflag;
15545 	int ecount = 0;
15546 	int hba_eqidx;
15547 	struct lpfc_eq_intr_info *eqi;
15548 
15549 	/* Get the driver's phba structure from the dev_id */
15550 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
15551 	phba = hba_eq_hdl->phba;
15552 	hba_eqidx = hba_eq_hdl->idx;
15553 
15554 	if (unlikely(!phba))
15555 		return IRQ_NONE;
15556 	if (unlikely(!phba->sli4_hba.hdwq))
15557 		return IRQ_NONE;
15558 
15559 	/* Get to the EQ struct associated with this vector */
15560 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
15561 	if (unlikely(!fpeq))
15562 		return IRQ_NONE;
15563 
15564 	/* Check device state for handling interrupt */
15565 	if (unlikely(lpfc_intr_state_check(phba))) {
15566 		/* Check again for link_state with lock held */
15567 		spin_lock_irqsave(&phba->hbalock, iflag);
15568 		if (phba->link_state < LPFC_LINK_DOWN)
15569 			/* Flush, clear interrupt, and rearm the EQ */
15570 			lpfc_sli4_eqcq_flush(phba, fpeq);
15571 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15572 		return IRQ_NONE;
15573 	}
15574 
15575 	eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
15576 	eqi->icnt++;
15577 
15578 	fpeq->last_cpu = raw_smp_processor_id();
15579 
15580 	if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
15581 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
15582 	    phba->cfg_auto_imax &&
15583 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
15584 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
15585 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
15586 
15587 	/* process and rearm the EQ */
15588 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
15589 
15590 	if (unlikely(ecount == 0)) {
15591 		fpeq->EQ_no_entry++;
15592 		if (phba->intr_type == MSIX)
15593 			/* MSI-X treated interrupt served as no EQ share INT */
15594 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15595 					"0358 MSI-X interrupt with no EQE\n");
15596 		else
15597 			/* Non MSI-X treated on interrupt as EQ share INT */
15598 			return IRQ_NONE;
15599 	}
15600 
15601 	return IRQ_HANDLED;
15602 } /* lpfc_sli4_hba_intr_handler */
15603 
15604 /**
15605  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
15606  * @irq: Interrupt number.
15607  * @dev_id: The device context pointer.
15608  *
15609  * This function is the device-level interrupt handler to device with SLI-4
15610  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
15611  * interrupt mode is enabled and there is an event in the HBA which requires
15612  * driver attention. This function invokes the slow-path interrupt attention
15613  * handling function and fast-path interrupt attention handling function in
15614  * turn to process the relevant HBA attention events. This function is called
15615  * without any lock held. It gets the hbalock to access and update SLI data
15616  * structures.
15617  *
15618  * This function returns IRQ_HANDLED when interrupt is handled, else it
15619  * returns IRQ_NONE.
15620  **/
15621 irqreturn_t
15622 lpfc_sli4_intr_handler(int irq, void *dev_id)
15623 {
15624 	struct lpfc_hba  *phba;
15625 	irqreturn_t hba_irq_rc;
15626 	bool hba_handled = false;
15627 	int qidx;
15628 
15629 	/* Get the driver's phba structure from the dev_id */
15630 	phba = (struct lpfc_hba *)dev_id;
15631 
15632 	if (unlikely(!phba))
15633 		return IRQ_NONE;
15634 
15635 	/*
15636 	 * Invoke fast-path host attention interrupt handling as appropriate.
15637 	 */
15638 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
15639 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
15640 					&phba->sli4_hba.hba_eq_hdl[qidx]);
15641 		if (hba_irq_rc == IRQ_HANDLED)
15642 			hba_handled |= true;
15643 	}
15644 
15645 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
15646 } /* lpfc_sli4_intr_handler */
15647 
15648 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
15649 {
15650 	struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
15651 	struct lpfc_queue *eq;
15652 
15653 	rcu_read_lock();
15654 
15655 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
15656 		lpfc_sli4_poll_eq(eq);
15657 	if (!list_empty(&phba->poll_list))
15658 		mod_timer(&phba->cpuhp_poll_timer,
15659 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15660 
15661 	rcu_read_unlock();
15662 }
15663 
15664 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
15665 {
15666 	struct lpfc_hba *phba = eq->phba;
15667 
15668 	/* kickstart slowpath processing if needed */
15669 	if (list_empty(&phba->poll_list))
15670 		mod_timer(&phba->cpuhp_poll_timer,
15671 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15672 
15673 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
15674 	synchronize_rcu();
15675 }
15676 
15677 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
15678 {
15679 	struct lpfc_hba *phba = eq->phba;
15680 
15681 	/* Disable slowpath processing for this eq.  Kick start the eq
15682 	 * by RE-ARMING the eq's ASAP
15683 	 */
15684 	list_del_rcu(&eq->_poll_list);
15685 	synchronize_rcu();
15686 
15687 	if (list_empty(&phba->poll_list))
15688 		del_timer_sync(&phba->cpuhp_poll_timer);
15689 }
15690 
15691 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
15692 {
15693 	struct lpfc_queue *eq, *next;
15694 
15695 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
15696 		list_del(&eq->_poll_list);
15697 
15698 	INIT_LIST_HEAD(&phba->poll_list);
15699 	synchronize_rcu();
15700 }
15701 
15702 static inline void
15703 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
15704 {
15705 	if (mode == eq->mode)
15706 		return;
15707 	/*
15708 	 * currently this function is only called during a hotplug
15709 	 * event and the cpu on which this function is executing
15710 	 * is going offline.  By now the hotplug has instructed
15711 	 * the scheduler to remove this cpu from cpu active mask.
15712 	 * So we don't need to work about being put aside by the
15713 	 * scheduler for a high priority process.  Yes, the inte-
15714 	 * rrupts could come but they are known to retire ASAP.
15715 	 */
15716 
15717 	/* Disable polling in the fastpath */
15718 	WRITE_ONCE(eq->mode, mode);
15719 	/* flush out the store buffer */
15720 	smp_wmb();
15721 
15722 	/*
15723 	 * Add this eq to the polling list and start polling. For
15724 	 * a grace period both interrupt handler and poller will
15725 	 * try to process the eq _but_ that's fine.  We have a
15726 	 * synchronization mechanism in place (queue_claimed) to
15727 	 * deal with it.  This is just a draining phase for int-
15728 	 * errupt handler (not eq's) as we have guranteed through
15729 	 * barrier that all the CPUs have seen the new CQ_POLLED
15730 	 * state. which will effectively disable the REARMING of
15731 	 * the EQ.  The whole idea is eq's die off eventually as
15732 	 * we are not rearming EQ's anymore.
15733 	 */
15734 	mode ? lpfc_sli4_add_to_poll_list(eq) :
15735 	       lpfc_sli4_remove_from_poll_list(eq);
15736 }
15737 
15738 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15739 {
15740 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15741 }
15742 
15743 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15744 {
15745 	struct lpfc_hba *phba = eq->phba;
15746 
15747 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15748 
15749 	/* Kick start for the pending io's in h/w.
15750 	 * Once we switch back to interrupt processing on a eq
15751 	 * the io path completion will only arm eq's when it
15752 	 * receives a completion.  But since eq's are in disa-
15753 	 * rmed state it doesn't receive a completion.  This
15754 	 * creates a deadlock scenaro.
15755 	 */
15756 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15757 }
15758 
15759 /**
15760  * lpfc_sli4_queue_free - free a queue structure and associated memory
15761  * @queue: The queue structure to free.
15762  *
15763  * This function frees a queue structure and the DMAable memory used for
15764  * the host resident queue. This function must be called after destroying the
15765  * queue on the HBA.
15766  **/
15767 void
15768 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15769 {
15770 	struct lpfc_dmabuf *dmabuf;
15771 
15772 	if (!queue)
15773 		return;
15774 
15775 	if (!list_empty(&queue->wq_list))
15776 		list_del(&queue->wq_list);
15777 
15778 	while (!list_empty(&queue->page_list)) {
15779 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15780 				 list);
15781 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15782 				  dmabuf->virt, dmabuf->phys);
15783 		kfree(dmabuf);
15784 	}
15785 	if (queue->rqbp) {
15786 		lpfc_free_rq_buffer(queue->phba, queue);
15787 		kfree(queue->rqbp);
15788 	}
15789 
15790 	if (!list_empty(&queue->cpu_list))
15791 		list_del(&queue->cpu_list);
15792 
15793 	kfree(queue);
15794 	return;
15795 }
15796 
15797 /**
15798  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15799  * @phba: The HBA that this queue is being created on.
15800  * @page_size: The size of a queue page
15801  * @entry_size: The size of each queue entry for this queue.
15802  * @entry_count: The number of entries that this queue will handle.
15803  * @cpu: The cpu that will primarily utilize this queue.
15804  *
15805  * This function allocates a queue structure and the DMAable memory used for
15806  * the host resident queue. This function must be called before creating the
15807  * queue on the HBA.
15808  **/
15809 struct lpfc_queue *
15810 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15811 		      uint32_t entry_size, uint32_t entry_count, int cpu)
15812 {
15813 	struct lpfc_queue *queue;
15814 	struct lpfc_dmabuf *dmabuf;
15815 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15816 	uint16_t x, pgcnt;
15817 
15818 	if (!phba->sli4_hba.pc_sli4_params.supported)
15819 		hw_page_size = page_size;
15820 
15821 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15822 
15823 	/* If needed, Adjust page count to match the max the adapter supports */
15824 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15825 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15826 
15827 	queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
15828 			     GFP_KERNEL, cpu_to_node(cpu));
15829 	if (!queue)
15830 		return NULL;
15831 
15832 	INIT_LIST_HEAD(&queue->list);
15833 	INIT_LIST_HEAD(&queue->_poll_list);
15834 	INIT_LIST_HEAD(&queue->wq_list);
15835 	INIT_LIST_HEAD(&queue->wqfull_list);
15836 	INIT_LIST_HEAD(&queue->page_list);
15837 	INIT_LIST_HEAD(&queue->child_list);
15838 	INIT_LIST_HEAD(&queue->cpu_list);
15839 
15840 	/* Set queue parameters now.  If the system cannot provide memory
15841 	 * resources, the free routine needs to know what was allocated.
15842 	 */
15843 	queue->page_count = pgcnt;
15844 	queue->q_pgs = (void **)&queue[1];
15845 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
15846 	queue->entry_size = entry_size;
15847 	queue->entry_count = entry_count;
15848 	queue->page_size = hw_page_size;
15849 	queue->phba = phba;
15850 
15851 	for (x = 0; x < queue->page_count; x++) {
15852 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15853 				      dev_to_node(&phba->pcidev->dev));
15854 		if (!dmabuf)
15855 			goto out_fail;
15856 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15857 						  hw_page_size, &dmabuf->phys,
15858 						  GFP_KERNEL);
15859 		if (!dmabuf->virt) {
15860 			kfree(dmabuf);
15861 			goto out_fail;
15862 		}
15863 		dmabuf->buffer_tag = x;
15864 		list_add_tail(&dmabuf->list, &queue->page_list);
15865 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
15866 		queue->q_pgs[x] = dmabuf->virt;
15867 	}
15868 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15869 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15870 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15871 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15872 
15873 	/* notify_interval will be set during q creation */
15874 
15875 	return queue;
15876 out_fail:
15877 	lpfc_sli4_queue_free(queue);
15878 	return NULL;
15879 }
15880 
15881 /**
15882  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15883  * @phba: HBA structure that indicates port to create a queue on.
15884  * @pci_barset: PCI BAR set flag.
15885  *
15886  * This function shall perform iomap of the specified PCI BAR address to host
15887  * memory address if not already done so and return it. The returned host
15888  * memory address can be NULL.
15889  */
15890 static void __iomem *
15891 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15892 {
15893 	if (!phba->pcidev)
15894 		return NULL;
15895 
15896 	switch (pci_barset) {
15897 	case WQ_PCI_BAR_0_AND_1:
15898 		return phba->pci_bar0_memmap_p;
15899 	case WQ_PCI_BAR_2_AND_3:
15900 		return phba->pci_bar2_memmap_p;
15901 	case WQ_PCI_BAR_4_AND_5:
15902 		return phba->pci_bar4_memmap_p;
15903 	default:
15904 		break;
15905 	}
15906 	return NULL;
15907 }
15908 
15909 /**
15910  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
15911  * @phba: HBA structure that EQs are on.
15912  * @startq: The starting EQ index to modify
15913  * @numq: The number of EQs (consecutive indexes) to modify
15914  * @usdelay: amount of delay
15915  *
15916  * This function revises the EQ delay on 1 or more EQs. The EQ delay
15917  * is set either by writing to a register (if supported by the SLI Port)
15918  * or by mailbox command. The mailbox command allows several EQs to be
15919  * updated at once.
15920  *
15921  * The @phba struct is used to send a mailbox command to HBA. The @startq
15922  * is used to get the starting EQ index to change. The @numq value is
15923  * used to specify how many consecutive EQ indexes, starting at EQ index,
15924  * are to be changed. This function is asynchronous and will wait for any
15925  * mailbox commands to finish before returning.
15926  *
15927  * On success this function will return a zero. If unable to allocate
15928  * enough memory this function will return -ENOMEM. If a mailbox command
15929  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
15930  * have had their delay multipler changed.
15931  **/
15932 void
15933 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
15934 			 uint32_t numq, uint32_t usdelay)
15935 {
15936 	struct lpfc_mbx_modify_eq_delay *eq_delay;
15937 	LPFC_MBOXQ_t *mbox;
15938 	struct lpfc_queue *eq;
15939 	int cnt = 0, rc, length;
15940 	uint32_t shdr_status, shdr_add_status;
15941 	uint32_t dmult;
15942 	int qidx;
15943 	union lpfc_sli4_cfg_shdr *shdr;
15944 
15945 	if (startq >= phba->cfg_irq_chann)
15946 		return;
15947 
15948 	if (usdelay > 0xFFFF) {
15949 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
15950 				"6429 usdelay %d too large. Scaled down to "
15951 				"0xFFFF.\n", usdelay);
15952 		usdelay = 0xFFFF;
15953 	}
15954 
15955 	/* set values by EQ_DELAY register if supported */
15956 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
15957 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15958 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15959 			if (!eq)
15960 				continue;
15961 
15962 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
15963 
15964 			if (++cnt >= numq)
15965 				break;
15966 		}
15967 		return;
15968 	}
15969 
15970 	/* Otherwise, set values by mailbox cmd */
15971 
15972 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15973 	if (!mbox) {
15974 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15975 				"6428 Failed allocating mailbox cmd buffer."
15976 				" EQ delay was not set.\n");
15977 		return;
15978 	}
15979 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
15980 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15981 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15982 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
15983 			 length, LPFC_SLI4_MBX_EMBED);
15984 	eq_delay = &mbox->u.mqe.un.eq_delay;
15985 
15986 	/* Calculate delay multiper from maximum interrupt per second */
15987 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
15988 	if (dmult)
15989 		dmult--;
15990 	if (dmult > LPFC_DMULT_MAX)
15991 		dmult = LPFC_DMULT_MAX;
15992 
15993 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15994 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15995 		if (!eq)
15996 			continue;
15997 		eq->q_mode = usdelay;
15998 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
15999 		eq_delay->u.request.eq[cnt].phase = 0;
16000 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
16001 
16002 		if (++cnt >= numq)
16003 			break;
16004 	}
16005 	eq_delay->u.request.num_eq = cnt;
16006 
16007 	mbox->vport = phba->pport;
16008 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16009 	mbox->ctx_ndlp = NULL;
16010 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16011 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
16012 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16013 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16014 	if (shdr_status || shdr_add_status || rc) {
16015 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16016 				"2512 MODIFY_EQ_DELAY mailbox failed with "
16017 				"status x%x add_status x%x, mbx status x%x\n",
16018 				shdr_status, shdr_add_status, rc);
16019 	}
16020 	mempool_free(mbox, phba->mbox_mem_pool);
16021 	return;
16022 }
16023 
16024 /**
16025  * lpfc_eq_create - Create an Event Queue on the HBA
16026  * @phba: HBA structure that indicates port to create a queue on.
16027  * @eq: The queue structure to use to create the event queue.
16028  * @imax: The maximum interrupt per second limit.
16029  *
16030  * This function creates an event queue, as detailed in @eq, on a port,
16031  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
16032  *
16033  * The @phba struct is used to send mailbox command to HBA. The @eq struct
16034  * is used to get the entry count and entry size that are necessary to
16035  * determine the number of pages to allocate and use for this queue. This
16036  * function will send the EQ_CREATE mailbox command to the HBA to setup the
16037  * event queue. This function is asynchronous and will wait for the mailbox
16038  * command to finish before continuing.
16039  *
16040  * On success this function will return a zero. If unable to allocate enough
16041  * memory this function will return -ENOMEM. If the queue create mailbox command
16042  * fails this function will return -ENXIO.
16043  **/
16044 int
16045 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
16046 {
16047 	struct lpfc_mbx_eq_create *eq_create;
16048 	LPFC_MBOXQ_t *mbox;
16049 	int rc, length, status = 0;
16050 	struct lpfc_dmabuf *dmabuf;
16051 	uint32_t shdr_status, shdr_add_status;
16052 	union lpfc_sli4_cfg_shdr *shdr;
16053 	uint16_t dmult;
16054 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16055 
16056 	/* sanity check on queue memory */
16057 	if (!eq)
16058 		return -ENODEV;
16059 	if (!phba->sli4_hba.pc_sli4_params.supported)
16060 		hw_page_size = SLI4_PAGE_SIZE;
16061 
16062 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16063 	if (!mbox)
16064 		return -ENOMEM;
16065 	length = (sizeof(struct lpfc_mbx_eq_create) -
16066 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16067 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16068 			 LPFC_MBOX_OPCODE_EQ_CREATE,
16069 			 length, LPFC_SLI4_MBX_EMBED);
16070 	eq_create = &mbox->u.mqe.un.eq_create;
16071 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
16072 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
16073 	       eq->page_count);
16074 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
16075 	       LPFC_EQE_SIZE);
16076 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
16077 
16078 	/* Use version 2 of CREATE_EQ if eqav is set */
16079 	if (phba->sli4_hba.pc_sli4_params.eqav) {
16080 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16081 		       LPFC_Q_CREATE_VERSION_2);
16082 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
16083 		       phba->sli4_hba.pc_sli4_params.eqav);
16084 	}
16085 
16086 	/* don't setup delay multiplier using EQ_CREATE */
16087 	dmult = 0;
16088 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
16089 	       dmult);
16090 	switch (eq->entry_count) {
16091 	default:
16092 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16093 				"0360 Unsupported EQ count. (%d)\n",
16094 				eq->entry_count);
16095 		if (eq->entry_count < 256) {
16096 			status = -EINVAL;
16097 			goto out;
16098 		}
16099 		fallthrough;	/* otherwise default to smallest count */
16100 	case 256:
16101 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16102 		       LPFC_EQ_CNT_256);
16103 		break;
16104 	case 512:
16105 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16106 		       LPFC_EQ_CNT_512);
16107 		break;
16108 	case 1024:
16109 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16110 		       LPFC_EQ_CNT_1024);
16111 		break;
16112 	case 2048:
16113 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16114 		       LPFC_EQ_CNT_2048);
16115 		break;
16116 	case 4096:
16117 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16118 		       LPFC_EQ_CNT_4096);
16119 		break;
16120 	}
16121 	list_for_each_entry(dmabuf, &eq->page_list, list) {
16122 		memset(dmabuf->virt, 0, hw_page_size);
16123 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16124 					putPaddrLow(dmabuf->phys);
16125 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16126 					putPaddrHigh(dmabuf->phys);
16127 	}
16128 	mbox->vport = phba->pport;
16129 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16130 	mbox->ctx_buf = NULL;
16131 	mbox->ctx_ndlp = NULL;
16132 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16133 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16134 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16135 	if (shdr_status || shdr_add_status || rc) {
16136 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16137 				"2500 EQ_CREATE mailbox failed with "
16138 				"status x%x add_status x%x, mbx status x%x\n",
16139 				shdr_status, shdr_add_status, rc);
16140 		status = -ENXIO;
16141 	}
16142 	eq->type = LPFC_EQ;
16143 	eq->subtype = LPFC_NONE;
16144 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
16145 	if (eq->queue_id == 0xFFFF)
16146 		status = -ENXIO;
16147 	eq->host_index = 0;
16148 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
16149 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
16150 out:
16151 	mempool_free(mbox, phba->mbox_mem_pool);
16152 	return status;
16153 }
16154 
16155 static int lpfc_cq_poll_hdler(struct irq_poll *iop, int budget)
16156 {
16157 	struct lpfc_queue *cq = container_of(iop, struct lpfc_queue, iop);
16158 
16159 	__lpfc_sli4_hba_process_cq(cq, LPFC_IRQ_POLL);
16160 
16161 	return 1;
16162 }
16163 
16164 /**
16165  * lpfc_cq_create - Create a Completion Queue on the HBA
16166  * @phba: HBA structure that indicates port to create a queue on.
16167  * @cq: The queue structure to use to create the completion queue.
16168  * @eq: The event queue to bind this completion queue to.
16169  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16170  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16171  *
16172  * This function creates a completion queue, as detailed in @wq, on a port,
16173  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
16174  *
16175  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16176  * is used to get the entry count and entry size that are necessary to
16177  * determine the number of pages to allocate and use for this queue. The @eq
16178  * is used to indicate which event queue to bind this completion queue to. This
16179  * function will send the CQ_CREATE mailbox command to the HBA to setup the
16180  * completion queue. This function is asynchronous and will wait for the mailbox
16181  * command to finish before continuing.
16182  *
16183  * On success this function will return a zero. If unable to allocate enough
16184  * memory this function will return -ENOMEM. If the queue create mailbox command
16185  * fails this function will return -ENXIO.
16186  **/
16187 int
16188 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
16189 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
16190 {
16191 	struct lpfc_mbx_cq_create *cq_create;
16192 	struct lpfc_dmabuf *dmabuf;
16193 	LPFC_MBOXQ_t *mbox;
16194 	int rc, length, status = 0;
16195 	uint32_t shdr_status, shdr_add_status;
16196 	union lpfc_sli4_cfg_shdr *shdr;
16197 
16198 	/* sanity check on queue memory */
16199 	if (!cq || !eq)
16200 		return -ENODEV;
16201 
16202 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16203 	if (!mbox)
16204 		return -ENOMEM;
16205 	length = (sizeof(struct lpfc_mbx_cq_create) -
16206 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16207 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16208 			 LPFC_MBOX_OPCODE_CQ_CREATE,
16209 			 length, LPFC_SLI4_MBX_EMBED);
16210 	cq_create = &mbox->u.mqe.un.cq_create;
16211 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
16212 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
16213 		    cq->page_count);
16214 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
16215 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
16216 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16217 	       phba->sli4_hba.pc_sli4_params.cqv);
16218 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
16219 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
16220 		       (cq->page_size / SLI4_PAGE_SIZE));
16221 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
16222 		       eq->queue_id);
16223 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
16224 		       phba->sli4_hba.pc_sli4_params.cqav);
16225 	} else {
16226 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
16227 		       eq->queue_id);
16228 	}
16229 	switch (cq->entry_count) {
16230 	case 2048:
16231 	case 4096:
16232 		if (phba->sli4_hba.pc_sli4_params.cqv ==
16233 		    LPFC_Q_CREATE_VERSION_2) {
16234 			cq_create->u.request.context.lpfc_cq_context_count =
16235 				cq->entry_count;
16236 			bf_set(lpfc_cq_context_count,
16237 			       &cq_create->u.request.context,
16238 			       LPFC_CQ_CNT_WORD7);
16239 			break;
16240 		}
16241 		fallthrough;
16242 	default:
16243 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16244 				"0361 Unsupported CQ count: "
16245 				"entry cnt %d sz %d pg cnt %d\n",
16246 				cq->entry_count, cq->entry_size,
16247 				cq->page_count);
16248 		if (cq->entry_count < 256) {
16249 			status = -EINVAL;
16250 			goto out;
16251 		}
16252 		fallthrough;	/* otherwise default to smallest count */
16253 	case 256:
16254 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16255 		       LPFC_CQ_CNT_256);
16256 		break;
16257 	case 512:
16258 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16259 		       LPFC_CQ_CNT_512);
16260 		break;
16261 	case 1024:
16262 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16263 		       LPFC_CQ_CNT_1024);
16264 		break;
16265 	}
16266 	list_for_each_entry(dmabuf, &cq->page_list, list) {
16267 		memset(dmabuf->virt, 0, cq->page_size);
16268 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16269 					putPaddrLow(dmabuf->phys);
16270 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16271 					putPaddrHigh(dmabuf->phys);
16272 	}
16273 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16274 
16275 	/* The IOCTL status is embedded in the mailbox subheader. */
16276 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16277 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16278 	if (shdr_status || shdr_add_status || rc) {
16279 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16280 				"2501 CQ_CREATE mailbox failed with "
16281 				"status x%x add_status x%x, mbx status x%x\n",
16282 				shdr_status, shdr_add_status, rc);
16283 		status = -ENXIO;
16284 		goto out;
16285 	}
16286 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16287 	if (cq->queue_id == 0xFFFF) {
16288 		status = -ENXIO;
16289 		goto out;
16290 	}
16291 	/* link the cq onto the parent eq child list */
16292 	list_add_tail(&cq->list, &eq->child_list);
16293 	/* Set up completion queue's type and subtype */
16294 	cq->type = type;
16295 	cq->subtype = subtype;
16296 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16297 	cq->assoc_qid = eq->queue_id;
16298 	cq->assoc_qp = eq;
16299 	cq->host_index = 0;
16300 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16301 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
16302 
16303 	if (cq->queue_id > phba->sli4_hba.cq_max)
16304 		phba->sli4_hba.cq_max = cq->queue_id;
16305 
16306 	irq_poll_init(&cq->iop, LPFC_IRQ_POLL_WEIGHT, lpfc_cq_poll_hdler);
16307 out:
16308 	mempool_free(mbox, phba->mbox_mem_pool);
16309 	return status;
16310 }
16311 
16312 /**
16313  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
16314  * @phba: HBA structure that indicates port to create a queue on.
16315  * @cqp: The queue structure array to use to create the completion queues.
16316  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
16317  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16318  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16319  *
16320  * This function creates a set of  completion queue, s to support MRQ
16321  * as detailed in @cqp, on a port,
16322  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
16323  *
16324  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16325  * is used to get the entry count and entry size that are necessary to
16326  * determine the number of pages to allocate and use for this queue. The @eq
16327  * is used to indicate which event queue to bind this completion queue to. This
16328  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
16329  * completion queue. This function is asynchronous and will wait for the mailbox
16330  * command to finish before continuing.
16331  *
16332  * On success this function will return a zero. If unable to allocate enough
16333  * memory this function will return -ENOMEM. If the queue create mailbox command
16334  * fails this function will return -ENXIO.
16335  **/
16336 int
16337 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
16338 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
16339 		   uint32_t subtype)
16340 {
16341 	struct lpfc_queue *cq;
16342 	struct lpfc_queue *eq;
16343 	struct lpfc_mbx_cq_create_set *cq_set;
16344 	struct lpfc_dmabuf *dmabuf;
16345 	LPFC_MBOXQ_t *mbox;
16346 	int rc, length, alloclen, status = 0;
16347 	int cnt, idx, numcq, page_idx = 0;
16348 	uint32_t shdr_status, shdr_add_status;
16349 	union lpfc_sli4_cfg_shdr *shdr;
16350 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16351 
16352 	/* sanity check on queue memory */
16353 	numcq = phba->cfg_nvmet_mrq;
16354 	if (!cqp || !hdwq || !numcq)
16355 		return -ENODEV;
16356 
16357 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16358 	if (!mbox)
16359 		return -ENOMEM;
16360 
16361 	length = sizeof(struct lpfc_mbx_cq_create_set);
16362 	length += ((numcq * cqp[0]->page_count) *
16363 		   sizeof(struct dma_address));
16364 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16365 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
16366 			LPFC_SLI4_MBX_NEMBED);
16367 	if (alloclen < length) {
16368 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16369 				"3098 Allocated DMA memory size (%d) is "
16370 				"less than the requested DMA memory size "
16371 				"(%d)\n", alloclen, length);
16372 		status = -ENOMEM;
16373 		goto out;
16374 	}
16375 	cq_set = mbox->sge_array->addr[0];
16376 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
16377 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
16378 
16379 	for (idx = 0; idx < numcq; idx++) {
16380 		cq = cqp[idx];
16381 		eq = hdwq[idx].hba_eq;
16382 		if (!cq || !eq) {
16383 			status = -ENOMEM;
16384 			goto out;
16385 		}
16386 		if (!phba->sli4_hba.pc_sli4_params.supported)
16387 			hw_page_size = cq->page_size;
16388 
16389 		switch (idx) {
16390 		case 0:
16391 			bf_set(lpfc_mbx_cq_create_set_page_size,
16392 			       &cq_set->u.request,
16393 			       (hw_page_size / SLI4_PAGE_SIZE));
16394 			bf_set(lpfc_mbx_cq_create_set_num_pages,
16395 			       &cq_set->u.request, cq->page_count);
16396 			bf_set(lpfc_mbx_cq_create_set_evt,
16397 			       &cq_set->u.request, 1);
16398 			bf_set(lpfc_mbx_cq_create_set_valid,
16399 			       &cq_set->u.request, 1);
16400 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
16401 			       &cq_set->u.request, 0);
16402 			bf_set(lpfc_mbx_cq_create_set_num_cq,
16403 			       &cq_set->u.request, numcq);
16404 			bf_set(lpfc_mbx_cq_create_set_autovalid,
16405 			       &cq_set->u.request,
16406 			       phba->sli4_hba.pc_sli4_params.cqav);
16407 			switch (cq->entry_count) {
16408 			case 2048:
16409 			case 4096:
16410 				if (phba->sli4_hba.pc_sli4_params.cqv ==
16411 				    LPFC_Q_CREATE_VERSION_2) {
16412 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16413 					       &cq_set->u.request,
16414 						cq->entry_count);
16415 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16416 					       &cq_set->u.request,
16417 					       LPFC_CQ_CNT_WORD7);
16418 					break;
16419 				}
16420 				fallthrough;
16421 			default:
16422 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16423 						"3118 Bad CQ count. (%d)\n",
16424 						cq->entry_count);
16425 				if (cq->entry_count < 256) {
16426 					status = -EINVAL;
16427 					goto out;
16428 				}
16429 				fallthrough;	/* otherwise default to smallest */
16430 			case 256:
16431 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16432 				       &cq_set->u.request, LPFC_CQ_CNT_256);
16433 				break;
16434 			case 512:
16435 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16436 				       &cq_set->u.request, LPFC_CQ_CNT_512);
16437 				break;
16438 			case 1024:
16439 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16440 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
16441 				break;
16442 			}
16443 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
16444 			       &cq_set->u.request, eq->queue_id);
16445 			break;
16446 		case 1:
16447 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
16448 			       &cq_set->u.request, eq->queue_id);
16449 			break;
16450 		case 2:
16451 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
16452 			       &cq_set->u.request, eq->queue_id);
16453 			break;
16454 		case 3:
16455 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
16456 			       &cq_set->u.request, eq->queue_id);
16457 			break;
16458 		case 4:
16459 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
16460 			       &cq_set->u.request, eq->queue_id);
16461 			break;
16462 		case 5:
16463 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
16464 			       &cq_set->u.request, eq->queue_id);
16465 			break;
16466 		case 6:
16467 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
16468 			       &cq_set->u.request, eq->queue_id);
16469 			break;
16470 		case 7:
16471 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
16472 			       &cq_set->u.request, eq->queue_id);
16473 			break;
16474 		case 8:
16475 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
16476 			       &cq_set->u.request, eq->queue_id);
16477 			break;
16478 		case 9:
16479 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
16480 			       &cq_set->u.request, eq->queue_id);
16481 			break;
16482 		case 10:
16483 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
16484 			       &cq_set->u.request, eq->queue_id);
16485 			break;
16486 		case 11:
16487 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
16488 			       &cq_set->u.request, eq->queue_id);
16489 			break;
16490 		case 12:
16491 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
16492 			       &cq_set->u.request, eq->queue_id);
16493 			break;
16494 		case 13:
16495 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
16496 			       &cq_set->u.request, eq->queue_id);
16497 			break;
16498 		case 14:
16499 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
16500 			       &cq_set->u.request, eq->queue_id);
16501 			break;
16502 		case 15:
16503 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
16504 			       &cq_set->u.request, eq->queue_id);
16505 			break;
16506 		}
16507 
16508 		/* link the cq onto the parent eq child list */
16509 		list_add_tail(&cq->list, &eq->child_list);
16510 		/* Set up completion queue's type and subtype */
16511 		cq->type = type;
16512 		cq->subtype = subtype;
16513 		cq->assoc_qid = eq->queue_id;
16514 		cq->assoc_qp = eq;
16515 		cq->host_index = 0;
16516 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16517 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
16518 					 cq->entry_count);
16519 		cq->chann = idx;
16520 
16521 		rc = 0;
16522 		list_for_each_entry(dmabuf, &cq->page_list, list) {
16523 			memset(dmabuf->virt, 0, hw_page_size);
16524 			cnt = page_idx + dmabuf->buffer_tag;
16525 			cq_set->u.request.page[cnt].addr_lo =
16526 					putPaddrLow(dmabuf->phys);
16527 			cq_set->u.request.page[cnt].addr_hi =
16528 					putPaddrHigh(dmabuf->phys);
16529 			rc++;
16530 		}
16531 		page_idx += rc;
16532 	}
16533 
16534 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16535 
16536 	/* The IOCTL status is embedded in the mailbox subheader. */
16537 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16538 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16539 	if (shdr_status || shdr_add_status || rc) {
16540 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16541 				"3119 CQ_CREATE_SET mailbox failed with "
16542 				"status x%x add_status x%x, mbx status x%x\n",
16543 				shdr_status, shdr_add_status, rc);
16544 		status = -ENXIO;
16545 		goto out;
16546 	}
16547 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
16548 	if (rc == 0xFFFF) {
16549 		status = -ENXIO;
16550 		goto out;
16551 	}
16552 
16553 	for (idx = 0; idx < numcq; idx++) {
16554 		cq = cqp[idx];
16555 		cq->queue_id = rc + idx;
16556 		if (cq->queue_id > phba->sli4_hba.cq_max)
16557 			phba->sli4_hba.cq_max = cq->queue_id;
16558 	}
16559 
16560 out:
16561 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16562 	return status;
16563 }
16564 
16565 /**
16566  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
16567  * @phba: HBA structure that indicates port to create a queue on.
16568  * @mq: The queue structure to use to create the mailbox queue.
16569  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
16570  * @cq: The completion queue to associate with this cq.
16571  *
16572  * This function provides failback (fb) functionality when the
16573  * mq_create_ext fails on older FW generations.  It's purpose is identical
16574  * to mq_create_ext otherwise.
16575  *
16576  * This routine cannot fail as all attributes were previously accessed and
16577  * initialized in mq_create_ext.
16578  **/
16579 static void
16580 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
16581 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
16582 {
16583 	struct lpfc_mbx_mq_create *mq_create;
16584 	struct lpfc_dmabuf *dmabuf;
16585 	int length;
16586 
16587 	length = (sizeof(struct lpfc_mbx_mq_create) -
16588 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16589 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16590 			 LPFC_MBOX_OPCODE_MQ_CREATE,
16591 			 length, LPFC_SLI4_MBX_EMBED);
16592 	mq_create = &mbox->u.mqe.un.mq_create;
16593 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
16594 	       mq->page_count);
16595 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
16596 	       cq->queue_id);
16597 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
16598 	switch (mq->entry_count) {
16599 	case 16:
16600 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16601 		       LPFC_MQ_RING_SIZE_16);
16602 		break;
16603 	case 32:
16604 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16605 		       LPFC_MQ_RING_SIZE_32);
16606 		break;
16607 	case 64:
16608 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16609 		       LPFC_MQ_RING_SIZE_64);
16610 		break;
16611 	case 128:
16612 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16613 		       LPFC_MQ_RING_SIZE_128);
16614 		break;
16615 	}
16616 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16617 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16618 			putPaddrLow(dmabuf->phys);
16619 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16620 			putPaddrHigh(dmabuf->phys);
16621 	}
16622 }
16623 
16624 /**
16625  * lpfc_mq_create - Create a mailbox Queue on the HBA
16626  * @phba: HBA structure that indicates port to create a queue on.
16627  * @mq: The queue structure to use to create the mailbox queue.
16628  * @cq: The completion queue to associate with this cq.
16629  * @subtype: The queue's subtype.
16630  *
16631  * This function creates a mailbox queue, as detailed in @mq, on a port,
16632  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
16633  *
16634  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16635  * is used to get the entry count and entry size that are necessary to
16636  * determine the number of pages to allocate and use for this queue. This
16637  * function will send the MQ_CREATE mailbox command to the HBA to setup the
16638  * mailbox queue. This function is asynchronous and will wait for the mailbox
16639  * command to finish before continuing.
16640  *
16641  * On success this function will return a zero. If unable to allocate enough
16642  * memory this function will return -ENOMEM. If the queue create mailbox command
16643  * fails this function will return -ENXIO.
16644  **/
16645 int32_t
16646 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
16647 	       struct lpfc_queue *cq, uint32_t subtype)
16648 {
16649 	struct lpfc_mbx_mq_create *mq_create;
16650 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
16651 	struct lpfc_dmabuf *dmabuf;
16652 	LPFC_MBOXQ_t *mbox;
16653 	int rc, length, status = 0;
16654 	uint32_t shdr_status, shdr_add_status;
16655 	union lpfc_sli4_cfg_shdr *shdr;
16656 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16657 
16658 	/* sanity check on queue memory */
16659 	if (!mq || !cq)
16660 		return -ENODEV;
16661 	if (!phba->sli4_hba.pc_sli4_params.supported)
16662 		hw_page_size = SLI4_PAGE_SIZE;
16663 
16664 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16665 	if (!mbox)
16666 		return -ENOMEM;
16667 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
16668 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16669 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16670 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
16671 			 length, LPFC_SLI4_MBX_EMBED);
16672 
16673 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
16674 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
16675 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
16676 	       &mq_create_ext->u.request, mq->page_count);
16677 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
16678 	       &mq_create_ext->u.request, 1);
16679 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
16680 	       &mq_create_ext->u.request, 1);
16681 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
16682 	       &mq_create_ext->u.request, 1);
16683 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
16684 	       &mq_create_ext->u.request, 1);
16685 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
16686 	       &mq_create_ext->u.request, 1);
16687 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
16688 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16689 	       phba->sli4_hba.pc_sli4_params.mqv);
16690 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
16691 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
16692 		       cq->queue_id);
16693 	else
16694 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
16695 		       cq->queue_id);
16696 	switch (mq->entry_count) {
16697 	default:
16698 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16699 				"0362 Unsupported MQ count. (%d)\n",
16700 				mq->entry_count);
16701 		if (mq->entry_count < 16) {
16702 			status = -EINVAL;
16703 			goto out;
16704 		}
16705 		fallthrough;	/* otherwise default to smallest count */
16706 	case 16:
16707 		bf_set(lpfc_mq_context_ring_size,
16708 		       &mq_create_ext->u.request.context,
16709 		       LPFC_MQ_RING_SIZE_16);
16710 		break;
16711 	case 32:
16712 		bf_set(lpfc_mq_context_ring_size,
16713 		       &mq_create_ext->u.request.context,
16714 		       LPFC_MQ_RING_SIZE_32);
16715 		break;
16716 	case 64:
16717 		bf_set(lpfc_mq_context_ring_size,
16718 		       &mq_create_ext->u.request.context,
16719 		       LPFC_MQ_RING_SIZE_64);
16720 		break;
16721 	case 128:
16722 		bf_set(lpfc_mq_context_ring_size,
16723 		       &mq_create_ext->u.request.context,
16724 		       LPFC_MQ_RING_SIZE_128);
16725 		break;
16726 	}
16727 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16728 		memset(dmabuf->virt, 0, hw_page_size);
16729 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16730 					putPaddrLow(dmabuf->phys);
16731 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16732 					putPaddrHigh(dmabuf->phys);
16733 	}
16734 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16735 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16736 			      &mq_create_ext->u.response);
16737 	if (rc != MBX_SUCCESS) {
16738 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16739 				"2795 MQ_CREATE_EXT failed with "
16740 				"status x%x. Failback to MQ_CREATE.\n",
16741 				rc);
16742 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16743 		mq_create = &mbox->u.mqe.un.mq_create;
16744 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16745 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16746 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16747 				      &mq_create->u.response);
16748 	}
16749 
16750 	/* The IOCTL status is embedded in the mailbox subheader. */
16751 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16752 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16753 	if (shdr_status || shdr_add_status || rc) {
16754 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16755 				"2502 MQ_CREATE mailbox failed with "
16756 				"status x%x add_status x%x, mbx status x%x\n",
16757 				shdr_status, shdr_add_status, rc);
16758 		status = -ENXIO;
16759 		goto out;
16760 	}
16761 	if (mq->queue_id == 0xFFFF) {
16762 		status = -ENXIO;
16763 		goto out;
16764 	}
16765 	mq->type = LPFC_MQ;
16766 	mq->assoc_qid = cq->queue_id;
16767 	mq->subtype = subtype;
16768 	mq->host_index = 0;
16769 	mq->hba_index = 0;
16770 
16771 	/* link the mq onto the parent cq child list */
16772 	list_add_tail(&mq->list, &cq->child_list);
16773 out:
16774 	mempool_free(mbox, phba->mbox_mem_pool);
16775 	return status;
16776 }
16777 
16778 /**
16779  * lpfc_wq_create - Create a Work Queue on the HBA
16780  * @phba: HBA structure that indicates port to create a queue on.
16781  * @wq: The queue structure to use to create the work queue.
16782  * @cq: The completion queue to bind this work queue to.
16783  * @subtype: The subtype of the work queue indicating its functionality.
16784  *
16785  * This function creates a work queue, as detailed in @wq, on a port, described
16786  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16787  *
16788  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16789  * is used to get the entry count and entry size that are necessary to
16790  * determine the number of pages to allocate and use for this queue. The @cq
16791  * is used to indicate which completion queue to bind this work queue to. This
16792  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16793  * work queue. This function is asynchronous and will wait for the mailbox
16794  * command to finish before continuing.
16795  *
16796  * On success this function will return a zero. If unable to allocate enough
16797  * memory this function will return -ENOMEM. If the queue create mailbox command
16798  * fails this function will return -ENXIO.
16799  **/
16800 int
16801 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16802 	       struct lpfc_queue *cq, uint32_t subtype)
16803 {
16804 	struct lpfc_mbx_wq_create *wq_create;
16805 	struct lpfc_dmabuf *dmabuf;
16806 	LPFC_MBOXQ_t *mbox;
16807 	int rc, length, status = 0;
16808 	uint32_t shdr_status, shdr_add_status;
16809 	union lpfc_sli4_cfg_shdr *shdr;
16810 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16811 	struct dma_address *page;
16812 	void __iomem *bar_memmap_p;
16813 	uint32_t db_offset;
16814 	uint16_t pci_barset;
16815 	uint8_t dpp_barset;
16816 	uint32_t dpp_offset;
16817 	uint8_t wq_create_version;
16818 #ifdef CONFIG_X86
16819 	unsigned long pg_addr;
16820 #endif
16821 
16822 	/* sanity check on queue memory */
16823 	if (!wq || !cq)
16824 		return -ENODEV;
16825 	if (!phba->sli4_hba.pc_sli4_params.supported)
16826 		hw_page_size = wq->page_size;
16827 
16828 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16829 	if (!mbox)
16830 		return -ENOMEM;
16831 	length = (sizeof(struct lpfc_mbx_wq_create) -
16832 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16833 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16834 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16835 			 length, LPFC_SLI4_MBX_EMBED);
16836 	wq_create = &mbox->u.mqe.un.wq_create;
16837 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16838 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16839 		    wq->page_count);
16840 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16841 		    cq->queue_id);
16842 
16843 	/* wqv is the earliest version supported, NOT the latest */
16844 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16845 	       phba->sli4_hba.pc_sli4_params.wqv);
16846 
16847 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16848 	    (wq->page_size > SLI4_PAGE_SIZE))
16849 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
16850 	else
16851 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
16852 
16853 	switch (wq_create_version) {
16854 	case LPFC_Q_CREATE_VERSION_1:
16855 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
16856 		       wq->entry_count);
16857 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16858 		       LPFC_Q_CREATE_VERSION_1);
16859 
16860 		switch (wq->entry_size) {
16861 		default:
16862 		case 64:
16863 			bf_set(lpfc_mbx_wq_create_wqe_size,
16864 			       &wq_create->u.request_1,
16865 			       LPFC_WQ_WQE_SIZE_64);
16866 			break;
16867 		case 128:
16868 			bf_set(lpfc_mbx_wq_create_wqe_size,
16869 			       &wq_create->u.request_1,
16870 			       LPFC_WQ_WQE_SIZE_128);
16871 			break;
16872 		}
16873 		/* Request DPP by default */
16874 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
16875 		bf_set(lpfc_mbx_wq_create_page_size,
16876 		       &wq_create->u.request_1,
16877 		       (wq->page_size / SLI4_PAGE_SIZE));
16878 		page = wq_create->u.request_1.page;
16879 		break;
16880 	default:
16881 		page = wq_create->u.request.page;
16882 		break;
16883 	}
16884 
16885 	list_for_each_entry(dmabuf, &wq->page_list, list) {
16886 		memset(dmabuf->virt, 0, hw_page_size);
16887 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
16888 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
16889 	}
16890 
16891 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16892 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
16893 
16894 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16895 	/* The IOCTL status is embedded in the mailbox subheader. */
16896 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16897 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16898 	if (shdr_status || shdr_add_status || rc) {
16899 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16900 				"2503 WQ_CREATE mailbox failed with "
16901 				"status x%x add_status x%x, mbx status x%x\n",
16902 				shdr_status, shdr_add_status, rc);
16903 		status = -ENXIO;
16904 		goto out;
16905 	}
16906 
16907 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
16908 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
16909 					&wq_create->u.response);
16910 	else
16911 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
16912 					&wq_create->u.response_1);
16913 
16914 	if (wq->queue_id == 0xFFFF) {
16915 		status = -ENXIO;
16916 		goto out;
16917 	}
16918 
16919 	wq->db_format = LPFC_DB_LIST_FORMAT;
16920 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
16921 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16922 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
16923 					       &wq_create->u.response);
16924 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
16925 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
16926 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16927 						"3265 WQ[%d] doorbell format "
16928 						"not supported: x%x\n",
16929 						wq->queue_id, wq->db_format);
16930 				status = -EINVAL;
16931 				goto out;
16932 			}
16933 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
16934 					    &wq_create->u.response);
16935 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16936 								   pci_barset);
16937 			if (!bar_memmap_p) {
16938 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16939 						"3263 WQ[%d] failed to memmap "
16940 						"pci barset:x%x\n",
16941 						wq->queue_id, pci_barset);
16942 				status = -ENOMEM;
16943 				goto out;
16944 			}
16945 			db_offset = wq_create->u.response.doorbell_offset;
16946 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
16947 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
16948 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16949 						"3252 WQ[%d] doorbell offset "
16950 						"not supported: x%x\n",
16951 						wq->queue_id, db_offset);
16952 				status = -EINVAL;
16953 				goto out;
16954 			}
16955 			wq->db_regaddr = bar_memmap_p + db_offset;
16956 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16957 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
16958 					"format:x%x\n", wq->queue_id,
16959 					pci_barset, db_offset, wq->db_format);
16960 		} else
16961 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
16962 	} else {
16963 		/* Check if DPP was honored by the firmware */
16964 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
16965 				    &wq_create->u.response_1);
16966 		if (wq->dpp_enable) {
16967 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
16968 					    &wq_create->u.response_1);
16969 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16970 								   pci_barset);
16971 			if (!bar_memmap_p) {
16972 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16973 						"3267 WQ[%d] failed to memmap "
16974 						"pci barset:x%x\n",
16975 						wq->queue_id, pci_barset);
16976 				status = -ENOMEM;
16977 				goto out;
16978 			}
16979 			db_offset = wq_create->u.response_1.doorbell_offset;
16980 			wq->db_regaddr = bar_memmap_p + db_offset;
16981 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
16982 					    &wq_create->u.response_1);
16983 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
16984 					    &wq_create->u.response_1);
16985 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16986 								   dpp_barset);
16987 			if (!bar_memmap_p) {
16988 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16989 						"3268 WQ[%d] failed to memmap "
16990 						"pci barset:x%x\n",
16991 						wq->queue_id, dpp_barset);
16992 				status = -ENOMEM;
16993 				goto out;
16994 			}
16995 			dpp_offset = wq_create->u.response_1.dpp_offset;
16996 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
16997 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16998 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
16999 					"dpp_id:x%x dpp_barset:x%x "
17000 					"dpp_offset:x%x\n",
17001 					wq->queue_id, pci_barset, db_offset,
17002 					wq->dpp_id, dpp_barset, dpp_offset);
17003 
17004 #ifdef CONFIG_X86
17005 			/* Enable combined writes for DPP aperture */
17006 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
17007 			rc = set_memory_wc(pg_addr, 1);
17008 			if (rc) {
17009 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17010 					"3272 Cannot setup Combined "
17011 					"Write on WQ[%d] - disable DPP\n",
17012 					wq->queue_id);
17013 				phba->cfg_enable_dpp = 0;
17014 			}
17015 #else
17016 			phba->cfg_enable_dpp = 0;
17017 #endif
17018 		} else
17019 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17020 	}
17021 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
17022 	if (wq->pring == NULL) {
17023 		status = -ENOMEM;
17024 		goto out;
17025 	}
17026 	wq->type = LPFC_WQ;
17027 	wq->assoc_qid = cq->queue_id;
17028 	wq->subtype = subtype;
17029 	wq->host_index = 0;
17030 	wq->hba_index = 0;
17031 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
17032 
17033 	/* link the wq onto the parent cq child list */
17034 	list_add_tail(&wq->list, &cq->child_list);
17035 out:
17036 	mempool_free(mbox, phba->mbox_mem_pool);
17037 	return status;
17038 }
17039 
17040 /**
17041  * lpfc_rq_create - Create a Receive Queue on the HBA
17042  * @phba: HBA structure that indicates port to create a queue on.
17043  * @hrq: The queue structure to use to create the header receive queue.
17044  * @drq: The queue structure to use to create the data receive queue.
17045  * @cq: The completion queue to bind this work queue to.
17046  * @subtype: The subtype of the work queue indicating its functionality.
17047  *
17048  * This function creates a receive buffer queue pair , as detailed in @hrq and
17049  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17050  * to the HBA.
17051  *
17052  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17053  * struct is used to get the entry count that is necessary to determine the
17054  * number of pages to use for this queue. The @cq is used to indicate which
17055  * completion queue to bind received buffers that are posted to these queues to.
17056  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17057  * receive queue pair. This function is asynchronous and will wait for the
17058  * mailbox command to finish before continuing.
17059  *
17060  * On success this function will return a zero. If unable to allocate enough
17061  * memory this function will return -ENOMEM. If the queue create mailbox command
17062  * fails this function will return -ENXIO.
17063  **/
17064 int
17065 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17066 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
17067 {
17068 	struct lpfc_mbx_rq_create *rq_create;
17069 	struct lpfc_dmabuf *dmabuf;
17070 	LPFC_MBOXQ_t *mbox;
17071 	int rc, length, status = 0;
17072 	uint32_t shdr_status, shdr_add_status;
17073 	union lpfc_sli4_cfg_shdr *shdr;
17074 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17075 	void __iomem *bar_memmap_p;
17076 	uint32_t db_offset;
17077 	uint16_t pci_barset;
17078 
17079 	/* sanity check on queue memory */
17080 	if (!hrq || !drq || !cq)
17081 		return -ENODEV;
17082 	if (!phba->sli4_hba.pc_sli4_params.supported)
17083 		hw_page_size = SLI4_PAGE_SIZE;
17084 
17085 	if (hrq->entry_count != drq->entry_count)
17086 		return -EINVAL;
17087 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17088 	if (!mbox)
17089 		return -ENOMEM;
17090 	length = (sizeof(struct lpfc_mbx_rq_create) -
17091 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17092 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17093 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17094 			 length, LPFC_SLI4_MBX_EMBED);
17095 	rq_create = &mbox->u.mqe.un.rq_create;
17096 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17097 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17098 	       phba->sli4_hba.pc_sli4_params.rqv);
17099 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17100 		bf_set(lpfc_rq_context_rqe_count_1,
17101 		       &rq_create->u.request.context,
17102 		       hrq->entry_count);
17103 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
17104 		bf_set(lpfc_rq_context_rqe_size,
17105 		       &rq_create->u.request.context,
17106 		       LPFC_RQE_SIZE_8);
17107 		bf_set(lpfc_rq_context_page_size,
17108 		       &rq_create->u.request.context,
17109 		       LPFC_RQ_PAGE_SIZE_4096);
17110 	} else {
17111 		switch (hrq->entry_count) {
17112 		default:
17113 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17114 					"2535 Unsupported RQ count. (%d)\n",
17115 					hrq->entry_count);
17116 			if (hrq->entry_count < 512) {
17117 				status = -EINVAL;
17118 				goto out;
17119 			}
17120 			fallthrough;	/* otherwise default to smallest count */
17121 		case 512:
17122 			bf_set(lpfc_rq_context_rqe_count,
17123 			       &rq_create->u.request.context,
17124 			       LPFC_RQ_RING_SIZE_512);
17125 			break;
17126 		case 1024:
17127 			bf_set(lpfc_rq_context_rqe_count,
17128 			       &rq_create->u.request.context,
17129 			       LPFC_RQ_RING_SIZE_1024);
17130 			break;
17131 		case 2048:
17132 			bf_set(lpfc_rq_context_rqe_count,
17133 			       &rq_create->u.request.context,
17134 			       LPFC_RQ_RING_SIZE_2048);
17135 			break;
17136 		case 4096:
17137 			bf_set(lpfc_rq_context_rqe_count,
17138 			       &rq_create->u.request.context,
17139 			       LPFC_RQ_RING_SIZE_4096);
17140 			break;
17141 		}
17142 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
17143 		       LPFC_HDR_BUF_SIZE);
17144 	}
17145 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17146 	       cq->queue_id);
17147 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17148 	       hrq->page_count);
17149 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
17150 		memset(dmabuf->virt, 0, hw_page_size);
17151 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17152 					putPaddrLow(dmabuf->phys);
17153 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17154 					putPaddrHigh(dmabuf->phys);
17155 	}
17156 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17157 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17158 
17159 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17160 	/* The IOCTL status is embedded in the mailbox subheader. */
17161 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17162 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17163 	if (shdr_status || shdr_add_status || rc) {
17164 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17165 				"2504 RQ_CREATE mailbox failed with "
17166 				"status x%x add_status x%x, mbx status x%x\n",
17167 				shdr_status, shdr_add_status, rc);
17168 		status = -ENXIO;
17169 		goto out;
17170 	}
17171 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17172 	if (hrq->queue_id == 0xFFFF) {
17173 		status = -ENXIO;
17174 		goto out;
17175 	}
17176 
17177 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
17178 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
17179 					&rq_create->u.response);
17180 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
17181 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
17182 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17183 					"3262 RQ [%d] doorbell format not "
17184 					"supported: x%x\n", hrq->queue_id,
17185 					hrq->db_format);
17186 			status = -EINVAL;
17187 			goto out;
17188 		}
17189 
17190 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
17191 				    &rq_create->u.response);
17192 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
17193 		if (!bar_memmap_p) {
17194 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17195 					"3269 RQ[%d] failed to memmap pci "
17196 					"barset:x%x\n", hrq->queue_id,
17197 					pci_barset);
17198 			status = -ENOMEM;
17199 			goto out;
17200 		}
17201 
17202 		db_offset = rq_create->u.response.doorbell_offset;
17203 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
17204 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
17205 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17206 					"3270 RQ[%d] doorbell offset not "
17207 					"supported: x%x\n", hrq->queue_id,
17208 					db_offset);
17209 			status = -EINVAL;
17210 			goto out;
17211 		}
17212 		hrq->db_regaddr = bar_memmap_p + db_offset;
17213 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17214 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
17215 				"format:x%x\n", hrq->queue_id, pci_barset,
17216 				db_offset, hrq->db_format);
17217 	} else {
17218 		hrq->db_format = LPFC_DB_RING_FORMAT;
17219 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17220 	}
17221 	hrq->type = LPFC_HRQ;
17222 	hrq->assoc_qid = cq->queue_id;
17223 	hrq->subtype = subtype;
17224 	hrq->host_index = 0;
17225 	hrq->hba_index = 0;
17226 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17227 
17228 	/* now create the data queue */
17229 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17230 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17231 			 length, LPFC_SLI4_MBX_EMBED);
17232 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17233 	       phba->sli4_hba.pc_sli4_params.rqv);
17234 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17235 		bf_set(lpfc_rq_context_rqe_count_1,
17236 		       &rq_create->u.request.context, hrq->entry_count);
17237 		if (subtype == LPFC_NVMET)
17238 			rq_create->u.request.context.buffer_size =
17239 				LPFC_NVMET_DATA_BUF_SIZE;
17240 		else
17241 			rq_create->u.request.context.buffer_size =
17242 				LPFC_DATA_BUF_SIZE;
17243 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
17244 		       LPFC_RQE_SIZE_8);
17245 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
17246 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
17247 	} else {
17248 		switch (drq->entry_count) {
17249 		default:
17250 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17251 					"2536 Unsupported RQ count. (%d)\n",
17252 					drq->entry_count);
17253 			if (drq->entry_count < 512) {
17254 				status = -EINVAL;
17255 				goto out;
17256 			}
17257 			fallthrough;	/* otherwise default to smallest count */
17258 		case 512:
17259 			bf_set(lpfc_rq_context_rqe_count,
17260 			       &rq_create->u.request.context,
17261 			       LPFC_RQ_RING_SIZE_512);
17262 			break;
17263 		case 1024:
17264 			bf_set(lpfc_rq_context_rqe_count,
17265 			       &rq_create->u.request.context,
17266 			       LPFC_RQ_RING_SIZE_1024);
17267 			break;
17268 		case 2048:
17269 			bf_set(lpfc_rq_context_rqe_count,
17270 			       &rq_create->u.request.context,
17271 			       LPFC_RQ_RING_SIZE_2048);
17272 			break;
17273 		case 4096:
17274 			bf_set(lpfc_rq_context_rqe_count,
17275 			       &rq_create->u.request.context,
17276 			       LPFC_RQ_RING_SIZE_4096);
17277 			break;
17278 		}
17279 		if (subtype == LPFC_NVMET)
17280 			bf_set(lpfc_rq_context_buf_size,
17281 			       &rq_create->u.request.context,
17282 			       LPFC_NVMET_DATA_BUF_SIZE);
17283 		else
17284 			bf_set(lpfc_rq_context_buf_size,
17285 			       &rq_create->u.request.context,
17286 			       LPFC_DATA_BUF_SIZE);
17287 	}
17288 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17289 	       cq->queue_id);
17290 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17291 	       drq->page_count);
17292 	list_for_each_entry(dmabuf, &drq->page_list, list) {
17293 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17294 					putPaddrLow(dmabuf->phys);
17295 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17296 					putPaddrHigh(dmabuf->phys);
17297 	}
17298 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17299 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17300 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17301 	/* The IOCTL status is embedded in the mailbox subheader. */
17302 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17303 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17304 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17305 	if (shdr_status || shdr_add_status || rc) {
17306 		status = -ENXIO;
17307 		goto out;
17308 	}
17309 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17310 	if (drq->queue_id == 0xFFFF) {
17311 		status = -ENXIO;
17312 		goto out;
17313 	}
17314 	drq->type = LPFC_DRQ;
17315 	drq->assoc_qid = cq->queue_id;
17316 	drq->subtype = subtype;
17317 	drq->host_index = 0;
17318 	drq->hba_index = 0;
17319 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17320 
17321 	/* link the header and data RQs onto the parent cq child list */
17322 	list_add_tail(&hrq->list, &cq->child_list);
17323 	list_add_tail(&drq->list, &cq->child_list);
17324 
17325 out:
17326 	mempool_free(mbox, phba->mbox_mem_pool);
17327 	return status;
17328 }
17329 
17330 /**
17331  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
17332  * @phba: HBA structure that indicates port to create a queue on.
17333  * @hrqp: The queue structure array to use to create the header receive queues.
17334  * @drqp: The queue structure array to use to create the data receive queues.
17335  * @cqp: The completion queue array to bind these receive queues to.
17336  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
17337  *
17338  * This function creates a receive buffer queue pair , as detailed in @hrq and
17339  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17340  * to the HBA.
17341  *
17342  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17343  * struct is used to get the entry count that is necessary to determine the
17344  * number of pages to use for this queue. The @cq is used to indicate which
17345  * completion queue to bind received buffers that are posted to these queues to.
17346  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17347  * receive queue pair. This function is asynchronous and will wait for the
17348  * mailbox command to finish before continuing.
17349  *
17350  * On success this function will return a zero. If unable to allocate enough
17351  * memory this function will return -ENOMEM. If the queue create mailbox command
17352  * fails this function will return -ENXIO.
17353  **/
17354 int
17355 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
17356 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
17357 		uint32_t subtype)
17358 {
17359 	struct lpfc_queue *hrq, *drq, *cq;
17360 	struct lpfc_mbx_rq_create_v2 *rq_create;
17361 	struct lpfc_dmabuf *dmabuf;
17362 	LPFC_MBOXQ_t *mbox;
17363 	int rc, length, alloclen, status = 0;
17364 	int cnt, idx, numrq, page_idx = 0;
17365 	uint32_t shdr_status, shdr_add_status;
17366 	union lpfc_sli4_cfg_shdr *shdr;
17367 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17368 
17369 	numrq = phba->cfg_nvmet_mrq;
17370 	/* sanity check on array memory */
17371 	if (!hrqp || !drqp || !cqp || !numrq)
17372 		return -ENODEV;
17373 	if (!phba->sli4_hba.pc_sli4_params.supported)
17374 		hw_page_size = SLI4_PAGE_SIZE;
17375 
17376 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17377 	if (!mbox)
17378 		return -ENOMEM;
17379 
17380 	length = sizeof(struct lpfc_mbx_rq_create_v2);
17381 	length += ((2 * numrq * hrqp[0]->page_count) *
17382 		   sizeof(struct dma_address));
17383 
17384 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17385 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
17386 				    LPFC_SLI4_MBX_NEMBED);
17387 	if (alloclen < length) {
17388 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17389 				"3099 Allocated DMA memory size (%d) is "
17390 				"less than the requested DMA memory size "
17391 				"(%d)\n", alloclen, length);
17392 		status = -ENOMEM;
17393 		goto out;
17394 	}
17395 
17396 
17397 
17398 	rq_create = mbox->sge_array->addr[0];
17399 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
17400 
17401 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
17402 	cnt = 0;
17403 
17404 	for (idx = 0; idx < numrq; idx++) {
17405 		hrq = hrqp[idx];
17406 		drq = drqp[idx];
17407 		cq  = cqp[idx];
17408 
17409 		/* sanity check on queue memory */
17410 		if (!hrq || !drq || !cq) {
17411 			status = -ENODEV;
17412 			goto out;
17413 		}
17414 
17415 		if (hrq->entry_count != drq->entry_count) {
17416 			status = -EINVAL;
17417 			goto out;
17418 		}
17419 
17420 		if (idx == 0) {
17421 			bf_set(lpfc_mbx_rq_create_num_pages,
17422 			       &rq_create->u.request,
17423 			       hrq->page_count);
17424 			bf_set(lpfc_mbx_rq_create_rq_cnt,
17425 			       &rq_create->u.request, (numrq * 2));
17426 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
17427 			       1);
17428 			bf_set(lpfc_rq_context_base_cq,
17429 			       &rq_create->u.request.context,
17430 			       cq->queue_id);
17431 			bf_set(lpfc_rq_context_data_size,
17432 			       &rq_create->u.request.context,
17433 			       LPFC_NVMET_DATA_BUF_SIZE);
17434 			bf_set(lpfc_rq_context_hdr_size,
17435 			       &rq_create->u.request.context,
17436 			       LPFC_HDR_BUF_SIZE);
17437 			bf_set(lpfc_rq_context_rqe_count_1,
17438 			       &rq_create->u.request.context,
17439 			       hrq->entry_count);
17440 			bf_set(lpfc_rq_context_rqe_size,
17441 			       &rq_create->u.request.context,
17442 			       LPFC_RQE_SIZE_8);
17443 			bf_set(lpfc_rq_context_page_size,
17444 			       &rq_create->u.request.context,
17445 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
17446 		}
17447 		rc = 0;
17448 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
17449 			memset(dmabuf->virt, 0, hw_page_size);
17450 			cnt = page_idx + dmabuf->buffer_tag;
17451 			rq_create->u.request.page[cnt].addr_lo =
17452 					putPaddrLow(dmabuf->phys);
17453 			rq_create->u.request.page[cnt].addr_hi =
17454 					putPaddrHigh(dmabuf->phys);
17455 			rc++;
17456 		}
17457 		page_idx += rc;
17458 
17459 		rc = 0;
17460 		list_for_each_entry(dmabuf, &drq->page_list, list) {
17461 			memset(dmabuf->virt, 0, hw_page_size);
17462 			cnt = page_idx + dmabuf->buffer_tag;
17463 			rq_create->u.request.page[cnt].addr_lo =
17464 					putPaddrLow(dmabuf->phys);
17465 			rq_create->u.request.page[cnt].addr_hi =
17466 					putPaddrHigh(dmabuf->phys);
17467 			rc++;
17468 		}
17469 		page_idx += rc;
17470 
17471 		hrq->db_format = LPFC_DB_RING_FORMAT;
17472 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17473 		hrq->type = LPFC_HRQ;
17474 		hrq->assoc_qid = cq->queue_id;
17475 		hrq->subtype = subtype;
17476 		hrq->host_index = 0;
17477 		hrq->hba_index = 0;
17478 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17479 
17480 		drq->db_format = LPFC_DB_RING_FORMAT;
17481 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17482 		drq->type = LPFC_DRQ;
17483 		drq->assoc_qid = cq->queue_id;
17484 		drq->subtype = subtype;
17485 		drq->host_index = 0;
17486 		drq->hba_index = 0;
17487 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17488 
17489 		list_add_tail(&hrq->list, &cq->child_list);
17490 		list_add_tail(&drq->list, &cq->child_list);
17491 	}
17492 
17493 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17494 	/* The IOCTL status is embedded in the mailbox subheader. */
17495 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17496 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17497 	if (shdr_status || shdr_add_status || rc) {
17498 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17499 				"3120 RQ_CREATE mailbox failed with "
17500 				"status x%x add_status x%x, mbx status x%x\n",
17501 				shdr_status, shdr_add_status, rc);
17502 		status = -ENXIO;
17503 		goto out;
17504 	}
17505 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17506 	if (rc == 0xFFFF) {
17507 		status = -ENXIO;
17508 		goto out;
17509 	}
17510 
17511 	/* Initialize all RQs with associated queue id */
17512 	for (idx = 0; idx < numrq; idx++) {
17513 		hrq = hrqp[idx];
17514 		hrq->queue_id = rc + (2 * idx);
17515 		drq = drqp[idx];
17516 		drq->queue_id = rc + (2 * idx) + 1;
17517 	}
17518 
17519 out:
17520 	lpfc_sli4_mbox_cmd_free(phba, mbox);
17521 	return status;
17522 }
17523 
17524 /**
17525  * lpfc_eq_destroy - Destroy an event Queue on the HBA
17526  * @phba: HBA structure that indicates port to destroy a queue on.
17527  * @eq: The queue structure associated with the queue to destroy.
17528  *
17529  * This function destroys a queue, as detailed in @eq by sending an mailbox
17530  * command, specific to the type of queue, to the HBA.
17531  *
17532  * The @eq struct is used to get the queue ID of the queue to destroy.
17533  *
17534  * On success this function will return a zero. If the queue destroy mailbox
17535  * command fails this function will return -ENXIO.
17536  **/
17537 int
17538 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
17539 {
17540 	LPFC_MBOXQ_t *mbox;
17541 	int rc, length, status = 0;
17542 	uint32_t shdr_status, shdr_add_status;
17543 	union lpfc_sli4_cfg_shdr *shdr;
17544 
17545 	/* sanity check on queue memory */
17546 	if (!eq)
17547 		return -ENODEV;
17548 
17549 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
17550 	if (!mbox)
17551 		return -ENOMEM;
17552 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
17553 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17554 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17555 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
17556 			 length, LPFC_SLI4_MBX_EMBED);
17557 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
17558 	       eq->queue_id);
17559 	mbox->vport = eq->phba->pport;
17560 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17561 
17562 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
17563 	/* The IOCTL status is embedded in the mailbox subheader. */
17564 	shdr = (union lpfc_sli4_cfg_shdr *)
17565 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
17566 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17567 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17568 	if (shdr_status || shdr_add_status || rc) {
17569 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17570 				"2505 EQ_DESTROY mailbox failed with "
17571 				"status x%x add_status x%x, mbx status x%x\n",
17572 				shdr_status, shdr_add_status, rc);
17573 		status = -ENXIO;
17574 	}
17575 
17576 	/* Remove eq from any list */
17577 	list_del_init(&eq->list);
17578 	mempool_free(mbox, eq->phba->mbox_mem_pool);
17579 	return status;
17580 }
17581 
17582 /**
17583  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
17584  * @phba: HBA structure that indicates port to destroy a queue on.
17585  * @cq: The queue structure associated with the queue to destroy.
17586  *
17587  * This function destroys a queue, as detailed in @cq by sending an mailbox
17588  * command, specific to the type of queue, to the HBA.
17589  *
17590  * The @cq struct is used to get the queue ID of the queue to destroy.
17591  *
17592  * On success this function will return a zero. If the queue destroy mailbox
17593  * command fails this function will return -ENXIO.
17594  **/
17595 int
17596 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
17597 {
17598 	LPFC_MBOXQ_t *mbox;
17599 	int rc, length, status = 0;
17600 	uint32_t shdr_status, shdr_add_status;
17601 	union lpfc_sli4_cfg_shdr *shdr;
17602 
17603 	/* sanity check on queue memory */
17604 	if (!cq)
17605 		return -ENODEV;
17606 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
17607 	if (!mbox)
17608 		return -ENOMEM;
17609 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
17610 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17611 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17612 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
17613 			 length, LPFC_SLI4_MBX_EMBED);
17614 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
17615 	       cq->queue_id);
17616 	mbox->vport = cq->phba->pport;
17617 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17618 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
17619 	/* The IOCTL status is embedded in the mailbox subheader. */
17620 	shdr = (union lpfc_sli4_cfg_shdr *)
17621 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
17622 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17623 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17624 	if (shdr_status || shdr_add_status || rc) {
17625 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17626 				"2506 CQ_DESTROY mailbox failed with "
17627 				"status x%x add_status x%x, mbx status x%x\n",
17628 				shdr_status, shdr_add_status, rc);
17629 		status = -ENXIO;
17630 	}
17631 	/* Remove cq from any list */
17632 	list_del_init(&cq->list);
17633 	mempool_free(mbox, cq->phba->mbox_mem_pool);
17634 	return status;
17635 }
17636 
17637 /**
17638  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
17639  * @phba: HBA structure that indicates port to destroy a queue on.
17640  * @mq: The queue structure associated with the queue to destroy.
17641  *
17642  * This function destroys a queue, as detailed in @mq by sending an mailbox
17643  * command, specific to the type of queue, to the HBA.
17644  *
17645  * The @mq struct is used to get the queue ID of the queue to destroy.
17646  *
17647  * On success this function will return a zero. If the queue destroy mailbox
17648  * command fails this function will return -ENXIO.
17649  **/
17650 int
17651 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
17652 {
17653 	LPFC_MBOXQ_t *mbox;
17654 	int rc, length, status = 0;
17655 	uint32_t shdr_status, shdr_add_status;
17656 	union lpfc_sli4_cfg_shdr *shdr;
17657 
17658 	/* sanity check on queue memory */
17659 	if (!mq)
17660 		return -ENODEV;
17661 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
17662 	if (!mbox)
17663 		return -ENOMEM;
17664 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
17665 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17666 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17667 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
17668 			 length, LPFC_SLI4_MBX_EMBED);
17669 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
17670 	       mq->queue_id);
17671 	mbox->vport = mq->phba->pport;
17672 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17673 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
17674 	/* The IOCTL status is embedded in the mailbox subheader. */
17675 	shdr = (union lpfc_sli4_cfg_shdr *)
17676 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
17677 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17678 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17679 	if (shdr_status || shdr_add_status || rc) {
17680 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17681 				"2507 MQ_DESTROY mailbox failed with "
17682 				"status x%x add_status x%x, mbx status x%x\n",
17683 				shdr_status, shdr_add_status, rc);
17684 		status = -ENXIO;
17685 	}
17686 	/* Remove mq from any list */
17687 	list_del_init(&mq->list);
17688 	mempool_free(mbox, mq->phba->mbox_mem_pool);
17689 	return status;
17690 }
17691 
17692 /**
17693  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
17694  * @phba: HBA structure that indicates port to destroy a queue on.
17695  * @wq: The queue structure associated with the queue to destroy.
17696  *
17697  * This function destroys a queue, as detailed in @wq by sending an mailbox
17698  * command, specific to the type of queue, to the HBA.
17699  *
17700  * The @wq struct is used to get the queue ID of the queue to destroy.
17701  *
17702  * On success this function will return a zero. If the queue destroy mailbox
17703  * command fails this function will return -ENXIO.
17704  **/
17705 int
17706 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
17707 {
17708 	LPFC_MBOXQ_t *mbox;
17709 	int rc, length, status = 0;
17710 	uint32_t shdr_status, shdr_add_status;
17711 	union lpfc_sli4_cfg_shdr *shdr;
17712 
17713 	/* sanity check on queue memory */
17714 	if (!wq)
17715 		return -ENODEV;
17716 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17717 	if (!mbox)
17718 		return -ENOMEM;
17719 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
17720 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17721 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17722 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17723 			 length, LPFC_SLI4_MBX_EMBED);
17724 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17725 	       wq->queue_id);
17726 	mbox->vport = wq->phba->pport;
17727 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17728 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17729 	shdr = (union lpfc_sli4_cfg_shdr *)
17730 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17731 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17732 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17733 	if (shdr_status || shdr_add_status || rc) {
17734 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17735 				"2508 WQ_DESTROY mailbox failed with "
17736 				"status x%x add_status x%x, mbx status x%x\n",
17737 				shdr_status, shdr_add_status, rc);
17738 		status = -ENXIO;
17739 	}
17740 	/* Remove wq from any list */
17741 	list_del_init(&wq->list);
17742 	kfree(wq->pring);
17743 	wq->pring = NULL;
17744 	mempool_free(mbox, wq->phba->mbox_mem_pool);
17745 	return status;
17746 }
17747 
17748 /**
17749  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17750  * @phba: HBA structure that indicates port to destroy a queue on.
17751  * @hrq: The queue structure associated with the queue to destroy.
17752  * @drq: The queue structure associated with the queue to destroy.
17753  *
17754  * This function destroys a queue, as detailed in @rq by sending an mailbox
17755  * command, specific to the type of queue, to the HBA.
17756  *
17757  * The @rq struct is used to get the queue ID of the queue to destroy.
17758  *
17759  * On success this function will return a zero. If the queue destroy mailbox
17760  * command fails this function will return -ENXIO.
17761  **/
17762 int
17763 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17764 		struct lpfc_queue *drq)
17765 {
17766 	LPFC_MBOXQ_t *mbox;
17767 	int rc, length, status = 0;
17768 	uint32_t shdr_status, shdr_add_status;
17769 	union lpfc_sli4_cfg_shdr *shdr;
17770 
17771 	/* sanity check on queue memory */
17772 	if (!hrq || !drq)
17773 		return -ENODEV;
17774 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17775 	if (!mbox)
17776 		return -ENOMEM;
17777 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
17778 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17779 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17780 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17781 			 length, LPFC_SLI4_MBX_EMBED);
17782 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17783 	       hrq->queue_id);
17784 	mbox->vport = hrq->phba->pport;
17785 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17786 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17787 	/* The IOCTL status is embedded in the mailbox subheader. */
17788 	shdr = (union lpfc_sli4_cfg_shdr *)
17789 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17790 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17791 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17792 	if (shdr_status || shdr_add_status || rc) {
17793 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17794 				"2509 RQ_DESTROY mailbox failed with "
17795 				"status x%x add_status x%x, mbx status x%x\n",
17796 				shdr_status, shdr_add_status, rc);
17797 		mempool_free(mbox, hrq->phba->mbox_mem_pool);
17798 		return -ENXIO;
17799 	}
17800 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17801 	       drq->queue_id);
17802 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17803 	shdr = (union lpfc_sli4_cfg_shdr *)
17804 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17805 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17806 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17807 	if (shdr_status || shdr_add_status || rc) {
17808 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17809 				"2510 RQ_DESTROY mailbox failed with "
17810 				"status x%x add_status x%x, mbx status x%x\n",
17811 				shdr_status, shdr_add_status, rc);
17812 		status = -ENXIO;
17813 	}
17814 	list_del_init(&hrq->list);
17815 	list_del_init(&drq->list);
17816 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
17817 	return status;
17818 }
17819 
17820 /**
17821  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17822  * @phba: The virtual port for which this call being executed.
17823  * @pdma_phys_addr0: Physical address of the 1st SGL page.
17824  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
17825  * @xritag: the xritag that ties this io to the SGL pages.
17826  *
17827  * This routine will post the sgl pages for the IO that has the xritag
17828  * that is in the iocbq structure. The xritag is assigned during iocbq
17829  * creation and persists for as long as the driver is loaded.
17830  * if the caller has fewer than 256 scatter gather segments to map then
17831  * pdma_phys_addr1 should be 0.
17832  * If the caller needs to map more than 256 scatter gather segment then
17833  * pdma_phys_addr1 should be a valid physical address.
17834  * physical address for SGLs must be 64 byte aligned.
17835  * If you are going to map 2 SGL's then the first one must have 256 entries
17836  * the second sgl can have between 1 and 256 entries.
17837  *
17838  * Return codes:
17839  * 	0 - Success
17840  * 	-ENXIO, -ENOMEM - Failure
17841  **/
17842 int
17843 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
17844 		dma_addr_t pdma_phys_addr0,
17845 		dma_addr_t pdma_phys_addr1,
17846 		uint16_t xritag)
17847 {
17848 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
17849 	LPFC_MBOXQ_t *mbox;
17850 	int rc;
17851 	uint32_t shdr_status, shdr_add_status;
17852 	uint32_t mbox_tmo;
17853 	union lpfc_sli4_cfg_shdr *shdr;
17854 
17855 	if (xritag == NO_XRI) {
17856 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17857 				"0364 Invalid param:\n");
17858 		return -EINVAL;
17859 	}
17860 
17861 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17862 	if (!mbox)
17863 		return -ENOMEM;
17864 
17865 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17866 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17867 			sizeof(struct lpfc_mbx_post_sgl_pages) -
17868 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17869 
17870 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
17871 				&mbox->u.mqe.un.post_sgl_pages;
17872 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
17873 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
17874 
17875 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
17876 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
17877 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
17878 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
17879 
17880 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
17881 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
17882 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
17883 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
17884 	if (!phba->sli4_hba.intr_enable)
17885 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17886 	else {
17887 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17888 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17889 	}
17890 	/* The IOCTL status is embedded in the mailbox subheader. */
17891 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
17892 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17893 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17894 	if (!phba->sli4_hba.intr_enable)
17895 		mempool_free(mbox, phba->mbox_mem_pool);
17896 	else if (rc != MBX_TIMEOUT)
17897 		mempool_free(mbox, phba->mbox_mem_pool);
17898 	if (shdr_status || shdr_add_status || rc) {
17899 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17900 				"2511 POST_SGL mailbox failed with "
17901 				"status x%x add_status x%x, mbx status x%x\n",
17902 				shdr_status, shdr_add_status, rc);
17903 	}
17904 	return 0;
17905 }
17906 
17907 /**
17908  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
17909  * @phba: pointer to lpfc hba data structure.
17910  *
17911  * This routine is invoked to post rpi header templates to the
17912  * HBA consistent with the SLI-4 interface spec.  This routine
17913  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
17914  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
17915  *
17916  * Returns
17917  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
17918  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
17919  **/
17920 static uint16_t
17921 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
17922 {
17923 	unsigned long xri;
17924 
17925 	/*
17926 	 * Fetch the next logical xri.  Because this index is logical,
17927 	 * the driver starts at 0 each time.
17928 	 */
17929 	spin_lock_irq(&phba->hbalock);
17930 	xri = find_first_zero_bit(phba->sli4_hba.xri_bmask,
17931 				 phba->sli4_hba.max_cfg_param.max_xri);
17932 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
17933 		spin_unlock_irq(&phba->hbalock);
17934 		return NO_XRI;
17935 	} else {
17936 		set_bit(xri, phba->sli4_hba.xri_bmask);
17937 		phba->sli4_hba.max_cfg_param.xri_used++;
17938 	}
17939 	spin_unlock_irq(&phba->hbalock);
17940 	return xri;
17941 }
17942 
17943 /**
17944  * __lpfc_sli4_free_xri - Release an xri for reuse.
17945  * @phba: pointer to lpfc hba data structure.
17946  * @xri: xri to release.
17947  *
17948  * This routine is invoked to release an xri to the pool of
17949  * available rpis maintained by the driver.
17950  **/
17951 static void
17952 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
17953 {
17954 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
17955 		phba->sli4_hba.max_cfg_param.xri_used--;
17956 	}
17957 }
17958 
17959 /**
17960  * lpfc_sli4_free_xri - Release an xri for reuse.
17961  * @phba: pointer to lpfc hba data structure.
17962  * @xri: xri to release.
17963  *
17964  * This routine is invoked to release an xri to the pool of
17965  * available rpis maintained by the driver.
17966  **/
17967 void
17968 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
17969 {
17970 	spin_lock_irq(&phba->hbalock);
17971 	__lpfc_sli4_free_xri(phba, xri);
17972 	spin_unlock_irq(&phba->hbalock);
17973 }
17974 
17975 /**
17976  * lpfc_sli4_next_xritag - Get an xritag for the io
17977  * @phba: Pointer to HBA context object.
17978  *
17979  * This function gets an xritag for the iocb. If there is no unused xritag
17980  * it will return 0xffff.
17981  * The function returns the allocated xritag if successful, else returns zero.
17982  * Zero is not a valid xritag.
17983  * The caller is not required to hold any lock.
17984  **/
17985 uint16_t
17986 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
17987 {
17988 	uint16_t xri_index;
17989 
17990 	xri_index = lpfc_sli4_alloc_xri(phba);
17991 	if (xri_index == NO_XRI)
17992 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
17993 				"2004 Failed to allocate XRI.last XRITAG is %d"
17994 				" Max XRI is %d, Used XRI is %d\n",
17995 				xri_index,
17996 				phba->sli4_hba.max_cfg_param.max_xri,
17997 				phba->sli4_hba.max_cfg_param.xri_used);
17998 	return xri_index;
17999 }
18000 
18001 /**
18002  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
18003  * @phba: pointer to lpfc hba data structure.
18004  * @post_sgl_list: pointer to els sgl entry list.
18005  * @post_cnt: number of els sgl entries on the list.
18006  *
18007  * This routine is invoked to post a block of driver's sgl pages to the
18008  * HBA using non-embedded mailbox command. No Lock is held. This routine
18009  * is only called when the driver is loading and after all IO has been
18010  * stopped.
18011  **/
18012 static int
18013 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
18014 			    struct list_head *post_sgl_list,
18015 			    int post_cnt)
18016 {
18017 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
18018 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18019 	struct sgl_page_pairs *sgl_pg_pairs;
18020 	void *viraddr;
18021 	LPFC_MBOXQ_t *mbox;
18022 	uint32_t reqlen, alloclen, pg_pairs;
18023 	uint32_t mbox_tmo;
18024 	uint16_t xritag_start = 0;
18025 	int rc = 0;
18026 	uint32_t shdr_status, shdr_add_status;
18027 	union lpfc_sli4_cfg_shdr *shdr;
18028 
18029 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
18030 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18031 	if (reqlen > SLI4_PAGE_SIZE) {
18032 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18033 				"2559 Block sgl registration required DMA "
18034 				"size (%d) great than a page\n", reqlen);
18035 		return -ENOMEM;
18036 	}
18037 
18038 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18039 	if (!mbox)
18040 		return -ENOMEM;
18041 
18042 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18043 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18044 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
18045 			 LPFC_SLI4_MBX_NEMBED);
18046 
18047 	if (alloclen < reqlen) {
18048 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18049 				"0285 Allocated DMA memory size (%d) is "
18050 				"less than the requested DMA memory "
18051 				"size (%d)\n", alloclen, reqlen);
18052 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18053 		return -ENOMEM;
18054 	}
18055 	/* Set up the SGL pages in the non-embedded DMA pages */
18056 	viraddr = mbox->sge_array->addr[0];
18057 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18058 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18059 
18060 	pg_pairs = 0;
18061 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
18062 		/* Set up the sge entry */
18063 		sgl_pg_pairs->sgl_pg0_addr_lo =
18064 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
18065 		sgl_pg_pairs->sgl_pg0_addr_hi =
18066 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
18067 		sgl_pg_pairs->sgl_pg1_addr_lo =
18068 				cpu_to_le32(putPaddrLow(0));
18069 		sgl_pg_pairs->sgl_pg1_addr_hi =
18070 				cpu_to_le32(putPaddrHigh(0));
18071 
18072 		/* Keep the first xritag on the list */
18073 		if (pg_pairs == 0)
18074 			xritag_start = sglq_entry->sli4_xritag;
18075 		sgl_pg_pairs++;
18076 		pg_pairs++;
18077 	}
18078 
18079 	/* Complete initialization and perform endian conversion. */
18080 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18081 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
18082 	sgl->word0 = cpu_to_le32(sgl->word0);
18083 
18084 	if (!phba->sli4_hba.intr_enable)
18085 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18086 	else {
18087 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18088 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18089 	}
18090 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
18091 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18092 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18093 	if (!phba->sli4_hba.intr_enable)
18094 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18095 	else if (rc != MBX_TIMEOUT)
18096 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18097 	if (shdr_status || shdr_add_status || rc) {
18098 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18099 				"2513 POST_SGL_BLOCK mailbox command failed "
18100 				"status x%x add_status x%x mbx status x%x\n",
18101 				shdr_status, shdr_add_status, rc);
18102 		rc = -ENXIO;
18103 	}
18104 	return rc;
18105 }
18106 
18107 /**
18108  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
18109  * @phba: pointer to lpfc hba data structure.
18110  * @nblist: pointer to nvme buffer list.
18111  * @count: number of scsi buffers on the list.
18112  *
18113  * This routine is invoked to post a block of @count scsi sgl pages from a
18114  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
18115  * No Lock is held.
18116  *
18117  **/
18118 static int
18119 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
18120 			    int count)
18121 {
18122 	struct lpfc_io_buf *lpfc_ncmd;
18123 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18124 	struct sgl_page_pairs *sgl_pg_pairs;
18125 	void *viraddr;
18126 	LPFC_MBOXQ_t *mbox;
18127 	uint32_t reqlen, alloclen, pg_pairs;
18128 	uint32_t mbox_tmo;
18129 	uint16_t xritag_start = 0;
18130 	int rc = 0;
18131 	uint32_t shdr_status, shdr_add_status;
18132 	dma_addr_t pdma_phys_bpl1;
18133 	union lpfc_sli4_cfg_shdr *shdr;
18134 
18135 	/* Calculate the requested length of the dma memory */
18136 	reqlen = count * sizeof(struct sgl_page_pairs) +
18137 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18138 	if (reqlen > SLI4_PAGE_SIZE) {
18139 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
18140 				"6118 Block sgl registration required DMA "
18141 				"size (%d) great than a page\n", reqlen);
18142 		return -ENOMEM;
18143 	}
18144 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18145 	if (!mbox) {
18146 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18147 				"6119 Failed to allocate mbox cmd memory\n");
18148 		return -ENOMEM;
18149 	}
18150 
18151 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18152 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18153 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
18154 				    reqlen, LPFC_SLI4_MBX_NEMBED);
18155 
18156 	if (alloclen < reqlen) {
18157 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18158 				"6120 Allocated DMA memory size (%d) is "
18159 				"less than the requested DMA memory "
18160 				"size (%d)\n", alloclen, reqlen);
18161 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18162 		return -ENOMEM;
18163 	}
18164 
18165 	/* Get the first SGE entry from the non-embedded DMA memory */
18166 	viraddr = mbox->sge_array->addr[0];
18167 
18168 	/* Set up the SGL pages in the non-embedded DMA pages */
18169 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18170 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18171 
18172 	pg_pairs = 0;
18173 	list_for_each_entry(lpfc_ncmd, nblist, list) {
18174 		/* Set up the sge entry */
18175 		sgl_pg_pairs->sgl_pg0_addr_lo =
18176 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
18177 		sgl_pg_pairs->sgl_pg0_addr_hi =
18178 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
18179 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
18180 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
18181 						SGL_PAGE_SIZE;
18182 		else
18183 			pdma_phys_bpl1 = 0;
18184 		sgl_pg_pairs->sgl_pg1_addr_lo =
18185 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
18186 		sgl_pg_pairs->sgl_pg1_addr_hi =
18187 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
18188 		/* Keep the first xritag on the list */
18189 		if (pg_pairs == 0)
18190 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
18191 		sgl_pg_pairs++;
18192 		pg_pairs++;
18193 	}
18194 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18195 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
18196 	/* Perform endian conversion if necessary */
18197 	sgl->word0 = cpu_to_le32(sgl->word0);
18198 
18199 	if (!phba->sli4_hba.intr_enable) {
18200 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18201 	} else {
18202 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18203 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18204 	}
18205 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
18206 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18207 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18208 	if (!phba->sli4_hba.intr_enable)
18209 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18210 	else if (rc != MBX_TIMEOUT)
18211 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18212 	if (shdr_status || shdr_add_status || rc) {
18213 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18214 				"6125 POST_SGL_BLOCK mailbox command failed "
18215 				"status x%x add_status x%x mbx status x%x\n",
18216 				shdr_status, shdr_add_status, rc);
18217 		rc = -ENXIO;
18218 	}
18219 	return rc;
18220 }
18221 
18222 /**
18223  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
18224  * @phba: pointer to lpfc hba data structure.
18225  * @post_nblist: pointer to the nvme buffer list.
18226  * @sb_count: number of nvme buffers.
18227  *
18228  * This routine walks a list of nvme buffers that was passed in. It attempts
18229  * to construct blocks of nvme buffer sgls which contains contiguous xris and
18230  * uses the non-embedded SGL block post mailbox commands to post to the port.
18231  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
18232  * embedded SGL post mailbox command for posting. The @post_nblist passed in
18233  * must be local list, thus no lock is needed when manipulate the list.
18234  *
18235  * Returns: 0 = failure, non-zero number of successfully posted buffers.
18236  **/
18237 int
18238 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
18239 			   struct list_head *post_nblist, int sb_count)
18240 {
18241 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
18242 	int status, sgl_size;
18243 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
18244 	dma_addr_t pdma_phys_sgl1;
18245 	int last_xritag = NO_XRI;
18246 	int cur_xritag;
18247 	LIST_HEAD(prep_nblist);
18248 	LIST_HEAD(blck_nblist);
18249 	LIST_HEAD(nvme_nblist);
18250 
18251 	/* sanity check */
18252 	if (sb_count <= 0)
18253 		return -EINVAL;
18254 
18255 	sgl_size = phba->cfg_sg_dma_buf_size;
18256 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
18257 		list_del_init(&lpfc_ncmd->list);
18258 		block_cnt++;
18259 		if ((last_xritag != NO_XRI) &&
18260 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
18261 			/* a hole in xri block, form a sgl posting block */
18262 			list_splice_init(&prep_nblist, &blck_nblist);
18263 			post_cnt = block_cnt - 1;
18264 			/* prepare list for next posting block */
18265 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18266 			block_cnt = 1;
18267 		} else {
18268 			/* prepare list for next posting block */
18269 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18270 			/* enough sgls for non-embed sgl mbox command */
18271 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
18272 				list_splice_init(&prep_nblist, &blck_nblist);
18273 				post_cnt = block_cnt;
18274 				block_cnt = 0;
18275 			}
18276 		}
18277 		num_posting++;
18278 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18279 
18280 		/* end of repost sgl list condition for NVME buffers */
18281 		if (num_posting == sb_count) {
18282 			if (post_cnt == 0) {
18283 				/* last sgl posting block */
18284 				list_splice_init(&prep_nblist, &blck_nblist);
18285 				post_cnt = block_cnt;
18286 			} else if (block_cnt == 1) {
18287 				/* last single sgl with non-contiguous xri */
18288 				if (sgl_size > SGL_PAGE_SIZE)
18289 					pdma_phys_sgl1 =
18290 						lpfc_ncmd->dma_phys_sgl +
18291 						SGL_PAGE_SIZE;
18292 				else
18293 					pdma_phys_sgl1 = 0;
18294 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18295 				status = lpfc_sli4_post_sgl(
18296 						phba, lpfc_ncmd->dma_phys_sgl,
18297 						pdma_phys_sgl1, cur_xritag);
18298 				if (status) {
18299 					/* Post error.  Buffer unavailable. */
18300 					lpfc_ncmd->flags |=
18301 						LPFC_SBUF_NOT_POSTED;
18302 				} else {
18303 					/* Post success. Bffer available. */
18304 					lpfc_ncmd->flags &=
18305 						~LPFC_SBUF_NOT_POSTED;
18306 					lpfc_ncmd->status = IOSTAT_SUCCESS;
18307 					num_posted++;
18308 				}
18309 				/* success, put on NVME buffer sgl list */
18310 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18311 			}
18312 		}
18313 
18314 		/* continue until a nembed page worth of sgls */
18315 		if (post_cnt == 0)
18316 			continue;
18317 
18318 		/* post block of NVME buffer list sgls */
18319 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
18320 						     post_cnt);
18321 
18322 		/* don't reset xirtag due to hole in xri block */
18323 		if (block_cnt == 0)
18324 			last_xritag = NO_XRI;
18325 
18326 		/* reset NVME buffer post count for next round of posting */
18327 		post_cnt = 0;
18328 
18329 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
18330 		while (!list_empty(&blck_nblist)) {
18331 			list_remove_head(&blck_nblist, lpfc_ncmd,
18332 					 struct lpfc_io_buf, list);
18333 			if (status) {
18334 				/* Post error.  Mark buffer unavailable. */
18335 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
18336 			} else {
18337 				/* Post success, Mark buffer available. */
18338 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
18339 				lpfc_ncmd->status = IOSTAT_SUCCESS;
18340 				num_posted++;
18341 			}
18342 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18343 		}
18344 	}
18345 	/* Push NVME buffers with sgl posted to the available list */
18346 	lpfc_io_buf_replenish(phba, &nvme_nblist);
18347 
18348 	return num_posted;
18349 }
18350 
18351 /**
18352  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
18353  * @phba: pointer to lpfc_hba struct that the frame was received on
18354  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18355  *
18356  * This function checks the fields in the @fc_hdr to see if the FC frame is a
18357  * valid type of frame that the LPFC driver will handle. This function will
18358  * return a zero if the frame is a valid frame or a non zero value when the
18359  * frame does not pass the check.
18360  **/
18361 static int
18362 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
18363 {
18364 	/*  make rctl_names static to save stack space */
18365 	struct fc_vft_header *fc_vft_hdr;
18366 	uint32_t *header = (uint32_t *) fc_hdr;
18367 
18368 #define FC_RCTL_MDS_DIAGS	0xF4
18369 
18370 	switch (fc_hdr->fh_r_ctl) {
18371 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
18372 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
18373 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
18374 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
18375 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
18376 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
18377 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
18378 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
18379 	case FC_RCTL_ELS_REQ:	/* extended link services request */
18380 	case FC_RCTL_ELS_REP:	/* extended link services reply */
18381 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
18382 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
18383 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
18384 	case FC_RCTL_BA_RMC: 	/* remove connection */
18385 	case FC_RCTL_BA_ACC:	/* basic accept */
18386 	case FC_RCTL_BA_RJT:	/* basic reject */
18387 	case FC_RCTL_BA_PRMT:
18388 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
18389 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
18390 	case FC_RCTL_P_RJT:	/* port reject */
18391 	case FC_RCTL_F_RJT:	/* fabric reject */
18392 	case FC_RCTL_P_BSY:	/* port busy */
18393 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
18394 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
18395 	case FC_RCTL_LCR:	/* link credit reset */
18396 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
18397 	case FC_RCTL_END:	/* end */
18398 		break;
18399 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
18400 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18401 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
18402 		return lpfc_fc_frame_check(phba, fc_hdr);
18403 	case FC_RCTL_BA_NOP:	/* basic link service NOP */
18404 	default:
18405 		goto drop;
18406 	}
18407 
18408 	switch (fc_hdr->fh_type) {
18409 	case FC_TYPE_BLS:
18410 	case FC_TYPE_ELS:
18411 	case FC_TYPE_FCP:
18412 	case FC_TYPE_CT:
18413 	case FC_TYPE_NVME:
18414 		break;
18415 	case FC_TYPE_IP:
18416 	case FC_TYPE_ILS:
18417 	default:
18418 		goto drop;
18419 	}
18420 
18421 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
18422 			"2538 Received frame rctl:x%x, type:x%x, "
18423 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
18424 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
18425 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
18426 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
18427 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
18428 			be32_to_cpu(header[6]));
18429 	return 0;
18430 drop:
18431 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
18432 			"2539 Dropped frame rctl:x%x type:x%x\n",
18433 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18434 	return 1;
18435 }
18436 
18437 /**
18438  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
18439  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18440  *
18441  * This function processes the FC header to retrieve the VFI from the VF
18442  * header, if one exists. This function will return the VFI if one exists
18443  * or 0 if no VSAN Header exists.
18444  **/
18445 static uint32_t
18446 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
18447 {
18448 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18449 
18450 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
18451 		return 0;
18452 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
18453 }
18454 
18455 /**
18456  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
18457  * @phba: Pointer to the HBA structure to search for the vport on
18458  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18459  * @fcfi: The FC Fabric ID that the frame came from
18460  * @did: Destination ID to match against
18461  *
18462  * This function searches the @phba for a vport that matches the content of the
18463  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
18464  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
18465  * returns the matching vport pointer or NULL if unable to match frame to a
18466  * vport.
18467  **/
18468 static struct lpfc_vport *
18469 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
18470 		       uint16_t fcfi, uint32_t did)
18471 {
18472 	struct lpfc_vport **vports;
18473 	struct lpfc_vport *vport = NULL;
18474 	int i;
18475 
18476 	if (did == Fabric_DID)
18477 		return phba->pport;
18478 	if ((phba->pport->fc_flag & FC_PT2PT) &&
18479 		!(phba->link_state == LPFC_HBA_READY))
18480 		return phba->pport;
18481 
18482 	vports = lpfc_create_vport_work_array(phba);
18483 	if (vports != NULL) {
18484 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
18485 			if (phba->fcf.fcfi == fcfi &&
18486 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
18487 			    vports[i]->fc_myDID == did) {
18488 				vport = vports[i];
18489 				break;
18490 			}
18491 		}
18492 	}
18493 	lpfc_destroy_vport_work_array(phba, vports);
18494 	return vport;
18495 }
18496 
18497 /**
18498  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
18499  * @vport: The vport to work on.
18500  *
18501  * This function updates the receive sequence time stamp for this vport. The
18502  * receive sequence time stamp indicates the time that the last frame of the
18503  * the sequence that has been idle for the longest amount of time was received.
18504  * the driver uses this time stamp to indicate if any received sequences have
18505  * timed out.
18506  **/
18507 static void
18508 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
18509 {
18510 	struct lpfc_dmabuf *h_buf;
18511 	struct hbq_dmabuf *dmabuf = NULL;
18512 
18513 	/* get the oldest sequence on the rcv list */
18514 	h_buf = list_get_first(&vport->rcv_buffer_list,
18515 			       struct lpfc_dmabuf, list);
18516 	if (!h_buf)
18517 		return;
18518 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18519 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
18520 }
18521 
18522 /**
18523  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
18524  * @vport: The vport that the received sequences were sent to.
18525  *
18526  * This function cleans up all outstanding received sequences. This is called
18527  * by the driver when a link event or user action invalidates all the received
18528  * sequences.
18529  **/
18530 void
18531 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
18532 {
18533 	struct lpfc_dmabuf *h_buf, *hnext;
18534 	struct lpfc_dmabuf *d_buf, *dnext;
18535 	struct hbq_dmabuf *dmabuf = NULL;
18536 
18537 	/* start with the oldest sequence on the rcv list */
18538 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18539 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18540 		list_del_init(&dmabuf->hbuf.list);
18541 		list_for_each_entry_safe(d_buf, dnext,
18542 					 &dmabuf->dbuf.list, list) {
18543 			list_del_init(&d_buf->list);
18544 			lpfc_in_buf_free(vport->phba, d_buf);
18545 		}
18546 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18547 	}
18548 }
18549 
18550 /**
18551  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
18552  * @vport: The vport that the received sequences were sent to.
18553  *
18554  * This function determines whether any received sequences have timed out by
18555  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
18556  * indicates that there is at least one timed out sequence this routine will
18557  * go through the received sequences one at a time from most inactive to most
18558  * active to determine which ones need to be cleaned up. Once it has determined
18559  * that a sequence needs to be cleaned up it will simply free up the resources
18560  * without sending an abort.
18561  **/
18562 void
18563 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
18564 {
18565 	struct lpfc_dmabuf *h_buf, *hnext;
18566 	struct lpfc_dmabuf *d_buf, *dnext;
18567 	struct hbq_dmabuf *dmabuf = NULL;
18568 	unsigned long timeout;
18569 	int abort_count = 0;
18570 
18571 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18572 		   vport->rcv_buffer_time_stamp);
18573 	if (list_empty(&vport->rcv_buffer_list) ||
18574 	    time_before(jiffies, timeout))
18575 		return;
18576 	/* start with the oldest sequence on the rcv list */
18577 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18578 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18579 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18580 			   dmabuf->time_stamp);
18581 		if (time_before(jiffies, timeout))
18582 			break;
18583 		abort_count++;
18584 		list_del_init(&dmabuf->hbuf.list);
18585 		list_for_each_entry_safe(d_buf, dnext,
18586 					 &dmabuf->dbuf.list, list) {
18587 			list_del_init(&d_buf->list);
18588 			lpfc_in_buf_free(vport->phba, d_buf);
18589 		}
18590 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18591 	}
18592 	if (abort_count)
18593 		lpfc_update_rcv_time_stamp(vport);
18594 }
18595 
18596 /**
18597  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
18598  * @vport: pointer to a vitural port
18599  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
18600  *
18601  * This function searches through the existing incomplete sequences that have
18602  * been sent to this @vport. If the frame matches one of the incomplete
18603  * sequences then the dbuf in the @dmabuf is added to the list of frames that
18604  * make up that sequence. If no sequence is found that matches this frame then
18605  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
18606  * This function returns a pointer to the first dmabuf in the sequence list that
18607  * the frame was linked to.
18608  **/
18609 static struct hbq_dmabuf *
18610 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18611 {
18612 	struct fc_frame_header *new_hdr;
18613 	struct fc_frame_header *temp_hdr;
18614 	struct lpfc_dmabuf *d_buf;
18615 	struct lpfc_dmabuf *h_buf;
18616 	struct hbq_dmabuf *seq_dmabuf = NULL;
18617 	struct hbq_dmabuf *temp_dmabuf = NULL;
18618 	uint8_t	found = 0;
18619 
18620 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18621 	dmabuf->time_stamp = jiffies;
18622 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18623 
18624 	/* Use the hdr_buf to find the sequence that this frame belongs to */
18625 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18626 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18627 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18628 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18629 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18630 			continue;
18631 		/* found a pending sequence that matches this frame */
18632 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18633 		break;
18634 	}
18635 	if (!seq_dmabuf) {
18636 		/*
18637 		 * This indicates first frame received for this sequence.
18638 		 * Queue the buffer on the vport's rcv_buffer_list.
18639 		 */
18640 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18641 		lpfc_update_rcv_time_stamp(vport);
18642 		return dmabuf;
18643 	}
18644 	temp_hdr = seq_dmabuf->hbuf.virt;
18645 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
18646 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18647 		list_del_init(&seq_dmabuf->hbuf.list);
18648 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18649 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18650 		lpfc_update_rcv_time_stamp(vport);
18651 		return dmabuf;
18652 	}
18653 	/* move this sequence to the tail to indicate a young sequence */
18654 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
18655 	seq_dmabuf->time_stamp = jiffies;
18656 	lpfc_update_rcv_time_stamp(vport);
18657 	if (list_empty(&seq_dmabuf->dbuf.list)) {
18658 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18659 		return seq_dmabuf;
18660 	}
18661 	/* find the correct place in the sequence to insert this frame */
18662 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
18663 	while (!found) {
18664 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18665 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
18666 		/*
18667 		 * If the frame's sequence count is greater than the frame on
18668 		 * the list then insert the frame right after this frame
18669 		 */
18670 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
18671 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18672 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
18673 			found = 1;
18674 			break;
18675 		}
18676 
18677 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
18678 			break;
18679 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
18680 	}
18681 
18682 	if (found)
18683 		return seq_dmabuf;
18684 	return NULL;
18685 }
18686 
18687 /**
18688  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
18689  * @vport: pointer to a vitural port
18690  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18691  *
18692  * This function tries to abort from the partially assembed sequence, described
18693  * by the information from basic abbort @dmabuf. It checks to see whether such
18694  * partially assembled sequence held by the driver. If so, it shall free up all
18695  * the frames from the partially assembled sequence.
18696  *
18697  * Return
18698  * true  -- if there is matching partially assembled sequence present and all
18699  *          the frames freed with the sequence;
18700  * false -- if there is no matching partially assembled sequence present so
18701  *          nothing got aborted in the lower layer driver
18702  **/
18703 static bool
18704 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
18705 			    struct hbq_dmabuf *dmabuf)
18706 {
18707 	struct fc_frame_header *new_hdr;
18708 	struct fc_frame_header *temp_hdr;
18709 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
18710 	struct hbq_dmabuf *seq_dmabuf = NULL;
18711 
18712 	/* Use the hdr_buf to find the sequence that matches this frame */
18713 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18714 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
18715 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18716 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18717 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18718 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18719 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18720 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18721 			continue;
18722 		/* found a pending sequence that matches this frame */
18723 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18724 		break;
18725 	}
18726 
18727 	/* Free up all the frames from the partially assembled sequence */
18728 	if (seq_dmabuf) {
18729 		list_for_each_entry_safe(d_buf, n_buf,
18730 					 &seq_dmabuf->dbuf.list, list) {
18731 			list_del_init(&d_buf->list);
18732 			lpfc_in_buf_free(vport->phba, d_buf);
18733 		}
18734 		return true;
18735 	}
18736 	return false;
18737 }
18738 
18739 /**
18740  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18741  * @vport: pointer to a vitural port
18742  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18743  *
18744  * This function tries to abort from the assembed sequence from upper level
18745  * protocol, described by the information from basic abbort @dmabuf. It
18746  * checks to see whether such pending context exists at upper level protocol.
18747  * If so, it shall clean up the pending context.
18748  *
18749  * Return
18750  * true  -- if there is matching pending context of the sequence cleaned
18751  *          at ulp;
18752  * false -- if there is no matching pending context of the sequence present
18753  *          at ulp.
18754  **/
18755 static bool
18756 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18757 {
18758 	struct lpfc_hba *phba = vport->phba;
18759 	int handled;
18760 
18761 	/* Accepting abort at ulp with SLI4 only */
18762 	if (phba->sli_rev < LPFC_SLI_REV4)
18763 		return false;
18764 
18765 	/* Register all caring upper level protocols to attend abort */
18766 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18767 	if (handled)
18768 		return true;
18769 
18770 	return false;
18771 }
18772 
18773 /**
18774  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18775  * @phba: Pointer to HBA context object.
18776  * @cmd_iocbq: pointer to the command iocbq structure.
18777  * @rsp_iocbq: pointer to the response iocbq structure.
18778  *
18779  * This function handles the sequence abort response iocb command complete
18780  * event. It properly releases the memory allocated to the sequence abort
18781  * accept iocb.
18782  **/
18783 static void
18784 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18785 			     struct lpfc_iocbq *cmd_iocbq,
18786 			     struct lpfc_iocbq *rsp_iocbq)
18787 {
18788 	if (cmd_iocbq) {
18789 		lpfc_nlp_put(cmd_iocbq->ndlp);
18790 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
18791 	}
18792 
18793 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
18794 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18795 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18796 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
18797 			get_job_ulpstatus(phba, rsp_iocbq),
18798 			get_job_word4(phba, rsp_iocbq));
18799 }
18800 
18801 /**
18802  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
18803  * @phba: Pointer to HBA context object.
18804  * @xri: xri id in transaction.
18805  *
18806  * This function validates the xri maps to the known range of XRIs allocated an
18807  * used by the driver.
18808  **/
18809 uint16_t
18810 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
18811 		      uint16_t xri)
18812 {
18813 	uint16_t i;
18814 
18815 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
18816 		if (xri == phba->sli4_hba.xri_ids[i])
18817 			return i;
18818 	}
18819 	return NO_XRI;
18820 }
18821 
18822 /**
18823  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
18824  * @vport: pointer to a virtual port.
18825  * @fc_hdr: pointer to a FC frame header.
18826  * @aborted: was the partially assembled receive sequence successfully aborted
18827  *
18828  * This function sends a basic response to a previous unsol sequence abort
18829  * event after aborting the sequence handling.
18830  **/
18831 void
18832 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
18833 			struct fc_frame_header *fc_hdr, bool aborted)
18834 {
18835 	struct lpfc_hba *phba = vport->phba;
18836 	struct lpfc_iocbq *ctiocb = NULL;
18837 	struct lpfc_nodelist *ndlp;
18838 	uint16_t oxid, rxid, xri, lxri;
18839 	uint32_t sid, fctl;
18840 	union lpfc_wqe128 *icmd;
18841 	int rc;
18842 
18843 	if (!lpfc_is_link_up(phba))
18844 		return;
18845 
18846 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18847 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
18848 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
18849 
18850 	ndlp = lpfc_findnode_did(vport, sid);
18851 	if (!ndlp) {
18852 		ndlp = lpfc_nlp_init(vport, sid);
18853 		if (!ndlp) {
18854 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
18855 					 "1268 Failed to allocate ndlp for "
18856 					 "oxid:x%x SID:x%x\n", oxid, sid);
18857 			return;
18858 		}
18859 		/* Put ndlp onto pport node list */
18860 		lpfc_enqueue_node(vport, ndlp);
18861 	}
18862 
18863 	/* Allocate buffer for rsp iocb */
18864 	ctiocb = lpfc_sli_get_iocbq(phba);
18865 	if (!ctiocb)
18866 		return;
18867 
18868 	icmd = &ctiocb->wqe;
18869 
18870 	/* Extract the F_CTL field from FC_HDR */
18871 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
18872 
18873 	ctiocb->ndlp = lpfc_nlp_get(ndlp);
18874 	if (!ctiocb->ndlp) {
18875 		lpfc_sli_release_iocbq(phba, ctiocb);
18876 		return;
18877 	}
18878 
18879 	ctiocb->vport = phba->pport;
18880 	ctiocb->cmd_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
18881 	ctiocb->sli4_lxritag = NO_XRI;
18882 	ctiocb->sli4_xritag = NO_XRI;
18883 	ctiocb->abort_rctl = FC_RCTL_BA_ACC;
18884 
18885 	if (fctl & FC_FC_EX_CTX)
18886 		/* Exchange responder sent the abort so we
18887 		 * own the oxid.
18888 		 */
18889 		xri = oxid;
18890 	else
18891 		xri = rxid;
18892 	lxri = lpfc_sli4_xri_inrange(phba, xri);
18893 	if (lxri != NO_XRI)
18894 		lpfc_set_rrq_active(phba, ndlp, lxri,
18895 			(xri == oxid) ? rxid : oxid, 0);
18896 	/* For BA_ABTS from exchange responder, if the logical xri with
18897 	 * the oxid maps to the FCP XRI range, the port no longer has
18898 	 * that exchange context, send a BLS_RJT. Override the IOCB for
18899 	 * a BA_RJT.
18900 	 */
18901 	if ((fctl & FC_FC_EX_CTX) &&
18902 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
18903 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
18904 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
18905 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
18906 		       FC_BA_RJT_INV_XID);
18907 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
18908 		       FC_BA_RJT_UNABLE);
18909 	}
18910 
18911 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
18912 	 * the driver no longer has that exchange, send a BLS_RJT. Override
18913 	 * the IOCB for a BA_RJT.
18914 	 */
18915 	if (aborted == false) {
18916 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
18917 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
18918 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
18919 		       FC_BA_RJT_INV_XID);
18920 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
18921 		       FC_BA_RJT_UNABLE);
18922 	}
18923 
18924 	if (fctl & FC_FC_EX_CTX) {
18925 		/* ABTS sent by responder to CT exchange, construction
18926 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
18927 		 * field and RX_ID from ABTS for RX_ID field.
18928 		 */
18929 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_RSP;
18930 		bf_set(xmit_bls_rsp64_rxid, &icmd->xmit_bls_rsp, rxid);
18931 	} else {
18932 		/* ABTS sent by initiator to CT exchange, construction
18933 		 * of BA_ACC will need to allocate a new XRI as for the
18934 		 * XRI_TAG field.
18935 		 */
18936 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_INT;
18937 	}
18938 
18939 	/* OX_ID is invariable to who sent ABTS to CT exchange */
18940 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, oxid);
18941 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, rxid);
18942 
18943 	/* Use CT=VPI */
18944 	bf_set(wqe_els_did, &icmd->xmit_bls_rsp.wqe_dest,
18945 	       ndlp->nlp_DID);
18946 	bf_set(xmit_bls_rsp64_temprpi, &icmd->xmit_bls_rsp,
18947 	       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
18948 	bf_set(wqe_cmnd, &icmd->generic.wqe_com, CMD_XMIT_BLS_RSP64_CX);
18949 
18950 	/* Xmit CT abts response on exchange <xid> */
18951 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
18952 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
18953 			 ctiocb->abort_rctl, oxid, phba->link_state);
18954 
18955 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
18956 	if (rc == IOCB_ERROR) {
18957 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
18958 				 "2925 Failed to issue CT ABTS RSP x%x on "
18959 				 "xri x%x, Data x%x\n",
18960 				 ctiocb->abort_rctl, oxid,
18961 				 phba->link_state);
18962 		lpfc_nlp_put(ndlp);
18963 		ctiocb->ndlp = NULL;
18964 		lpfc_sli_release_iocbq(phba, ctiocb);
18965 	}
18966 }
18967 
18968 /**
18969  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
18970  * @vport: Pointer to the vport on which this sequence was received
18971  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18972  *
18973  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
18974  * receive sequence is only partially assembed by the driver, it shall abort
18975  * the partially assembled frames for the sequence. Otherwise, if the
18976  * unsolicited receive sequence has been completely assembled and passed to
18977  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
18978  * unsolicited sequence has been aborted. After that, it will issue a basic
18979  * accept to accept the abort.
18980  **/
18981 static void
18982 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
18983 			     struct hbq_dmabuf *dmabuf)
18984 {
18985 	struct lpfc_hba *phba = vport->phba;
18986 	struct fc_frame_header fc_hdr;
18987 	uint32_t fctl;
18988 	bool aborted;
18989 
18990 	/* Make a copy of fc_hdr before the dmabuf being released */
18991 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
18992 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
18993 
18994 	if (fctl & FC_FC_EX_CTX) {
18995 		/* ABTS by responder to exchange, no cleanup needed */
18996 		aborted = true;
18997 	} else {
18998 		/* ABTS by initiator to exchange, need to do cleanup */
18999 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
19000 		if (aborted == false)
19001 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
19002 	}
19003 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19004 
19005 	if (phba->nvmet_support) {
19006 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
19007 		return;
19008 	}
19009 
19010 	/* Respond with BA_ACC or BA_RJT accordingly */
19011 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
19012 }
19013 
19014 /**
19015  * lpfc_seq_complete - Indicates if a sequence is complete
19016  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19017  *
19018  * This function checks the sequence, starting with the frame described by
19019  * @dmabuf, to see if all the frames associated with this sequence are present.
19020  * the frames associated with this sequence are linked to the @dmabuf using the
19021  * dbuf list. This function looks for two major things. 1) That the first frame
19022  * has a sequence count of zero. 2) There is a frame with last frame of sequence
19023  * set. 3) That there are no holes in the sequence count. The function will
19024  * return 1 when the sequence is complete, otherwise it will return 0.
19025  **/
19026 static int
19027 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
19028 {
19029 	struct fc_frame_header *hdr;
19030 	struct lpfc_dmabuf *d_buf;
19031 	struct hbq_dmabuf *seq_dmabuf;
19032 	uint32_t fctl;
19033 	int seq_count = 0;
19034 
19035 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19036 	/* make sure first fame of sequence has a sequence count of zero */
19037 	if (hdr->fh_seq_cnt != seq_count)
19038 		return 0;
19039 	fctl = (hdr->fh_f_ctl[0] << 16 |
19040 		hdr->fh_f_ctl[1] << 8 |
19041 		hdr->fh_f_ctl[2]);
19042 	/* If last frame of sequence we can return success. */
19043 	if (fctl & FC_FC_END_SEQ)
19044 		return 1;
19045 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
19046 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19047 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19048 		/* If there is a hole in the sequence count then fail. */
19049 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
19050 			return 0;
19051 		fctl = (hdr->fh_f_ctl[0] << 16 |
19052 			hdr->fh_f_ctl[1] << 8 |
19053 			hdr->fh_f_ctl[2]);
19054 		/* If last frame of sequence we can return success. */
19055 		if (fctl & FC_FC_END_SEQ)
19056 			return 1;
19057 	}
19058 	return 0;
19059 }
19060 
19061 /**
19062  * lpfc_prep_seq - Prep sequence for ULP processing
19063  * @vport: Pointer to the vport on which this sequence was received
19064  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
19065  *
19066  * This function takes a sequence, described by a list of frames, and creates
19067  * a list of iocbq structures to describe the sequence. This iocbq list will be
19068  * used to issue to the generic unsolicited sequence handler. This routine
19069  * returns a pointer to the first iocbq in the list. If the function is unable
19070  * to allocate an iocbq then it throw out the received frames that were not
19071  * able to be described and return a pointer to the first iocbq. If unable to
19072  * allocate any iocbqs (including the first) this function will return NULL.
19073  **/
19074 static struct lpfc_iocbq *
19075 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
19076 {
19077 	struct hbq_dmabuf *hbq_buf;
19078 	struct lpfc_dmabuf *d_buf, *n_buf;
19079 	struct lpfc_iocbq *first_iocbq, *iocbq;
19080 	struct fc_frame_header *fc_hdr;
19081 	uint32_t sid;
19082 	uint32_t len, tot_len;
19083 
19084 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19085 	/* remove from receive buffer list */
19086 	list_del_init(&seq_dmabuf->hbuf.list);
19087 	lpfc_update_rcv_time_stamp(vport);
19088 	/* get the Remote Port's SID */
19089 	sid = sli4_sid_from_fc_hdr(fc_hdr);
19090 	tot_len = 0;
19091 	/* Get an iocbq struct to fill in. */
19092 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
19093 	if (first_iocbq) {
19094 		/* Initialize the first IOCB. */
19095 		first_iocbq->wcqe_cmpl.total_data_placed = 0;
19096 		bf_set(lpfc_wcqe_c_status, &first_iocbq->wcqe_cmpl,
19097 		       IOSTAT_SUCCESS);
19098 		first_iocbq->vport = vport;
19099 
19100 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
19101 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
19102 			bf_set(els_rsp64_sid, &first_iocbq->wqe.xmit_els_rsp,
19103 			       sli4_did_from_fc_hdr(fc_hdr));
19104 		}
19105 
19106 		bf_set(wqe_ctxt_tag, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19107 		       NO_XRI);
19108 		bf_set(wqe_rcvoxid, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19109 		       be16_to_cpu(fc_hdr->fh_ox_id));
19110 
19111 		/* put the first buffer into the first iocb */
19112 		tot_len = bf_get(lpfc_rcqe_length,
19113 				 &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
19114 
19115 		first_iocbq->cmd_dmabuf = &seq_dmabuf->dbuf;
19116 		first_iocbq->bpl_dmabuf = NULL;
19117 		/* Keep track of the BDE count */
19118 		first_iocbq->wcqe_cmpl.word3 = 1;
19119 
19120 		if (tot_len > LPFC_DATA_BUF_SIZE)
19121 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize =
19122 				LPFC_DATA_BUF_SIZE;
19123 		else
19124 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize = tot_len;
19125 
19126 		first_iocbq->wcqe_cmpl.total_data_placed = tot_len;
19127 		bf_set(wqe_els_did, &first_iocbq->wqe.xmit_els_rsp.wqe_dest,
19128 		       sid);
19129 	}
19130 	iocbq = first_iocbq;
19131 	/*
19132 	 * Each IOCBq can have two Buffers assigned, so go through the list
19133 	 * of buffers for this sequence and save two buffers in each IOCBq
19134 	 */
19135 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
19136 		if (!iocbq) {
19137 			lpfc_in_buf_free(vport->phba, d_buf);
19138 			continue;
19139 		}
19140 		if (!iocbq->bpl_dmabuf) {
19141 			iocbq->bpl_dmabuf = d_buf;
19142 			iocbq->wcqe_cmpl.word3++;
19143 			/* We need to get the size out of the right CQE */
19144 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19145 			len = bf_get(lpfc_rcqe_length,
19146 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19147 			iocbq->unsol_rcv_len = len;
19148 			iocbq->wcqe_cmpl.total_data_placed += len;
19149 			tot_len += len;
19150 		} else {
19151 			iocbq = lpfc_sli_get_iocbq(vport->phba);
19152 			if (!iocbq) {
19153 				if (first_iocbq) {
19154 					bf_set(lpfc_wcqe_c_status,
19155 					       &first_iocbq->wcqe_cmpl,
19156 					       IOSTAT_SUCCESS);
19157 					first_iocbq->wcqe_cmpl.parameter =
19158 						IOERR_NO_RESOURCES;
19159 				}
19160 				lpfc_in_buf_free(vport->phba, d_buf);
19161 				continue;
19162 			}
19163 			/* We need to get the size out of the right CQE */
19164 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19165 			len = bf_get(lpfc_rcqe_length,
19166 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19167 			iocbq->cmd_dmabuf = d_buf;
19168 			iocbq->bpl_dmabuf = NULL;
19169 			iocbq->wcqe_cmpl.word3 = 1;
19170 
19171 			if (len > LPFC_DATA_BUF_SIZE)
19172 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19173 					LPFC_DATA_BUF_SIZE;
19174 			else
19175 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19176 					len;
19177 
19178 			tot_len += len;
19179 			iocbq->wcqe_cmpl.total_data_placed = tot_len;
19180 			bf_set(wqe_els_did, &iocbq->wqe.xmit_els_rsp.wqe_dest,
19181 			       sid);
19182 			list_add_tail(&iocbq->list, &first_iocbq->list);
19183 		}
19184 	}
19185 	/* Free the sequence's header buffer */
19186 	if (!first_iocbq)
19187 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
19188 
19189 	return first_iocbq;
19190 }
19191 
19192 static void
19193 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
19194 			  struct hbq_dmabuf *seq_dmabuf)
19195 {
19196 	struct fc_frame_header *fc_hdr;
19197 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
19198 	struct lpfc_hba *phba = vport->phba;
19199 
19200 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19201 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
19202 	if (!iocbq) {
19203 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19204 				"2707 Ring %d handler: Failed to allocate "
19205 				"iocb Rctl x%x Type x%x received\n",
19206 				LPFC_ELS_RING,
19207 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19208 		return;
19209 	}
19210 	if (!lpfc_complete_unsol_iocb(phba,
19211 				      phba->sli4_hba.els_wq->pring,
19212 				      iocbq, fc_hdr->fh_r_ctl,
19213 				      fc_hdr->fh_type)) {
19214 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19215 				"2540 Ring %d handler: unexpected Rctl "
19216 				"x%x Type x%x received\n",
19217 				LPFC_ELS_RING,
19218 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19219 		lpfc_in_buf_free(phba, &seq_dmabuf->dbuf);
19220 	}
19221 
19222 	/* Free iocb created in lpfc_prep_seq */
19223 	list_for_each_entry_safe(curr_iocb, next_iocb,
19224 				 &iocbq->list, list) {
19225 		list_del_init(&curr_iocb->list);
19226 		lpfc_sli_release_iocbq(phba, curr_iocb);
19227 	}
19228 	lpfc_sli_release_iocbq(phba, iocbq);
19229 }
19230 
19231 static void
19232 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
19233 			    struct lpfc_iocbq *rspiocb)
19234 {
19235 	struct lpfc_dmabuf *pcmd = cmdiocb->cmd_dmabuf;
19236 
19237 	if (pcmd && pcmd->virt)
19238 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19239 	kfree(pcmd);
19240 	lpfc_sli_release_iocbq(phba, cmdiocb);
19241 	lpfc_drain_txq(phba);
19242 }
19243 
19244 static void
19245 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
19246 			      struct hbq_dmabuf *dmabuf)
19247 {
19248 	struct fc_frame_header *fc_hdr;
19249 	struct lpfc_hba *phba = vport->phba;
19250 	struct lpfc_iocbq *iocbq = NULL;
19251 	union  lpfc_wqe128 *pwqe;
19252 	struct lpfc_dmabuf *pcmd = NULL;
19253 	uint32_t frame_len;
19254 	int rc;
19255 	unsigned long iflags;
19256 
19257 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19258 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
19259 
19260 	/* Send the received frame back */
19261 	iocbq = lpfc_sli_get_iocbq(phba);
19262 	if (!iocbq) {
19263 		/* Queue cq event and wakeup worker thread to process it */
19264 		spin_lock_irqsave(&phba->hbalock, iflags);
19265 		list_add_tail(&dmabuf->cq_event.list,
19266 			      &phba->sli4_hba.sp_queue_event);
19267 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
19268 		spin_unlock_irqrestore(&phba->hbalock, iflags);
19269 		lpfc_worker_wake_up(phba);
19270 		return;
19271 	}
19272 
19273 	/* Allocate buffer for command payload */
19274 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
19275 	if (pcmd)
19276 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
19277 					    &pcmd->phys);
19278 	if (!pcmd || !pcmd->virt)
19279 		goto exit;
19280 
19281 	INIT_LIST_HEAD(&pcmd->list);
19282 
19283 	/* copyin the payload */
19284 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
19285 
19286 	iocbq->cmd_dmabuf = pcmd;
19287 	iocbq->vport = vport;
19288 	iocbq->cmd_flag &= ~LPFC_FIP_ELS_ID_MASK;
19289 	iocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
19290 	iocbq->num_bdes = 0;
19291 
19292 	pwqe = &iocbq->wqe;
19293 	/* fill in BDE's for command */
19294 	pwqe->gen_req.bde.addrHigh = putPaddrHigh(pcmd->phys);
19295 	pwqe->gen_req.bde.addrLow = putPaddrLow(pcmd->phys);
19296 	pwqe->gen_req.bde.tus.f.bdeSize = frame_len;
19297 	pwqe->gen_req.bde.tus.f.bdeFlags = BUFF_TYPE_BDE_64;
19298 
19299 	pwqe->send_frame.frame_len = frame_len;
19300 	pwqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((__be32 *)fc_hdr));
19301 	pwqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((__be32 *)fc_hdr + 1));
19302 	pwqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((__be32 *)fc_hdr + 2));
19303 	pwqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((__be32 *)fc_hdr + 3));
19304 	pwqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((__be32 *)fc_hdr + 4));
19305 	pwqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((__be32 *)fc_hdr + 5));
19306 
19307 	pwqe->generic.wqe_com.word7 = 0;
19308 	pwqe->generic.wqe_com.word10 = 0;
19309 
19310 	bf_set(wqe_cmnd, &pwqe->generic.wqe_com, CMD_SEND_FRAME);
19311 	bf_set(wqe_sof, &pwqe->generic.wqe_com, 0x2E); /* SOF byte */
19312 	bf_set(wqe_eof, &pwqe->generic.wqe_com, 0x41); /* EOF byte */
19313 	bf_set(wqe_lenloc, &pwqe->generic.wqe_com, 1);
19314 	bf_set(wqe_xbl, &pwqe->generic.wqe_com, 1);
19315 	bf_set(wqe_dbde, &pwqe->generic.wqe_com, 1);
19316 	bf_set(wqe_xc, &pwqe->generic.wqe_com, 1);
19317 	bf_set(wqe_cmd_type, &pwqe->generic.wqe_com, 0xA);
19318 	bf_set(wqe_cqid, &pwqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
19319 	bf_set(wqe_xri_tag, &pwqe->generic.wqe_com, iocbq->sli4_xritag);
19320 	bf_set(wqe_reqtag, &pwqe->generic.wqe_com, iocbq->iotag);
19321 	bf_set(wqe_class, &pwqe->generic.wqe_com, CLASS3);
19322 	pwqe->generic.wqe_com.abort_tag = iocbq->iotag;
19323 
19324 	iocbq->cmd_cmpl = lpfc_sli4_mds_loopback_cmpl;
19325 
19326 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
19327 	if (rc == IOCB_ERROR)
19328 		goto exit;
19329 
19330 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19331 	return;
19332 
19333 exit:
19334 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
19335 			"2023 Unable to process MDS loopback frame\n");
19336 	if (pcmd && pcmd->virt)
19337 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19338 	kfree(pcmd);
19339 	if (iocbq)
19340 		lpfc_sli_release_iocbq(phba, iocbq);
19341 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19342 }
19343 
19344 /**
19345  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
19346  * @phba: Pointer to HBA context object.
19347  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
19348  *
19349  * This function is called with no lock held. This function processes all
19350  * the received buffers and gives it to upper layers when a received buffer
19351  * indicates that it is the final frame in the sequence. The interrupt
19352  * service routine processes received buffers at interrupt contexts.
19353  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
19354  * appropriate receive function when the final frame in a sequence is received.
19355  **/
19356 void
19357 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
19358 				 struct hbq_dmabuf *dmabuf)
19359 {
19360 	struct hbq_dmabuf *seq_dmabuf;
19361 	struct fc_frame_header *fc_hdr;
19362 	struct lpfc_vport *vport;
19363 	uint32_t fcfi;
19364 	uint32_t did;
19365 
19366 	/* Process each received buffer */
19367 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19368 
19369 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
19370 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
19371 		vport = phba->pport;
19372 		/* Handle MDS Loopback frames */
19373 		if  (!(phba->pport->load_flag & FC_UNLOADING))
19374 			lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19375 		else
19376 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19377 		return;
19378 	}
19379 
19380 	/* check to see if this a valid type of frame */
19381 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
19382 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19383 		return;
19384 	}
19385 
19386 	if ((bf_get(lpfc_cqe_code,
19387 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
19388 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
19389 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19390 	else
19391 		fcfi = bf_get(lpfc_rcqe_fcf_id,
19392 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19393 
19394 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
19395 		vport = phba->pport;
19396 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
19397 				"2023 MDS Loopback %d bytes\n",
19398 				bf_get(lpfc_rcqe_length,
19399 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
19400 		/* Handle MDS Loopback frames */
19401 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19402 		return;
19403 	}
19404 
19405 	/* d_id this frame is directed to */
19406 	did = sli4_did_from_fc_hdr(fc_hdr);
19407 
19408 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
19409 	if (!vport) {
19410 		/* throw out the frame */
19411 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19412 		return;
19413 	}
19414 
19415 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
19416 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
19417 		(did != Fabric_DID)) {
19418 		/*
19419 		 * Throw out the frame if we are not pt2pt.
19420 		 * The pt2pt protocol allows for discovery frames
19421 		 * to be received without a registered VPI.
19422 		 */
19423 		if (!(vport->fc_flag & FC_PT2PT) ||
19424 			(phba->link_state == LPFC_HBA_READY)) {
19425 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19426 			return;
19427 		}
19428 	}
19429 
19430 	/* Handle the basic abort sequence (BA_ABTS) event */
19431 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
19432 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
19433 		return;
19434 	}
19435 
19436 	/* Link this frame */
19437 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
19438 	if (!seq_dmabuf) {
19439 		/* unable to add frame to vport - throw it out */
19440 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19441 		return;
19442 	}
19443 	/* If not last frame in sequence continue processing frames. */
19444 	if (!lpfc_seq_complete(seq_dmabuf))
19445 		return;
19446 
19447 	/* Send the complete sequence to the upper layer protocol */
19448 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
19449 }
19450 
19451 /**
19452  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
19453  * @phba: pointer to lpfc hba data structure.
19454  *
19455  * This routine is invoked to post rpi header templates to the
19456  * HBA consistent with the SLI-4 interface spec.  This routine
19457  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19458  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19459  *
19460  * This routine does not require any locks.  It's usage is expected
19461  * to be driver load or reset recovery when the driver is
19462  * sequential.
19463  *
19464  * Return codes
19465  * 	0 - successful
19466  *      -EIO - The mailbox failed to complete successfully.
19467  * 	When this error occurs, the driver is not guaranteed
19468  *	to have any rpi regions posted to the device and
19469  *	must either attempt to repost the regions or take a
19470  *	fatal error.
19471  **/
19472 int
19473 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
19474 {
19475 	struct lpfc_rpi_hdr *rpi_page;
19476 	uint32_t rc = 0;
19477 	uint16_t lrpi = 0;
19478 
19479 	/* SLI4 ports that support extents do not require RPI headers. */
19480 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19481 		goto exit;
19482 	if (phba->sli4_hba.extents_in_use)
19483 		return -EIO;
19484 
19485 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
19486 		/*
19487 		 * Assign the rpi headers a physical rpi only if the driver
19488 		 * has not initialized those resources.  A port reset only
19489 		 * needs the headers posted.
19490 		 */
19491 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
19492 		    LPFC_RPI_RSRC_RDY)
19493 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19494 
19495 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
19496 		if (rc != MBX_SUCCESS) {
19497 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19498 					"2008 Error %d posting all rpi "
19499 					"headers\n", rc);
19500 			rc = -EIO;
19501 			break;
19502 		}
19503 	}
19504 
19505  exit:
19506 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
19507 	       LPFC_RPI_RSRC_RDY);
19508 	return rc;
19509 }
19510 
19511 /**
19512  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
19513  * @phba: pointer to lpfc hba data structure.
19514  * @rpi_page:  pointer to the rpi memory region.
19515  *
19516  * This routine is invoked to post a single rpi header to the
19517  * HBA consistent with the SLI-4 interface spec.  This memory region
19518  * maps up to 64 rpi context regions.
19519  *
19520  * Return codes
19521  * 	0 - successful
19522  * 	-ENOMEM - No available memory
19523  *      -EIO - The mailbox failed to complete successfully.
19524  **/
19525 int
19526 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
19527 {
19528 	LPFC_MBOXQ_t *mboxq;
19529 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
19530 	uint32_t rc = 0;
19531 	uint32_t shdr_status, shdr_add_status;
19532 	union lpfc_sli4_cfg_shdr *shdr;
19533 
19534 	/* SLI4 ports that support extents do not require RPI headers. */
19535 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19536 		return rc;
19537 	if (phba->sli4_hba.extents_in_use)
19538 		return -EIO;
19539 
19540 	/* The port is notified of the header region via a mailbox command. */
19541 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19542 	if (!mboxq) {
19543 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19544 				"2001 Unable to allocate memory for issuing "
19545 				"SLI_CONFIG_SPECIAL mailbox command\n");
19546 		return -ENOMEM;
19547 	}
19548 
19549 	/* Post all rpi memory regions to the port. */
19550 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
19551 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19552 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
19553 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
19554 			 sizeof(struct lpfc_sli4_cfg_mhdr),
19555 			 LPFC_SLI4_MBX_EMBED);
19556 
19557 
19558 	/* Post the physical rpi to the port for this rpi header. */
19559 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
19560 	       rpi_page->start_rpi);
19561 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
19562 	       hdr_tmpl, rpi_page->page_count);
19563 
19564 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
19565 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
19566 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19567 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
19568 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19569 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19570 	mempool_free(mboxq, phba->mbox_mem_pool);
19571 	if (shdr_status || shdr_add_status || rc) {
19572 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19573 				"2514 POST_RPI_HDR mailbox failed with "
19574 				"status x%x add_status x%x, mbx status x%x\n",
19575 				shdr_status, shdr_add_status, rc);
19576 		rc = -ENXIO;
19577 	} else {
19578 		/*
19579 		 * The next_rpi stores the next logical module-64 rpi value used
19580 		 * to post physical rpis in subsequent rpi postings.
19581 		 */
19582 		spin_lock_irq(&phba->hbalock);
19583 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
19584 		spin_unlock_irq(&phba->hbalock);
19585 	}
19586 	return rc;
19587 }
19588 
19589 /**
19590  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
19591  * @phba: pointer to lpfc hba data structure.
19592  *
19593  * This routine is invoked to post rpi header templates to the
19594  * HBA consistent with the SLI-4 interface spec.  This routine
19595  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19596  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19597  *
19598  * Returns
19599  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
19600  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
19601  **/
19602 int
19603 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
19604 {
19605 	unsigned long rpi;
19606 	uint16_t max_rpi, rpi_limit;
19607 	uint16_t rpi_remaining, lrpi = 0;
19608 	struct lpfc_rpi_hdr *rpi_hdr;
19609 	unsigned long iflag;
19610 
19611 	/*
19612 	 * Fetch the next logical rpi.  Because this index is logical,
19613 	 * the  driver starts at 0 each time.
19614 	 */
19615 	spin_lock_irqsave(&phba->hbalock, iflag);
19616 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
19617 	rpi_limit = phba->sli4_hba.next_rpi;
19618 
19619 	rpi = find_first_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit);
19620 	if (rpi >= rpi_limit)
19621 		rpi = LPFC_RPI_ALLOC_ERROR;
19622 	else {
19623 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
19624 		phba->sli4_hba.max_cfg_param.rpi_used++;
19625 		phba->sli4_hba.rpi_count++;
19626 	}
19627 	lpfc_printf_log(phba, KERN_INFO,
19628 			LOG_NODE | LOG_DISCOVERY,
19629 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
19630 			(int) rpi, max_rpi, rpi_limit);
19631 
19632 	/*
19633 	 * Don't try to allocate more rpi header regions if the device limit
19634 	 * has been exhausted.
19635 	 */
19636 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
19637 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
19638 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19639 		return rpi;
19640 	}
19641 
19642 	/*
19643 	 * RPI header postings are not required for SLI4 ports capable of
19644 	 * extents.
19645 	 */
19646 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
19647 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19648 		return rpi;
19649 	}
19650 
19651 	/*
19652 	 * If the driver is running low on rpi resources, allocate another
19653 	 * page now.  Note that the next_rpi value is used because
19654 	 * it represents how many are actually in use whereas max_rpi notes
19655 	 * how many are supported max by the device.
19656 	 */
19657 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
19658 	spin_unlock_irqrestore(&phba->hbalock, iflag);
19659 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
19660 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
19661 		if (!rpi_hdr) {
19662 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19663 					"2002 Error Could not grow rpi "
19664 					"count\n");
19665 		} else {
19666 			lrpi = rpi_hdr->start_rpi;
19667 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19668 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
19669 		}
19670 	}
19671 
19672 	return rpi;
19673 }
19674 
19675 /**
19676  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
19677  * @phba: pointer to lpfc hba data structure.
19678  * @rpi: rpi to free
19679  *
19680  * This routine is invoked to release an rpi to the pool of
19681  * available rpis maintained by the driver.
19682  **/
19683 static void
19684 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19685 {
19686 	/*
19687 	 * if the rpi value indicates a prior unreg has already
19688 	 * been done, skip the unreg.
19689 	 */
19690 	if (rpi == LPFC_RPI_ALLOC_ERROR)
19691 		return;
19692 
19693 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
19694 		phba->sli4_hba.rpi_count--;
19695 		phba->sli4_hba.max_cfg_param.rpi_used--;
19696 	} else {
19697 		lpfc_printf_log(phba, KERN_INFO,
19698 				LOG_NODE | LOG_DISCOVERY,
19699 				"2016 rpi %x not inuse\n",
19700 				rpi);
19701 	}
19702 }
19703 
19704 /**
19705  * lpfc_sli4_free_rpi - Release an rpi for reuse.
19706  * @phba: pointer to lpfc hba data structure.
19707  * @rpi: rpi to free
19708  *
19709  * This routine is invoked to release an rpi to the pool of
19710  * available rpis maintained by the driver.
19711  **/
19712 void
19713 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19714 {
19715 	spin_lock_irq(&phba->hbalock);
19716 	__lpfc_sli4_free_rpi(phba, rpi);
19717 	spin_unlock_irq(&phba->hbalock);
19718 }
19719 
19720 /**
19721  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19722  * @phba: pointer to lpfc hba data structure.
19723  *
19724  * This routine is invoked to remove the memory region that
19725  * provided rpi via a bitmask.
19726  **/
19727 void
19728 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19729 {
19730 	kfree(phba->sli4_hba.rpi_bmask);
19731 	kfree(phba->sli4_hba.rpi_ids);
19732 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19733 }
19734 
19735 /**
19736  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
19737  * @ndlp: pointer to lpfc nodelist data structure.
19738  * @cmpl: completion call-back.
19739  * @arg: data to load as MBox 'caller buffer information'
19740  *
19741  * This routine is invoked to remove the memory region that
19742  * provided rpi via a bitmask.
19743  **/
19744 int
19745 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19746 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
19747 {
19748 	LPFC_MBOXQ_t *mboxq;
19749 	struct lpfc_hba *phba = ndlp->phba;
19750 	int rc;
19751 
19752 	/* The port is notified of the header region via a mailbox command. */
19753 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19754 	if (!mboxq)
19755 		return -ENOMEM;
19756 
19757 	/* If cmpl assigned, then this nlp_get pairs with
19758 	 * lpfc_mbx_cmpl_resume_rpi.
19759 	 *
19760 	 * Else cmpl is NULL, then this nlp_get pairs with
19761 	 * lpfc_sli_def_mbox_cmpl.
19762 	 */
19763 	if (!lpfc_nlp_get(ndlp)) {
19764 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19765 				"2122 %s: Failed to get nlp ref\n",
19766 				__func__);
19767 		mempool_free(mboxq, phba->mbox_mem_pool);
19768 		return -EIO;
19769 	}
19770 
19771 	/* Post all rpi memory regions to the port. */
19772 	lpfc_resume_rpi(mboxq, ndlp);
19773 	if (cmpl) {
19774 		mboxq->mbox_cmpl = cmpl;
19775 		mboxq->ctx_buf = arg;
19776 	} else
19777 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19778 	mboxq->ctx_ndlp = ndlp;
19779 	mboxq->vport = ndlp->vport;
19780 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19781 	if (rc == MBX_NOT_FINISHED) {
19782 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19783 				"2010 Resume RPI Mailbox failed "
19784 				"status %d, mbxStatus x%x\n", rc,
19785 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19786 		lpfc_nlp_put(ndlp);
19787 		mempool_free(mboxq, phba->mbox_mem_pool);
19788 		return -EIO;
19789 	}
19790 	return 0;
19791 }
19792 
19793 /**
19794  * lpfc_sli4_init_vpi - Initialize a vpi with the port
19795  * @vport: Pointer to the vport for which the vpi is being initialized
19796  *
19797  * This routine is invoked to activate a vpi with the port.
19798  *
19799  * Returns:
19800  *    0 success
19801  *    -Evalue otherwise
19802  **/
19803 int
19804 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
19805 {
19806 	LPFC_MBOXQ_t *mboxq;
19807 	int rc = 0;
19808 	int retval = MBX_SUCCESS;
19809 	uint32_t mbox_tmo;
19810 	struct lpfc_hba *phba = vport->phba;
19811 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19812 	if (!mboxq)
19813 		return -ENOMEM;
19814 	lpfc_init_vpi(phba, mboxq, vport->vpi);
19815 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
19816 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
19817 	if (rc != MBX_SUCCESS) {
19818 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19819 				"2022 INIT VPI Mailbox failed "
19820 				"status %d, mbxStatus x%x\n", rc,
19821 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19822 		retval = -EIO;
19823 	}
19824 	if (rc != MBX_TIMEOUT)
19825 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
19826 
19827 	return retval;
19828 }
19829 
19830 /**
19831  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
19832  * @phba: pointer to lpfc hba data structure.
19833  * @mboxq: Pointer to mailbox object.
19834  *
19835  * This routine is invoked to manually add a single FCF record. The caller
19836  * must pass a completely initialized FCF_Record.  This routine takes
19837  * care of the nonembedded mailbox operations.
19838  **/
19839 static void
19840 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
19841 {
19842 	void *virt_addr;
19843 	union lpfc_sli4_cfg_shdr *shdr;
19844 	uint32_t shdr_status, shdr_add_status;
19845 
19846 	virt_addr = mboxq->sge_array->addr[0];
19847 	/* The IOCTL status is embedded in the mailbox subheader. */
19848 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
19849 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19850 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19851 
19852 	if ((shdr_status || shdr_add_status) &&
19853 		(shdr_status != STATUS_FCF_IN_USE))
19854 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19855 			"2558 ADD_FCF_RECORD mailbox failed with "
19856 			"status x%x add_status x%x\n",
19857 			shdr_status, shdr_add_status);
19858 
19859 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
19860 }
19861 
19862 /**
19863  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
19864  * @phba: pointer to lpfc hba data structure.
19865  * @fcf_record:  pointer to the initialized fcf record to add.
19866  *
19867  * This routine is invoked to manually add a single FCF record. The caller
19868  * must pass a completely initialized FCF_Record.  This routine takes
19869  * care of the nonembedded mailbox operations.
19870  **/
19871 int
19872 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
19873 {
19874 	int rc = 0;
19875 	LPFC_MBOXQ_t *mboxq;
19876 	uint8_t *bytep;
19877 	void *virt_addr;
19878 	struct lpfc_mbx_sge sge;
19879 	uint32_t alloc_len, req_len;
19880 	uint32_t fcfindex;
19881 
19882 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19883 	if (!mboxq) {
19884 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19885 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
19886 		return -ENOMEM;
19887 	}
19888 
19889 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
19890 		  sizeof(uint32_t);
19891 
19892 	/* Allocate DMA memory and set up the non-embedded mailbox command */
19893 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19894 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
19895 				     req_len, LPFC_SLI4_MBX_NEMBED);
19896 	if (alloc_len < req_len) {
19897 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19898 			"2523 Allocated DMA memory size (x%x) is "
19899 			"less than the requested DMA memory "
19900 			"size (x%x)\n", alloc_len, req_len);
19901 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19902 		return -ENOMEM;
19903 	}
19904 
19905 	/*
19906 	 * Get the first SGE entry from the non-embedded DMA memory.  This
19907 	 * routine only uses a single SGE.
19908 	 */
19909 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
19910 	virt_addr = mboxq->sge_array->addr[0];
19911 	/*
19912 	 * Configure the FCF record for FCFI 0.  This is the driver's
19913 	 * hardcoded default and gets used in nonFIP mode.
19914 	 */
19915 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
19916 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
19917 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
19918 
19919 	/*
19920 	 * Copy the fcf_index and the FCF Record Data. The data starts after
19921 	 * the FCoE header plus word10. The data copy needs to be endian
19922 	 * correct.
19923 	 */
19924 	bytep += sizeof(uint32_t);
19925 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
19926 	mboxq->vport = phba->pport;
19927 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
19928 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19929 	if (rc == MBX_NOT_FINISHED) {
19930 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19931 			"2515 ADD_FCF_RECORD mailbox failed with "
19932 			"status 0x%x\n", rc);
19933 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19934 		rc = -EIO;
19935 	} else
19936 		rc = 0;
19937 
19938 	return rc;
19939 }
19940 
19941 /**
19942  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
19943  * @phba: pointer to lpfc hba data structure.
19944  * @fcf_record:  pointer to the fcf record to write the default data.
19945  * @fcf_index: FCF table entry index.
19946  *
19947  * This routine is invoked to build the driver's default FCF record.  The
19948  * values used are hardcoded.  This routine handles memory initialization.
19949  *
19950  **/
19951 void
19952 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
19953 				struct fcf_record *fcf_record,
19954 				uint16_t fcf_index)
19955 {
19956 	memset(fcf_record, 0, sizeof(struct fcf_record));
19957 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
19958 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
19959 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
19960 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
19961 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
19962 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
19963 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
19964 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
19965 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
19966 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
19967 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
19968 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
19969 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
19970 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
19971 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
19972 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
19973 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
19974 	/* Set the VLAN bit map */
19975 	if (phba->valid_vlan) {
19976 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
19977 			= 1 << (phba->vlan_id % 8);
19978 	}
19979 }
19980 
19981 /**
19982  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
19983  * @phba: pointer to lpfc hba data structure.
19984  * @fcf_index: FCF table entry offset.
19985  *
19986  * This routine is invoked to scan the entire FCF table by reading FCF
19987  * record and processing it one at a time starting from the @fcf_index
19988  * for initial FCF discovery or fast FCF failover rediscovery.
19989  *
19990  * Return 0 if the mailbox command is submitted successfully, none 0
19991  * otherwise.
19992  **/
19993 int
19994 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19995 {
19996 	int rc = 0, error;
19997 	LPFC_MBOXQ_t *mboxq;
19998 
19999 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
20000 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
20001 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20002 	if (!mboxq) {
20003 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20004 				"2000 Failed to allocate mbox for "
20005 				"READ_FCF cmd\n");
20006 		error = -ENOMEM;
20007 		goto fail_fcf_scan;
20008 	}
20009 	/* Construct the read FCF record mailbox command */
20010 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20011 	if (rc) {
20012 		error = -EINVAL;
20013 		goto fail_fcf_scan;
20014 	}
20015 	/* Issue the mailbox command asynchronously */
20016 	mboxq->vport = phba->pport;
20017 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
20018 
20019 	spin_lock_irq(&phba->hbalock);
20020 	phba->hba_flag |= FCF_TS_INPROG;
20021 	spin_unlock_irq(&phba->hbalock);
20022 
20023 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20024 	if (rc == MBX_NOT_FINISHED)
20025 		error = -EIO;
20026 	else {
20027 		/* Reset eligible FCF count for new scan */
20028 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
20029 			phba->fcf.eligible_fcf_cnt = 0;
20030 		error = 0;
20031 	}
20032 fail_fcf_scan:
20033 	if (error) {
20034 		if (mboxq)
20035 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
20036 		/* FCF scan failed, clear FCF_TS_INPROG flag */
20037 		spin_lock_irq(&phba->hbalock);
20038 		phba->hba_flag &= ~FCF_TS_INPROG;
20039 		spin_unlock_irq(&phba->hbalock);
20040 	}
20041 	return error;
20042 }
20043 
20044 /**
20045  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
20046  * @phba: pointer to lpfc hba data structure.
20047  * @fcf_index: FCF table entry offset.
20048  *
20049  * This routine is invoked to read an FCF record indicated by @fcf_index
20050  * and to use it for FLOGI roundrobin FCF failover.
20051  *
20052  * Return 0 if the mailbox command is submitted successfully, none 0
20053  * otherwise.
20054  **/
20055 int
20056 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20057 {
20058 	int rc = 0, error;
20059 	LPFC_MBOXQ_t *mboxq;
20060 
20061 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20062 	if (!mboxq) {
20063 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20064 				"2763 Failed to allocate mbox for "
20065 				"READ_FCF cmd\n");
20066 		error = -ENOMEM;
20067 		goto fail_fcf_read;
20068 	}
20069 	/* Construct the read FCF record mailbox command */
20070 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20071 	if (rc) {
20072 		error = -EINVAL;
20073 		goto fail_fcf_read;
20074 	}
20075 	/* Issue the mailbox command asynchronously */
20076 	mboxq->vport = phba->pport;
20077 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
20078 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20079 	if (rc == MBX_NOT_FINISHED)
20080 		error = -EIO;
20081 	else
20082 		error = 0;
20083 
20084 fail_fcf_read:
20085 	if (error && mboxq)
20086 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20087 	return error;
20088 }
20089 
20090 /**
20091  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
20092  * @phba: pointer to lpfc hba data structure.
20093  * @fcf_index: FCF table entry offset.
20094  *
20095  * This routine is invoked to read an FCF record indicated by @fcf_index to
20096  * determine whether it's eligible for FLOGI roundrobin failover list.
20097  *
20098  * Return 0 if the mailbox command is submitted successfully, none 0
20099  * otherwise.
20100  **/
20101 int
20102 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20103 {
20104 	int rc = 0, error;
20105 	LPFC_MBOXQ_t *mboxq;
20106 
20107 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20108 	if (!mboxq) {
20109 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20110 				"2758 Failed to allocate mbox for "
20111 				"READ_FCF cmd\n");
20112 				error = -ENOMEM;
20113 				goto fail_fcf_read;
20114 	}
20115 	/* Construct the read FCF record mailbox command */
20116 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20117 	if (rc) {
20118 		error = -EINVAL;
20119 		goto fail_fcf_read;
20120 	}
20121 	/* Issue the mailbox command asynchronously */
20122 	mboxq->vport = phba->pport;
20123 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
20124 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20125 	if (rc == MBX_NOT_FINISHED)
20126 		error = -EIO;
20127 	else
20128 		error = 0;
20129 
20130 fail_fcf_read:
20131 	if (error && mboxq)
20132 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20133 	return error;
20134 }
20135 
20136 /**
20137  * lpfc_check_next_fcf_pri_level
20138  * @phba: pointer to the lpfc_hba struct for this port.
20139  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
20140  * routine when the rr_bmask is empty. The FCF indecies are put into the
20141  * rr_bmask based on their priority level. Starting from the highest priority
20142  * to the lowest. The most likely FCF candidate will be in the highest
20143  * priority group. When this routine is called it searches the fcf_pri list for
20144  * next lowest priority group and repopulates the rr_bmask with only those
20145  * fcf_indexes.
20146  * returns:
20147  * 1=success 0=failure
20148  **/
20149 static int
20150 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
20151 {
20152 	uint16_t next_fcf_pri;
20153 	uint16_t last_index;
20154 	struct lpfc_fcf_pri *fcf_pri;
20155 	int rc;
20156 	int ret = 0;
20157 
20158 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20159 			LPFC_SLI4_FCF_TBL_INDX_MAX);
20160 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20161 			"3060 Last IDX %d\n", last_index);
20162 
20163 	/* Verify the priority list has 2 or more entries */
20164 	spin_lock_irq(&phba->hbalock);
20165 	if (list_empty(&phba->fcf.fcf_pri_list) ||
20166 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
20167 		spin_unlock_irq(&phba->hbalock);
20168 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20169 			"3061 Last IDX %d\n", last_index);
20170 		return 0; /* Empty rr list */
20171 	}
20172 	spin_unlock_irq(&phba->hbalock);
20173 
20174 	next_fcf_pri = 0;
20175 	/*
20176 	 * Clear the rr_bmask and set all of the bits that are at this
20177 	 * priority.
20178 	 */
20179 	memset(phba->fcf.fcf_rr_bmask, 0,
20180 			sizeof(*phba->fcf.fcf_rr_bmask));
20181 	spin_lock_irq(&phba->hbalock);
20182 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20183 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
20184 			continue;
20185 		/*
20186 		 * the 1st priority that has not FLOGI failed
20187 		 * will be the highest.
20188 		 */
20189 		if (!next_fcf_pri)
20190 			next_fcf_pri = fcf_pri->fcf_rec.priority;
20191 		spin_unlock_irq(&phba->hbalock);
20192 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20193 			rc = lpfc_sli4_fcf_rr_index_set(phba,
20194 						fcf_pri->fcf_rec.fcf_index);
20195 			if (rc)
20196 				return 0;
20197 		}
20198 		spin_lock_irq(&phba->hbalock);
20199 	}
20200 	/*
20201 	 * if next_fcf_pri was not set above and the list is not empty then
20202 	 * we have failed flogis on all of them. So reset flogi failed
20203 	 * and start at the beginning.
20204 	 */
20205 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
20206 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20207 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
20208 			/*
20209 			 * the 1st priority that has not FLOGI failed
20210 			 * will be the highest.
20211 			 */
20212 			if (!next_fcf_pri)
20213 				next_fcf_pri = fcf_pri->fcf_rec.priority;
20214 			spin_unlock_irq(&phba->hbalock);
20215 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20216 				rc = lpfc_sli4_fcf_rr_index_set(phba,
20217 						fcf_pri->fcf_rec.fcf_index);
20218 				if (rc)
20219 					return 0;
20220 			}
20221 			spin_lock_irq(&phba->hbalock);
20222 		}
20223 	} else
20224 		ret = 1;
20225 	spin_unlock_irq(&phba->hbalock);
20226 
20227 	return ret;
20228 }
20229 /**
20230  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
20231  * @phba: pointer to lpfc hba data structure.
20232  *
20233  * This routine is to get the next eligible FCF record index in a round
20234  * robin fashion. If the next eligible FCF record index equals to the
20235  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
20236  * shall be returned, otherwise, the next eligible FCF record's index
20237  * shall be returned.
20238  **/
20239 uint16_t
20240 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
20241 {
20242 	uint16_t next_fcf_index;
20243 
20244 initial_priority:
20245 	/* Search start from next bit of currently registered FCF index */
20246 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
20247 
20248 next_priority:
20249 	/* Determine the next fcf index to check */
20250 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
20251 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
20252 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
20253 				       next_fcf_index);
20254 
20255 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
20256 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20257 		/*
20258 		 * If we have wrapped then we need to clear the bits that
20259 		 * have been tested so that we can detect when we should
20260 		 * change the priority level.
20261 		 */
20262 		next_fcf_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20263 					       LPFC_SLI4_FCF_TBL_INDX_MAX);
20264 	}
20265 
20266 
20267 	/* Check roundrobin failover list empty condition */
20268 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
20269 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
20270 		/*
20271 		 * If next fcf index is not found check if there are lower
20272 		 * Priority level fcf's in the fcf_priority list.
20273 		 * Set up the rr_bmask with all of the avaiable fcf bits
20274 		 * at that level and continue the selection process.
20275 		 */
20276 		if (lpfc_check_next_fcf_pri_level(phba))
20277 			goto initial_priority;
20278 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
20279 				"2844 No roundrobin failover FCF available\n");
20280 
20281 		return LPFC_FCOE_FCF_NEXT_NONE;
20282 	}
20283 
20284 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
20285 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
20286 		LPFC_FCF_FLOGI_FAILED) {
20287 		if (list_is_singular(&phba->fcf.fcf_pri_list))
20288 			return LPFC_FCOE_FCF_NEXT_NONE;
20289 
20290 		goto next_priority;
20291 	}
20292 
20293 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20294 			"2845 Get next roundrobin failover FCF (x%x)\n",
20295 			next_fcf_index);
20296 
20297 	return next_fcf_index;
20298 }
20299 
20300 /**
20301  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
20302  * @phba: pointer to lpfc hba data structure.
20303  * @fcf_index: index into the FCF table to 'set'
20304  *
20305  * This routine sets the FCF record index in to the eligible bmask for
20306  * roundrobin failover search. It checks to make sure that the index
20307  * does not go beyond the range of the driver allocated bmask dimension
20308  * before setting the bit.
20309  *
20310  * Returns 0 if the index bit successfully set, otherwise, it returns
20311  * -EINVAL.
20312  **/
20313 int
20314 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
20315 {
20316 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20317 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20318 				"2610 FCF (x%x) reached driver's book "
20319 				"keeping dimension:x%x\n",
20320 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20321 		return -EINVAL;
20322 	}
20323 	/* Set the eligible FCF record index bmask */
20324 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20325 
20326 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20327 			"2790 Set FCF (x%x) to roundrobin FCF failover "
20328 			"bmask\n", fcf_index);
20329 
20330 	return 0;
20331 }
20332 
20333 /**
20334  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
20335  * @phba: pointer to lpfc hba data structure.
20336  * @fcf_index: index into the FCF table to 'clear'
20337  *
20338  * This routine clears the FCF record index from the eligible bmask for
20339  * roundrobin failover search. It checks to make sure that the index
20340  * does not go beyond the range of the driver allocated bmask dimension
20341  * before clearing the bit.
20342  **/
20343 void
20344 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
20345 {
20346 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
20347 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20348 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20349 				"2762 FCF (x%x) reached driver's book "
20350 				"keeping dimension:x%x\n",
20351 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20352 		return;
20353 	}
20354 	/* Clear the eligible FCF record index bmask */
20355 	spin_lock_irq(&phba->hbalock);
20356 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
20357 				 list) {
20358 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
20359 			list_del_init(&fcf_pri->list);
20360 			break;
20361 		}
20362 	}
20363 	spin_unlock_irq(&phba->hbalock);
20364 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20365 
20366 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20367 			"2791 Clear FCF (x%x) from roundrobin failover "
20368 			"bmask\n", fcf_index);
20369 }
20370 
20371 /**
20372  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
20373  * @phba: pointer to lpfc hba data structure.
20374  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
20375  *
20376  * This routine is the completion routine for the rediscover FCF table mailbox
20377  * command. If the mailbox command returned failure, it will try to stop the
20378  * FCF rediscover wait timer.
20379  **/
20380 static void
20381 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
20382 {
20383 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20384 	uint32_t shdr_status, shdr_add_status;
20385 
20386 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20387 
20388 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20389 			     &redisc_fcf->header.cfg_shdr.response);
20390 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20391 			     &redisc_fcf->header.cfg_shdr.response);
20392 	if (shdr_status || shdr_add_status) {
20393 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20394 				"2746 Requesting for FCF rediscovery failed "
20395 				"status x%x add_status x%x\n",
20396 				shdr_status, shdr_add_status);
20397 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
20398 			spin_lock_irq(&phba->hbalock);
20399 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
20400 			spin_unlock_irq(&phba->hbalock);
20401 			/*
20402 			 * CVL event triggered FCF rediscover request failed,
20403 			 * last resort to re-try current registered FCF entry.
20404 			 */
20405 			lpfc_retry_pport_discovery(phba);
20406 		} else {
20407 			spin_lock_irq(&phba->hbalock);
20408 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
20409 			spin_unlock_irq(&phba->hbalock);
20410 			/*
20411 			 * DEAD FCF event triggered FCF rediscover request
20412 			 * failed, last resort to fail over as a link down
20413 			 * to FCF registration.
20414 			 */
20415 			lpfc_sli4_fcf_dead_failthrough(phba);
20416 		}
20417 	} else {
20418 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20419 				"2775 Start FCF rediscover quiescent timer\n");
20420 		/*
20421 		 * Start FCF rediscovery wait timer for pending FCF
20422 		 * before rescan FCF record table.
20423 		 */
20424 		lpfc_fcf_redisc_wait_start_timer(phba);
20425 	}
20426 
20427 	mempool_free(mbox, phba->mbox_mem_pool);
20428 }
20429 
20430 /**
20431  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
20432  * @phba: pointer to lpfc hba data structure.
20433  *
20434  * This routine is invoked to request for rediscovery of the entire FCF table
20435  * by the port.
20436  **/
20437 int
20438 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
20439 {
20440 	LPFC_MBOXQ_t *mbox;
20441 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20442 	int rc, length;
20443 
20444 	/* Cancel retry delay timers to all vports before FCF rediscover */
20445 	lpfc_cancel_all_vport_retry_delay_timer(phba);
20446 
20447 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20448 	if (!mbox) {
20449 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20450 				"2745 Failed to allocate mbox for "
20451 				"requesting FCF rediscover.\n");
20452 		return -ENOMEM;
20453 	}
20454 
20455 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
20456 		  sizeof(struct lpfc_sli4_cfg_mhdr));
20457 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
20458 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
20459 			 length, LPFC_SLI4_MBX_EMBED);
20460 
20461 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20462 	/* Set count to 0 for invalidating the entire FCF database */
20463 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
20464 
20465 	/* Issue the mailbox command asynchronously */
20466 	mbox->vport = phba->pport;
20467 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
20468 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
20469 
20470 	if (rc == MBX_NOT_FINISHED) {
20471 		mempool_free(mbox, phba->mbox_mem_pool);
20472 		return -EIO;
20473 	}
20474 	return 0;
20475 }
20476 
20477 /**
20478  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
20479  * @phba: pointer to lpfc hba data structure.
20480  *
20481  * This function is the failover routine as a last resort to the FCF DEAD
20482  * event when driver failed to perform fast FCF failover.
20483  **/
20484 void
20485 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
20486 {
20487 	uint32_t link_state;
20488 
20489 	/*
20490 	 * Last resort as FCF DEAD event failover will treat this as
20491 	 * a link down, but save the link state because we don't want
20492 	 * it to be changed to Link Down unless it is already down.
20493 	 */
20494 	link_state = phba->link_state;
20495 	lpfc_linkdown(phba);
20496 	phba->link_state = link_state;
20497 
20498 	/* Unregister FCF if no devices connected to it */
20499 	lpfc_unregister_unused_fcf(phba);
20500 }
20501 
20502 /**
20503  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
20504  * @phba: pointer to lpfc hba data structure.
20505  * @rgn23_data: pointer to configure region 23 data.
20506  *
20507  * This function gets SLI3 port configure region 23 data through memory dump
20508  * mailbox command. When it successfully retrieves data, the size of the data
20509  * will be returned, otherwise, 0 will be returned.
20510  **/
20511 static uint32_t
20512 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20513 {
20514 	LPFC_MBOXQ_t *pmb = NULL;
20515 	MAILBOX_t *mb;
20516 	uint32_t offset = 0;
20517 	int rc;
20518 
20519 	if (!rgn23_data)
20520 		return 0;
20521 
20522 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20523 	if (!pmb) {
20524 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20525 				"2600 failed to allocate mailbox memory\n");
20526 		return 0;
20527 	}
20528 	mb = &pmb->u.mb;
20529 
20530 	do {
20531 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
20532 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
20533 
20534 		if (rc != MBX_SUCCESS) {
20535 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20536 					"2601 failed to read config "
20537 					"region 23, rc 0x%x Status 0x%x\n",
20538 					rc, mb->mbxStatus);
20539 			mb->un.varDmp.word_cnt = 0;
20540 		}
20541 		/*
20542 		 * dump mem may return a zero when finished or we got a
20543 		 * mailbox error, either way we are done.
20544 		 */
20545 		if (mb->un.varDmp.word_cnt == 0)
20546 			break;
20547 
20548 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
20549 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
20550 
20551 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
20552 				       rgn23_data + offset,
20553 				       mb->un.varDmp.word_cnt);
20554 		offset += mb->un.varDmp.word_cnt;
20555 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
20556 
20557 	mempool_free(pmb, phba->mbox_mem_pool);
20558 	return offset;
20559 }
20560 
20561 /**
20562  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
20563  * @phba: pointer to lpfc hba data structure.
20564  * @rgn23_data: pointer to configure region 23 data.
20565  *
20566  * This function gets SLI4 port configure region 23 data through memory dump
20567  * mailbox command. When it successfully retrieves data, the size of the data
20568  * will be returned, otherwise, 0 will be returned.
20569  **/
20570 static uint32_t
20571 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20572 {
20573 	LPFC_MBOXQ_t *mboxq = NULL;
20574 	struct lpfc_dmabuf *mp = NULL;
20575 	struct lpfc_mqe *mqe;
20576 	uint32_t data_length = 0;
20577 	int rc;
20578 
20579 	if (!rgn23_data)
20580 		return 0;
20581 
20582 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20583 	if (!mboxq) {
20584 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20585 				"3105 failed to allocate mailbox memory\n");
20586 		return 0;
20587 	}
20588 
20589 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
20590 		goto out;
20591 	mqe = &mboxq->u.mqe;
20592 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
20593 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
20594 	if (rc)
20595 		goto out;
20596 	data_length = mqe->un.mb_words[5];
20597 	if (data_length == 0)
20598 		goto out;
20599 	if (data_length > DMP_RGN23_SIZE) {
20600 		data_length = 0;
20601 		goto out;
20602 	}
20603 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
20604 out:
20605 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
20606 	return data_length;
20607 }
20608 
20609 /**
20610  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
20611  * @phba: pointer to lpfc hba data structure.
20612  *
20613  * This function read region 23 and parse TLV for port status to
20614  * decide if the user disaled the port. If the TLV indicates the
20615  * port is disabled, the hba_flag is set accordingly.
20616  **/
20617 void
20618 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
20619 {
20620 	uint8_t *rgn23_data = NULL;
20621 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
20622 	uint32_t offset = 0;
20623 
20624 	/* Get adapter Region 23 data */
20625 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
20626 	if (!rgn23_data)
20627 		goto out;
20628 
20629 	if (phba->sli_rev < LPFC_SLI_REV4)
20630 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
20631 	else {
20632 		if_type = bf_get(lpfc_sli_intf_if_type,
20633 				 &phba->sli4_hba.sli_intf);
20634 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
20635 			goto out;
20636 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
20637 	}
20638 
20639 	if (!data_size)
20640 		goto out;
20641 
20642 	/* Check the region signature first */
20643 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
20644 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20645 			"2619 Config region 23 has bad signature\n");
20646 			goto out;
20647 	}
20648 	offset += 4;
20649 
20650 	/* Check the data structure version */
20651 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
20652 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20653 			"2620 Config region 23 has bad version\n");
20654 		goto out;
20655 	}
20656 	offset += 4;
20657 
20658 	/* Parse TLV entries in the region */
20659 	while (offset < data_size) {
20660 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
20661 			break;
20662 		/*
20663 		 * If the TLV is not driver specific TLV or driver id is
20664 		 * not linux driver id, skip the record.
20665 		 */
20666 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
20667 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
20668 		    (rgn23_data[offset + 3] != 0)) {
20669 			offset += rgn23_data[offset + 1] * 4 + 4;
20670 			continue;
20671 		}
20672 
20673 		/* Driver found a driver specific TLV in the config region */
20674 		sub_tlv_len = rgn23_data[offset + 1] * 4;
20675 		offset += 4;
20676 		tlv_offset = 0;
20677 
20678 		/*
20679 		 * Search for configured port state sub-TLV.
20680 		 */
20681 		while ((offset < data_size) &&
20682 			(tlv_offset < sub_tlv_len)) {
20683 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
20684 				offset += 4;
20685 				tlv_offset += 4;
20686 				break;
20687 			}
20688 			if (rgn23_data[offset] != PORT_STE_TYPE) {
20689 				offset += rgn23_data[offset + 1] * 4 + 4;
20690 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
20691 				continue;
20692 			}
20693 
20694 			/* This HBA contains PORT_STE configured */
20695 			if (!rgn23_data[offset + 2])
20696 				phba->hba_flag |= LINK_DISABLED;
20697 
20698 			goto out;
20699 		}
20700 	}
20701 
20702 out:
20703 	kfree(rgn23_data);
20704 	return;
20705 }
20706 
20707 /**
20708  * lpfc_log_fw_write_cmpl - logs firmware write completion status
20709  * @phba: pointer to lpfc hba data structure
20710  * @shdr_status: wr_object rsp's status field
20711  * @shdr_add_status: wr_object rsp's add_status field
20712  * @shdr_add_status_2: wr_object rsp's add_status_2 field
20713  * @shdr_change_status: wr_object rsp's change_status field
20714  * @shdr_csf: wr_object rsp's csf bit
20715  *
20716  * This routine is intended to be called after a firmware write completes.
20717  * It will log next action items to be performed by the user to instantiate
20718  * the newly downloaded firmware or reason for incompatibility.
20719  **/
20720 static void
20721 lpfc_log_fw_write_cmpl(struct lpfc_hba *phba, u32 shdr_status,
20722 		       u32 shdr_add_status, u32 shdr_add_status_2,
20723 		       u32 shdr_change_status, u32 shdr_csf)
20724 {
20725 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20726 			"4198 %s: flash_id x%02x, asic_rev x%02x, "
20727 			"status x%02x, add_status x%02x, add_status_2 x%02x, "
20728 			"change_status x%02x, csf %01x\n", __func__,
20729 			phba->sli4_hba.flash_id, phba->sli4_hba.asic_rev,
20730 			shdr_status, shdr_add_status, shdr_add_status_2,
20731 			shdr_change_status, shdr_csf);
20732 
20733 	if (shdr_add_status == LPFC_ADD_STATUS_INCOMPAT_OBJ) {
20734 		switch (shdr_add_status_2) {
20735 		case LPFC_ADD_STATUS_2_INCOMPAT_FLASH:
20736 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20737 					"4199 Firmware write failed: "
20738 					"image incompatible with flash x%02x\n",
20739 					phba->sli4_hba.flash_id);
20740 			break;
20741 		case LPFC_ADD_STATUS_2_INCORRECT_ASIC:
20742 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20743 					"4200 Firmware write failed: "
20744 					"image incompatible with ASIC "
20745 					"architecture x%02x\n",
20746 					phba->sli4_hba.asic_rev);
20747 			break;
20748 		default:
20749 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20750 					"4210 Firmware write failed: "
20751 					"add_status_2 x%02x\n",
20752 					shdr_add_status_2);
20753 			break;
20754 		}
20755 	} else if (!shdr_status && !shdr_add_status) {
20756 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20757 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20758 			if (shdr_csf)
20759 				shdr_change_status =
20760 						   LPFC_CHANGE_STATUS_PCI_RESET;
20761 		}
20762 
20763 		switch (shdr_change_status) {
20764 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20765 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20766 					"3198 Firmware write complete: System "
20767 					"reboot required to instantiate\n");
20768 			break;
20769 		case (LPFC_CHANGE_STATUS_FW_RESET):
20770 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20771 					"3199 Firmware write complete: "
20772 					"Firmware reset required to "
20773 					"instantiate\n");
20774 			break;
20775 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20776 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20777 					"3200 Firmware write complete: Port "
20778 					"Migration or PCI Reset required to "
20779 					"instantiate\n");
20780 			break;
20781 		case (LPFC_CHANGE_STATUS_PCI_RESET):
20782 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20783 					"3201 Firmware write complete: PCI "
20784 					"Reset required to instantiate\n");
20785 			break;
20786 		default:
20787 			break;
20788 		}
20789 	}
20790 }
20791 
20792 /**
20793  * lpfc_wr_object - write an object to the firmware
20794  * @phba: HBA structure that indicates port to create a queue on.
20795  * @dmabuf_list: list of dmabufs to write to the port.
20796  * @size: the total byte value of the objects to write to the port.
20797  * @offset: the current offset to be used to start the transfer.
20798  *
20799  * This routine will create a wr_object mailbox command to send to the port.
20800  * the mailbox command will be constructed using the dma buffers described in
20801  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
20802  * BDEs that the imbedded mailbox can support. The @offset variable will be
20803  * used to indicate the starting offset of the transfer and will also return
20804  * the offset after the write object mailbox has completed. @size is used to
20805  * determine the end of the object and whether the eof bit should be set.
20806  *
20807  * Return 0 is successful and offset will contain the new offset to use
20808  * for the next write.
20809  * Return negative value for error cases.
20810  **/
20811 int
20812 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
20813 	       uint32_t size, uint32_t *offset)
20814 {
20815 	struct lpfc_mbx_wr_object *wr_object;
20816 	LPFC_MBOXQ_t *mbox;
20817 	int rc = 0, i = 0;
20818 	int mbox_status = 0;
20819 	uint32_t shdr_status, shdr_add_status, shdr_add_status_2;
20820 	uint32_t shdr_change_status = 0, shdr_csf = 0;
20821 	uint32_t mbox_tmo;
20822 	struct lpfc_dmabuf *dmabuf;
20823 	uint32_t written = 0;
20824 	bool check_change_status = false;
20825 
20826 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20827 	if (!mbox)
20828 		return -ENOMEM;
20829 
20830 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
20831 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
20832 			sizeof(struct lpfc_mbx_wr_object) -
20833 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
20834 
20835 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
20836 	wr_object->u.request.write_offset = *offset;
20837 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
20838 	wr_object->u.request.object_name[0] =
20839 		cpu_to_le32(wr_object->u.request.object_name[0]);
20840 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
20841 	list_for_each_entry(dmabuf, dmabuf_list, list) {
20842 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
20843 			break;
20844 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
20845 		wr_object->u.request.bde[i].addrHigh =
20846 			putPaddrHigh(dmabuf->phys);
20847 		if (written + SLI4_PAGE_SIZE >= size) {
20848 			wr_object->u.request.bde[i].tus.f.bdeSize =
20849 				(size - written);
20850 			written += (size - written);
20851 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
20852 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
20853 			check_change_status = true;
20854 		} else {
20855 			wr_object->u.request.bde[i].tus.f.bdeSize =
20856 				SLI4_PAGE_SIZE;
20857 			written += SLI4_PAGE_SIZE;
20858 		}
20859 		i++;
20860 	}
20861 	wr_object->u.request.bde_count = i;
20862 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
20863 	if (!phba->sli4_hba.intr_enable)
20864 		mbox_status = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
20865 	else {
20866 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
20867 		mbox_status = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
20868 	}
20869 
20870 	/* The mbox status needs to be maintained to detect MBOX_TIMEOUT. */
20871 	rc = mbox_status;
20872 
20873 	/* The IOCTL status is embedded in the mailbox subheader. */
20874 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20875 			     &wr_object->header.cfg_shdr.response);
20876 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20877 				 &wr_object->header.cfg_shdr.response);
20878 	shdr_add_status_2 = bf_get(lpfc_mbox_hdr_add_status_2,
20879 				   &wr_object->header.cfg_shdr.response);
20880 	if (check_change_status) {
20881 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
20882 					    &wr_object->u.response);
20883 		shdr_csf = bf_get(lpfc_wr_object_csf,
20884 				  &wr_object->u.response);
20885 	}
20886 
20887 	if (shdr_status || shdr_add_status || shdr_add_status_2 || rc) {
20888 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20889 				"3025 Write Object mailbox failed with "
20890 				"status x%x add_status x%x, add_status_2 x%x, "
20891 				"mbx status x%x\n",
20892 				shdr_status, shdr_add_status, shdr_add_status_2,
20893 				rc);
20894 		rc = -ENXIO;
20895 		*offset = shdr_add_status;
20896 	} else {
20897 		*offset += wr_object->u.response.actual_write_length;
20898 	}
20899 
20900 	if (rc || check_change_status)
20901 		lpfc_log_fw_write_cmpl(phba, shdr_status, shdr_add_status,
20902 				       shdr_add_status_2, shdr_change_status,
20903 				       shdr_csf);
20904 
20905 	if (!phba->sli4_hba.intr_enable)
20906 		mempool_free(mbox, phba->mbox_mem_pool);
20907 	else if (mbox_status != MBX_TIMEOUT)
20908 		mempool_free(mbox, phba->mbox_mem_pool);
20909 
20910 	return rc;
20911 }
20912 
20913 /**
20914  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
20915  * @vport: pointer to vport data structure.
20916  *
20917  * This function iterate through the mailboxq and clean up all REG_LOGIN
20918  * and REG_VPI mailbox commands associated with the vport. This function
20919  * is called when driver want to restart discovery of the vport due to
20920  * a Clear Virtual Link event.
20921  **/
20922 void
20923 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
20924 {
20925 	struct lpfc_hba *phba = vport->phba;
20926 	LPFC_MBOXQ_t *mb, *nextmb;
20927 	struct lpfc_nodelist *ndlp;
20928 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
20929 	LIST_HEAD(mbox_cmd_list);
20930 	uint8_t restart_loop;
20931 
20932 	/* Clean up internally queued mailbox commands with the vport */
20933 	spin_lock_irq(&phba->hbalock);
20934 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
20935 		if (mb->vport != vport)
20936 			continue;
20937 
20938 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
20939 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
20940 			continue;
20941 
20942 		list_move_tail(&mb->list, &mbox_cmd_list);
20943 	}
20944 	/* Clean up active mailbox command with the vport */
20945 	mb = phba->sli.mbox_active;
20946 	if (mb && (mb->vport == vport)) {
20947 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
20948 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
20949 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
20950 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20951 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20952 
20953 			/* This reference is local to this routine.  The
20954 			 * reference is removed at routine exit.
20955 			 */
20956 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
20957 
20958 			/* Unregister the RPI when mailbox complete */
20959 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
20960 		}
20961 	}
20962 	/* Cleanup any mailbox completions which are not yet processed */
20963 	do {
20964 		restart_loop = 0;
20965 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
20966 			/*
20967 			 * If this mailox is already processed or it is
20968 			 * for another vport ignore it.
20969 			 */
20970 			if ((mb->vport != vport) ||
20971 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
20972 				continue;
20973 
20974 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
20975 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
20976 				continue;
20977 
20978 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
20979 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20980 				ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20981 				/* Unregister the RPI when mailbox complete */
20982 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
20983 				restart_loop = 1;
20984 				spin_unlock_irq(&phba->hbalock);
20985 				spin_lock(&ndlp->lock);
20986 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20987 				spin_unlock(&ndlp->lock);
20988 				spin_lock_irq(&phba->hbalock);
20989 				break;
20990 			}
20991 		}
20992 	} while (restart_loop);
20993 
20994 	spin_unlock_irq(&phba->hbalock);
20995 
20996 	/* Release the cleaned-up mailbox commands */
20997 	while (!list_empty(&mbox_cmd_list)) {
20998 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
20999 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21000 			ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
21001 			mb->ctx_ndlp = NULL;
21002 			if (ndlp) {
21003 				spin_lock(&ndlp->lock);
21004 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21005 				spin_unlock(&ndlp->lock);
21006 				lpfc_nlp_put(ndlp);
21007 			}
21008 		}
21009 		lpfc_mbox_rsrc_cleanup(phba, mb, MBOX_THD_UNLOCKED);
21010 	}
21011 
21012 	/* Release the ndlp with the cleaned-up active mailbox command */
21013 	if (act_mbx_ndlp) {
21014 		spin_lock(&act_mbx_ndlp->lock);
21015 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21016 		spin_unlock(&act_mbx_ndlp->lock);
21017 		lpfc_nlp_put(act_mbx_ndlp);
21018 	}
21019 }
21020 
21021 /**
21022  * lpfc_drain_txq - Drain the txq
21023  * @phba: Pointer to HBA context object.
21024  *
21025  * This function attempt to submit IOCBs on the txq
21026  * to the adapter.  For SLI4 adapters, the txq contains
21027  * ELS IOCBs that have been deferred because the there
21028  * are no SGLs.  This congestion can occur with large
21029  * vport counts during node discovery.
21030  **/
21031 
21032 uint32_t
21033 lpfc_drain_txq(struct lpfc_hba *phba)
21034 {
21035 	LIST_HEAD(completions);
21036 	struct lpfc_sli_ring *pring;
21037 	struct lpfc_iocbq *piocbq = NULL;
21038 	unsigned long iflags = 0;
21039 	char *fail_msg = NULL;
21040 	uint32_t txq_cnt = 0;
21041 	struct lpfc_queue *wq;
21042 	int ret = 0;
21043 
21044 	if (phba->link_flag & LS_MDS_LOOPBACK) {
21045 		/* MDS WQE are posted only to first WQ*/
21046 		wq = phba->sli4_hba.hdwq[0].io_wq;
21047 		if (unlikely(!wq))
21048 			return 0;
21049 		pring = wq->pring;
21050 	} else {
21051 		wq = phba->sli4_hba.els_wq;
21052 		if (unlikely(!wq))
21053 			return 0;
21054 		pring = lpfc_phba_elsring(phba);
21055 	}
21056 
21057 	if (unlikely(!pring) || list_empty(&pring->txq))
21058 		return 0;
21059 
21060 	spin_lock_irqsave(&pring->ring_lock, iflags);
21061 	list_for_each_entry(piocbq, &pring->txq, list) {
21062 		txq_cnt++;
21063 	}
21064 
21065 	if (txq_cnt > pring->txq_max)
21066 		pring->txq_max = txq_cnt;
21067 
21068 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
21069 
21070 	while (!list_empty(&pring->txq)) {
21071 		spin_lock_irqsave(&pring->ring_lock, iflags);
21072 
21073 		piocbq = lpfc_sli_ringtx_get(phba, pring);
21074 		if (!piocbq) {
21075 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21076 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21077 				"2823 txq empty and txq_cnt is %d\n ",
21078 				txq_cnt);
21079 			break;
21080 		}
21081 		txq_cnt--;
21082 
21083 		ret = __lpfc_sli_issue_iocb(phba, pring->ringno, piocbq, 0);
21084 
21085 		if (ret && ret != IOCB_BUSY) {
21086 			fail_msg = " - Cannot send IO ";
21087 			piocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21088 		}
21089 		if (fail_msg) {
21090 			piocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
21091 			/* Failed means we can't issue and need to cancel */
21092 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21093 					"2822 IOCB failed %s iotag 0x%x "
21094 					"xri 0x%x %d flg x%x\n",
21095 					fail_msg, piocbq->iotag,
21096 					piocbq->sli4_xritag, ret,
21097 					piocbq->cmd_flag);
21098 			list_add_tail(&piocbq->list, &completions);
21099 			fail_msg = NULL;
21100 		}
21101 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21102 		if (txq_cnt == 0 || ret == IOCB_BUSY)
21103 			break;
21104 	}
21105 	/* Cancel all the IOCBs that cannot be issued */
21106 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
21107 			      IOERR_SLI_ABORTED);
21108 
21109 	return txq_cnt;
21110 }
21111 
21112 /**
21113  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
21114  * @phba: Pointer to HBA context object.
21115  * @pwqeq: Pointer to command WQE.
21116  * @sglq: Pointer to the scatter gather queue object.
21117  *
21118  * This routine converts the bpl or bde that is in the WQE
21119  * to a sgl list for the sli4 hardware. The physical address
21120  * of the bpl/bde is converted back to a virtual address.
21121  * If the WQE contains a BPL then the list of BDE's is
21122  * converted to sli4_sge's. If the WQE contains a single
21123  * BDE then it is converted to a single sli_sge.
21124  * The WQE is still in cpu endianness so the contents of
21125  * the bpl can be used without byte swapping.
21126  *
21127  * Returns valid XRI = Success, NO_XRI = Failure.
21128  */
21129 static uint16_t
21130 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
21131 		 struct lpfc_sglq *sglq)
21132 {
21133 	uint16_t xritag = NO_XRI;
21134 	struct ulp_bde64 *bpl = NULL;
21135 	struct ulp_bde64 bde;
21136 	struct sli4_sge *sgl  = NULL;
21137 	struct lpfc_dmabuf *dmabuf;
21138 	union lpfc_wqe128 *wqe;
21139 	int numBdes = 0;
21140 	int i = 0;
21141 	uint32_t offset = 0; /* accumulated offset in the sg request list */
21142 	int inbound = 0; /* number of sg reply entries inbound from firmware */
21143 	uint32_t cmd;
21144 
21145 	if (!pwqeq || !sglq)
21146 		return xritag;
21147 
21148 	sgl  = (struct sli4_sge *)sglq->sgl;
21149 	wqe = &pwqeq->wqe;
21150 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
21151 
21152 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
21153 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
21154 		return sglq->sli4_xritag;
21155 	numBdes = pwqeq->num_bdes;
21156 	if (numBdes) {
21157 		/* The addrHigh and addrLow fields within the WQE
21158 		 * have not been byteswapped yet so there is no
21159 		 * need to swap them back.
21160 		 */
21161 		if (pwqeq->bpl_dmabuf)
21162 			dmabuf = pwqeq->bpl_dmabuf;
21163 		else
21164 			return xritag;
21165 
21166 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
21167 		if (!bpl)
21168 			return xritag;
21169 
21170 		for (i = 0; i < numBdes; i++) {
21171 			/* Should already be byte swapped. */
21172 			sgl->addr_hi = bpl->addrHigh;
21173 			sgl->addr_lo = bpl->addrLow;
21174 
21175 			sgl->word2 = le32_to_cpu(sgl->word2);
21176 			if ((i+1) == numBdes)
21177 				bf_set(lpfc_sli4_sge_last, sgl, 1);
21178 			else
21179 				bf_set(lpfc_sli4_sge_last, sgl, 0);
21180 			/* swap the size field back to the cpu so we
21181 			 * can assign it to the sgl.
21182 			 */
21183 			bde.tus.w = le32_to_cpu(bpl->tus.w);
21184 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
21185 			/* The offsets in the sgl need to be accumulated
21186 			 * separately for the request and reply lists.
21187 			 * The request is always first, the reply follows.
21188 			 */
21189 			switch (cmd) {
21190 			case CMD_GEN_REQUEST64_WQE:
21191 				/* add up the reply sg entries */
21192 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
21193 					inbound++;
21194 				/* first inbound? reset the offset */
21195 				if (inbound == 1)
21196 					offset = 0;
21197 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21198 				bf_set(lpfc_sli4_sge_type, sgl,
21199 					LPFC_SGE_TYPE_DATA);
21200 				offset += bde.tus.f.bdeSize;
21201 				break;
21202 			case CMD_FCP_TRSP64_WQE:
21203 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
21204 				bf_set(lpfc_sli4_sge_type, sgl,
21205 					LPFC_SGE_TYPE_DATA);
21206 				break;
21207 			case CMD_FCP_TSEND64_WQE:
21208 			case CMD_FCP_TRECEIVE64_WQE:
21209 				bf_set(lpfc_sli4_sge_type, sgl,
21210 					bpl->tus.f.bdeFlags);
21211 				if (i < 3)
21212 					offset = 0;
21213 				else
21214 					offset += bde.tus.f.bdeSize;
21215 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21216 				break;
21217 			}
21218 			sgl->word2 = cpu_to_le32(sgl->word2);
21219 			bpl++;
21220 			sgl++;
21221 		}
21222 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
21223 		/* The addrHigh and addrLow fields of the BDE have not
21224 		 * been byteswapped yet so they need to be swapped
21225 		 * before putting them in the sgl.
21226 		 */
21227 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
21228 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
21229 		sgl->word2 = le32_to_cpu(sgl->word2);
21230 		bf_set(lpfc_sli4_sge_last, sgl, 1);
21231 		sgl->word2 = cpu_to_le32(sgl->word2);
21232 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
21233 	}
21234 	return sglq->sli4_xritag;
21235 }
21236 
21237 /**
21238  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
21239  * @phba: Pointer to HBA context object.
21240  * @qp: Pointer to HDW queue.
21241  * @pwqe: Pointer to command WQE.
21242  **/
21243 int
21244 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21245 		    struct lpfc_iocbq *pwqe)
21246 {
21247 	union lpfc_wqe128 *wqe = &pwqe->wqe;
21248 	struct lpfc_async_xchg_ctx *ctxp;
21249 	struct lpfc_queue *wq;
21250 	struct lpfc_sglq *sglq;
21251 	struct lpfc_sli_ring *pring;
21252 	unsigned long iflags;
21253 	uint32_t ret = 0;
21254 
21255 	/* NVME_LS and NVME_LS ABTS requests. */
21256 	if (pwqe->cmd_flag & LPFC_IO_NVME_LS) {
21257 		pring =  phba->sli4_hba.nvmels_wq->pring;
21258 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21259 					  qp, wq_access);
21260 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
21261 		if (!sglq) {
21262 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21263 			return WQE_BUSY;
21264 		}
21265 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
21266 		pwqe->sli4_xritag = sglq->sli4_xritag;
21267 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
21268 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21269 			return WQE_ERROR;
21270 		}
21271 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21272 		       pwqe->sli4_xritag);
21273 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
21274 		if (ret) {
21275 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21276 			return ret;
21277 		}
21278 
21279 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21280 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21281 
21282 		lpfc_sli4_poll_eq(qp->hba_eq);
21283 		return 0;
21284 	}
21285 
21286 	/* NVME_FCREQ and NVME_ABTS requests */
21287 	if (pwqe->cmd_flag & (LPFC_IO_NVME | LPFC_IO_FCP | LPFC_IO_CMF)) {
21288 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21289 		wq = qp->io_wq;
21290 		pring = wq->pring;
21291 
21292 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21293 
21294 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21295 					  qp, wq_access);
21296 		ret = lpfc_sli4_wq_put(wq, wqe);
21297 		if (ret) {
21298 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21299 			return ret;
21300 		}
21301 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21302 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21303 
21304 		lpfc_sli4_poll_eq(qp->hba_eq);
21305 		return 0;
21306 	}
21307 
21308 	/* NVMET requests */
21309 	if (pwqe->cmd_flag & LPFC_IO_NVMET) {
21310 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21311 		wq = qp->io_wq;
21312 		pring = wq->pring;
21313 
21314 		ctxp = pwqe->context_un.axchg;
21315 		sglq = ctxp->ctxbuf->sglq;
21316 		if (pwqe->sli4_xritag ==  NO_XRI) {
21317 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
21318 			pwqe->sli4_xritag = sglq->sli4_xritag;
21319 		}
21320 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21321 		       pwqe->sli4_xritag);
21322 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21323 
21324 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21325 					  qp, wq_access);
21326 		ret = lpfc_sli4_wq_put(wq, wqe);
21327 		if (ret) {
21328 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21329 			return ret;
21330 		}
21331 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21332 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21333 
21334 		lpfc_sli4_poll_eq(qp->hba_eq);
21335 		return 0;
21336 	}
21337 	return WQE_ERROR;
21338 }
21339 
21340 /**
21341  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
21342  * @phba: Pointer to HBA context object.
21343  * @cmdiocb: Pointer to driver command iocb object.
21344  * @cmpl: completion function.
21345  *
21346  * Fill the appropriate fields for the abort WQE and call
21347  * internal routine lpfc_sli4_issue_wqe to send the WQE
21348  * This function is called with hbalock held and no ring_lock held.
21349  *
21350  * RETURNS 0 - SUCCESS
21351  **/
21352 
21353 int
21354 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
21355 			    void *cmpl)
21356 {
21357 	struct lpfc_vport *vport = cmdiocb->vport;
21358 	struct lpfc_iocbq *abtsiocb = NULL;
21359 	union lpfc_wqe128 *abtswqe;
21360 	struct lpfc_io_buf *lpfc_cmd;
21361 	int retval = IOCB_ERROR;
21362 	u16 xritag = cmdiocb->sli4_xritag;
21363 
21364 	/*
21365 	 * The scsi command can not be in txq and it is in flight because the
21366 	 * pCmd is still pointing at the SCSI command we have to abort. There
21367 	 * is no need to search the txcmplq. Just send an abort to the FW.
21368 	 */
21369 
21370 	abtsiocb = __lpfc_sli_get_iocbq(phba);
21371 	if (!abtsiocb)
21372 		return WQE_NORESOURCE;
21373 
21374 	/* Indicate the IO is being aborted by the driver. */
21375 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
21376 
21377 	abtswqe = &abtsiocb->wqe;
21378 	memset(abtswqe, 0, sizeof(*abtswqe));
21379 
21380 	if (!lpfc_is_link_up(phba) || (phba->link_flag & LS_EXTERNAL_LOOPBACK))
21381 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
21382 	bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
21383 	abtswqe->abort_cmd.rsrvd5 = 0;
21384 	abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
21385 	bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
21386 	bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
21387 	bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
21388 	bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
21389 	bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
21390 	bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
21391 
21392 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
21393 	abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
21394 	abtsiocb->cmd_flag |= LPFC_USE_FCPWQIDX;
21395 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
21396 		abtsiocb->cmd_flag |= LPFC_IO_FCP;
21397 	if (cmdiocb->cmd_flag & LPFC_IO_NVME)
21398 		abtsiocb->cmd_flag |= LPFC_IO_NVME;
21399 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
21400 		abtsiocb->cmd_flag |= LPFC_IO_FOF;
21401 	abtsiocb->vport = vport;
21402 	abtsiocb->cmd_cmpl = cmpl;
21403 
21404 	lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
21405 	retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
21406 
21407 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21408 			 "0359 Abort xri x%x, original iotag x%x, "
21409 			 "abort cmd iotag x%x retval x%x\n",
21410 			 xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
21411 
21412 	if (retval) {
21413 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21414 		__lpfc_sli_release_iocbq(phba, abtsiocb);
21415 	}
21416 
21417 	return retval;
21418 }
21419 
21420 #ifdef LPFC_MXP_STAT
21421 /**
21422  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
21423  * @phba: pointer to lpfc hba data structure.
21424  * @hwqid: belong to which HWQ.
21425  *
21426  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
21427  * 15 seconds after a test case is running.
21428  *
21429  * The user should call lpfc_debugfs_multixripools_write before running a test
21430  * case to clear stat_snapshot_taken. Then the user starts a test case. During
21431  * test case is running, stat_snapshot_taken is incremented by 1 every time when
21432  * this routine is called from heartbeat timer. When stat_snapshot_taken is
21433  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
21434  **/
21435 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
21436 {
21437 	struct lpfc_sli4_hdw_queue *qp;
21438 	struct lpfc_multixri_pool *multixri_pool;
21439 	struct lpfc_pvt_pool *pvt_pool;
21440 	struct lpfc_pbl_pool *pbl_pool;
21441 	u32 txcmplq_cnt;
21442 
21443 	qp = &phba->sli4_hba.hdwq[hwqid];
21444 	multixri_pool = qp->p_multixri_pool;
21445 	if (!multixri_pool)
21446 		return;
21447 
21448 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
21449 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21450 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21451 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21452 
21453 		multixri_pool->stat_pbl_count = pbl_pool->count;
21454 		multixri_pool->stat_pvt_count = pvt_pool->count;
21455 		multixri_pool->stat_busy_count = txcmplq_cnt;
21456 	}
21457 
21458 	multixri_pool->stat_snapshot_taken++;
21459 }
21460 #endif
21461 
21462 /**
21463  * lpfc_adjust_pvt_pool_count - Adjust private pool count
21464  * @phba: pointer to lpfc hba data structure.
21465  * @hwqid: belong to which HWQ.
21466  *
21467  * This routine moves some XRIs from private to public pool when private pool
21468  * is not busy.
21469  **/
21470 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
21471 {
21472 	struct lpfc_multixri_pool *multixri_pool;
21473 	u32 io_req_count;
21474 	u32 prev_io_req_count;
21475 
21476 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21477 	if (!multixri_pool)
21478 		return;
21479 	io_req_count = multixri_pool->io_req_count;
21480 	prev_io_req_count = multixri_pool->prev_io_req_count;
21481 
21482 	if (prev_io_req_count != io_req_count) {
21483 		/* Private pool is busy */
21484 		multixri_pool->prev_io_req_count = io_req_count;
21485 	} else {
21486 		/* Private pool is not busy.
21487 		 * Move XRIs from private to public pool.
21488 		 */
21489 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
21490 	}
21491 }
21492 
21493 /**
21494  * lpfc_adjust_high_watermark - Adjust high watermark
21495  * @phba: pointer to lpfc hba data structure.
21496  * @hwqid: belong to which HWQ.
21497  *
21498  * This routine sets high watermark as number of outstanding XRIs,
21499  * but make sure the new value is between xri_limit/2 and xri_limit.
21500  **/
21501 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
21502 {
21503 	u32 new_watermark;
21504 	u32 watermark_max;
21505 	u32 watermark_min;
21506 	u32 xri_limit;
21507 	u32 txcmplq_cnt;
21508 	u32 abts_io_bufs;
21509 	struct lpfc_multixri_pool *multixri_pool;
21510 	struct lpfc_sli4_hdw_queue *qp;
21511 
21512 	qp = &phba->sli4_hba.hdwq[hwqid];
21513 	multixri_pool = qp->p_multixri_pool;
21514 	if (!multixri_pool)
21515 		return;
21516 	xri_limit = multixri_pool->xri_limit;
21517 
21518 	watermark_max = xri_limit;
21519 	watermark_min = xri_limit / 2;
21520 
21521 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21522 	abts_io_bufs = qp->abts_scsi_io_bufs;
21523 	abts_io_bufs += qp->abts_nvme_io_bufs;
21524 
21525 	new_watermark = txcmplq_cnt + abts_io_bufs;
21526 	new_watermark = min(watermark_max, new_watermark);
21527 	new_watermark = max(watermark_min, new_watermark);
21528 	multixri_pool->pvt_pool.high_watermark = new_watermark;
21529 
21530 #ifdef LPFC_MXP_STAT
21531 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
21532 					  new_watermark);
21533 #endif
21534 }
21535 
21536 /**
21537  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
21538  * @phba: pointer to lpfc hba data structure.
21539  * @hwqid: belong to which HWQ.
21540  *
21541  * This routine is called from hearbeat timer when pvt_pool is idle.
21542  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
21543  * The first step moves (all - low_watermark) amount of XRIs.
21544  * The second step moves the rest of XRIs.
21545  **/
21546 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
21547 {
21548 	struct lpfc_pbl_pool *pbl_pool;
21549 	struct lpfc_pvt_pool *pvt_pool;
21550 	struct lpfc_sli4_hdw_queue *qp;
21551 	struct lpfc_io_buf *lpfc_ncmd;
21552 	struct lpfc_io_buf *lpfc_ncmd_next;
21553 	unsigned long iflag;
21554 	struct list_head tmp_list;
21555 	u32 tmp_count;
21556 
21557 	qp = &phba->sli4_hba.hdwq[hwqid];
21558 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
21559 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
21560 	tmp_count = 0;
21561 
21562 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
21563 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
21564 
21565 	if (pvt_pool->count > pvt_pool->low_watermark) {
21566 		/* Step 1: move (all - low_watermark) from pvt_pool
21567 		 * to pbl_pool
21568 		 */
21569 
21570 		/* Move low watermark of bufs from pvt_pool to tmp_list */
21571 		INIT_LIST_HEAD(&tmp_list);
21572 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21573 					 &pvt_pool->list, list) {
21574 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
21575 			tmp_count++;
21576 			if (tmp_count >= pvt_pool->low_watermark)
21577 				break;
21578 		}
21579 
21580 		/* Move all bufs from pvt_pool to pbl_pool */
21581 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21582 
21583 		/* Move all bufs from tmp_list to pvt_pool */
21584 		list_splice(&tmp_list, &pvt_pool->list);
21585 
21586 		pbl_pool->count += (pvt_pool->count - tmp_count);
21587 		pvt_pool->count = tmp_count;
21588 	} else {
21589 		/* Step 2: move the rest from pvt_pool to pbl_pool */
21590 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21591 		pbl_pool->count += pvt_pool->count;
21592 		pvt_pool->count = 0;
21593 	}
21594 
21595 	spin_unlock(&pvt_pool->lock);
21596 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21597 }
21598 
21599 /**
21600  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21601  * @phba: pointer to lpfc hba data structure
21602  * @qp: pointer to HDW queue
21603  * @pbl_pool: specified public free XRI pool
21604  * @pvt_pool: specified private free XRI pool
21605  * @count: number of XRIs to move
21606  *
21607  * This routine tries to move some free common bufs from the specified pbl_pool
21608  * to the specified pvt_pool. It might move less than count XRIs if there's not
21609  * enough in public pool.
21610  *
21611  * Return:
21612  *   true - if XRIs are successfully moved from the specified pbl_pool to the
21613  *          specified pvt_pool
21614  *   false - if the specified pbl_pool is empty or locked by someone else
21615  **/
21616 static bool
21617 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21618 			  struct lpfc_pbl_pool *pbl_pool,
21619 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
21620 {
21621 	struct lpfc_io_buf *lpfc_ncmd;
21622 	struct lpfc_io_buf *lpfc_ncmd_next;
21623 	unsigned long iflag;
21624 	int ret;
21625 
21626 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
21627 	if (ret) {
21628 		if (pbl_pool->count) {
21629 			/* Move a batch of XRIs from public to private pool */
21630 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
21631 			list_for_each_entry_safe(lpfc_ncmd,
21632 						 lpfc_ncmd_next,
21633 						 &pbl_pool->list,
21634 						 list) {
21635 				list_move_tail(&lpfc_ncmd->list,
21636 					       &pvt_pool->list);
21637 				pvt_pool->count++;
21638 				pbl_pool->count--;
21639 				count--;
21640 				if (count == 0)
21641 					break;
21642 			}
21643 
21644 			spin_unlock(&pvt_pool->lock);
21645 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21646 			return true;
21647 		}
21648 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21649 	}
21650 
21651 	return false;
21652 }
21653 
21654 /**
21655  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21656  * @phba: pointer to lpfc hba data structure.
21657  * @hwqid: belong to which HWQ.
21658  * @count: number of XRIs to move
21659  *
21660  * This routine tries to find some free common bufs in one of public pools with
21661  * Round Robin method. The search always starts from local hwqid, then the next
21662  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
21663  * a batch of free common bufs are moved to private pool on hwqid.
21664  * It might move less than count XRIs if there's not enough in public pool.
21665  **/
21666 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
21667 {
21668 	struct lpfc_multixri_pool *multixri_pool;
21669 	struct lpfc_multixri_pool *next_multixri_pool;
21670 	struct lpfc_pvt_pool *pvt_pool;
21671 	struct lpfc_pbl_pool *pbl_pool;
21672 	struct lpfc_sli4_hdw_queue *qp;
21673 	u32 next_hwqid;
21674 	u32 hwq_count;
21675 	int ret;
21676 
21677 	qp = &phba->sli4_hba.hdwq[hwqid];
21678 	multixri_pool = qp->p_multixri_pool;
21679 	pvt_pool = &multixri_pool->pvt_pool;
21680 	pbl_pool = &multixri_pool->pbl_pool;
21681 
21682 	/* Check if local pbl_pool is available */
21683 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
21684 	if (ret) {
21685 #ifdef LPFC_MXP_STAT
21686 		multixri_pool->local_pbl_hit_count++;
21687 #endif
21688 		return;
21689 	}
21690 
21691 	hwq_count = phba->cfg_hdw_queue;
21692 
21693 	/* Get the next hwqid which was found last time */
21694 	next_hwqid = multixri_pool->rrb_next_hwqid;
21695 
21696 	do {
21697 		/* Go to next hwq */
21698 		next_hwqid = (next_hwqid + 1) % hwq_count;
21699 
21700 		next_multixri_pool =
21701 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
21702 		pbl_pool = &next_multixri_pool->pbl_pool;
21703 
21704 		/* Check if the public free xri pool is available */
21705 		ret = _lpfc_move_xri_pbl_to_pvt(
21706 			phba, qp, pbl_pool, pvt_pool, count);
21707 
21708 		/* Exit while-loop if success or all hwqid are checked */
21709 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
21710 
21711 	/* Starting point for the next time */
21712 	multixri_pool->rrb_next_hwqid = next_hwqid;
21713 
21714 	if (!ret) {
21715 		/* stats: all public pools are empty*/
21716 		multixri_pool->pbl_empty_count++;
21717 	}
21718 
21719 #ifdef LPFC_MXP_STAT
21720 	if (ret) {
21721 		if (next_hwqid == hwqid)
21722 			multixri_pool->local_pbl_hit_count++;
21723 		else
21724 			multixri_pool->other_pbl_hit_count++;
21725 	}
21726 #endif
21727 }
21728 
21729 /**
21730  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
21731  * @phba: pointer to lpfc hba data structure.
21732  * @hwqid: belong to which HWQ.
21733  *
21734  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
21735  * low watermark.
21736  **/
21737 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
21738 {
21739 	struct lpfc_multixri_pool *multixri_pool;
21740 	struct lpfc_pvt_pool *pvt_pool;
21741 
21742 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21743 	pvt_pool = &multixri_pool->pvt_pool;
21744 
21745 	if (pvt_pool->count < pvt_pool->low_watermark)
21746 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21747 }
21748 
21749 /**
21750  * lpfc_release_io_buf - Return one IO buf back to free pool
21751  * @phba: pointer to lpfc hba data structure.
21752  * @lpfc_ncmd: IO buf to be returned.
21753  * @qp: belong to which HWQ.
21754  *
21755  * This routine returns one IO buf back to free pool. If this is an urgent IO,
21756  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
21757  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
21758  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
21759  * lpfc_io_buf_list_put.
21760  **/
21761 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
21762 			 struct lpfc_sli4_hdw_queue *qp)
21763 {
21764 	unsigned long iflag;
21765 	struct lpfc_pbl_pool *pbl_pool;
21766 	struct lpfc_pvt_pool *pvt_pool;
21767 	struct lpfc_epd_pool *epd_pool;
21768 	u32 txcmplq_cnt;
21769 	u32 xri_owned;
21770 	u32 xri_limit;
21771 	u32 abts_io_bufs;
21772 
21773 	/* MUST zero fields if buffer is reused by another protocol */
21774 	lpfc_ncmd->nvmeCmd = NULL;
21775 	lpfc_ncmd->cur_iocbq.cmd_cmpl = NULL;
21776 
21777 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
21778 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
21779 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
21780 
21781 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
21782 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
21783 
21784 	if (phba->cfg_xri_rebalancing) {
21785 		if (lpfc_ncmd->expedite) {
21786 			/* Return to expedite pool */
21787 			epd_pool = &phba->epd_pool;
21788 			spin_lock_irqsave(&epd_pool->lock, iflag);
21789 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21790 			epd_pool->count++;
21791 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
21792 			return;
21793 		}
21794 
21795 		/* Avoid invalid access if an IO sneaks in and is being rejected
21796 		 * just _after_ xri pools are destroyed in lpfc_offline.
21797 		 * Nothing much can be done at this point.
21798 		 */
21799 		if (!qp->p_multixri_pool)
21800 			return;
21801 
21802 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21803 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21804 
21805 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21806 		abts_io_bufs = qp->abts_scsi_io_bufs;
21807 		abts_io_bufs += qp->abts_nvme_io_bufs;
21808 
21809 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21810 		xri_limit = qp->p_multixri_pool->xri_limit;
21811 
21812 #ifdef LPFC_MXP_STAT
21813 		if (xri_owned <= xri_limit)
21814 			qp->p_multixri_pool->below_limit_count++;
21815 		else
21816 			qp->p_multixri_pool->above_limit_count++;
21817 #endif
21818 
21819 		/* XRI goes to either public or private free xri pool
21820 		 *     based on watermark and xri_limit
21821 		 */
21822 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
21823 		    (xri_owned < xri_limit &&
21824 		     pvt_pool->count < pvt_pool->high_watermark)) {
21825 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
21826 						  qp, free_pvt_pool);
21827 			list_add_tail(&lpfc_ncmd->list,
21828 				      &pvt_pool->list);
21829 			pvt_pool->count++;
21830 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21831 		} else {
21832 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
21833 						  qp, free_pub_pool);
21834 			list_add_tail(&lpfc_ncmd->list,
21835 				      &pbl_pool->list);
21836 			pbl_pool->count++;
21837 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21838 		}
21839 	} else {
21840 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
21841 					  qp, free_xri);
21842 		list_add_tail(&lpfc_ncmd->list,
21843 			      &qp->lpfc_io_buf_list_put);
21844 		qp->put_io_bufs++;
21845 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
21846 				       iflag);
21847 	}
21848 }
21849 
21850 /**
21851  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
21852  * @phba: pointer to lpfc hba data structure.
21853  * @qp: pointer to HDW queue
21854  * @pvt_pool: pointer to private pool data structure.
21855  * @ndlp: pointer to lpfc nodelist data structure.
21856  *
21857  * This routine tries to get one free IO buf from private pool.
21858  *
21859  * Return:
21860  *   pointer to one free IO buf - if private pool is not empty
21861  *   NULL - if private pool is empty
21862  **/
21863 static struct lpfc_io_buf *
21864 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
21865 				  struct lpfc_sli4_hdw_queue *qp,
21866 				  struct lpfc_pvt_pool *pvt_pool,
21867 				  struct lpfc_nodelist *ndlp)
21868 {
21869 	struct lpfc_io_buf *lpfc_ncmd;
21870 	struct lpfc_io_buf *lpfc_ncmd_next;
21871 	unsigned long iflag;
21872 
21873 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
21874 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21875 				 &pvt_pool->list, list) {
21876 		if (lpfc_test_rrq_active(
21877 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
21878 			continue;
21879 		list_del(&lpfc_ncmd->list);
21880 		pvt_pool->count--;
21881 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21882 		return lpfc_ncmd;
21883 	}
21884 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21885 
21886 	return NULL;
21887 }
21888 
21889 /**
21890  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
21891  * @phba: pointer to lpfc hba data structure.
21892  *
21893  * This routine tries to get one free IO buf from expedite pool.
21894  *
21895  * Return:
21896  *   pointer to one free IO buf - if expedite pool is not empty
21897  *   NULL - if expedite pool is empty
21898  **/
21899 static struct lpfc_io_buf *
21900 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
21901 {
21902 	struct lpfc_io_buf *lpfc_ncmd = NULL, *iter;
21903 	struct lpfc_io_buf *lpfc_ncmd_next;
21904 	unsigned long iflag;
21905 	struct lpfc_epd_pool *epd_pool;
21906 
21907 	epd_pool = &phba->epd_pool;
21908 
21909 	spin_lock_irqsave(&epd_pool->lock, iflag);
21910 	if (epd_pool->count > 0) {
21911 		list_for_each_entry_safe(iter, lpfc_ncmd_next,
21912 					 &epd_pool->list, list) {
21913 			list_del(&iter->list);
21914 			epd_pool->count--;
21915 			lpfc_ncmd = iter;
21916 			break;
21917 		}
21918 	}
21919 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
21920 
21921 	return lpfc_ncmd;
21922 }
21923 
21924 /**
21925  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
21926  * @phba: pointer to lpfc hba data structure.
21927  * @ndlp: pointer to lpfc nodelist data structure.
21928  * @hwqid: belong to which HWQ
21929  * @expedite: 1 means this request is urgent.
21930  *
21931  * This routine will do the following actions and then return a pointer to
21932  * one free IO buf.
21933  *
21934  * 1. If private free xri count is empty, move some XRIs from public to
21935  *    private pool.
21936  * 2. Get one XRI from private free xri pool.
21937  * 3. If we fail to get one from pvt_pool and this is an expedite request,
21938  *    get one free xri from expedite pool.
21939  *
21940  * Note: ndlp is only used on SCSI side for RRQ testing.
21941  *       The caller should pass NULL for ndlp on NVME side.
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_multixri_pools(struct lpfc_hba *phba,
21949 				    struct lpfc_nodelist *ndlp,
21950 				    int hwqid, int expedite)
21951 {
21952 	struct lpfc_sli4_hdw_queue *qp;
21953 	struct lpfc_multixri_pool *multixri_pool;
21954 	struct lpfc_pvt_pool *pvt_pool;
21955 	struct lpfc_io_buf *lpfc_ncmd;
21956 
21957 	qp = &phba->sli4_hba.hdwq[hwqid];
21958 	lpfc_ncmd = NULL;
21959 	if (!qp) {
21960 		lpfc_printf_log(phba, KERN_INFO,
21961 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21962 				"5556 NULL qp for hwqid  x%x\n", hwqid);
21963 		return lpfc_ncmd;
21964 	}
21965 	multixri_pool = qp->p_multixri_pool;
21966 	if (!multixri_pool) {
21967 		lpfc_printf_log(phba, KERN_INFO,
21968 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21969 				"5557 NULL multixri for hwqid  x%x\n", hwqid);
21970 		return lpfc_ncmd;
21971 	}
21972 	pvt_pool = &multixri_pool->pvt_pool;
21973 	if (!pvt_pool) {
21974 		lpfc_printf_log(phba, KERN_INFO,
21975 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21976 				"5558 NULL pvt_pool for hwqid  x%x\n", hwqid);
21977 		return lpfc_ncmd;
21978 	}
21979 	multixri_pool->io_req_count++;
21980 
21981 	/* If pvt_pool is empty, move some XRIs from public to private pool */
21982 	if (pvt_pool->count == 0)
21983 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21984 
21985 	/* Get one XRI from private free xri pool */
21986 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
21987 
21988 	if (lpfc_ncmd) {
21989 		lpfc_ncmd->hdwq = qp;
21990 		lpfc_ncmd->hdwq_no = hwqid;
21991 	} else if (expedite) {
21992 		/* If we fail to get one from pvt_pool and this is an expedite
21993 		 * request, get one free xri from expedite pool.
21994 		 */
21995 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
21996 	}
21997 
21998 	return lpfc_ncmd;
21999 }
22000 
22001 static inline struct lpfc_io_buf *
22002 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
22003 {
22004 	struct lpfc_sli4_hdw_queue *qp;
22005 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
22006 
22007 	qp = &phba->sli4_hba.hdwq[idx];
22008 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
22009 				 &qp->lpfc_io_buf_list_get, list) {
22010 		if (lpfc_test_rrq_active(phba, ndlp,
22011 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
22012 			continue;
22013 
22014 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
22015 			continue;
22016 
22017 		list_del_init(&lpfc_cmd->list);
22018 		qp->get_io_bufs--;
22019 		lpfc_cmd->hdwq = qp;
22020 		lpfc_cmd->hdwq_no = idx;
22021 		return lpfc_cmd;
22022 	}
22023 	return NULL;
22024 }
22025 
22026 /**
22027  * lpfc_get_io_buf - Get one IO buffer from free pool
22028  * @phba: The HBA for which this call is being executed.
22029  * @ndlp: pointer to lpfc nodelist data structure.
22030  * @hwqid: belong to which HWQ
22031  * @expedite: 1 means this request is urgent.
22032  *
22033  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
22034  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
22035  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
22036  *
22037  * Note: ndlp is only used on SCSI side for RRQ testing.
22038  *       The caller should pass NULL for ndlp on NVME side.
22039  *
22040  * Return codes:
22041  *   NULL - Error
22042  *   Pointer to lpfc_io_buf - Success
22043  **/
22044 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
22045 				    struct lpfc_nodelist *ndlp,
22046 				    u32 hwqid, int expedite)
22047 {
22048 	struct lpfc_sli4_hdw_queue *qp;
22049 	unsigned long iflag;
22050 	struct lpfc_io_buf *lpfc_cmd;
22051 
22052 	qp = &phba->sli4_hba.hdwq[hwqid];
22053 	lpfc_cmd = NULL;
22054 	if (!qp) {
22055 		lpfc_printf_log(phba, KERN_WARNING,
22056 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22057 				"5555 NULL qp for hwqid  x%x\n", hwqid);
22058 		return lpfc_cmd;
22059 	}
22060 
22061 	if (phba->cfg_xri_rebalancing)
22062 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
22063 			phba, ndlp, hwqid, expedite);
22064 	else {
22065 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
22066 					  qp, alloc_xri_get);
22067 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
22068 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22069 		if (!lpfc_cmd) {
22070 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
22071 					  qp, alloc_xri_put);
22072 			list_splice(&qp->lpfc_io_buf_list_put,
22073 				    &qp->lpfc_io_buf_list_get);
22074 			qp->get_io_bufs += qp->put_io_bufs;
22075 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
22076 			qp->put_io_bufs = 0;
22077 			spin_unlock(&qp->io_buf_list_put_lock);
22078 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
22079 			    expedite)
22080 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22081 		}
22082 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
22083 	}
22084 
22085 	return lpfc_cmd;
22086 }
22087 
22088 /**
22089  * lpfc_read_object - Retrieve object data from HBA
22090  * @phba: The HBA for which this call is being executed.
22091  * @rdobject: Pathname of object data we want to read.
22092  * @datap: Pointer to where data will be copied to.
22093  * @datasz: size of data area
22094  *
22095  * This routine is limited to object sizes of LPFC_BPL_SIZE (1024) or less.
22096  * The data will be truncated if datasz is not large enough.
22097  * Version 1 is not supported with Embedded mbox cmd, so we must use version 0.
22098  * Returns the actual bytes read from the object.
22099  */
22100 int
22101 lpfc_read_object(struct lpfc_hba *phba, char *rdobject, uint32_t *datap,
22102 		 uint32_t datasz)
22103 {
22104 	struct lpfc_mbx_read_object *read_object;
22105 	LPFC_MBOXQ_t *mbox;
22106 	int rc, length, eof, j, byte_cnt = 0;
22107 	uint32_t shdr_status, shdr_add_status;
22108 	union lpfc_sli4_cfg_shdr *shdr;
22109 	struct lpfc_dmabuf *pcmd;
22110 	u32 rd_object_name[LPFC_MBX_OBJECT_NAME_LEN_DW] = {0};
22111 
22112 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
22113 	if (!mbox)
22114 		return -ENOMEM;
22115 	length = (sizeof(struct lpfc_mbx_read_object) -
22116 		  sizeof(struct lpfc_sli4_cfg_mhdr));
22117 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
22118 			 LPFC_MBOX_OPCODE_READ_OBJECT,
22119 			 length, LPFC_SLI4_MBX_EMBED);
22120 	read_object = &mbox->u.mqe.un.read_object;
22121 	shdr = (union lpfc_sli4_cfg_shdr *)&read_object->header.cfg_shdr;
22122 
22123 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_0);
22124 	bf_set(lpfc_mbx_rd_object_rlen, &read_object->u.request, datasz);
22125 	read_object->u.request.rd_object_offset = 0;
22126 	read_object->u.request.rd_object_cnt = 1;
22127 
22128 	memset((void *)read_object->u.request.rd_object_name, 0,
22129 	       LPFC_OBJ_NAME_SZ);
22130 	scnprintf((char *)rd_object_name, sizeof(rd_object_name), rdobject);
22131 	for (j = 0; j < strlen(rdobject); j++)
22132 		read_object->u.request.rd_object_name[j] =
22133 			cpu_to_le32(rd_object_name[j]);
22134 
22135 	pcmd = kmalloc(sizeof(*pcmd), GFP_KERNEL);
22136 	if (pcmd)
22137 		pcmd->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &pcmd->phys);
22138 	if (!pcmd || !pcmd->virt) {
22139 		kfree(pcmd);
22140 		mempool_free(mbox, phba->mbox_mem_pool);
22141 		return -ENOMEM;
22142 	}
22143 	memset((void *)pcmd->virt, 0, LPFC_BPL_SIZE);
22144 	read_object->u.request.rd_object_hbuf[0].pa_lo =
22145 		putPaddrLow(pcmd->phys);
22146 	read_object->u.request.rd_object_hbuf[0].pa_hi =
22147 		putPaddrHigh(pcmd->phys);
22148 	read_object->u.request.rd_object_hbuf[0].length = LPFC_BPL_SIZE;
22149 
22150 	mbox->vport = phba->pport;
22151 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
22152 	mbox->ctx_ndlp = NULL;
22153 
22154 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
22155 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
22156 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
22157 
22158 	if (shdr_status == STATUS_FAILED &&
22159 	    shdr_add_status == ADD_STATUS_INVALID_OBJECT_NAME) {
22160 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22161 				"4674 No port cfg file in FW.\n");
22162 		byte_cnt = -ENOENT;
22163 	} else if (shdr_status || shdr_add_status || rc) {
22164 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22165 				"2625 READ_OBJECT mailbox failed with "
22166 				"status x%x add_status x%x, mbx status x%x\n",
22167 				shdr_status, shdr_add_status, rc);
22168 		byte_cnt = -ENXIO;
22169 	} else {
22170 		/* Success */
22171 		length = read_object->u.response.rd_object_actual_rlen;
22172 		eof = bf_get(lpfc_mbx_rd_object_eof, &read_object->u.response);
22173 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_CGN_MGMT,
22174 				"2626 READ_OBJECT Success len %d:%d, EOF %d\n",
22175 				length, datasz, eof);
22176 
22177 		/* Detect the port config file exists but is empty */
22178 		if (!length && eof) {
22179 			byte_cnt = 0;
22180 			goto exit;
22181 		}
22182 
22183 		byte_cnt = length;
22184 		lpfc_sli_pcimem_bcopy(pcmd->virt, datap, byte_cnt);
22185 	}
22186 
22187  exit:
22188 	/* This is an embedded SLI4 mailbox with an external buffer allocated.
22189 	 * Free the pcmd and then cleanup with the correct routine.
22190 	 */
22191 	lpfc_mbuf_free(phba, pcmd->virt, pcmd->phys);
22192 	kfree(pcmd);
22193 	lpfc_sli4_mbox_cmd_free(phba, mbox);
22194 	return byte_cnt;
22195 }
22196 
22197 /**
22198  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
22199  * @phba: The HBA for which this call is being executed.
22200  * @lpfc_buf: IO buf structure to append the SGL chunk
22201  *
22202  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
22203  * and will allocate an SGL chunk if the pool is empty.
22204  *
22205  * Return codes:
22206  *   NULL - Error
22207  *   Pointer to sli4_hybrid_sgl - Success
22208  **/
22209 struct sli4_hybrid_sgl *
22210 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22211 {
22212 	struct sli4_hybrid_sgl *list_entry = NULL;
22213 	struct sli4_hybrid_sgl *tmp = NULL;
22214 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
22215 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22216 	struct list_head *buf_list = &hdwq->sgl_list;
22217 	unsigned long iflags;
22218 
22219 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22220 
22221 	if (likely(!list_empty(buf_list))) {
22222 		/* break off 1 chunk from the sgl_list */
22223 		list_for_each_entry_safe(list_entry, tmp,
22224 					 buf_list, list_node) {
22225 			list_move_tail(&list_entry->list_node,
22226 				       &lpfc_buf->dma_sgl_xtra_list);
22227 			break;
22228 		}
22229 	} else {
22230 		/* allocate more */
22231 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22232 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22233 				   cpu_to_node(hdwq->io_wq->chann));
22234 		if (!tmp) {
22235 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22236 					"8353 error kmalloc memory for HDWQ "
22237 					"%d %s\n",
22238 					lpfc_buf->hdwq_no, __func__);
22239 			return NULL;
22240 		}
22241 
22242 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
22243 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
22244 		if (!tmp->dma_sgl) {
22245 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22246 					"8354 error pool_alloc memory for HDWQ "
22247 					"%d %s\n",
22248 					lpfc_buf->hdwq_no, __func__);
22249 			kfree(tmp);
22250 			return NULL;
22251 		}
22252 
22253 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22254 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
22255 	}
22256 
22257 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
22258 					struct sli4_hybrid_sgl,
22259 					list_node);
22260 
22261 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22262 
22263 	return allocated_sgl;
22264 }
22265 
22266 /**
22267  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
22268  * @phba: The HBA for which this call is being executed.
22269  * @lpfc_buf: IO buf structure with the SGL chunk
22270  *
22271  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
22272  *
22273  * Return codes:
22274  *   0 - Success
22275  *   -EINVAL - Error
22276  **/
22277 int
22278 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22279 {
22280 	int rc = 0;
22281 	struct sli4_hybrid_sgl *list_entry = NULL;
22282 	struct sli4_hybrid_sgl *tmp = NULL;
22283 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22284 	struct list_head *buf_list = &hdwq->sgl_list;
22285 	unsigned long iflags;
22286 
22287 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22288 
22289 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
22290 		list_for_each_entry_safe(list_entry, tmp,
22291 					 &lpfc_buf->dma_sgl_xtra_list,
22292 					 list_node) {
22293 			list_move_tail(&list_entry->list_node,
22294 				       buf_list);
22295 		}
22296 	} else {
22297 		rc = -EINVAL;
22298 	}
22299 
22300 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22301 	return rc;
22302 }
22303 
22304 /**
22305  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
22306  * @phba: phba object
22307  * @hdwq: hdwq to cleanup sgl buff resources on
22308  *
22309  * This routine frees all SGL chunks of hdwq SGL chunk pool.
22310  *
22311  * Return codes:
22312  *   None
22313  **/
22314 void
22315 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
22316 		       struct lpfc_sli4_hdw_queue *hdwq)
22317 {
22318 	struct list_head *buf_list = &hdwq->sgl_list;
22319 	struct sli4_hybrid_sgl *list_entry = NULL;
22320 	struct sli4_hybrid_sgl *tmp = NULL;
22321 	unsigned long iflags;
22322 
22323 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22324 
22325 	/* Free sgl pool */
22326 	list_for_each_entry_safe(list_entry, tmp,
22327 				 buf_list, list_node) {
22328 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
22329 			      list_entry->dma_sgl,
22330 			      list_entry->dma_phys_sgl);
22331 		list_del(&list_entry->list_node);
22332 		kfree(list_entry);
22333 	}
22334 
22335 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22336 }
22337 
22338 /**
22339  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
22340  * @phba: The HBA for which this call is being executed.
22341  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
22342  *
22343  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
22344  * and will allocate an CMD/RSP buffer if the pool is empty.
22345  *
22346  * Return codes:
22347  *   NULL - Error
22348  *   Pointer to fcp_cmd_rsp_buf - Success
22349  **/
22350 struct fcp_cmd_rsp_buf *
22351 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22352 			      struct lpfc_io_buf *lpfc_buf)
22353 {
22354 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22355 	struct fcp_cmd_rsp_buf *tmp = NULL;
22356 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
22357 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22358 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22359 	unsigned long iflags;
22360 
22361 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22362 
22363 	if (likely(!list_empty(buf_list))) {
22364 		/* break off 1 chunk from the list */
22365 		list_for_each_entry_safe(list_entry, tmp,
22366 					 buf_list,
22367 					 list_node) {
22368 			list_move_tail(&list_entry->list_node,
22369 				       &lpfc_buf->dma_cmd_rsp_list);
22370 			break;
22371 		}
22372 	} else {
22373 		/* allocate more */
22374 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22375 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22376 				   cpu_to_node(hdwq->io_wq->chann));
22377 		if (!tmp) {
22378 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22379 					"8355 error kmalloc memory for HDWQ "
22380 					"%d %s\n",
22381 					lpfc_buf->hdwq_no, __func__);
22382 			return NULL;
22383 		}
22384 
22385 		tmp->fcp_cmnd = dma_pool_zalloc(phba->lpfc_cmd_rsp_buf_pool,
22386 						GFP_ATOMIC,
22387 						&tmp->fcp_cmd_rsp_dma_handle);
22388 
22389 		if (!tmp->fcp_cmnd) {
22390 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22391 					"8356 error pool_alloc memory for HDWQ "
22392 					"%d %s\n",
22393 					lpfc_buf->hdwq_no, __func__);
22394 			kfree(tmp);
22395 			return NULL;
22396 		}
22397 
22398 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
22399 				sizeof(struct fcp_cmnd));
22400 
22401 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22402 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
22403 	}
22404 
22405 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
22406 					struct fcp_cmd_rsp_buf,
22407 					list_node);
22408 
22409 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22410 
22411 	return allocated_buf;
22412 }
22413 
22414 /**
22415  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
22416  * @phba: The HBA for which this call is being executed.
22417  * @lpfc_buf: IO buf structure with the CMD/RSP buf
22418  *
22419  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
22420  *
22421  * Return codes:
22422  *   0 - Success
22423  *   -EINVAL - Error
22424  **/
22425 int
22426 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22427 			      struct lpfc_io_buf *lpfc_buf)
22428 {
22429 	int rc = 0;
22430 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22431 	struct fcp_cmd_rsp_buf *tmp = NULL;
22432 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22433 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22434 	unsigned long iflags;
22435 
22436 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22437 
22438 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
22439 		list_for_each_entry_safe(list_entry, tmp,
22440 					 &lpfc_buf->dma_cmd_rsp_list,
22441 					 list_node) {
22442 			list_move_tail(&list_entry->list_node,
22443 				       buf_list);
22444 		}
22445 	} else {
22446 		rc = -EINVAL;
22447 	}
22448 
22449 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22450 	return rc;
22451 }
22452 
22453 /**
22454  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
22455  * @phba: phba object
22456  * @hdwq: hdwq to cleanup cmd rsp buff resources on
22457  *
22458  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
22459  *
22460  * Return codes:
22461  *   None
22462  **/
22463 void
22464 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22465 			       struct lpfc_sli4_hdw_queue *hdwq)
22466 {
22467 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22468 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22469 	struct fcp_cmd_rsp_buf *tmp = NULL;
22470 	unsigned long iflags;
22471 
22472 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22473 
22474 	/* Free cmd_rsp buf pool */
22475 	list_for_each_entry_safe(list_entry, tmp,
22476 				 buf_list,
22477 				 list_node) {
22478 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
22479 			      list_entry->fcp_cmnd,
22480 			      list_entry->fcp_cmd_rsp_dma_handle);
22481 		list_del(&list_entry->list_node);
22482 		kfree(list_entry);
22483 	}
22484 
22485 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22486 }
22487 
22488 /**
22489  * lpfc_sli_prep_wqe - Prepare WQE for the command to be posted
22490  * @phba: phba object
22491  * @job: job entry of the command to be posted.
22492  *
22493  * Fill the common fields of the wqe for each of the command.
22494  *
22495  * Return codes:
22496  *	None
22497  **/
22498 void
22499 lpfc_sli_prep_wqe(struct lpfc_hba *phba, struct lpfc_iocbq *job)
22500 {
22501 	u8 cmnd;
22502 	u32 *pcmd;
22503 	u32 if_type = 0;
22504 	u32 fip, abort_tag;
22505 	struct lpfc_nodelist *ndlp = NULL;
22506 	union lpfc_wqe128 *wqe = &job->wqe;
22507 	u8 command_type = ELS_COMMAND_NON_FIP;
22508 
22509 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
22510 	/* The fcp commands will set command type */
22511 	if (job->cmd_flag &  LPFC_IO_FCP)
22512 		command_type = FCP_COMMAND;
22513 	else if (fip && (job->cmd_flag & LPFC_FIP_ELS_ID_MASK))
22514 		command_type = ELS_COMMAND_FIP;
22515 	else
22516 		command_type = ELS_COMMAND_NON_FIP;
22517 
22518 	abort_tag = job->iotag;
22519 	cmnd = bf_get(wqe_cmnd, &wqe->els_req.wqe_com);
22520 
22521 	switch (cmnd) {
22522 	case CMD_ELS_REQUEST64_WQE:
22523 		ndlp = job->ndlp;
22524 
22525 		if_type = bf_get(lpfc_sli_intf_if_type,
22526 				 &phba->sli4_hba.sli_intf);
22527 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22528 			pcmd = (u32 *)job->cmd_dmabuf->virt;
22529 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
22530 				     *pcmd == ELS_CMD_SCR ||
22531 				     *pcmd == ELS_CMD_RDF ||
22532 				     *pcmd == ELS_CMD_EDC ||
22533 				     *pcmd == ELS_CMD_RSCN_XMT ||
22534 				     *pcmd == ELS_CMD_FDISC ||
22535 				     *pcmd == ELS_CMD_LOGO ||
22536 				     *pcmd == ELS_CMD_QFPA ||
22537 				     *pcmd == ELS_CMD_UVEM ||
22538 				     *pcmd == ELS_CMD_PLOGI)) {
22539 				bf_set(els_req64_sp, &wqe->els_req, 1);
22540 				bf_set(els_req64_sid, &wqe->els_req,
22541 				       job->vport->fc_myDID);
22542 
22543 				if ((*pcmd == ELS_CMD_FLOGI) &&
22544 				    !(phba->fc_topology ==
22545 				      LPFC_TOPOLOGY_LOOP))
22546 					bf_set(els_req64_sid, &wqe->els_req, 0);
22547 
22548 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
22549 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22550 				       phba->vpi_ids[job->vport->vpi]);
22551 			} else if (pcmd) {
22552 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
22553 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22554 				       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22555 			}
22556 		}
22557 
22558 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
22559 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22560 
22561 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
22562 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
22563 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
22564 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22565 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
22566 		break;
22567 	case CMD_XMIT_ELS_RSP64_WQE:
22568 		ndlp = job->ndlp;
22569 
22570 		/* word4 */
22571 		wqe->xmit_els_rsp.word4 = 0;
22572 
22573 		if_type = bf_get(lpfc_sli_intf_if_type,
22574 				 &phba->sli4_hba.sli_intf);
22575 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22576 			if (job->vport->fc_flag & FC_PT2PT) {
22577 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22578 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22579 				       job->vport->fc_myDID);
22580 				if (job->vport->fc_myDID == Fabric_DID) {
22581 					bf_set(wqe_els_did,
22582 					       &wqe->xmit_els_rsp.wqe_dest, 0);
22583 				}
22584 			}
22585 		}
22586 
22587 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
22588 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
22589 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
22590 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
22591 		       LPFC_WQE_LENLOC_WORD3);
22592 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
22593 
22594 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
22595 			bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22596 			bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22597 			       job->vport->fc_myDID);
22598 			bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
22599 		}
22600 
22601 		if (phba->sli_rev == LPFC_SLI_REV4) {
22602 			bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
22603 			       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22604 
22605 			if (bf_get(wqe_ct, &wqe->xmit_els_rsp.wqe_com))
22606 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
22607 				       phba->vpi_ids[job->vport->vpi]);
22608 		}
22609 		command_type = OTHER_COMMAND;
22610 		break;
22611 	case CMD_GEN_REQUEST64_WQE:
22612 		/* Word 10 */
22613 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
22614 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
22615 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
22616 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22617 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
22618 		command_type = OTHER_COMMAND;
22619 		break;
22620 	case CMD_XMIT_SEQUENCE64_WQE:
22621 		if (phba->link_flag & LS_LOOPBACK_MODE)
22622 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
22623 
22624 		wqe->xmit_sequence.rsvd3 = 0;
22625 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
22626 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
22627 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
22628 		       LPFC_WQE_IOD_WRITE);
22629 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
22630 		       LPFC_WQE_LENLOC_WORD12);
22631 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
22632 		command_type = OTHER_COMMAND;
22633 		break;
22634 	case CMD_XMIT_BLS_RSP64_WQE:
22635 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
22636 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
22637 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
22638 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
22639 		       phba->vpi_ids[phba->pport->vpi]);
22640 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
22641 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
22642 		       LPFC_WQE_LENLOC_NONE);
22643 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
22644 		command_type = OTHER_COMMAND;
22645 		break;
22646 	case CMD_FCP_ICMND64_WQE:	/* task mgmt commands */
22647 	case CMD_ABORT_XRI_WQE:		/* abort iotag */
22648 	case CMD_SEND_FRAME:		/* mds loopback */
22649 		/* cases already formatted for sli4 wqe - no chgs necessary */
22650 		return;
22651 	default:
22652 		dump_stack();
22653 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
22654 				"6207 Invalid command 0x%x\n",
22655 				cmnd);
22656 		break;
22657 	}
22658 
22659 	wqe->generic.wqe_com.abort_tag = abort_tag;
22660 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, job->iotag);
22661 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
22662 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
22663 }
22664