xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision 185c8f33)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2023 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.     *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/pci.h>
26 #include <linux/interrupt.h>
27 #include <linux/delay.h>
28 #include <linux/slab.h>
29 #include <linux/lockdep.h>
30 
31 #include <scsi/scsi.h>
32 #include <scsi/scsi_cmnd.h>
33 #include <scsi/scsi_device.h>
34 #include <scsi/scsi_host.h>
35 #include <scsi/scsi_transport_fc.h>
36 #include <scsi/fc/fc_fs.h>
37 #include <linux/crash_dump.h>
38 #ifdef CONFIG_X86
39 #include <asm/set_memory.h>
40 #endif
41 
42 #include "lpfc_hw4.h"
43 #include "lpfc_hw.h"
44 #include "lpfc_sli.h"
45 #include "lpfc_sli4.h"
46 #include "lpfc_nl.h"
47 #include "lpfc_disc.h"
48 #include "lpfc.h"
49 #include "lpfc_scsi.h"
50 #include "lpfc_nvme.h"
51 #include "lpfc_crtn.h"
52 #include "lpfc_logmsg.h"
53 #include "lpfc_compat.h"
54 #include "lpfc_debugfs.h"
55 #include "lpfc_vport.h"
56 #include "lpfc_version.h"
57 
58 /* There are only four IOCB completion types. */
59 typedef enum _lpfc_iocb_type {
60 	LPFC_UNKNOWN_IOCB,
61 	LPFC_UNSOL_IOCB,
62 	LPFC_SOL_IOCB,
63 	LPFC_ABORT_IOCB
64 } lpfc_iocb_type;
65 
66 
67 /* Provide function prototypes local to this module. */
68 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
69 				  uint32_t);
70 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
71 			      uint8_t *, uint32_t *);
72 static struct lpfc_iocbq *
73 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
74 				  struct lpfc_iocbq *rspiocbq);
75 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
76 				      struct hbq_dmabuf *);
77 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
78 					  struct hbq_dmabuf *dmabuf);
79 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
80 				   struct lpfc_queue *cq, struct lpfc_cqe *cqe);
81 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
82 				       int);
83 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
84 				     struct lpfc_queue *eq,
85 				     struct lpfc_eqe *eqe,
86 				     enum lpfc_poll_mode poll_mode);
87 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
88 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
89 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
90 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
91 				    struct lpfc_queue *cq,
92 				    struct lpfc_cqe *cqe);
93 static uint16_t lpfc_wqe_bpl2sgl(struct lpfc_hba *phba,
94 				 struct lpfc_iocbq *pwqeq,
95 				 struct lpfc_sglq *sglq);
96 
97 union lpfc_wqe128 lpfc_iread_cmd_template;
98 union lpfc_wqe128 lpfc_iwrite_cmd_template;
99 union lpfc_wqe128 lpfc_icmnd_cmd_template;
100 
101 /* Setup WQE templates for IOs */
102 void lpfc_wqe_cmd_template(void)
103 {
104 	union lpfc_wqe128 *wqe;
105 
106 	/* IREAD template */
107 	wqe = &lpfc_iread_cmd_template;
108 	memset(wqe, 0, sizeof(union lpfc_wqe128));
109 
110 	/* Word 0, 1, 2 - BDE is variable */
111 
112 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
113 
114 	/* Word 4 - total_xfer_len is variable */
115 
116 	/* Word 5 - is zero */
117 
118 	/* Word 6 - ctxt_tag, xri_tag is variable */
119 
120 	/* Word 7 */
121 	bf_set(wqe_cmnd, &wqe->fcp_iread.wqe_com, CMD_FCP_IREAD64_WQE);
122 	bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, PARM_READ_CHECK);
123 	bf_set(wqe_class, &wqe->fcp_iread.wqe_com, CLASS3);
124 	bf_set(wqe_ct, &wqe->fcp_iread.wqe_com, SLI4_CT_RPI);
125 
126 	/* Word 8 - abort_tag is variable */
127 
128 	/* Word 9  - reqtag is variable */
129 
130 	/* Word 10 - dbde, wqes is variable */
131 	bf_set(wqe_qosd, &wqe->fcp_iread.wqe_com, 0);
132 	bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
133 	bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com, LPFC_WQE_LENLOC_WORD4);
134 	bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
135 	bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
136 
137 	/* Word 11 - pbde is variable */
138 	bf_set(wqe_cmd_type, &wqe->fcp_iread.wqe_com, COMMAND_DATA_IN);
139 	bf_set(wqe_cqid, &wqe->fcp_iread.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
140 	bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
141 
142 	/* Word 12 - is zero */
143 
144 	/* Word 13, 14, 15 - PBDE is variable */
145 
146 	/* IWRITE template */
147 	wqe = &lpfc_iwrite_cmd_template;
148 	memset(wqe, 0, sizeof(union lpfc_wqe128));
149 
150 	/* Word 0, 1, 2 - BDE is variable */
151 
152 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
153 
154 	/* Word 4 - total_xfer_len is variable */
155 
156 	/* Word 5 - initial_xfer_len is variable */
157 
158 	/* Word 6 - ctxt_tag, xri_tag is variable */
159 
160 	/* Word 7 */
161 	bf_set(wqe_cmnd, &wqe->fcp_iwrite.wqe_com, CMD_FCP_IWRITE64_WQE);
162 	bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, PARM_READ_CHECK);
163 	bf_set(wqe_class, &wqe->fcp_iwrite.wqe_com, CLASS3);
164 	bf_set(wqe_ct, &wqe->fcp_iwrite.wqe_com, SLI4_CT_RPI);
165 
166 	/* Word 8 - abort_tag is variable */
167 
168 	/* Word 9  - reqtag is variable */
169 
170 	/* Word 10 - dbde, wqes is variable */
171 	bf_set(wqe_qosd, &wqe->fcp_iwrite.wqe_com, 0);
172 	bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
173 	bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_LENLOC_WORD4);
174 	bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
175 	bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
176 
177 	/* Word 11 - pbde is variable */
178 	bf_set(wqe_cmd_type, &wqe->fcp_iwrite.wqe_com, COMMAND_DATA_OUT);
179 	bf_set(wqe_cqid, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
180 	bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
181 
182 	/* Word 12 - is zero */
183 
184 	/* Word 13, 14, 15 - PBDE is variable */
185 
186 	/* ICMND template */
187 	wqe = &lpfc_icmnd_cmd_template;
188 	memset(wqe, 0, sizeof(union lpfc_wqe128));
189 
190 	/* Word 0, 1, 2 - BDE is variable */
191 
192 	/* Word 3 - payload_offset_len is variable */
193 
194 	/* Word 4, 5 - is zero */
195 
196 	/* Word 6 - ctxt_tag, xri_tag is variable */
197 
198 	/* Word 7 */
199 	bf_set(wqe_cmnd, &wqe->fcp_icmd.wqe_com, CMD_FCP_ICMND64_WQE);
200 	bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
201 	bf_set(wqe_class, &wqe->fcp_icmd.wqe_com, CLASS3);
202 	bf_set(wqe_ct, &wqe->fcp_icmd.wqe_com, SLI4_CT_RPI);
203 
204 	/* Word 8 - abort_tag is variable */
205 
206 	/* Word 9  - reqtag is variable */
207 
208 	/* Word 10 - dbde, wqes is variable */
209 	bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
210 	bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_NONE);
211 	bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com, LPFC_WQE_LENLOC_NONE);
212 	bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
213 	bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
214 
215 	/* Word 11 */
216 	bf_set(wqe_cmd_type, &wqe->fcp_icmd.wqe_com, COMMAND_DATA_IN);
217 	bf_set(wqe_cqid, &wqe->fcp_icmd.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
218 	bf_set(wqe_pbde, &wqe->fcp_icmd.wqe_com, 0);
219 
220 	/* Word 12, 13, 14, 15 - is zero */
221 }
222 
223 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
224 /**
225  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
226  * @srcp: Source memory pointer.
227  * @destp: Destination memory pointer.
228  * @cnt: Number of words required to be copied.
229  *       Must be a multiple of sizeof(uint64_t)
230  *
231  * This function is used for copying data between driver memory
232  * and the SLI WQ. This function also changes the endianness
233  * of each word if native endianness is different from SLI
234  * endianness. This function can be called with or without
235  * lock.
236  **/
237 static void
238 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
239 {
240 	uint64_t *src = srcp;
241 	uint64_t *dest = destp;
242 	int i;
243 
244 	for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
245 		*dest++ = *src++;
246 }
247 #else
248 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
249 #endif
250 
251 /**
252  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
253  * @q: The Work Queue to operate on.
254  * @wqe: The work Queue Entry to put on the Work queue.
255  *
256  * This routine will copy the contents of @wqe to the next available entry on
257  * the @q. This function will then ring the Work Queue Doorbell to signal the
258  * HBA to start processing the Work Queue Entry. This function returns 0 if
259  * successful. If no entries are available on @q then this function will return
260  * -ENOMEM.
261  * The caller is expected to hold the hbalock when calling this routine.
262  **/
263 static int
264 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
265 {
266 	union lpfc_wqe *temp_wqe;
267 	struct lpfc_register doorbell;
268 	uint32_t host_index;
269 	uint32_t idx;
270 	uint32_t i = 0;
271 	uint8_t *tmp;
272 	u32 if_type;
273 
274 	/* sanity check on queue memory */
275 	if (unlikely(!q))
276 		return -ENOMEM;
277 
278 	temp_wqe = lpfc_sli4_qe(q, q->host_index);
279 
280 	/* If the host has not yet processed the next entry then we are done */
281 	idx = ((q->host_index + 1) % q->entry_count);
282 	if (idx == q->hba_index) {
283 		q->WQ_overflow++;
284 		return -EBUSY;
285 	}
286 	q->WQ_posted++;
287 	/* set consumption flag every once in a while */
288 	if (!((q->host_index + 1) % q->notify_interval))
289 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
290 	else
291 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
292 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
293 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
294 	lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
295 	if (q->dpp_enable && q->phba->cfg_enable_dpp) {
296 		/* write to DPP aperture taking advatage of Combined Writes */
297 		tmp = (uint8_t *)temp_wqe;
298 #ifdef __raw_writeq
299 		for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
300 			__raw_writeq(*((uint64_t *)(tmp + i)),
301 					q->dpp_regaddr + i);
302 #else
303 		for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
304 			__raw_writel(*((uint32_t *)(tmp + i)),
305 					q->dpp_regaddr + i);
306 #endif
307 	}
308 	/* ensure WQE bcopy and DPP flushed before doorbell write */
309 	wmb();
310 
311 	/* Update the host index before invoking device */
312 	host_index = q->host_index;
313 
314 	q->host_index = idx;
315 
316 	/* Ring Doorbell */
317 	doorbell.word0 = 0;
318 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
319 		if (q->dpp_enable && q->phba->cfg_enable_dpp) {
320 			bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
321 			bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
322 			bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
323 			    q->dpp_id);
324 			bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
325 			    q->queue_id);
326 		} else {
327 			bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
328 			bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
329 
330 			/* Leave bits <23:16> clear for if_type 6 dpp */
331 			if_type = bf_get(lpfc_sli_intf_if_type,
332 					 &q->phba->sli4_hba.sli_intf);
333 			if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
334 				bf_set(lpfc_wq_db_list_fm_index, &doorbell,
335 				       host_index);
336 		}
337 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
338 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
339 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
340 	} else {
341 		return -EINVAL;
342 	}
343 	writel(doorbell.word0, q->db_regaddr);
344 
345 	return 0;
346 }
347 
348 /**
349  * lpfc_sli4_wq_release - Updates internal hba index for WQ
350  * @q: The Work Queue to operate on.
351  * @index: The index to advance the hba index to.
352  *
353  * This routine will update the HBA index of a queue to reflect consumption of
354  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
355  * an entry the host calls this function to update the queue's internal
356  * pointers.
357  **/
358 static void
359 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
360 {
361 	/* sanity check on queue memory */
362 	if (unlikely(!q))
363 		return;
364 
365 	q->hba_index = index;
366 }
367 
368 /**
369  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
370  * @q: The Mailbox Queue to operate on.
371  * @mqe: The Mailbox Queue Entry to put on the Work queue.
372  *
373  * This routine will copy the contents of @mqe to the next available entry on
374  * the @q. This function will then ring the Work Queue Doorbell to signal the
375  * HBA to start processing the Work Queue Entry. This function returns 0 if
376  * successful. If no entries are available on @q then this function will return
377  * -ENOMEM.
378  * The caller is expected to hold the hbalock when calling this routine.
379  **/
380 static uint32_t
381 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
382 {
383 	struct lpfc_mqe *temp_mqe;
384 	struct lpfc_register doorbell;
385 
386 	/* sanity check on queue memory */
387 	if (unlikely(!q))
388 		return -ENOMEM;
389 	temp_mqe = lpfc_sli4_qe(q, q->host_index);
390 
391 	/* If the host has not yet processed the next entry then we are done */
392 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
393 		return -ENOMEM;
394 	lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
395 	/* Save off the mailbox pointer for completion */
396 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
397 
398 	/* Update the host index before invoking device */
399 	q->host_index = ((q->host_index + 1) % q->entry_count);
400 
401 	/* Ring Doorbell */
402 	doorbell.word0 = 0;
403 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
404 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
405 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
406 	return 0;
407 }
408 
409 /**
410  * lpfc_sli4_mq_release - Updates internal hba index for MQ
411  * @q: The Mailbox Queue to operate on.
412  *
413  * This routine will update the HBA index of a queue to reflect consumption of
414  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
415  * an entry the host calls this function to update the queue's internal
416  * pointers. This routine returns the number of entries that were consumed by
417  * the HBA.
418  **/
419 static uint32_t
420 lpfc_sli4_mq_release(struct lpfc_queue *q)
421 {
422 	/* sanity check on queue memory */
423 	if (unlikely(!q))
424 		return 0;
425 
426 	/* Clear the mailbox pointer for completion */
427 	q->phba->mbox = NULL;
428 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
429 	return 1;
430 }
431 
432 /**
433  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
434  * @q: The Event Queue to get the first valid EQE from
435  *
436  * This routine will get the first valid Event Queue Entry from @q, update
437  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
438  * the Queue (no more work to do), or the Queue is full of EQEs that have been
439  * processed, but not popped back to the HBA then this routine will return NULL.
440  **/
441 static struct lpfc_eqe *
442 lpfc_sli4_eq_get(struct lpfc_queue *q)
443 {
444 	struct lpfc_eqe *eqe;
445 
446 	/* sanity check on queue memory */
447 	if (unlikely(!q))
448 		return NULL;
449 	eqe = lpfc_sli4_qe(q, q->host_index);
450 
451 	/* If the next EQE is not valid then we are done */
452 	if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
453 		return NULL;
454 
455 	/*
456 	 * insert barrier for instruction interlock : data from the hardware
457 	 * must have the valid bit checked before it can be copied and acted
458 	 * upon. Speculative instructions were allowing a bcopy at the start
459 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
460 	 * after our return, to copy data before the valid bit check above
461 	 * was done. As such, some of the copied data was stale. The barrier
462 	 * ensures the check is before any data is copied.
463 	 */
464 	mb();
465 	return eqe;
466 }
467 
468 /**
469  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
470  * @q: The Event Queue to disable interrupts
471  *
472  **/
473 void
474 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
475 {
476 	struct lpfc_register doorbell;
477 
478 	doorbell.word0 = 0;
479 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
480 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
481 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
482 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
483 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
484 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
485 }
486 
487 /**
488  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
489  * @q: The Event Queue to disable interrupts
490  *
491  **/
492 void
493 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
494 {
495 	struct lpfc_register doorbell;
496 
497 	doorbell.word0 = 0;
498 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
499 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
500 }
501 
502 /**
503  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
504  * @phba: adapter with EQ
505  * @q: The Event Queue that the host has completed processing for.
506  * @count: Number of elements that have been consumed
507  * @arm: Indicates whether the host wants to arms this CQ.
508  *
509  * This routine will notify the HBA, by ringing the doorbell, that count
510  * number of EQEs have been processed. The @arm parameter indicates whether
511  * the queue should be rearmed when ringing the doorbell.
512  **/
513 void
514 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
515 		     uint32_t count, bool arm)
516 {
517 	struct lpfc_register doorbell;
518 
519 	/* sanity check on queue memory */
520 	if (unlikely(!q || (count == 0 && !arm)))
521 		return;
522 
523 	/* ring doorbell for number popped */
524 	doorbell.word0 = 0;
525 	if (arm) {
526 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
527 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
528 	}
529 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
530 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
531 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
532 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
533 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
534 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
535 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
536 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
537 		readl(q->phba->sli4_hba.EQDBregaddr);
538 }
539 
540 /**
541  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
542  * @phba: adapter with EQ
543  * @q: The Event Queue that the host has completed processing for.
544  * @count: Number of elements that have been consumed
545  * @arm: Indicates whether the host wants to arms this CQ.
546  *
547  * This routine will notify the HBA, by ringing the doorbell, that count
548  * number of EQEs have been processed. The @arm parameter indicates whether
549  * the queue should be rearmed when ringing the doorbell.
550  **/
551 void
552 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
553 			  uint32_t count, bool arm)
554 {
555 	struct lpfc_register doorbell;
556 
557 	/* sanity check on queue memory */
558 	if (unlikely(!q || (count == 0 && !arm)))
559 		return;
560 
561 	/* ring doorbell for number popped */
562 	doorbell.word0 = 0;
563 	if (arm)
564 		bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
565 	bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
566 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
567 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
568 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
569 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
570 		readl(q->phba->sli4_hba.EQDBregaddr);
571 }
572 
573 static void
574 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
575 			struct lpfc_eqe *eqe)
576 {
577 	if (!phba->sli4_hba.pc_sli4_params.eqav)
578 		bf_set_le32(lpfc_eqe_valid, eqe, 0);
579 
580 	eq->host_index = ((eq->host_index + 1) % eq->entry_count);
581 
582 	/* if the index wrapped around, toggle the valid bit */
583 	if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
584 		eq->qe_valid = (eq->qe_valid) ? 0 : 1;
585 }
586 
587 static void
588 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
589 {
590 	struct lpfc_eqe *eqe = NULL;
591 	u32 eq_count = 0, cq_count = 0;
592 	struct lpfc_cqe *cqe = NULL;
593 	struct lpfc_queue *cq = NULL, *childq = NULL;
594 	int cqid = 0;
595 
596 	/* walk all the EQ entries and drop on the floor */
597 	eqe = lpfc_sli4_eq_get(eq);
598 	while (eqe) {
599 		/* Get the reference to the corresponding CQ */
600 		cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
601 		cq = NULL;
602 
603 		list_for_each_entry(childq, &eq->child_list, list) {
604 			if (childq->queue_id == cqid) {
605 				cq = childq;
606 				break;
607 			}
608 		}
609 		/* If CQ is valid, iterate through it and drop all the CQEs */
610 		if (cq) {
611 			cqe = lpfc_sli4_cq_get(cq);
612 			while (cqe) {
613 				__lpfc_sli4_consume_cqe(phba, cq, cqe);
614 				cq_count++;
615 				cqe = lpfc_sli4_cq_get(cq);
616 			}
617 			/* Clear and re-arm the CQ */
618 			phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
619 			    LPFC_QUEUE_REARM);
620 			cq_count = 0;
621 		}
622 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
623 		eq_count++;
624 		eqe = lpfc_sli4_eq_get(eq);
625 	}
626 
627 	/* Clear and re-arm the EQ */
628 	phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
629 }
630 
631 static int
632 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
633 		     u8 rearm, enum lpfc_poll_mode poll_mode)
634 {
635 	struct lpfc_eqe *eqe;
636 	int count = 0, consumed = 0;
637 
638 	if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
639 		goto rearm_and_exit;
640 
641 	eqe = lpfc_sli4_eq_get(eq);
642 	while (eqe) {
643 		lpfc_sli4_hba_handle_eqe(phba, eq, eqe, poll_mode);
644 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
645 
646 		consumed++;
647 		if (!(++count % eq->max_proc_limit))
648 			break;
649 
650 		if (!(count % eq->notify_interval)) {
651 			phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
652 							LPFC_QUEUE_NOARM);
653 			consumed = 0;
654 		}
655 
656 		eqe = lpfc_sli4_eq_get(eq);
657 	}
658 	eq->EQ_processed += count;
659 
660 	/* Track the max number of EQEs processed in 1 intr */
661 	if (count > eq->EQ_max_eqe)
662 		eq->EQ_max_eqe = count;
663 
664 	xchg(&eq->queue_claimed, 0);
665 
666 rearm_and_exit:
667 	/* Always clear the EQ. */
668 	phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
669 
670 	return count;
671 }
672 
673 /**
674  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
675  * @q: The Completion Queue to get the first valid CQE from
676  *
677  * This routine will get the first valid Completion Queue Entry from @q, update
678  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
679  * the Queue (no more work to do), or the Queue is full of CQEs that have been
680  * processed, but not popped back to the HBA then this routine will return NULL.
681  **/
682 static struct lpfc_cqe *
683 lpfc_sli4_cq_get(struct lpfc_queue *q)
684 {
685 	struct lpfc_cqe *cqe;
686 
687 	/* sanity check on queue memory */
688 	if (unlikely(!q))
689 		return NULL;
690 	cqe = lpfc_sli4_qe(q, q->host_index);
691 
692 	/* If the next CQE is not valid then we are done */
693 	if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
694 		return NULL;
695 
696 	/*
697 	 * insert barrier for instruction interlock : data from the hardware
698 	 * must have the valid bit checked before it can be copied and acted
699 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
700 	 * instructions allowing action on content before valid bit checked,
701 	 * add barrier here as well. May not be needed as "content" is a
702 	 * single 32-bit entity here (vs multi word structure for cq's).
703 	 */
704 	mb();
705 	return cqe;
706 }
707 
708 static void
709 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
710 			struct lpfc_cqe *cqe)
711 {
712 	if (!phba->sli4_hba.pc_sli4_params.cqav)
713 		bf_set_le32(lpfc_cqe_valid, cqe, 0);
714 
715 	cq->host_index = ((cq->host_index + 1) % cq->entry_count);
716 
717 	/* if the index wrapped around, toggle the valid bit */
718 	if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
719 		cq->qe_valid = (cq->qe_valid) ? 0 : 1;
720 }
721 
722 /**
723  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
724  * @phba: the adapter with the CQ
725  * @q: The Completion Queue that the host has completed processing for.
726  * @count: the number of elements that were consumed
727  * @arm: Indicates whether the host wants to arms this CQ.
728  *
729  * This routine will notify the HBA, by ringing the doorbell, that the
730  * CQEs have been processed. The @arm parameter specifies whether the
731  * queue should be rearmed when ringing the doorbell.
732  **/
733 void
734 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
735 		     uint32_t count, bool arm)
736 {
737 	struct lpfc_register doorbell;
738 
739 	/* sanity check on queue memory */
740 	if (unlikely(!q || (count == 0 && !arm)))
741 		return;
742 
743 	/* ring doorbell for number popped */
744 	doorbell.word0 = 0;
745 	if (arm)
746 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
747 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
748 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
749 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
750 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
751 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
752 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
753 }
754 
755 /**
756  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
757  * @phba: the adapter with the CQ
758  * @q: The Completion Queue that the host has completed processing for.
759  * @count: the number of elements that were consumed
760  * @arm: Indicates whether the host wants to arms this CQ.
761  *
762  * This routine will notify the HBA, by ringing the doorbell, that the
763  * CQEs have been processed. The @arm parameter specifies whether the
764  * queue should be rearmed when ringing the doorbell.
765  **/
766 void
767 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
768 			 uint32_t count, bool arm)
769 {
770 	struct lpfc_register doorbell;
771 
772 	/* sanity check on queue memory */
773 	if (unlikely(!q || (count == 0 && !arm)))
774 		return;
775 
776 	/* ring doorbell for number popped */
777 	doorbell.word0 = 0;
778 	if (arm)
779 		bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
780 	bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
781 	bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
782 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
783 }
784 
785 /*
786  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
787  *
788  * This routine will copy the contents of @wqe to the next available entry on
789  * the @q. This function will then ring the Receive Queue Doorbell to signal the
790  * HBA to start processing the Receive Queue Entry. This function returns the
791  * index that the rqe was copied to if successful. If no entries are available
792  * on @q then this function will return -ENOMEM.
793  * The caller is expected to hold the hbalock when calling this routine.
794  **/
795 int
796 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
797 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
798 {
799 	struct lpfc_rqe *temp_hrqe;
800 	struct lpfc_rqe *temp_drqe;
801 	struct lpfc_register doorbell;
802 	int hq_put_index;
803 	int dq_put_index;
804 
805 	/* sanity check on queue memory */
806 	if (unlikely(!hq) || unlikely(!dq))
807 		return -ENOMEM;
808 	hq_put_index = hq->host_index;
809 	dq_put_index = dq->host_index;
810 	temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
811 	temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
812 
813 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
814 		return -EINVAL;
815 	if (hq_put_index != dq_put_index)
816 		return -EINVAL;
817 	/* If the host has not yet processed the next entry then we are done */
818 	if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
819 		return -EBUSY;
820 	lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
821 	lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
822 
823 	/* Update the host index to point to the next slot */
824 	hq->host_index = ((hq_put_index + 1) % hq->entry_count);
825 	dq->host_index = ((dq_put_index + 1) % dq->entry_count);
826 	hq->RQ_buf_posted++;
827 
828 	/* Ring The Header Receive Queue Doorbell */
829 	if (!(hq->host_index % hq->notify_interval)) {
830 		doorbell.word0 = 0;
831 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
832 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
833 			       hq->notify_interval);
834 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
835 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
836 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
837 			       hq->notify_interval);
838 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
839 			       hq->host_index);
840 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
841 		} else {
842 			return -EINVAL;
843 		}
844 		writel(doorbell.word0, hq->db_regaddr);
845 	}
846 	return hq_put_index;
847 }
848 
849 /*
850  * lpfc_sli4_rq_release - Updates internal hba index for RQ
851  *
852  * This routine will update the HBA index of a queue to reflect consumption of
853  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
854  * consumed an entry the host calls this function to update the queue's
855  * internal pointers. This routine returns the number of entries that were
856  * consumed by the HBA.
857  **/
858 static uint32_t
859 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
860 {
861 	/* sanity check on queue memory */
862 	if (unlikely(!hq) || unlikely(!dq))
863 		return 0;
864 
865 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
866 		return 0;
867 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
868 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
869 	return 1;
870 }
871 
872 /**
873  * lpfc_cmd_iocb - Get next command iocb entry in the ring
874  * @phba: Pointer to HBA context object.
875  * @pring: Pointer to driver SLI ring object.
876  *
877  * This function returns pointer to next command iocb entry
878  * in the command ring. The caller must hold hbalock to prevent
879  * other threads consume the next command iocb.
880  * SLI-2/SLI-3 provide different sized iocbs.
881  **/
882 static inline IOCB_t *
883 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
884 {
885 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
886 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
887 }
888 
889 /**
890  * lpfc_resp_iocb - Get next response iocb entry in the ring
891  * @phba: Pointer to HBA context object.
892  * @pring: Pointer to driver SLI ring object.
893  *
894  * This function returns pointer to next response iocb entry
895  * in the response ring. The caller must hold hbalock to make sure
896  * that no other thread consume the next response iocb.
897  * SLI-2/SLI-3 provide different sized iocbs.
898  **/
899 static inline IOCB_t *
900 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
901 {
902 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
903 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
904 }
905 
906 /**
907  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
908  * @phba: Pointer to HBA context object.
909  *
910  * This function is called with hbalock held. This function
911  * allocates a new driver iocb object from the iocb pool. If the
912  * allocation is successful, it returns pointer to the newly
913  * allocated iocb object else it returns NULL.
914  **/
915 struct lpfc_iocbq *
916 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
917 {
918 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
919 	struct lpfc_iocbq * iocbq = NULL;
920 
921 	lockdep_assert_held(&phba->hbalock);
922 
923 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
924 	if (iocbq)
925 		phba->iocb_cnt++;
926 	if (phba->iocb_cnt > phba->iocb_max)
927 		phba->iocb_max = phba->iocb_cnt;
928 	return iocbq;
929 }
930 
931 /**
932  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
933  * @phba: Pointer to HBA context object.
934  * @xritag: XRI value.
935  *
936  * This function clears the sglq pointer from the array of active
937  * sglq's. The xritag that is passed in is used to index into the
938  * array. Before the xritag can be used it needs to be adjusted
939  * by subtracting the xribase.
940  *
941  * Returns sglq ponter = success, NULL = Failure.
942  **/
943 struct lpfc_sglq *
944 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
945 {
946 	struct lpfc_sglq *sglq;
947 
948 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
949 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
950 	return sglq;
951 }
952 
953 /**
954  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
955  * @phba: Pointer to HBA context object.
956  * @xritag: XRI value.
957  *
958  * This function returns the sglq pointer from the array of active
959  * sglq's. The xritag that is passed in is used to index into the
960  * array. Before the xritag can be used it needs to be adjusted
961  * by subtracting the xribase.
962  *
963  * Returns sglq ponter = success, NULL = Failure.
964  **/
965 struct lpfc_sglq *
966 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
967 {
968 	struct lpfc_sglq *sglq;
969 
970 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
971 	return sglq;
972 }
973 
974 /**
975  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
976  * @phba: Pointer to HBA context object.
977  * @xritag: xri used in this exchange.
978  * @rrq: The RRQ to be cleared.
979  *
980  **/
981 void
982 lpfc_clr_rrq_active(struct lpfc_hba *phba,
983 		    uint16_t xritag,
984 		    struct lpfc_node_rrq *rrq)
985 {
986 	struct lpfc_nodelist *ndlp = NULL;
987 
988 	/* Lookup did to verify if did is still active on this vport */
989 	if (rrq->vport)
990 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
991 
992 	if (!ndlp)
993 		goto out;
994 
995 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
996 		rrq->send_rrq = 0;
997 		rrq->xritag = 0;
998 		rrq->rrq_stop_time = 0;
999 	}
1000 out:
1001 	mempool_free(rrq, phba->rrq_pool);
1002 }
1003 
1004 /**
1005  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
1006  * @phba: Pointer to HBA context object.
1007  *
1008  * This function is called with hbalock held. This function
1009  * Checks if stop_time (ratov from setting rrq active) has
1010  * been reached, if it has and the send_rrq flag is set then
1011  * it will call lpfc_send_rrq. If the send_rrq flag is not set
1012  * then it will just call the routine to clear the rrq and
1013  * free the rrq resource.
1014  * The timer is set to the next rrq that is going to expire before
1015  * leaving the routine.
1016  *
1017  **/
1018 void
1019 lpfc_handle_rrq_active(struct lpfc_hba *phba)
1020 {
1021 	struct lpfc_node_rrq *rrq;
1022 	struct lpfc_node_rrq *nextrrq;
1023 	unsigned long next_time;
1024 	unsigned long iflags;
1025 	LIST_HEAD(send_rrq);
1026 
1027 	spin_lock_irqsave(&phba->hbalock, iflags);
1028 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1029 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1030 	list_for_each_entry_safe(rrq, nextrrq,
1031 				 &phba->active_rrq_list, list) {
1032 		if (time_after(jiffies, rrq->rrq_stop_time))
1033 			list_move(&rrq->list, &send_rrq);
1034 		else if (time_before(rrq->rrq_stop_time, next_time))
1035 			next_time = rrq->rrq_stop_time;
1036 	}
1037 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1038 	if ((!list_empty(&phba->active_rrq_list)) &&
1039 	    (!(phba->pport->load_flag & FC_UNLOADING)))
1040 		mod_timer(&phba->rrq_tmr, next_time);
1041 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
1042 		list_del(&rrq->list);
1043 		if (!rrq->send_rrq) {
1044 			/* this call will free the rrq */
1045 			lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1046 		} else if (lpfc_send_rrq(phba, rrq)) {
1047 			/* if we send the rrq then the completion handler
1048 			*  will clear the bit in the xribitmap.
1049 			*/
1050 			lpfc_clr_rrq_active(phba, rrq->xritag,
1051 					    rrq);
1052 		}
1053 	}
1054 }
1055 
1056 /**
1057  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
1058  * @vport: Pointer to vport context object.
1059  * @xri: The xri used in the exchange.
1060  * @did: The targets DID for this exchange.
1061  *
1062  * returns NULL = rrq not found in the phba->active_rrq_list.
1063  *         rrq = rrq for this xri and target.
1064  **/
1065 struct lpfc_node_rrq *
1066 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
1067 {
1068 	struct lpfc_hba *phba = vport->phba;
1069 	struct lpfc_node_rrq *rrq;
1070 	struct lpfc_node_rrq *nextrrq;
1071 	unsigned long iflags;
1072 
1073 	if (phba->sli_rev != LPFC_SLI_REV4)
1074 		return NULL;
1075 	spin_lock_irqsave(&phba->hbalock, iflags);
1076 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1077 		if (rrq->vport == vport && rrq->xritag == xri &&
1078 				rrq->nlp_DID == did){
1079 			list_del(&rrq->list);
1080 			spin_unlock_irqrestore(&phba->hbalock, iflags);
1081 			return rrq;
1082 		}
1083 	}
1084 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1085 	return NULL;
1086 }
1087 
1088 /**
1089  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
1090  * @vport: Pointer to vport context object.
1091  * @ndlp: Pointer to the lpfc_node_list structure.
1092  * If ndlp is NULL Remove all active RRQs for this vport from the
1093  * phba->active_rrq_list and clear the rrq.
1094  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
1095  **/
1096 void
1097 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
1098 
1099 {
1100 	struct lpfc_hba *phba = vport->phba;
1101 	struct lpfc_node_rrq *rrq;
1102 	struct lpfc_node_rrq *nextrrq;
1103 	unsigned long iflags;
1104 	LIST_HEAD(rrq_list);
1105 
1106 	if (phba->sli_rev != LPFC_SLI_REV4)
1107 		return;
1108 	if (!ndlp) {
1109 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
1110 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
1111 	}
1112 	spin_lock_irqsave(&phba->hbalock, iflags);
1113 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1114 		if (rrq->vport != vport)
1115 			continue;
1116 
1117 		if (!ndlp || ndlp == lpfc_findnode_did(vport, rrq->nlp_DID))
1118 			list_move(&rrq->list, &rrq_list);
1119 
1120 	}
1121 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1122 
1123 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1124 		list_del(&rrq->list);
1125 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1126 	}
1127 }
1128 
1129 /**
1130  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1131  * @phba: Pointer to HBA context object.
1132  * @ndlp: Targets nodelist pointer for this exchange.
1133  * @xritag: the xri in the bitmap to test.
1134  *
1135  * This function returns:
1136  * 0 = rrq not active for this xri
1137  * 1 = rrq is valid for this xri.
1138  **/
1139 int
1140 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1141 			uint16_t  xritag)
1142 {
1143 	if (!ndlp)
1144 		return 0;
1145 	if (!ndlp->active_rrqs_xri_bitmap)
1146 		return 0;
1147 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1148 		return 1;
1149 	else
1150 		return 0;
1151 }
1152 
1153 /**
1154  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1155  * @phba: Pointer to HBA context object.
1156  * @ndlp: nodelist pointer for this target.
1157  * @xritag: xri used in this exchange.
1158  * @rxid: Remote Exchange ID.
1159  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1160  *
1161  * This function takes the hbalock.
1162  * The active bit is always set in the active rrq xri_bitmap even
1163  * if there is no slot avaiable for the other rrq information.
1164  *
1165  * returns 0 rrq actived for this xri
1166  *         < 0 No memory or invalid ndlp.
1167  **/
1168 int
1169 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1170 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1171 {
1172 	unsigned long iflags;
1173 	struct lpfc_node_rrq *rrq;
1174 	int empty;
1175 
1176 	if (!ndlp)
1177 		return -EINVAL;
1178 
1179 	if (!phba->cfg_enable_rrq)
1180 		return -EINVAL;
1181 
1182 	spin_lock_irqsave(&phba->hbalock, iflags);
1183 	if (phba->pport->load_flag & FC_UNLOADING) {
1184 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1185 		goto out;
1186 	}
1187 
1188 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
1189 		goto out;
1190 
1191 	if (!ndlp->active_rrqs_xri_bitmap)
1192 		goto out;
1193 
1194 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1195 		goto out;
1196 
1197 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1198 	rrq = mempool_alloc(phba->rrq_pool, GFP_ATOMIC);
1199 	if (!rrq) {
1200 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1201 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1202 				" DID:0x%x Send:%d\n",
1203 				xritag, rxid, ndlp->nlp_DID, send_rrq);
1204 		return -EINVAL;
1205 	}
1206 	if (phba->cfg_enable_rrq == 1)
1207 		rrq->send_rrq = send_rrq;
1208 	else
1209 		rrq->send_rrq = 0;
1210 	rrq->xritag = xritag;
1211 	rrq->rrq_stop_time = jiffies +
1212 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1213 	rrq->nlp_DID = ndlp->nlp_DID;
1214 	rrq->vport = ndlp->vport;
1215 	rrq->rxid = rxid;
1216 	spin_lock_irqsave(&phba->hbalock, iflags);
1217 	empty = list_empty(&phba->active_rrq_list);
1218 	list_add_tail(&rrq->list, &phba->active_rrq_list);
1219 	phba->hba_flag |= HBA_RRQ_ACTIVE;
1220 	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 	u8 warn_sync_period = 0;
1936 
1937 	/* First address any alarm / warning activity */
1938 	atot = atomic_xchg(&phba->cgn_sync_alarm_cnt, 0);
1939 	wtot = atomic_xchg(&phba->cgn_sync_warn_cnt, 0);
1940 
1941 	/* ONLY Managed mode will send the CMF_SYNC_WQE to the HBA */
1942 	if (phba->cmf_active_mode != LPFC_CFG_MANAGED ||
1943 	    phba->link_state == LPFC_LINK_DOWN)
1944 		return 0;
1945 
1946 	spin_lock_irqsave(&phba->hbalock, iflags);
1947 	sync_buf = __lpfc_sli_get_iocbq(phba);
1948 	if (!sync_buf) {
1949 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
1950 				"6244 No available WQEs for CMF_SYNC_WQE\n");
1951 		ret_val = ENOMEM;
1952 		goto out_unlock;
1953 	}
1954 
1955 	wqe = &sync_buf->wqe;
1956 
1957 	/* WQEs are reused.  Clear stale data and set key fields to zero */
1958 	memset(wqe, 0, sizeof(*wqe));
1959 
1960 	/* If this is the very first CMF_SYNC_WQE, issue an init operation */
1961 	if (!ms) {
1962 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1963 				"6441 CMF Init %d - CMF_SYNC_WQE\n",
1964 				phba->fc_eventTag);
1965 		bf_set(cmf_sync_op, &wqe->cmf_sync, 1); /* 1=init */
1966 		bf_set(cmf_sync_interval, &wqe->cmf_sync, LPFC_CMF_INTERVAL);
1967 		goto initpath;
1968 	}
1969 
1970 	bf_set(cmf_sync_op, &wqe->cmf_sync, 0); /* 0=recalc */
1971 	bf_set(cmf_sync_interval, &wqe->cmf_sync, ms);
1972 
1973 	/* Check for alarms / warnings */
1974 	if (atot) {
1975 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1976 			/* We hit an Signal alarm condition */
1977 			bf_set(cmf_sync_asig, &wqe->cmf_sync, 1);
1978 		} else {
1979 			/* We hit a FPIN alarm condition */
1980 			bf_set(cmf_sync_afpin, &wqe->cmf_sync, 1);
1981 		}
1982 	} else if (wtot) {
1983 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
1984 		    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1985 			/* We hit an Signal warning condition */
1986 			max = LPFC_SEC_TO_MSEC / lpfc_fabric_cgn_frequency *
1987 				lpfc_acqe_cgn_frequency;
1988 			bf_set(cmf_sync_wsigmax, &wqe->cmf_sync, max);
1989 			bf_set(cmf_sync_wsigcnt, &wqe->cmf_sync, wtot);
1990 			warn_sync_period = lpfc_acqe_cgn_frequency;
1991 		} else {
1992 			/* We hit a FPIN warning condition */
1993 			bf_set(cmf_sync_wfpinmax, &wqe->cmf_sync, 1);
1994 			bf_set(cmf_sync_wfpincnt, &wqe->cmf_sync, 1);
1995 			if (phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ)
1996 				warn_sync_period =
1997 				LPFC_MSECS_TO_SECS(phba->cgn_fpin_frequency);
1998 		}
1999 	}
2000 
2001 	/* Update total read blocks during previous timer interval */
2002 	wqe->cmf_sync.read_bytes = (u32)(total / LPFC_CMF_BLK_SIZE);
2003 
2004 initpath:
2005 	bf_set(cmf_sync_ver, &wqe->cmf_sync, LPFC_CMF_SYNC_VER);
2006 	wqe->cmf_sync.event_tag = phba->fc_eventTag;
2007 	bf_set(cmf_sync_cmnd, &wqe->cmf_sync, CMD_CMF_SYNC_WQE);
2008 
2009 	/* Setup reqtag to match the wqe completion. */
2010 	bf_set(cmf_sync_reqtag, &wqe->cmf_sync, sync_buf->iotag);
2011 
2012 	bf_set(cmf_sync_qosd, &wqe->cmf_sync, 1);
2013 	bf_set(cmf_sync_period, &wqe->cmf_sync, warn_sync_period);
2014 
2015 	bf_set(cmf_sync_cmd_type, &wqe->cmf_sync, CMF_SYNC_COMMAND);
2016 	bf_set(cmf_sync_wqec, &wqe->cmf_sync, 1);
2017 	bf_set(cmf_sync_cqid, &wqe->cmf_sync, LPFC_WQE_CQ_ID_DEFAULT);
2018 
2019 	sync_buf->vport = phba->pport;
2020 	sync_buf->cmd_cmpl = lpfc_cmf_sync_cmpl;
2021 	sync_buf->cmd_dmabuf = NULL;
2022 	sync_buf->rsp_dmabuf = NULL;
2023 	sync_buf->bpl_dmabuf = NULL;
2024 	sync_buf->sli4_xritag = NO_XRI;
2025 
2026 	sync_buf->cmd_flag |= LPFC_IO_CMF;
2027 	ret_val = lpfc_sli4_issue_wqe(phba, &phba->sli4_hba.hdwq[0], sync_buf);
2028 	if (ret_val) {
2029 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
2030 				"6214 Cannot issue CMF_SYNC_WQE: x%x\n",
2031 				ret_val);
2032 		__lpfc_sli_release_iocbq(phba, sync_buf);
2033 	}
2034 out_unlock:
2035 	spin_unlock_irqrestore(&phba->hbalock, iflags);
2036 	return ret_val;
2037 }
2038 
2039 /**
2040  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
2041  * @phba: Pointer to HBA context object.
2042  * @pring: Pointer to driver SLI ring object.
2043  *
2044  * This function is called with hbalock held and the caller must post the
2045  * iocb without releasing the lock. If the caller releases the lock,
2046  * iocb slot returned by the function is not guaranteed to be available.
2047  * The function returns pointer to the next available iocb slot if there
2048  * is available slot in the ring, else it returns NULL.
2049  * If the get index of the ring is ahead of the put index, the function
2050  * will post an error attention event to the worker thread to take the
2051  * HBA to offline state.
2052  **/
2053 static IOCB_t *
2054 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2055 {
2056 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2057 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
2058 
2059 	lockdep_assert_held(&phba->hbalock);
2060 
2061 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
2062 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
2063 		pring->sli.sli3.next_cmdidx = 0;
2064 
2065 	if (unlikely(pring->sli.sli3.local_getidx ==
2066 		pring->sli.sli3.next_cmdidx)) {
2067 
2068 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
2069 
2070 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
2071 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2072 					"0315 Ring %d issue: portCmdGet %d "
2073 					"is bigger than cmd ring %d\n",
2074 					pring->ringno,
2075 					pring->sli.sli3.local_getidx,
2076 					max_cmd_idx);
2077 
2078 			phba->link_state = LPFC_HBA_ERROR;
2079 			/*
2080 			 * All error attention handlers are posted to
2081 			 * worker thread
2082 			 */
2083 			phba->work_ha |= HA_ERATT;
2084 			phba->work_hs = HS_FFER3;
2085 
2086 			lpfc_worker_wake_up(phba);
2087 
2088 			return NULL;
2089 		}
2090 
2091 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
2092 			return NULL;
2093 	}
2094 
2095 	return lpfc_cmd_iocb(phba, pring);
2096 }
2097 
2098 /**
2099  * lpfc_sli_next_iotag - Get an iotag for the iocb
2100  * @phba: Pointer to HBA context object.
2101  * @iocbq: Pointer to driver iocb object.
2102  *
2103  * This function gets an iotag for the iocb. If there is no unused iotag and
2104  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
2105  * array and assigns a new iotag.
2106  * The function returns the allocated iotag if successful, else returns zero.
2107  * Zero is not a valid iotag.
2108  * The caller is not required to hold any lock.
2109  **/
2110 uint16_t
2111 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
2112 {
2113 	struct lpfc_iocbq **new_arr;
2114 	struct lpfc_iocbq **old_arr;
2115 	size_t new_len;
2116 	struct lpfc_sli *psli = &phba->sli;
2117 	uint16_t iotag;
2118 
2119 	spin_lock_irq(&phba->hbalock);
2120 	iotag = psli->last_iotag;
2121 	if(++iotag < psli->iocbq_lookup_len) {
2122 		psli->last_iotag = iotag;
2123 		psli->iocbq_lookup[iotag] = iocbq;
2124 		spin_unlock_irq(&phba->hbalock);
2125 		iocbq->iotag = iotag;
2126 		return iotag;
2127 	} else if (psli->iocbq_lookup_len < (0xffff
2128 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
2129 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
2130 		spin_unlock_irq(&phba->hbalock);
2131 		new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
2132 				  GFP_KERNEL);
2133 		if (new_arr) {
2134 			spin_lock_irq(&phba->hbalock);
2135 			old_arr = psli->iocbq_lookup;
2136 			if (new_len <= psli->iocbq_lookup_len) {
2137 				/* highly unprobable case */
2138 				kfree(new_arr);
2139 				iotag = psli->last_iotag;
2140 				if(++iotag < psli->iocbq_lookup_len) {
2141 					psli->last_iotag = iotag;
2142 					psli->iocbq_lookup[iotag] = iocbq;
2143 					spin_unlock_irq(&phba->hbalock);
2144 					iocbq->iotag = iotag;
2145 					return iotag;
2146 				}
2147 				spin_unlock_irq(&phba->hbalock);
2148 				return 0;
2149 			}
2150 			if (psli->iocbq_lookup)
2151 				memcpy(new_arr, old_arr,
2152 				       ((psli->last_iotag  + 1) *
2153 					sizeof (struct lpfc_iocbq *)));
2154 			psli->iocbq_lookup = new_arr;
2155 			psli->iocbq_lookup_len = new_len;
2156 			psli->last_iotag = iotag;
2157 			psli->iocbq_lookup[iotag] = iocbq;
2158 			spin_unlock_irq(&phba->hbalock);
2159 			iocbq->iotag = iotag;
2160 			kfree(old_arr);
2161 			return iotag;
2162 		}
2163 	} else
2164 		spin_unlock_irq(&phba->hbalock);
2165 
2166 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2167 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
2168 			psli->last_iotag);
2169 
2170 	return 0;
2171 }
2172 
2173 /**
2174  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
2175  * @phba: Pointer to HBA context object.
2176  * @pring: Pointer to driver SLI ring object.
2177  * @iocb: Pointer to iocb slot in the ring.
2178  * @nextiocb: Pointer to driver iocb object which need to be
2179  *            posted to firmware.
2180  *
2181  * This function is called to post a new iocb to the firmware. This
2182  * function copies the new iocb to ring iocb slot and updates the
2183  * ring pointers. It adds the new iocb to txcmplq if there is
2184  * a completion call back for this iocb else the function will free the
2185  * iocb object.  The hbalock is asserted held in the code path calling
2186  * this routine.
2187  **/
2188 static void
2189 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2190 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
2191 {
2192 	/*
2193 	 * Set up an iotag
2194 	 */
2195 	nextiocb->iocb.ulpIoTag = (nextiocb->cmd_cmpl) ? nextiocb->iotag : 0;
2196 
2197 
2198 	if (pring->ringno == LPFC_ELS_RING) {
2199 		lpfc_debugfs_slow_ring_trc(phba,
2200 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
2201 			*(((uint32_t *) &nextiocb->iocb) + 4),
2202 			*(((uint32_t *) &nextiocb->iocb) + 6),
2203 			*(((uint32_t *) &nextiocb->iocb) + 7));
2204 	}
2205 
2206 	/*
2207 	 * Issue iocb command to adapter
2208 	 */
2209 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
2210 	wmb();
2211 	pring->stats.iocb_cmd++;
2212 
2213 	/*
2214 	 * If there is no completion routine to call, we can release the
2215 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
2216 	 * that have no rsp ring completion, cmd_cmpl MUST be NULL.
2217 	 */
2218 	if (nextiocb->cmd_cmpl)
2219 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
2220 	else
2221 		__lpfc_sli_release_iocbq(phba, nextiocb);
2222 
2223 	/*
2224 	 * Let the HBA know what IOCB slot will be the next one the
2225 	 * driver will put a command into.
2226 	 */
2227 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
2228 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
2229 }
2230 
2231 /**
2232  * lpfc_sli_update_full_ring - Update the chip attention register
2233  * @phba: Pointer to HBA context object.
2234  * @pring: Pointer to driver SLI ring object.
2235  *
2236  * The caller is not required to hold any lock for calling this function.
2237  * This function updates the chip attention bits for the ring to inform firmware
2238  * that there are pending work to be done for this ring and requests an
2239  * interrupt when there is space available in the ring. This function is
2240  * called when the driver is unable to post more iocbs to the ring due
2241  * to unavailability of space in the ring.
2242  **/
2243 static void
2244 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2245 {
2246 	int ringno = pring->ringno;
2247 
2248 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
2249 
2250 	wmb();
2251 
2252 	/*
2253 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
2254 	 * The HBA will tell us when an IOCB entry is available.
2255 	 */
2256 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
2257 	readl(phba->CAregaddr); /* flush */
2258 
2259 	pring->stats.iocb_cmd_full++;
2260 }
2261 
2262 /**
2263  * lpfc_sli_update_ring - Update chip attention register
2264  * @phba: Pointer to HBA context object.
2265  * @pring: Pointer to driver SLI ring object.
2266  *
2267  * This function updates the chip attention register bit for the
2268  * given ring to inform HBA that there is more work to be done
2269  * in this ring. The caller is not required to hold any lock.
2270  **/
2271 static void
2272 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2273 {
2274 	int ringno = pring->ringno;
2275 
2276 	/*
2277 	 * Tell the HBA that there is work to do in this ring.
2278 	 */
2279 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
2280 		wmb();
2281 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
2282 		readl(phba->CAregaddr); /* flush */
2283 	}
2284 }
2285 
2286 /**
2287  * lpfc_sli_resume_iocb - Process iocbs in the txq
2288  * @phba: Pointer to HBA context object.
2289  * @pring: Pointer to driver SLI ring object.
2290  *
2291  * This function is called with hbalock held to post pending iocbs
2292  * in the txq to the firmware. This function is called when driver
2293  * detects space available in the ring.
2294  **/
2295 static void
2296 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2297 {
2298 	IOCB_t *iocb;
2299 	struct lpfc_iocbq *nextiocb;
2300 
2301 	lockdep_assert_held(&phba->hbalock);
2302 
2303 	/*
2304 	 * Check to see if:
2305 	 *  (a) there is anything on the txq to send
2306 	 *  (b) link is up
2307 	 *  (c) link attention events can be processed (fcp ring only)
2308 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
2309 	 */
2310 
2311 	if (lpfc_is_link_up(phba) &&
2312 	    (!list_empty(&pring->txq)) &&
2313 	    (pring->ringno != LPFC_FCP_RING ||
2314 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
2315 
2316 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
2317 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
2318 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
2319 
2320 		if (iocb)
2321 			lpfc_sli_update_ring(phba, pring);
2322 		else
2323 			lpfc_sli_update_full_ring(phba, pring);
2324 	}
2325 
2326 	return;
2327 }
2328 
2329 /**
2330  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
2331  * @phba: Pointer to HBA context object.
2332  * @hbqno: HBQ number.
2333  *
2334  * This function is called with hbalock held to get the next
2335  * available slot for the given HBQ. If there is free slot
2336  * available for the HBQ it will return pointer to the next available
2337  * HBQ entry else it will return NULL.
2338  **/
2339 static struct lpfc_hbq_entry *
2340 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
2341 {
2342 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
2343 
2344 	lockdep_assert_held(&phba->hbalock);
2345 
2346 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
2347 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
2348 		hbqp->next_hbqPutIdx = 0;
2349 
2350 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
2351 		uint32_t raw_index = phba->hbq_get[hbqno];
2352 		uint32_t getidx = le32_to_cpu(raw_index);
2353 
2354 		hbqp->local_hbqGetIdx = getidx;
2355 
2356 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
2357 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2358 					"1802 HBQ %d: local_hbqGetIdx "
2359 					"%u is > than hbqp->entry_count %u\n",
2360 					hbqno, hbqp->local_hbqGetIdx,
2361 					hbqp->entry_count);
2362 
2363 			phba->link_state = LPFC_HBA_ERROR;
2364 			return NULL;
2365 		}
2366 
2367 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
2368 			return NULL;
2369 	}
2370 
2371 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
2372 			hbqp->hbqPutIdx;
2373 }
2374 
2375 /**
2376  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
2377  * @phba: Pointer to HBA context object.
2378  *
2379  * This function is called with no lock held to free all the
2380  * hbq buffers while uninitializing the SLI interface. It also
2381  * frees the HBQ buffers returned by the firmware but not yet
2382  * processed by the upper layers.
2383  **/
2384 void
2385 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
2386 {
2387 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
2388 	struct hbq_dmabuf *hbq_buf;
2389 	unsigned long flags;
2390 	int i, hbq_count;
2391 
2392 	hbq_count = lpfc_sli_hbq_count();
2393 	/* Return all memory used by all HBQs */
2394 	spin_lock_irqsave(&phba->hbalock, flags);
2395 	for (i = 0; i < hbq_count; ++i) {
2396 		list_for_each_entry_safe(dmabuf, next_dmabuf,
2397 				&phba->hbqs[i].hbq_buffer_list, list) {
2398 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2399 			list_del(&hbq_buf->dbuf.list);
2400 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2401 		}
2402 		phba->hbqs[i].buffer_count = 0;
2403 	}
2404 
2405 	/* Mark the HBQs not in use */
2406 	phba->hbq_in_use = 0;
2407 	spin_unlock_irqrestore(&phba->hbalock, flags);
2408 }
2409 
2410 /**
2411  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2412  * @phba: Pointer to HBA context object.
2413  * @hbqno: HBQ number.
2414  * @hbq_buf: Pointer to HBQ buffer.
2415  *
2416  * This function is called with the hbalock held to post a
2417  * hbq buffer to the firmware. If the function finds an empty
2418  * slot in the HBQ, it will post the buffer. The function will return
2419  * pointer to the hbq entry if it successfully post the buffer
2420  * else it will return NULL.
2421  **/
2422 static int
2423 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2424 			 struct hbq_dmabuf *hbq_buf)
2425 {
2426 	lockdep_assert_held(&phba->hbalock);
2427 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2428 }
2429 
2430 /**
2431  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2432  * @phba: Pointer to HBA context object.
2433  * @hbqno: HBQ number.
2434  * @hbq_buf: Pointer to HBQ buffer.
2435  *
2436  * This function is called with the hbalock held to post a hbq buffer to the
2437  * firmware. If the function finds an empty slot in the HBQ, it will post the
2438  * buffer and place it on the hbq_buffer_list. The function will return zero if
2439  * it successfully post the buffer else it will return an error.
2440  **/
2441 static int
2442 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2443 			    struct hbq_dmabuf *hbq_buf)
2444 {
2445 	struct lpfc_hbq_entry *hbqe;
2446 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
2447 
2448 	lockdep_assert_held(&phba->hbalock);
2449 	/* Get next HBQ entry slot to use */
2450 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2451 	if (hbqe) {
2452 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
2453 
2454 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2455 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2456 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2457 		hbqe->bde.tus.f.bdeFlags = 0;
2458 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2459 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2460 				/* Sync SLIM */
2461 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2462 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2463 				/* flush */
2464 		readl(phba->hbq_put + hbqno);
2465 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2466 		return 0;
2467 	} else
2468 		return -ENOMEM;
2469 }
2470 
2471 /**
2472  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2473  * @phba: Pointer to HBA context object.
2474  * @hbqno: HBQ number.
2475  * @hbq_buf: Pointer to HBQ buffer.
2476  *
2477  * This function is called with the hbalock held to post an RQE to the SLI4
2478  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2479  * the hbq_buffer_list and return zero, otherwise it will return an error.
2480  **/
2481 static int
2482 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2483 			    struct hbq_dmabuf *hbq_buf)
2484 {
2485 	int rc;
2486 	struct lpfc_rqe hrqe;
2487 	struct lpfc_rqe drqe;
2488 	struct lpfc_queue *hrq;
2489 	struct lpfc_queue *drq;
2490 
2491 	if (hbqno != LPFC_ELS_HBQ)
2492 		return 1;
2493 	hrq = phba->sli4_hba.hdr_rq;
2494 	drq = phba->sli4_hba.dat_rq;
2495 
2496 	lockdep_assert_held(&phba->hbalock);
2497 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2498 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2499 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2500 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2501 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2502 	if (rc < 0)
2503 		return rc;
2504 	hbq_buf->tag = (rc | (hbqno << 16));
2505 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2506 	return 0;
2507 }
2508 
2509 /* HBQ for ELS and CT traffic. */
2510 static struct lpfc_hbq_init lpfc_els_hbq = {
2511 	.rn = 1,
2512 	.entry_count = 256,
2513 	.mask_count = 0,
2514 	.profile = 0,
2515 	.ring_mask = (1 << LPFC_ELS_RING),
2516 	.buffer_count = 0,
2517 	.init_count = 40,
2518 	.add_count = 40,
2519 };
2520 
2521 /* Array of HBQs */
2522 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2523 	&lpfc_els_hbq,
2524 };
2525 
2526 /**
2527  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2528  * @phba: Pointer to HBA context object.
2529  * @hbqno: HBQ number.
2530  * @count: Number of HBQ buffers to be posted.
2531  *
2532  * This function is called with no lock held to post more hbq buffers to the
2533  * given HBQ. The function returns the number of HBQ buffers successfully
2534  * posted.
2535  **/
2536 static int
2537 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2538 {
2539 	uint32_t i, posted = 0;
2540 	unsigned long flags;
2541 	struct hbq_dmabuf *hbq_buffer;
2542 	LIST_HEAD(hbq_buf_list);
2543 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2544 		return 0;
2545 
2546 	if ((phba->hbqs[hbqno].buffer_count + count) >
2547 	    lpfc_hbq_defs[hbqno]->entry_count)
2548 		count = lpfc_hbq_defs[hbqno]->entry_count -
2549 					phba->hbqs[hbqno].buffer_count;
2550 	if (!count)
2551 		return 0;
2552 	/* Allocate HBQ entries */
2553 	for (i = 0; i < count; i++) {
2554 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2555 		if (!hbq_buffer)
2556 			break;
2557 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2558 	}
2559 	/* Check whether HBQ is still in use */
2560 	spin_lock_irqsave(&phba->hbalock, flags);
2561 	if (!phba->hbq_in_use)
2562 		goto err;
2563 	while (!list_empty(&hbq_buf_list)) {
2564 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2565 				 dbuf.list);
2566 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2567 				      (hbqno << 16));
2568 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2569 			phba->hbqs[hbqno].buffer_count++;
2570 			posted++;
2571 		} else
2572 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2573 	}
2574 	spin_unlock_irqrestore(&phba->hbalock, flags);
2575 	return posted;
2576 err:
2577 	spin_unlock_irqrestore(&phba->hbalock, flags);
2578 	while (!list_empty(&hbq_buf_list)) {
2579 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2580 				 dbuf.list);
2581 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2582 	}
2583 	return 0;
2584 }
2585 
2586 /**
2587  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2588  * @phba: Pointer to HBA context object.
2589  * @qno: HBQ number.
2590  *
2591  * This function posts more buffers to the HBQ. This function
2592  * is called with no lock held. The function returns the number of HBQ entries
2593  * successfully allocated.
2594  **/
2595 int
2596 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2597 {
2598 	if (phba->sli_rev == LPFC_SLI_REV4)
2599 		return 0;
2600 	else
2601 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2602 					 lpfc_hbq_defs[qno]->add_count);
2603 }
2604 
2605 /**
2606  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2607  * @phba: Pointer to HBA context object.
2608  * @qno:  HBQ queue number.
2609  *
2610  * This function is called from SLI initialization code path with
2611  * no lock held to post initial HBQ buffers to firmware. The
2612  * function returns the number of HBQ entries successfully allocated.
2613  **/
2614 static int
2615 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2616 {
2617 	if (phba->sli_rev == LPFC_SLI_REV4)
2618 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2619 					lpfc_hbq_defs[qno]->entry_count);
2620 	else
2621 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2622 					 lpfc_hbq_defs[qno]->init_count);
2623 }
2624 
2625 /*
2626  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2627  *
2628  * This function removes the first hbq buffer on an hbq list and returns a
2629  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2630  **/
2631 static struct hbq_dmabuf *
2632 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2633 {
2634 	struct lpfc_dmabuf *d_buf;
2635 
2636 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2637 	if (!d_buf)
2638 		return NULL;
2639 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2640 }
2641 
2642 /**
2643  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2644  * @phba: Pointer to HBA context object.
2645  * @hrq: HBQ number.
2646  *
2647  * This function removes the first RQ buffer on an RQ buffer list and returns a
2648  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2649  **/
2650 static struct rqb_dmabuf *
2651 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2652 {
2653 	struct lpfc_dmabuf *h_buf;
2654 	struct lpfc_rqb *rqbp;
2655 
2656 	rqbp = hrq->rqbp;
2657 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2658 			 struct lpfc_dmabuf, list);
2659 	if (!h_buf)
2660 		return NULL;
2661 	rqbp->buffer_count--;
2662 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2663 }
2664 
2665 /**
2666  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2667  * @phba: Pointer to HBA context object.
2668  * @tag: Tag of the hbq buffer.
2669  *
2670  * This function searches for the hbq buffer associated with the given tag in
2671  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2672  * otherwise it returns NULL.
2673  **/
2674 static struct hbq_dmabuf *
2675 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2676 {
2677 	struct lpfc_dmabuf *d_buf;
2678 	struct hbq_dmabuf *hbq_buf;
2679 	uint32_t hbqno;
2680 
2681 	hbqno = tag >> 16;
2682 	if (hbqno >= LPFC_MAX_HBQS)
2683 		return NULL;
2684 
2685 	spin_lock_irq(&phba->hbalock);
2686 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2687 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2688 		if (hbq_buf->tag == tag) {
2689 			spin_unlock_irq(&phba->hbalock);
2690 			return hbq_buf;
2691 		}
2692 	}
2693 	spin_unlock_irq(&phba->hbalock);
2694 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2695 			"1803 Bad hbq tag. Data: x%x x%x\n",
2696 			tag, phba->hbqs[tag >> 16].buffer_count);
2697 	return NULL;
2698 }
2699 
2700 /**
2701  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2702  * @phba: Pointer to HBA context object.
2703  * @hbq_buffer: Pointer to HBQ buffer.
2704  *
2705  * This function is called with hbalock. This function gives back
2706  * the hbq buffer to firmware. If the HBQ does not have space to
2707  * post the buffer, it will free the buffer.
2708  **/
2709 void
2710 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2711 {
2712 	uint32_t hbqno;
2713 
2714 	if (hbq_buffer) {
2715 		hbqno = hbq_buffer->tag >> 16;
2716 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2717 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2718 	}
2719 }
2720 
2721 /**
2722  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2723  * @mbxCommand: mailbox command code.
2724  *
2725  * This function is called by the mailbox event handler function to verify
2726  * that the completed mailbox command is a legitimate mailbox command. If the
2727  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2728  * and the mailbox event handler will take the HBA offline.
2729  **/
2730 static int
2731 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2732 {
2733 	uint8_t ret;
2734 
2735 	switch (mbxCommand) {
2736 	case MBX_LOAD_SM:
2737 	case MBX_READ_NV:
2738 	case MBX_WRITE_NV:
2739 	case MBX_WRITE_VPARMS:
2740 	case MBX_RUN_BIU_DIAG:
2741 	case MBX_INIT_LINK:
2742 	case MBX_DOWN_LINK:
2743 	case MBX_CONFIG_LINK:
2744 	case MBX_CONFIG_RING:
2745 	case MBX_RESET_RING:
2746 	case MBX_READ_CONFIG:
2747 	case MBX_READ_RCONFIG:
2748 	case MBX_READ_SPARM:
2749 	case MBX_READ_STATUS:
2750 	case MBX_READ_RPI:
2751 	case MBX_READ_XRI:
2752 	case MBX_READ_REV:
2753 	case MBX_READ_LNK_STAT:
2754 	case MBX_REG_LOGIN:
2755 	case MBX_UNREG_LOGIN:
2756 	case MBX_CLEAR_LA:
2757 	case MBX_DUMP_MEMORY:
2758 	case MBX_DUMP_CONTEXT:
2759 	case MBX_RUN_DIAGS:
2760 	case MBX_RESTART:
2761 	case MBX_UPDATE_CFG:
2762 	case MBX_DOWN_LOAD:
2763 	case MBX_DEL_LD_ENTRY:
2764 	case MBX_RUN_PROGRAM:
2765 	case MBX_SET_MASK:
2766 	case MBX_SET_VARIABLE:
2767 	case MBX_UNREG_D_ID:
2768 	case MBX_KILL_BOARD:
2769 	case MBX_CONFIG_FARP:
2770 	case MBX_BEACON:
2771 	case MBX_LOAD_AREA:
2772 	case MBX_RUN_BIU_DIAG64:
2773 	case MBX_CONFIG_PORT:
2774 	case MBX_READ_SPARM64:
2775 	case MBX_READ_RPI64:
2776 	case MBX_REG_LOGIN64:
2777 	case MBX_READ_TOPOLOGY:
2778 	case MBX_WRITE_WWN:
2779 	case MBX_SET_DEBUG:
2780 	case MBX_LOAD_EXP_ROM:
2781 	case MBX_ASYNCEVT_ENABLE:
2782 	case MBX_REG_VPI:
2783 	case MBX_UNREG_VPI:
2784 	case MBX_HEARTBEAT:
2785 	case MBX_PORT_CAPABILITIES:
2786 	case MBX_PORT_IOV_CONTROL:
2787 	case MBX_SLI4_CONFIG:
2788 	case MBX_SLI4_REQ_FTRS:
2789 	case MBX_REG_FCFI:
2790 	case MBX_UNREG_FCFI:
2791 	case MBX_REG_VFI:
2792 	case MBX_UNREG_VFI:
2793 	case MBX_INIT_VPI:
2794 	case MBX_INIT_VFI:
2795 	case MBX_RESUME_RPI:
2796 	case MBX_READ_EVENT_LOG_STATUS:
2797 	case MBX_READ_EVENT_LOG:
2798 	case MBX_SECURITY_MGMT:
2799 	case MBX_AUTH_PORT:
2800 	case MBX_ACCESS_VDATA:
2801 		ret = mbxCommand;
2802 		break;
2803 	default:
2804 		ret = MBX_SHUTDOWN;
2805 		break;
2806 	}
2807 	return ret;
2808 }
2809 
2810 /**
2811  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2812  * @phba: Pointer to HBA context object.
2813  * @pmboxq: Pointer to mailbox command.
2814  *
2815  * This is completion handler function for mailbox commands issued from
2816  * lpfc_sli_issue_mbox_wait function. This function is called by the
2817  * mailbox event handler function with no lock held. This function
2818  * will wake up thread waiting on the wait queue pointed by context1
2819  * of the mailbox.
2820  **/
2821 void
2822 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2823 {
2824 	unsigned long drvr_flag;
2825 	struct completion *pmbox_done;
2826 
2827 	/*
2828 	 * If pmbox_done is empty, the driver thread gave up waiting and
2829 	 * continued running.
2830 	 */
2831 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2832 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2833 	pmbox_done = (struct completion *)pmboxq->context3;
2834 	if (pmbox_done)
2835 		complete(pmbox_done);
2836 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2837 	return;
2838 }
2839 
2840 static void
2841 __lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2842 {
2843 	unsigned long iflags;
2844 
2845 	if (ndlp->nlp_flag & NLP_RELEASE_RPI) {
2846 		lpfc_sli4_free_rpi(vport->phba, ndlp->nlp_rpi);
2847 		spin_lock_irqsave(&ndlp->lock, iflags);
2848 		ndlp->nlp_flag &= ~NLP_RELEASE_RPI;
2849 		ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
2850 		spin_unlock_irqrestore(&ndlp->lock, iflags);
2851 	}
2852 	ndlp->nlp_flag &= ~NLP_UNREG_INP;
2853 }
2854 
2855 void
2856 lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2857 {
2858 	__lpfc_sli_rpi_release(vport, ndlp);
2859 }
2860 
2861 /**
2862  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2863  * @phba: Pointer to HBA context object.
2864  * @pmb: Pointer to mailbox object.
2865  *
2866  * This function is the default mailbox completion handler. It
2867  * frees the memory resources associated with the completed mailbox
2868  * command. If the completed command is a REG_LOGIN mailbox command,
2869  * this function will issue a UREG_LOGIN to re-claim the RPI.
2870  **/
2871 void
2872 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2873 {
2874 	struct lpfc_vport  *vport = pmb->vport;
2875 	struct lpfc_dmabuf *mp;
2876 	struct lpfc_nodelist *ndlp;
2877 	struct Scsi_Host *shost;
2878 	uint16_t rpi, vpi;
2879 	int rc;
2880 
2881 	/*
2882 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2883 	 * is in re-discovery driver need to cleanup the RPI.
2884 	 */
2885 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2886 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2887 	    !pmb->u.mb.mbxStatus) {
2888 		mp = (struct lpfc_dmabuf *)pmb->ctx_buf;
2889 		if (mp) {
2890 			pmb->ctx_buf = NULL;
2891 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
2892 			kfree(mp);
2893 		}
2894 		rpi = pmb->u.mb.un.varWords[0];
2895 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2896 		if (phba->sli_rev == LPFC_SLI_REV4)
2897 			vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2898 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2899 		pmb->vport = vport;
2900 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2901 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2902 		if (rc != MBX_NOT_FINISHED)
2903 			return;
2904 	}
2905 
2906 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2907 		!(phba->pport->load_flag & FC_UNLOADING) &&
2908 		!pmb->u.mb.mbxStatus) {
2909 		shost = lpfc_shost_from_vport(vport);
2910 		spin_lock_irq(shost->host_lock);
2911 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2912 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2913 		spin_unlock_irq(shost->host_lock);
2914 	}
2915 
2916 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2917 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2918 		lpfc_nlp_put(ndlp);
2919 	}
2920 
2921 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2922 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2923 
2924 		/* Check to see if there are any deferred events to process */
2925 		if (ndlp) {
2926 			lpfc_printf_vlog(
2927 				vport,
2928 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2929 				"1438 UNREG cmpl deferred mbox x%x "
2930 				"on NPort x%x Data: x%x x%x x%px x%x x%x\n",
2931 				ndlp->nlp_rpi, ndlp->nlp_DID,
2932 				ndlp->nlp_flag, ndlp->nlp_defer_did,
2933 				ndlp, vport->load_flag, kref_read(&ndlp->kref));
2934 
2935 			if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2936 			    (ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING)) {
2937 				ndlp->nlp_flag &= ~NLP_UNREG_INP;
2938 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2939 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2940 			} else {
2941 				__lpfc_sli_rpi_release(vport, ndlp);
2942 			}
2943 
2944 			/* The unreg_login mailbox is complete and had a
2945 			 * reference that has to be released.  The PLOGI
2946 			 * got its own ref.
2947 			 */
2948 			lpfc_nlp_put(ndlp);
2949 			pmb->ctx_ndlp = NULL;
2950 		}
2951 	}
2952 
2953 	/* This nlp_put pairs with lpfc_sli4_resume_rpi */
2954 	if (pmb->u.mb.mbxCommand == MBX_RESUME_RPI) {
2955 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2956 		lpfc_nlp_put(ndlp);
2957 	}
2958 
2959 	/* Check security permission status on INIT_LINK mailbox command */
2960 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2961 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2962 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2963 				"2860 SLI authentication is required "
2964 				"for INIT_LINK but has not done yet\n");
2965 
2966 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2967 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2968 	else
2969 		lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2970 }
2971  /**
2972  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2973  * @phba: Pointer to HBA context object.
2974  * @pmb: Pointer to mailbox object.
2975  *
2976  * This function is the unreg rpi mailbox completion handler. It
2977  * frees the memory resources associated with the completed mailbox
2978  * command. An additional reference is put on the ndlp to prevent
2979  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2980  * the unreg mailbox command completes, this routine puts the
2981  * reference back.
2982  *
2983  **/
2984 void
2985 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2986 {
2987 	struct lpfc_vport  *vport = pmb->vport;
2988 	struct lpfc_nodelist *ndlp;
2989 
2990 	ndlp = pmb->ctx_ndlp;
2991 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2992 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2993 		    (bf_get(lpfc_sli_intf_if_type,
2994 		     &phba->sli4_hba.sli_intf) >=
2995 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2996 			if (ndlp) {
2997 				lpfc_printf_vlog(
2998 					 vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2999 					 "0010 UNREG_LOGIN vpi:%x "
3000 					 "rpi:%x DID:%x defer x%x flg x%x "
3001 					 "x%px\n",
3002 					 vport->vpi, ndlp->nlp_rpi,
3003 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
3004 					 ndlp->nlp_flag,
3005 					 ndlp);
3006 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
3007 
3008 				/* Check to see if there are any deferred
3009 				 * events to process
3010 				 */
3011 				if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
3012 				    (ndlp->nlp_defer_did !=
3013 				    NLP_EVT_NOTHING_PENDING)) {
3014 					lpfc_printf_vlog(
3015 						vport, KERN_INFO, LOG_DISCOVERY,
3016 						"4111 UNREG cmpl deferred "
3017 						"clr x%x on "
3018 						"NPort x%x Data: x%x x%px\n",
3019 						ndlp->nlp_rpi, ndlp->nlp_DID,
3020 						ndlp->nlp_defer_did, ndlp);
3021 					ndlp->nlp_flag &= ~NLP_UNREG_INP;
3022 					ndlp->nlp_defer_did =
3023 						NLP_EVT_NOTHING_PENDING;
3024 					lpfc_issue_els_plogi(
3025 						vport, ndlp->nlp_DID, 0);
3026 				} else {
3027 					__lpfc_sli_rpi_release(vport, ndlp);
3028 				}
3029 				lpfc_nlp_put(ndlp);
3030 			}
3031 		}
3032 	}
3033 
3034 	mempool_free(pmb, phba->mbox_mem_pool);
3035 }
3036 
3037 /**
3038  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
3039  * @phba: Pointer to HBA context object.
3040  *
3041  * This function is called with no lock held. This function processes all
3042  * the completed mailbox commands and gives it to upper layers. The interrupt
3043  * service routine processes mailbox completion interrupt and adds completed
3044  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
3045  * Worker thread call lpfc_sli_handle_mb_event, which will return the
3046  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
3047  * function returns the mailbox commands to the upper layer by calling the
3048  * completion handler function of each mailbox.
3049  **/
3050 int
3051 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
3052 {
3053 	MAILBOX_t *pmbox;
3054 	LPFC_MBOXQ_t *pmb;
3055 	int rc;
3056 	LIST_HEAD(cmplq);
3057 
3058 	phba->sli.slistat.mbox_event++;
3059 
3060 	/* Get all completed mailboxe buffers into the cmplq */
3061 	spin_lock_irq(&phba->hbalock);
3062 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
3063 	spin_unlock_irq(&phba->hbalock);
3064 
3065 	/* Get a Mailbox buffer to setup mailbox commands for callback */
3066 	do {
3067 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
3068 		if (pmb == NULL)
3069 			break;
3070 
3071 		pmbox = &pmb->u.mb;
3072 
3073 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
3074 			if (pmb->vport) {
3075 				lpfc_debugfs_disc_trc(pmb->vport,
3076 					LPFC_DISC_TRC_MBOX_VPORT,
3077 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
3078 					(uint32_t)pmbox->mbxCommand,
3079 					pmbox->un.varWords[0],
3080 					pmbox->un.varWords[1]);
3081 			}
3082 			else {
3083 				lpfc_debugfs_disc_trc(phba->pport,
3084 					LPFC_DISC_TRC_MBOX,
3085 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
3086 					(uint32_t)pmbox->mbxCommand,
3087 					pmbox->un.varWords[0],
3088 					pmbox->un.varWords[1]);
3089 			}
3090 		}
3091 
3092 		/*
3093 		 * It is a fatal error if unknown mbox command completion.
3094 		 */
3095 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
3096 		    MBX_SHUTDOWN) {
3097 			/* Unknown mailbox command compl */
3098 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3099 					"(%d):0323 Unknown Mailbox command "
3100 					"x%x (x%x/x%x) Cmpl\n",
3101 					pmb->vport ? pmb->vport->vpi :
3102 					LPFC_VPORT_UNKNOWN,
3103 					pmbox->mbxCommand,
3104 					lpfc_sli_config_mbox_subsys_get(phba,
3105 									pmb),
3106 					lpfc_sli_config_mbox_opcode_get(phba,
3107 									pmb));
3108 			phba->link_state = LPFC_HBA_ERROR;
3109 			phba->work_hs = HS_FFER3;
3110 			lpfc_handle_eratt(phba);
3111 			continue;
3112 		}
3113 
3114 		if (pmbox->mbxStatus) {
3115 			phba->sli.slistat.mbox_stat_err++;
3116 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
3117 				/* Mbox cmd cmpl error - RETRYing */
3118 				lpfc_printf_log(phba, KERN_INFO,
3119 					LOG_MBOX | LOG_SLI,
3120 					"(%d):0305 Mbox cmd cmpl "
3121 					"error - RETRYing Data: x%x "
3122 					"(x%x/x%x) x%x x%x x%x\n",
3123 					pmb->vport ? pmb->vport->vpi :
3124 					LPFC_VPORT_UNKNOWN,
3125 					pmbox->mbxCommand,
3126 					lpfc_sli_config_mbox_subsys_get(phba,
3127 									pmb),
3128 					lpfc_sli_config_mbox_opcode_get(phba,
3129 									pmb),
3130 					pmbox->mbxStatus,
3131 					pmbox->un.varWords[0],
3132 					pmb->vport ? pmb->vport->port_state :
3133 					LPFC_VPORT_UNKNOWN);
3134 				pmbox->mbxStatus = 0;
3135 				pmbox->mbxOwner = OWN_HOST;
3136 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3137 				if (rc != MBX_NOT_FINISHED)
3138 					continue;
3139 			}
3140 		}
3141 
3142 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
3143 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
3144 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
3145 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
3146 				"x%x x%x x%x\n",
3147 				pmb->vport ? pmb->vport->vpi : 0,
3148 				pmbox->mbxCommand,
3149 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
3150 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
3151 				pmb->mbox_cmpl,
3152 				*((uint32_t *) pmbox),
3153 				pmbox->un.varWords[0],
3154 				pmbox->un.varWords[1],
3155 				pmbox->un.varWords[2],
3156 				pmbox->un.varWords[3],
3157 				pmbox->un.varWords[4],
3158 				pmbox->un.varWords[5],
3159 				pmbox->un.varWords[6],
3160 				pmbox->un.varWords[7],
3161 				pmbox->un.varWords[8],
3162 				pmbox->un.varWords[9],
3163 				pmbox->un.varWords[10]);
3164 
3165 		if (pmb->mbox_cmpl)
3166 			pmb->mbox_cmpl(phba,pmb);
3167 	} while (1);
3168 	return 0;
3169 }
3170 
3171 /**
3172  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
3173  * @phba: Pointer to HBA context object.
3174  * @pring: Pointer to driver SLI ring object.
3175  * @tag: buffer tag.
3176  *
3177  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
3178  * is set in the tag the buffer is posted for a particular exchange,
3179  * the function will return the buffer without replacing the buffer.
3180  * If the buffer is for unsolicited ELS or CT traffic, this function
3181  * returns the buffer and also posts another buffer to the firmware.
3182  **/
3183 static struct lpfc_dmabuf *
3184 lpfc_sli_get_buff(struct lpfc_hba *phba,
3185 		  struct lpfc_sli_ring *pring,
3186 		  uint32_t tag)
3187 {
3188 	struct hbq_dmabuf *hbq_entry;
3189 
3190 	if (tag & QUE_BUFTAG_BIT)
3191 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
3192 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
3193 	if (!hbq_entry)
3194 		return NULL;
3195 	return &hbq_entry->dbuf;
3196 }
3197 
3198 /**
3199  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
3200  *                              containing a NVME LS request.
3201  * @phba: pointer to lpfc hba data structure.
3202  * @piocb: pointer to the iocbq struct representing the sequence starting
3203  *        frame.
3204  *
3205  * This routine initially validates the NVME LS, validates there is a login
3206  * with the port that sent the LS, and then calls the appropriate nvme host
3207  * or target LS request handler.
3208  **/
3209 static void
3210 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
3211 {
3212 	struct lpfc_nodelist *ndlp;
3213 	struct lpfc_dmabuf *d_buf;
3214 	struct hbq_dmabuf *nvmebuf;
3215 	struct fc_frame_header *fc_hdr;
3216 	struct lpfc_async_xchg_ctx *axchg = NULL;
3217 	char *failwhy = NULL;
3218 	uint32_t oxid, sid, did, fctl, size;
3219 	int ret = 1;
3220 
3221 	d_buf = piocb->cmd_dmabuf;
3222 
3223 	nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
3224 	fc_hdr = nvmebuf->hbuf.virt;
3225 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
3226 	sid = sli4_sid_from_fc_hdr(fc_hdr);
3227 	did = sli4_did_from_fc_hdr(fc_hdr);
3228 	fctl = (fc_hdr->fh_f_ctl[0] << 16 |
3229 		fc_hdr->fh_f_ctl[1] << 8 |
3230 		fc_hdr->fh_f_ctl[2]);
3231 	size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
3232 
3233 	lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
3234 			 oxid, size, sid);
3235 
3236 	if (phba->pport->load_flag & FC_UNLOADING) {
3237 		failwhy = "Driver Unloading";
3238 	} else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
3239 		failwhy = "NVME FC4 Disabled";
3240 	} else if (!phba->nvmet_support && !phba->pport->localport) {
3241 		failwhy = "No Localport";
3242 	} else if (phba->nvmet_support && !phba->targetport) {
3243 		failwhy = "No Targetport";
3244 	} else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
3245 		failwhy = "Bad NVME LS R_CTL";
3246 	} else if (unlikely((fctl & 0x00FF0000) !=
3247 			(FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
3248 		failwhy = "Bad NVME LS F_CTL";
3249 	} else {
3250 		axchg = kzalloc(sizeof(*axchg), GFP_ATOMIC);
3251 		if (!axchg)
3252 			failwhy = "No CTX memory";
3253 	}
3254 
3255 	if (unlikely(failwhy)) {
3256 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3257 				"6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
3258 				sid, oxid, failwhy);
3259 		goto out_fail;
3260 	}
3261 
3262 	/* validate the source of the LS is logged in */
3263 	ndlp = lpfc_findnode_did(phba->pport, sid);
3264 	if (!ndlp ||
3265 	    ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
3266 	     (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
3267 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
3268 				"6216 NVME Unsol rcv: No ndlp: "
3269 				"NPort_ID x%x oxid x%x\n",
3270 				sid, oxid);
3271 		goto out_fail;
3272 	}
3273 
3274 	axchg->phba = phba;
3275 	axchg->ndlp = ndlp;
3276 	axchg->size = size;
3277 	axchg->oxid = oxid;
3278 	axchg->sid = sid;
3279 	axchg->wqeq = NULL;
3280 	axchg->state = LPFC_NVME_STE_LS_RCV;
3281 	axchg->entry_cnt = 1;
3282 	axchg->rqb_buffer = (void *)nvmebuf;
3283 	axchg->hdwq = &phba->sli4_hba.hdwq[0];
3284 	axchg->payload = nvmebuf->dbuf.virt;
3285 	INIT_LIST_HEAD(&axchg->list);
3286 
3287 	if (phba->nvmet_support) {
3288 		ret = lpfc_nvmet_handle_lsreq(phba, axchg);
3289 		spin_lock_irq(&ndlp->lock);
3290 		if (!ret && !(ndlp->fc4_xpt_flags & NLP_XPT_HAS_HH)) {
3291 			ndlp->fc4_xpt_flags |= NLP_XPT_HAS_HH;
3292 			spin_unlock_irq(&ndlp->lock);
3293 
3294 			/* This reference is a single occurrence to hold the
3295 			 * node valid until the nvmet transport calls
3296 			 * host_release.
3297 			 */
3298 			if (!lpfc_nlp_get(ndlp))
3299 				goto out_fail;
3300 
3301 			lpfc_printf_log(phba, KERN_ERR, LOG_NODE,
3302 					"6206 NVMET unsol ls_req ndlp x%px "
3303 					"DID x%x xflags x%x refcnt %d\n",
3304 					ndlp, ndlp->nlp_DID,
3305 					ndlp->fc4_xpt_flags,
3306 					kref_read(&ndlp->kref));
3307 		} else {
3308 			spin_unlock_irq(&ndlp->lock);
3309 		}
3310 	} else {
3311 		ret = lpfc_nvme_handle_lsreq(phba, axchg);
3312 	}
3313 
3314 	/* if zero, LS was successfully handled. If non-zero, LS not handled */
3315 	if (!ret)
3316 		return;
3317 
3318 out_fail:
3319 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3320 			"6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
3321 			"NVMe%s handler failed %d\n",
3322 			did, sid, oxid,
3323 			(phba->nvmet_support) ? "T" : "I", ret);
3324 
3325 	/* recycle receive buffer */
3326 	lpfc_in_buf_free(phba, &nvmebuf->dbuf);
3327 
3328 	/* If start of new exchange, abort it */
3329 	if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
3330 		ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
3331 
3332 	if (ret)
3333 		kfree(axchg);
3334 }
3335 
3336 /**
3337  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
3338  * @phba: Pointer to HBA context object.
3339  * @pring: Pointer to driver SLI ring object.
3340  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
3341  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
3342  * @fch_type: the type for the first frame of the sequence.
3343  *
3344  * This function is called with no lock held. This function uses the r_ctl and
3345  * type of the received sequence to find the correct callback function to call
3346  * to process the sequence.
3347  **/
3348 static int
3349 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3350 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
3351 			 uint32_t fch_type)
3352 {
3353 	int i;
3354 
3355 	switch (fch_type) {
3356 	case FC_TYPE_NVME:
3357 		lpfc_nvme_unsol_ls_handler(phba, saveq);
3358 		return 1;
3359 	default:
3360 		break;
3361 	}
3362 
3363 	/* unSolicited Responses */
3364 	if (pring->prt[0].profile) {
3365 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
3366 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
3367 									saveq);
3368 		return 1;
3369 	}
3370 	/* We must search, based on rctl / type
3371 	   for the right routine */
3372 	for (i = 0; i < pring->num_mask; i++) {
3373 		if ((pring->prt[i].rctl == fch_r_ctl) &&
3374 		    (pring->prt[i].type == fch_type)) {
3375 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
3376 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
3377 						(phba, pring, saveq);
3378 			return 1;
3379 		}
3380 	}
3381 	return 0;
3382 }
3383 
3384 static void
3385 lpfc_sli_prep_unsol_wqe(struct lpfc_hba *phba,
3386 			struct lpfc_iocbq *saveq)
3387 {
3388 	IOCB_t *irsp;
3389 	union lpfc_wqe128 *wqe;
3390 	u16 i = 0;
3391 
3392 	irsp = &saveq->iocb;
3393 	wqe = &saveq->wqe;
3394 
3395 	/* Fill wcqe with the IOCB status fields */
3396 	bf_set(lpfc_wcqe_c_status, &saveq->wcqe_cmpl, irsp->ulpStatus);
3397 	saveq->wcqe_cmpl.word3 = irsp->ulpBdeCount;
3398 	saveq->wcqe_cmpl.parameter = irsp->un.ulpWord[4];
3399 	saveq->wcqe_cmpl.total_data_placed = irsp->unsli3.rcvsli3.acc_len;
3400 
3401 	/* Source ID */
3402 	bf_set(els_rsp64_sid, &wqe->xmit_els_rsp, irsp->un.rcvels.parmRo);
3403 
3404 	/* rx-id of the response frame */
3405 	bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com, irsp->ulpContext);
3406 
3407 	/* ox-id of the frame */
3408 	bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
3409 	       irsp->unsli3.rcvsli3.ox_id);
3410 
3411 	/* DID */
3412 	bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
3413 	       irsp->un.rcvels.remoteID);
3414 
3415 	/* unsol data len */
3416 	for (i = 0; i < irsp->ulpBdeCount; i++) {
3417 		struct lpfc_hbq_entry *hbqe = NULL;
3418 
3419 		if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3420 			if (i == 0) {
3421 				hbqe = (struct lpfc_hbq_entry *)
3422 					&irsp->un.ulpWord[0];
3423 				saveq->wqe.gen_req.bde.tus.f.bdeSize =
3424 					hbqe->bde.tus.f.bdeSize;
3425 			} else if (i == 1) {
3426 				hbqe = (struct lpfc_hbq_entry *)
3427 					&irsp->unsli3.sli3Words[4];
3428 				saveq->unsol_rcv_len = hbqe->bde.tus.f.bdeSize;
3429 			}
3430 		}
3431 	}
3432 }
3433 
3434 /**
3435  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
3436  * @phba: Pointer to HBA context object.
3437  * @pring: Pointer to driver SLI ring object.
3438  * @saveq: Pointer to the unsolicited iocb.
3439  *
3440  * This function is called with no lock held by the ring event handler
3441  * when there is an unsolicited iocb posted to the response ring by the
3442  * firmware. This function gets the buffer associated with the iocbs
3443  * and calls the event handler for the ring. This function handles both
3444  * qring buffers and hbq buffers.
3445  * When the function returns 1 the caller can free the iocb object otherwise
3446  * upper layer functions will free the iocb objects.
3447  **/
3448 static int
3449 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3450 			    struct lpfc_iocbq *saveq)
3451 {
3452 	IOCB_t           * irsp;
3453 	WORD5            * w5p;
3454 	dma_addr_t	 paddr;
3455 	uint32_t           Rctl, Type;
3456 	struct lpfc_iocbq *iocbq;
3457 	struct lpfc_dmabuf *dmzbuf;
3458 
3459 	irsp = &saveq->iocb;
3460 	saveq->vport = phba->pport;
3461 
3462 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
3463 		if (pring->lpfc_sli_rcv_async_status)
3464 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
3465 		else
3466 			lpfc_printf_log(phba,
3467 					KERN_WARNING,
3468 					LOG_SLI,
3469 					"0316 Ring %d handler: unexpected "
3470 					"ASYNC_STATUS iocb received evt_code "
3471 					"0x%x\n",
3472 					pring->ringno,
3473 					irsp->un.asyncstat.evt_code);
3474 		return 1;
3475 	}
3476 
3477 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3478 	    (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3479 		if (irsp->ulpBdeCount > 0) {
3480 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3481 						   irsp->un.ulpWord[3]);
3482 			lpfc_in_buf_free(phba, dmzbuf);
3483 		}
3484 
3485 		if (irsp->ulpBdeCount > 1) {
3486 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3487 						   irsp->unsli3.sli3Words[3]);
3488 			lpfc_in_buf_free(phba, dmzbuf);
3489 		}
3490 
3491 		if (irsp->ulpBdeCount > 2) {
3492 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3493 						   irsp->unsli3.sli3Words[7]);
3494 			lpfc_in_buf_free(phba, dmzbuf);
3495 		}
3496 
3497 		return 1;
3498 	}
3499 
3500 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3501 		if (irsp->ulpBdeCount != 0) {
3502 			saveq->cmd_dmabuf = lpfc_sli_get_buff(phba, pring,
3503 						irsp->un.ulpWord[3]);
3504 			if (!saveq->cmd_dmabuf)
3505 				lpfc_printf_log(phba,
3506 					KERN_ERR,
3507 					LOG_SLI,
3508 					"0341 Ring %d Cannot find buffer for "
3509 					"an unsolicited iocb. tag 0x%x\n",
3510 					pring->ringno,
3511 					irsp->un.ulpWord[3]);
3512 		}
3513 		if (irsp->ulpBdeCount == 2) {
3514 			saveq->bpl_dmabuf = lpfc_sli_get_buff(phba, pring,
3515 						irsp->unsli3.sli3Words[7]);
3516 			if (!saveq->bpl_dmabuf)
3517 				lpfc_printf_log(phba,
3518 					KERN_ERR,
3519 					LOG_SLI,
3520 					"0342 Ring %d Cannot find buffer for an"
3521 					" unsolicited iocb. tag 0x%x\n",
3522 					pring->ringno,
3523 					irsp->unsli3.sli3Words[7]);
3524 		}
3525 		list_for_each_entry(iocbq, &saveq->list, list) {
3526 			irsp = &iocbq->iocb;
3527 			if (irsp->ulpBdeCount != 0) {
3528 				iocbq->cmd_dmabuf = lpfc_sli_get_buff(phba,
3529 							pring,
3530 							irsp->un.ulpWord[3]);
3531 				if (!iocbq->cmd_dmabuf)
3532 					lpfc_printf_log(phba,
3533 						KERN_ERR,
3534 						LOG_SLI,
3535 						"0343 Ring %d Cannot find "
3536 						"buffer for an unsolicited iocb"
3537 						". tag 0x%x\n", pring->ringno,
3538 						irsp->un.ulpWord[3]);
3539 			}
3540 			if (irsp->ulpBdeCount == 2) {
3541 				iocbq->bpl_dmabuf = lpfc_sli_get_buff(phba,
3542 						pring,
3543 						irsp->unsli3.sli3Words[7]);
3544 				if (!iocbq->bpl_dmabuf)
3545 					lpfc_printf_log(phba,
3546 						KERN_ERR,
3547 						LOG_SLI,
3548 						"0344 Ring %d Cannot find "
3549 						"buffer for an unsolicited "
3550 						"iocb. tag 0x%x\n",
3551 						pring->ringno,
3552 						irsp->unsli3.sli3Words[7]);
3553 			}
3554 		}
3555 	} else {
3556 		paddr = getPaddr(irsp->un.cont64[0].addrHigh,
3557 				 irsp->un.cont64[0].addrLow);
3558 		saveq->cmd_dmabuf = lpfc_sli_ringpostbuf_get(phba, pring,
3559 							     paddr);
3560 		if (irsp->ulpBdeCount == 2) {
3561 			paddr = getPaddr(irsp->un.cont64[1].addrHigh,
3562 					 irsp->un.cont64[1].addrLow);
3563 			saveq->bpl_dmabuf = lpfc_sli_ringpostbuf_get(phba,
3564 								   pring,
3565 								   paddr);
3566 		}
3567 	}
3568 
3569 	if (irsp->ulpBdeCount != 0 &&
3570 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3571 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3572 		int found = 0;
3573 
3574 		/* search continue save q for same XRI */
3575 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3576 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3577 				saveq->iocb.unsli3.rcvsli3.ox_id) {
3578 				list_add_tail(&saveq->list, &iocbq->list);
3579 				found = 1;
3580 				break;
3581 			}
3582 		}
3583 		if (!found)
3584 			list_add_tail(&saveq->clist,
3585 				      &pring->iocb_continue_saveq);
3586 
3587 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3588 			list_del_init(&iocbq->clist);
3589 			saveq = iocbq;
3590 			irsp = &saveq->iocb;
3591 		} else {
3592 			return 0;
3593 		}
3594 	}
3595 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3596 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3597 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3598 		Rctl = FC_RCTL_ELS_REQ;
3599 		Type = FC_TYPE_ELS;
3600 	} else {
3601 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3602 		Rctl = w5p->hcsw.Rctl;
3603 		Type = w5p->hcsw.Type;
3604 
3605 		/* Firmware Workaround */
3606 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3607 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3608 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3609 			Rctl = FC_RCTL_ELS_REQ;
3610 			Type = FC_TYPE_ELS;
3611 			w5p->hcsw.Rctl = Rctl;
3612 			w5p->hcsw.Type = Type;
3613 		}
3614 	}
3615 
3616 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) &&
3617 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX ||
3618 	    irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3619 		if (irsp->unsli3.rcvsli3.vpi == 0xffff)
3620 			saveq->vport = phba->pport;
3621 		else
3622 			saveq->vport = lpfc_find_vport_by_vpid(phba,
3623 					       irsp->unsli3.rcvsli3.vpi);
3624 	}
3625 
3626 	/* Prepare WQE with Unsol frame */
3627 	lpfc_sli_prep_unsol_wqe(phba, saveq);
3628 
3629 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3630 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3631 				"0313 Ring %d handler: unexpected Rctl x%x "
3632 				"Type x%x received\n",
3633 				pring->ringno, Rctl, Type);
3634 
3635 	return 1;
3636 }
3637 
3638 /**
3639  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3640  * @phba: Pointer to HBA context object.
3641  * @pring: Pointer to driver SLI ring object.
3642  * @prspiocb: Pointer to response iocb object.
3643  *
3644  * This function looks up the iocb_lookup table to get the command iocb
3645  * corresponding to the given response iocb using the iotag of the
3646  * response iocb. The driver calls this function with the hbalock held
3647  * for SLI3 ports or the ring lock held for SLI4 ports.
3648  * This function returns the command iocb object if it finds the command
3649  * iocb else returns NULL.
3650  **/
3651 static struct lpfc_iocbq *
3652 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3653 		      struct lpfc_sli_ring *pring,
3654 		      struct lpfc_iocbq *prspiocb)
3655 {
3656 	struct lpfc_iocbq *cmd_iocb = NULL;
3657 	u16 iotag;
3658 
3659 	if (phba->sli_rev == LPFC_SLI_REV4)
3660 		iotag = get_wqe_reqtag(prspiocb);
3661 	else
3662 		iotag = prspiocb->iocb.ulpIoTag;
3663 
3664 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3665 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3666 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3667 			/* remove from txcmpl queue list */
3668 			list_del_init(&cmd_iocb->list);
3669 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3670 			pring->txcmplq_cnt--;
3671 			return cmd_iocb;
3672 		}
3673 	}
3674 
3675 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3676 			"0317 iotag x%x is out of "
3677 			"range: max iotag x%x\n",
3678 			iotag, phba->sli.last_iotag);
3679 	return NULL;
3680 }
3681 
3682 /**
3683  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3684  * @phba: Pointer to HBA context object.
3685  * @pring: Pointer to driver SLI ring object.
3686  * @iotag: IOCB tag.
3687  *
3688  * This function looks up the iocb_lookup table to get the command iocb
3689  * corresponding to the given iotag. The driver calls this function with
3690  * the ring lock held because this function is an SLI4 port only helper.
3691  * This function returns the command iocb object if it finds the command
3692  * iocb else returns NULL.
3693  **/
3694 static struct lpfc_iocbq *
3695 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3696 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3697 {
3698 	struct lpfc_iocbq *cmd_iocb = NULL;
3699 
3700 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3701 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3702 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3703 			/* remove from txcmpl queue list */
3704 			list_del_init(&cmd_iocb->list);
3705 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3706 			pring->txcmplq_cnt--;
3707 			return cmd_iocb;
3708 		}
3709 	}
3710 
3711 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3712 			"0372 iotag x%x lookup error: max iotag (x%x) "
3713 			"cmd_flag x%x\n",
3714 			iotag, phba->sli.last_iotag,
3715 			cmd_iocb ? cmd_iocb->cmd_flag : 0xffff);
3716 	return NULL;
3717 }
3718 
3719 /**
3720  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3721  * @phba: Pointer to HBA context object.
3722  * @pring: Pointer to driver SLI ring object.
3723  * @saveq: Pointer to the response iocb to be processed.
3724  *
3725  * This function is called by the ring event handler for non-fcp
3726  * rings when there is a new response iocb in the response ring.
3727  * The caller is not required to hold any locks. This function
3728  * gets the command iocb associated with the response iocb and
3729  * calls the completion handler for the command iocb. If there
3730  * is no completion handler, the function will free the resources
3731  * associated with command iocb. If the response iocb is for
3732  * an already aborted command iocb, the status of the completion
3733  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3734  * This function always returns 1.
3735  **/
3736 static int
3737 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3738 			  struct lpfc_iocbq *saveq)
3739 {
3740 	struct lpfc_iocbq *cmdiocbp;
3741 	unsigned long iflag;
3742 	u32 ulp_command, ulp_status, ulp_word4, ulp_context, iotag;
3743 
3744 	if (phba->sli_rev == LPFC_SLI_REV4)
3745 		spin_lock_irqsave(&pring->ring_lock, iflag);
3746 	else
3747 		spin_lock_irqsave(&phba->hbalock, iflag);
3748 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3749 	if (phba->sli_rev == LPFC_SLI_REV4)
3750 		spin_unlock_irqrestore(&pring->ring_lock, iflag);
3751 	else
3752 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3753 
3754 	ulp_command = get_job_cmnd(phba, saveq);
3755 	ulp_status = get_job_ulpstatus(phba, saveq);
3756 	ulp_word4 = get_job_word4(phba, saveq);
3757 	ulp_context = get_job_ulpcontext(phba, saveq);
3758 	if (phba->sli_rev == LPFC_SLI_REV4)
3759 		iotag = get_wqe_reqtag(saveq);
3760 	else
3761 		iotag = saveq->iocb.ulpIoTag;
3762 
3763 	if (cmdiocbp) {
3764 		ulp_command = get_job_cmnd(phba, cmdiocbp);
3765 		if (cmdiocbp->cmd_cmpl) {
3766 			/*
3767 			 * If an ELS command failed send an event to mgmt
3768 			 * application.
3769 			 */
3770 			if (ulp_status &&
3771 			     (pring->ringno == LPFC_ELS_RING) &&
3772 			     (ulp_command == CMD_ELS_REQUEST64_CR))
3773 				lpfc_send_els_failure_event(phba,
3774 					cmdiocbp, saveq);
3775 
3776 			/*
3777 			 * Post all ELS completions to the worker thread.
3778 			 * All other are passed to the completion callback.
3779 			 */
3780 			if (pring->ringno == LPFC_ELS_RING) {
3781 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3782 				    (cmdiocbp->cmd_flag &
3783 							LPFC_DRIVER_ABORTED)) {
3784 					spin_lock_irqsave(&phba->hbalock,
3785 							  iflag);
3786 					cmdiocbp->cmd_flag &=
3787 						~LPFC_DRIVER_ABORTED;
3788 					spin_unlock_irqrestore(&phba->hbalock,
3789 							       iflag);
3790 					saveq->iocb.ulpStatus =
3791 						IOSTAT_LOCAL_REJECT;
3792 					saveq->iocb.un.ulpWord[4] =
3793 						IOERR_SLI_ABORTED;
3794 
3795 					/* Firmware could still be in progress
3796 					 * of DMAing payload, so don't free data
3797 					 * buffer till after a hbeat.
3798 					 */
3799 					spin_lock_irqsave(&phba->hbalock,
3800 							  iflag);
3801 					saveq->cmd_flag |= LPFC_DELAY_MEM_FREE;
3802 					spin_unlock_irqrestore(&phba->hbalock,
3803 							       iflag);
3804 				}
3805 				if (phba->sli_rev == LPFC_SLI_REV4) {
3806 					if (saveq->cmd_flag &
3807 					    LPFC_EXCHANGE_BUSY) {
3808 						/* Set cmdiocb flag for the
3809 						 * exchange busy so sgl (xri)
3810 						 * will not be released until
3811 						 * the abort xri is received
3812 						 * from hba.
3813 						 */
3814 						spin_lock_irqsave(
3815 							&phba->hbalock, iflag);
3816 						cmdiocbp->cmd_flag |=
3817 							LPFC_EXCHANGE_BUSY;
3818 						spin_unlock_irqrestore(
3819 							&phba->hbalock, iflag);
3820 					}
3821 					if (cmdiocbp->cmd_flag &
3822 					    LPFC_DRIVER_ABORTED) {
3823 						/*
3824 						 * Clear LPFC_DRIVER_ABORTED
3825 						 * bit in case it was driver
3826 						 * initiated abort.
3827 						 */
3828 						spin_lock_irqsave(
3829 							&phba->hbalock, iflag);
3830 						cmdiocbp->cmd_flag &=
3831 							~LPFC_DRIVER_ABORTED;
3832 						spin_unlock_irqrestore(
3833 							&phba->hbalock, iflag);
3834 						set_job_ulpstatus(cmdiocbp,
3835 								  IOSTAT_LOCAL_REJECT);
3836 						set_job_ulpword4(cmdiocbp,
3837 								 IOERR_ABORT_REQUESTED);
3838 						/*
3839 						 * For SLI4, irspiocb contains
3840 						 * NO_XRI in sli_xritag, it
3841 						 * shall not affect releasing
3842 						 * sgl (xri) process.
3843 						 */
3844 						set_job_ulpstatus(saveq,
3845 								  IOSTAT_LOCAL_REJECT);
3846 						set_job_ulpword4(saveq,
3847 								 IOERR_SLI_ABORTED);
3848 						spin_lock_irqsave(
3849 							&phba->hbalock, iflag);
3850 						saveq->cmd_flag |=
3851 							LPFC_DELAY_MEM_FREE;
3852 						spin_unlock_irqrestore(
3853 							&phba->hbalock, iflag);
3854 					}
3855 				}
3856 			}
3857 			cmdiocbp->cmd_cmpl(phba, cmdiocbp, saveq);
3858 		} else
3859 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3860 	} else {
3861 		/*
3862 		 * Unknown initiating command based on the response iotag.
3863 		 * This could be the case on the ELS ring because of
3864 		 * lpfc_els_abort().
3865 		 */
3866 		if (pring->ringno != LPFC_ELS_RING) {
3867 			/*
3868 			 * Ring <ringno> handler: unexpected completion IoTag
3869 			 * <IoTag>
3870 			 */
3871 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3872 					 "0322 Ring %d handler: "
3873 					 "unexpected completion IoTag x%x "
3874 					 "Data: x%x x%x x%x x%x\n",
3875 					 pring->ringno, iotag, ulp_status,
3876 					 ulp_word4, ulp_command, ulp_context);
3877 		}
3878 	}
3879 
3880 	return 1;
3881 }
3882 
3883 /**
3884  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3885  * @phba: Pointer to HBA context object.
3886  * @pring: Pointer to driver SLI ring object.
3887  *
3888  * This function is called from the iocb ring event handlers when
3889  * put pointer is ahead of the get pointer for a ring. This function signal
3890  * an error attention condition to the worker thread and the worker
3891  * thread will transition the HBA to offline state.
3892  **/
3893 static void
3894 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3895 {
3896 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3897 	/*
3898 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3899 	 * rsp ring <portRspMax>
3900 	 */
3901 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3902 			"0312 Ring %d handler: portRspPut %d "
3903 			"is bigger than rsp ring %d\n",
3904 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3905 			pring->sli.sli3.numRiocb);
3906 
3907 	phba->link_state = LPFC_HBA_ERROR;
3908 
3909 	/*
3910 	 * All error attention handlers are posted to
3911 	 * worker thread
3912 	 */
3913 	phba->work_ha |= HA_ERATT;
3914 	phba->work_hs = HS_FFER3;
3915 
3916 	lpfc_worker_wake_up(phba);
3917 
3918 	return;
3919 }
3920 
3921 /**
3922  * lpfc_poll_eratt - Error attention polling timer timeout handler
3923  * @t: Context to fetch pointer to address of HBA context object from.
3924  *
3925  * This function is invoked by the Error Attention polling timer when the
3926  * timer times out. It will check the SLI Error Attention register for
3927  * possible attention events. If so, it will post an Error Attention event
3928  * and wake up worker thread to process it. Otherwise, it will set up the
3929  * Error Attention polling timer for the next poll.
3930  **/
3931 void lpfc_poll_eratt(struct timer_list *t)
3932 {
3933 	struct lpfc_hba *phba;
3934 	uint32_t eratt = 0;
3935 	uint64_t sli_intr, cnt;
3936 
3937 	phba = from_timer(phba, t, eratt_poll);
3938 
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 
5208 	spin_lock_irq(&phba->hbalock);
5209 
5210 	psli = &phba->sli;
5211 
5212 	/* Restart HBA */
5213 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5214 			"0337 Restart HBA Data: x%x x%x\n",
5215 			(phba->pport) ? phba->pport->port_state : 0,
5216 			psli->sli_flag);
5217 
5218 	mb.word0 = 0;
5219 	mb.mbxCommand = MBX_RESTART;
5220 	mb.mbxHc = 1;
5221 
5222 	lpfc_reset_barrier(phba);
5223 
5224 	to_slim = phba->MBslimaddr;
5225 	writel(mb.word0, to_slim);
5226 	readl(to_slim); /* flush */
5227 
5228 	/* Only skip post after fc_ffinit is completed */
5229 	if (phba->pport && phba->pport->port_state)
5230 		mb.word0 = 1;	/* This is really setting up word1 */
5231 	else
5232 		mb.word0 = 0;	/* This is really setting up word1 */
5233 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
5234 	writel(mb.word0, to_slim);
5235 	readl(to_slim); /* flush */
5236 
5237 	lpfc_sli_brdreset(phba);
5238 	if (phba->pport)
5239 		phba->pport->stopped = 0;
5240 	phba->link_state = LPFC_INIT_START;
5241 	phba->hba_flag = 0;
5242 	spin_unlock_irq(&phba->hbalock);
5243 
5244 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5245 	psli->stats_start = ktime_get_seconds();
5246 
5247 	/* Give the INITFF and Post time to settle. */
5248 	mdelay(100);
5249 
5250 	lpfc_hba_down_post(phba);
5251 
5252 	return 0;
5253 }
5254 
5255 /**
5256  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
5257  * @phba: Pointer to HBA context object.
5258  *
5259  * This function is called in the SLI initialization code path to restart
5260  * a SLI4 HBA. The caller is not required to hold any lock.
5261  * At the end of the function, it calls lpfc_hba_down_post function to
5262  * free any pending commands.
5263  **/
5264 static int
5265 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
5266 {
5267 	struct lpfc_sli *psli = &phba->sli;
5268 	int rc;
5269 
5270 	/* Restart HBA */
5271 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5272 			"0296 Restart HBA Data: x%x x%x\n",
5273 			phba->pport->port_state, psli->sli_flag);
5274 
5275 	rc = lpfc_sli4_brdreset(phba);
5276 	if (rc) {
5277 		phba->link_state = LPFC_HBA_ERROR;
5278 		goto hba_down_queue;
5279 	}
5280 
5281 	spin_lock_irq(&phba->hbalock);
5282 	phba->pport->stopped = 0;
5283 	phba->link_state = LPFC_INIT_START;
5284 	phba->hba_flag = 0;
5285 	/* Preserve FA-PWWN expectation */
5286 	phba->sli4_hba.fawwpn_flag &= LPFC_FAWWPN_FABRIC;
5287 	spin_unlock_irq(&phba->hbalock);
5288 
5289 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5290 	psli->stats_start = ktime_get_seconds();
5291 
5292 hba_down_queue:
5293 	lpfc_hba_down_post(phba);
5294 	lpfc_sli4_queue_destroy(phba);
5295 
5296 	return rc;
5297 }
5298 
5299 /**
5300  * lpfc_sli_brdrestart - Wrapper func for restarting hba
5301  * @phba: Pointer to HBA context object.
5302  *
5303  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
5304  * API jump table function pointer from the lpfc_hba struct.
5305 **/
5306 int
5307 lpfc_sli_brdrestart(struct lpfc_hba *phba)
5308 {
5309 	return phba->lpfc_sli_brdrestart(phba);
5310 }
5311 
5312 /**
5313  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
5314  * @phba: Pointer to HBA context object.
5315  *
5316  * This function is called after a HBA restart to wait for successful
5317  * restart of the HBA. Successful restart of the HBA is indicated by
5318  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
5319  * iteration, the function will restart the HBA again. The function returns
5320  * zero if HBA successfully restarted else returns negative error code.
5321  **/
5322 int
5323 lpfc_sli_chipset_init(struct lpfc_hba *phba)
5324 {
5325 	uint32_t status, i = 0;
5326 
5327 	/* Read the HBA Host Status Register */
5328 	if (lpfc_readl(phba->HSregaddr, &status))
5329 		return -EIO;
5330 
5331 	/* Check status register to see what current state is */
5332 	i = 0;
5333 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
5334 
5335 		/* Check every 10ms for 10 retries, then every 100ms for 90
5336 		 * retries, then every 1 sec for 50 retires for a total of
5337 		 * ~60 seconds before reset the board again and check every
5338 		 * 1 sec for 50 retries. The up to 60 seconds before the
5339 		 * board ready is required by the Falcon FIPS zeroization
5340 		 * complete, and any reset the board in between shall cause
5341 		 * restart of zeroization, further delay the board ready.
5342 		 */
5343 		if (i++ >= 200) {
5344 			/* Adapter failed to init, timeout, status reg
5345 			   <status> */
5346 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5347 					"0436 Adapter failed to init, "
5348 					"timeout, status reg x%x, "
5349 					"FW Data: A8 x%x AC x%x\n", status,
5350 					readl(phba->MBslimaddr + 0xa8),
5351 					readl(phba->MBslimaddr + 0xac));
5352 			phba->link_state = LPFC_HBA_ERROR;
5353 			return -ETIMEDOUT;
5354 		}
5355 
5356 		/* Check to see if any errors occurred during init */
5357 		if (status & HS_FFERM) {
5358 			/* ERROR: During chipset initialization */
5359 			/* Adapter failed to init, chipset, status reg
5360 			   <status> */
5361 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5362 					"0437 Adapter failed to init, "
5363 					"chipset, status reg x%x, "
5364 					"FW Data: A8 x%x AC x%x\n", status,
5365 					readl(phba->MBslimaddr + 0xa8),
5366 					readl(phba->MBslimaddr + 0xac));
5367 			phba->link_state = LPFC_HBA_ERROR;
5368 			return -EIO;
5369 		}
5370 
5371 		if (i <= 10)
5372 			msleep(10);
5373 		else if (i <= 100)
5374 			msleep(100);
5375 		else
5376 			msleep(1000);
5377 
5378 		if (i == 150) {
5379 			/* Do post */
5380 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5381 			lpfc_sli_brdrestart(phba);
5382 		}
5383 		/* Read the HBA Host Status Register */
5384 		if (lpfc_readl(phba->HSregaddr, &status))
5385 			return -EIO;
5386 	}
5387 
5388 	/* Check to see if any errors occurred during init */
5389 	if (status & HS_FFERM) {
5390 		/* ERROR: During chipset initialization */
5391 		/* Adapter failed to init, chipset, status reg <status> */
5392 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5393 				"0438 Adapter failed to init, chipset, "
5394 				"status reg x%x, "
5395 				"FW Data: A8 x%x AC x%x\n", status,
5396 				readl(phba->MBslimaddr + 0xa8),
5397 				readl(phba->MBslimaddr + 0xac));
5398 		phba->link_state = LPFC_HBA_ERROR;
5399 		return -EIO;
5400 	}
5401 
5402 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5403 
5404 	/* Clear all interrupt enable conditions */
5405 	writel(0, phba->HCregaddr);
5406 	readl(phba->HCregaddr); /* flush */
5407 
5408 	/* setup host attn register */
5409 	writel(0xffffffff, phba->HAregaddr);
5410 	readl(phba->HAregaddr); /* flush */
5411 	return 0;
5412 }
5413 
5414 /**
5415  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5416  *
5417  * This function calculates and returns the number of HBQs required to be
5418  * configured.
5419  **/
5420 int
5421 lpfc_sli_hbq_count(void)
5422 {
5423 	return ARRAY_SIZE(lpfc_hbq_defs);
5424 }
5425 
5426 /**
5427  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5428  *
5429  * This function adds the number of hbq entries in every HBQ to get
5430  * the total number of hbq entries required for the HBA and returns
5431  * the total count.
5432  **/
5433 static int
5434 lpfc_sli_hbq_entry_count(void)
5435 {
5436 	int  hbq_count = lpfc_sli_hbq_count();
5437 	int  count = 0;
5438 	int  i;
5439 
5440 	for (i = 0; i < hbq_count; ++i)
5441 		count += lpfc_hbq_defs[i]->entry_count;
5442 	return count;
5443 }
5444 
5445 /**
5446  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5447  *
5448  * This function calculates amount of memory required for all hbq entries
5449  * to be configured and returns the total memory required.
5450  **/
5451 int
5452 lpfc_sli_hbq_size(void)
5453 {
5454 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5455 }
5456 
5457 /**
5458  * lpfc_sli_hbq_setup - configure and initialize HBQs
5459  * @phba: Pointer to HBA context object.
5460  *
5461  * This function is called during the SLI initialization to configure
5462  * all the HBQs and post buffers to the HBQ. The caller is not
5463  * required to hold any locks. This function will return zero if successful
5464  * else it will return negative error code.
5465  **/
5466 static int
5467 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5468 {
5469 	int  hbq_count = lpfc_sli_hbq_count();
5470 	LPFC_MBOXQ_t *pmb;
5471 	MAILBOX_t *pmbox;
5472 	uint32_t hbqno;
5473 	uint32_t hbq_entry_index;
5474 
5475 				/* Get a Mailbox buffer to setup mailbox
5476 				 * commands for HBA initialization
5477 				 */
5478 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5479 
5480 	if (!pmb)
5481 		return -ENOMEM;
5482 
5483 	pmbox = &pmb->u.mb;
5484 
5485 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
5486 	phba->link_state = LPFC_INIT_MBX_CMDS;
5487 	phba->hbq_in_use = 1;
5488 
5489 	hbq_entry_index = 0;
5490 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5491 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
5492 		phba->hbqs[hbqno].hbqPutIdx      = 0;
5493 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5494 		phba->hbqs[hbqno].entry_count =
5495 			lpfc_hbq_defs[hbqno]->entry_count;
5496 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5497 			hbq_entry_index, pmb);
5498 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
5499 
5500 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5501 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5502 			   mbxStatus <status>, ring <num> */
5503 
5504 			lpfc_printf_log(phba, KERN_ERR,
5505 					LOG_SLI | LOG_VPORT,
5506 					"1805 Adapter failed to init. "
5507 					"Data: x%x x%x x%x\n",
5508 					pmbox->mbxCommand,
5509 					pmbox->mbxStatus, hbqno);
5510 
5511 			phba->link_state = LPFC_HBA_ERROR;
5512 			mempool_free(pmb, phba->mbox_mem_pool);
5513 			return -ENXIO;
5514 		}
5515 	}
5516 	phba->hbq_count = hbq_count;
5517 
5518 	mempool_free(pmb, phba->mbox_mem_pool);
5519 
5520 	/* Initially populate or replenish the HBQs */
5521 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5522 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5523 	return 0;
5524 }
5525 
5526 /**
5527  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5528  * @phba: Pointer to HBA context object.
5529  *
5530  * This function is called during the SLI initialization to configure
5531  * all the HBQs and post buffers to the HBQ. The caller is not
5532  * required to hold any locks. This function will return zero if successful
5533  * else it will return negative error code.
5534  **/
5535 static int
5536 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5537 {
5538 	phba->hbq_in_use = 1;
5539 	/**
5540 	 * Specific case when the MDS diagnostics is enabled and supported.
5541 	 * The receive buffer count is truncated to manage the incoming
5542 	 * traffic.
5543 	 **/
5544 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5545 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5546 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5547 	else
5548 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5549 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5550 	phba->hbq_count = 1;
5551 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5552 	/* Initially populate or replenish the HBQs */
5553 	return 0;
5554 }
5555 
5556 /**
5557  * lpfc_sli_config_port - Issue config port mailbox command
5558  * @phba: Pointer to HBA context object.
5559  * @sli_mode: sli mode - 2/3
5560  *
5561  * This function is called by the sli initialization code path
5562  * to issue config_port mailbox command. This function restarts the
5563  * HBA firmware and issues a config_port mailbox command to configure
5564  * the SLI interface in the sli mode specified by sli_mode
5565  * variable. The caller is not required to hold any locks.
5566  * The function returns 0 if successful, else returns negative error
5567  * code.
5568  **/
5569 int
5570 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5571 {
5572 	LPFC_MBOXQ_t *pmb;
5573 	uint32_t resetcount = 0, rc = 0, done = 0;
5574 
5575 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5576 	if (!pmb) {
5577 		phba->link_state = LPFC_HBA_ERROR;
5578 		return -ENOMEM;
5579 	}
5580 
5581 	phba->sli_rev = sli_mode;
5582 	while (resetcount < 2 && !done) {
5583 		spin_lock_irq(&phba->hbalock);
5584 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5585 		spin_unlock_irq(&phba->hbalock);
5586 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5587 		lpfc_sli_brdrestart(phba);
5588 		rc = lpfc_sli_chipset_init(phba);
5589 		if (rc)
5590 			break;
5591 
5592 		spin_lock_irq(&phba->hbalock);
5593 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5594 		spin_unlock_irq(&phba->hbalock);
5595 		resetcount++;
5596 
5597 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5598 		 * value of 0 means the call was successful.  Any other
5599 		 * nonzero value is a failure, but if ERESTART is returned,
5600 		 * the driver may reset the HBA and try again.
5601 		 */
5602 		rc = lpfc_config_port_prep(phba);
5603 		if (rc == -ERESTART) {
5604 			phba->link_state = LPFC_LINK_UNKNOWN;
5605 			continue;
5606 		} else if (rc)
5607 			break;
5608 
5609 		phba->link_state = LPFC_INIT_MBX_CMDS;
5610 		lpfc_config_port(phba, pmb);
5611 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5612 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5613 					LPFC_SLI3_HBQ_ENABLED |
5614 					LPFC_SLI3_CRP_ENABLED |
5615 					LPFC_SLI3_DSS_ENABLED);
5616 		if (rc != MBX_SUCCESS) {
5617 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5618 				"0442 Adapter failed to init, mbxCmd x%x "
5619 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5620 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5621 			spin_lock_irq(&phba->hbalock);
5622 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5623 			spin_unlock_irq(&phba->hbalock);
5624 			rc = -ENXIO;
5625 		} else {
5626 			/* Allow asynchronous mailbox command to go through */
5627 			spin_lock_irq(&phba->hbalock);
5628 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5629 			spin_unlock_irq(&phba->hbalock);
5630 			done = 1;
5631 
5632 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5633 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5634 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5635 					"3110 Port did not grant ASABT\n");
5636 		}
5637 	}
5638 	if (!done) {
5639 		rc = -EINVAL;
5640 		goto do_prep_failed;
5641 	}
5642 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5643 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5644 			rc = -ENXIO;
5645 			goto do_prep_failed;
5646 		}
5647 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5648 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5649 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5650 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5651 				phba->max_vpi : phba->max_vports;
5652 
5653 		} else
5654 			phba->max_vpi = 0;
5655 		if (pmb->u.mb.un.varCfgPort.gerbm)
5656 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5657 		if (pmb->u.mb.un.varCfgPort.gcrp)
5658 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5659 
5660 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5661 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5662 
5663 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5664 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5665 				phba->cfg_enable_bg = 0;
5666 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5667 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5668 						"0443 Adapter did not grant "
5669 						"BlockGuard\n");
5670 			}
5671 		}
5672 	} else {
5673 		phba->hbq_get = NULL;
5674 		phba->port_gp = phba->mbox->us.s2.port;
5675 		phba->max_vpi = 0;
5676 	}
5677 do_prep_failed:
5678 	mempool_free(pmb, phba->mbox_mem_pool);
5679 	return rc;
5680 }
5681 
5682 
5683 /**
5684  * lpfc_sli_hba_setup - SLI initialization function
5685  * @phba: Pointer to HBA context object.
5686  *
5687  * This function is the main SLI initialization function. This function
5688  * is called by the HBA initialization code, HBA reset code and HBA
5689  * error attention handler code. Caller is not required to hold any
5690  * locks. This function issues config_port mailbox command to configure
5691  * the SLI, setup iocb rings and HBQ rings. In the end the function
5692  * calls the config_port_post function to issue init_link mailbox
5693  * command and to start the discovery. The function will return zero
5694  * if successful, else it will return negative error code.
5695  **/
5696 int
5697 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5698 {
5699 	uint32_t rc;
5700 	int  i;
5701 	int longs;
5702 
5703 	/* Enable ISR already does config_port because of config_msi mbx */
5704 	if (phba->hba_flag & HBA_NEEDS_CFG_PORT) {
5705 		rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5706 		if (rc)
5707 			return -EIO;
5708 		phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
5709 	}
5710 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5711 
5712 	if (phba->sli_rev == 3) {
5713 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5714 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5715 	} else {
5716 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5717 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5718 		phba->sli3_options = 0;
5719 	}
5720 
5721 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5722 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5723 			phba->sli_rev, phba->max_vpi);
5724 	rc = lpfc_sli_ring_map(phba);
5725 
5726 	if (rc)
5727 		goto lpfc_sli_hba_setup_error;
5728 
5729 	/* Initialize VPIs. */
5730 	if (phba->sli_rev == LPFC_SLI_REV3) {
5731 		/*
5732 		 * The VPI bitmask and physical ID array are allocated
5733 		 * and initialized once only - at driver load.  A port
5734 		 * reset doesn't need to reinitialize this memory.
5735 		 */
5736 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5737 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5738 			phba->vpi_bmask = kcalloc(longs,
5739 						  sizeof(unsigned long),
5740 						  GFP_KERNEL);
5741 			if (!phba->vpi_bmask) {
5742 				rc = -ENOMEM;
5743 				goto lpfc_sli_hba_setup_error;
5744 			}
5745 
5746 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5747 						sizeof(uint16_t),
5748 						GFP_KERNEL);
5749 			if (!phba->vpi_ids) {
5750 				kfree(phba->vpi_bmask);
5751 				rc = -ENOMEM;
5752 				goto lpfc_sli_hba_setup_error;
5753 			}
5754 			for (i = 0; i < phba->max_vpi; i++)
5755 				phba->vpi_ids[i] = i;
5756 		}
5757 	}
5758 
5759 	/* Init HBQs */
5760 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5761 		rc = lpfc_sli_hbq_setup(phba);
5762 		if (rc)
5763 			goto lpfc_sli_hba_setup_error;
5764 	}
5765 	spin_lock_irq(&phba->hbalock);
5766 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5767 	spin_unlock_irq(&phba->hbalock);
5768 
5769 	rc = lpfc_config_port_post(phba);
5770 	if (rc)
5771 		goto lpfc_sli_hba_setup_error;
5772 
5773 	return rc;
5774 
5775 lpfc_sli_hba_setup_error:
5776 	phba->link_state = LPFC_HBA_ERROR;
5777 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5778 			"0445 Firmware initialization failed\n");
5779 	return rc;
5780 }
5781 
5782 /**
5783  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5784  * @phba: Pointer to HBA context object.
5785  *
5786  * This function issue a dump mailbox command to read config region
5787  * 23 and parse the records in the region and populate driver
5788  * data structure.
5789  **/
5790 static int
5791 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5792 {
5793 	LPFC_MBOXQ_t *mboxq;
5794 	struct lpfc_dmabuf *mp;
5795 	struct lpfc_mqe *mqe;
5796 	uint32_t data_length;
5797 	int rc;
5798 
5799 	/* Program the default value of vlan_id and fc_map */
5800 	phba->valid_vlan = 0;
5801 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5802 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5803 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5804 
5805 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5806 	if (!mboxq)
5807 		return -ENOMEM;
5808 
5809 	mqe = &mboxq->u.mqe;
5810 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5811 		rc = -ENOMEM;
5812 		goto out_free_mboxq;
5813 	}
5814 
5815 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5816 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5817 
5818 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5819 			"(%d):2571 Mailbox cmd x%x Status x%x "
5820 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5821 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5822 			"CQ: x%x x%x x%x x%x\n",
5823 			mboxq->vport ? mboxq->vport->vpi : 0,
5824 			bf_get(lpfc_mqe_command, mqe),
5825 			bf_get(lpfc_mqe_status, mqe),
5826 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5827 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5828 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5829 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5830 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5831 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5832 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5833 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5834 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5835 			mboxq->mcqe.word0,
5836 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5837 			mboxq->mcqe.trailer);
5838 
5839 	if (rc) {
5840 		rc = -EIO;
5841 		goto out_free_mboxq;
5842 	}
5843 	data_length = mqe->un.mb_words[5];
5844 	if (data_length > DMP_RGN23_SIZE) {
5845 		rc = -EIO;
5846 		goto out_free_mboxq;
5847 	}
5848 
5849 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5850 	rc = 0;
5851 
5852 out_free_mboxq:
5853 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
5854 	return rc;
5855 }
5856 
5857 /**
5858  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5859  * @phba: pointer to lpfc hba data structure.
5860  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5861  * @vpd: pointer to the memory to hold resulting port vpd data.
5862  * @vpd_size: On input, the number of bytes allocated to @vpd.
5863  *	      On output, the number of data bytes in @vpd.
5864  *
5865  * This routine executes a READ_REV SLI4 mailbox command.  In
5866  * addition, this routine gets the port vpd data.
5867  *
5868  * Return codes
5869  * 	0 - successful
5870  * 	-ENOMEM - could not allocated memory.
5871  **/
5872 static int
5873 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5874 		    uint8_t *vpd, uint32_t *vpd_size)
5875 {
5876 	int rc = 0;
5877 	uint32_t dma_size;
5878 	struct lpfc_dmabuf *dmabuf;
5879 	struct lpfc_mqe *mqe;
5880 
5881 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5882 	if (!dmabuf)
5883 		return -ENOMEM;
5884 
5885 	/*
5886 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5887 	 * mailbox command.
5888 	 */
5889 	dma_size = *vpd_size;
5890 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5891 					  &dmabuf->phys, GFP_KERNEL);
5892 	if (!dmabuf->virt) {
5893 		kfree(dmabuf);
5894 		return -ENOMEM;
5895 	}
5896 
5897 	/*
5898 	 * The SLI4 implementation of READ_REV conflicts at word1,
5899 	 * bits 31:16 and SLI4 adds vpd functionality not present
5900 	 * in SLI3.  This code corrects the conflicts.
5901 	 */
5902 	lpfc_read_rev(phba, mboxq);
5903 	mqe = &mboxq->u.mqe;
5904 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5905 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5906 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5907 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5908 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5909 
5910 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5911 	if (rc) {
5912 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5913 				  dmabuf->virt, dmabuf->phys);
5914 		kfree(dmabuf);
5915 		return -EIO;
5916 	}
5917 
5918 	/*
5919 	 * The available vpd length cannot be bigger than the
5920 	 * DMA buffer passed to the port.  Catch the less than
5921 	 * case and update the caller's size.
5922 	 */
5923 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5924 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5925 
5926 	memcpy(vpd, dmabuf->virt, *vpd_size);
5927 
5928 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5929 			  dmabuf->virt, dmabuf->phys);
5930 	kfree(dmabuf);
5931 	return 0;
5932 }
5933 
5934 /**
5935  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5936  * @phba: pointer to lpfc hba data structure.
5937  *
5938  * This routine retrieves SLI4 device physical port name this PCI function
5939  * is attached to.
5940  *
5941  * Return codes
5942  *      0 - successful
5943  *      otherwise - failed to retrieve controller attributes
5944  **/
5945 static int
5946 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5947 {
5948 	LPFC_MBOXQ_t *mboxq;
5949 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5950 	struct lpfc_controller_attribute *cntl_attr;
5951 	void *virtaddr = NULL;
5952 	uint32_t alloclen, reqlen;
5953 	uint32_t shdr_status, shdr_add_status;
5954 	union lpfc_sli4_cfg_shdr *shdr;
5955 	int rc;
5956 
5957 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5958 	if (!mboxq)
5959 		return -ENOMEM;
5960 
5961 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5962 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5963 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5964 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5965 			LPFC_SLI4_MBX_NEMBED);
5966 
5967 	if (alloclen < reqlen) {
5968 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5969 				"3084 Allocated DMA memory size (%d) is "
5970 				"less than the requested DMA memory size "
5971 				"(%d)\n", alloclen, reqlen);
5972 		rc = -ENOMEM;
5973 		goto out_free_mboxq;
5974 	}
5975 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5976 	virtaddr = mboxq->sge_array->addr[0];
5977 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5978 	shdr = &mbx_cntl_attr->cfg_shdr;
5979 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5980 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5981 	if (shdr_status || shdr_add_status || rc) {
5982 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5983 				"3085 Mailbox x%x (x%x/x%x) failed, "
5984 				"rc:x%x, status:x%x, add_status:x%x\n",
5985 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5986 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5987 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5988 				rc, shdr_status, shdr_add_status);
5989 		rc = -ENXIO;
5990 		goto out_free_mboxq;
5991 	}
5992 
5993 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5994 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5995 	phba->sli4_hba.lnk_info.lnk_tp =
5996 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5997 	phba->sli4_hba.lnk_info.lnk_no =
5998 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5999 	phba->sli4_hba.flash_id = bf_get(lpfc_cntl_attr_flash_id, cntl_attr);
6000 	phba->sli4_hba.asic_rev = bf_get(lpfc_cntl_attr_asic_rev, cntl_attr);
6001 
6002 	memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
6003 	strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
6004 		sizeof(phba->BIOSVersion));
6005 
6006 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6007 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s, "
6008 			"flash_id: x%02x, asic_rev: x%02x\n",
6009 			phba->sli4_hba.lnk_info.lnk_tp,
6010 			phba->sli4_hba.lnk_info.lnk_no,
6011 			phba->BIOSVersion, phba->sli4_hba.flash_id,
6012 			phba->sli4_hba.asic_rev);
6013 out_free_mboxq:
6014 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6015 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6016 	else
6017 		mempool_free(mboxq, phba->mbox_mem_pool);
6018 	return rc;
6019 }
6020 
6021 /**
6022  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
6023  * @phba: pointer to lpfc hba data structure.
6024  *
6025  * This routine retrieves SLI4 device physical port name this PCI function
6026  * is attached to.
6027  *
6028  * Return codes
6029  *      0 - successful
6030  *      otherwise - failed to retrieve physical port name
6031  **/
6032 static int
6033 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
6034 {
6035 	LPFC_MBOXQ_t *mboxq;
6036 	struct lpfc_mbx_get_port_name *get_port_name;
6037 	uint32_t shdr_status, shdr_add_status;
6038 	union lpfc_sli4_cfg_shdr *shdr;
6039 	char cport_name = 0;
6040 	int rc;
6041 
6042 	/* We assume nothing at this point */
6043 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6044 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
6045 
6046 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6047 	if (!mboxq)
6048 		return -ENOMEM;
6049 	/* obtain link type and link number via READ_CONFIG */
6050 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6051 	lpfc_sli4_read_config(phba);
6052 
6053 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG)
6054 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
6055 
6056 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
6057 		goto retrieve_ppname;
6058 
6059 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
6060 	rc = lpfc_sli4_get_ctl_attr(phba);
6061 	if (rc)
6062 		goto out_free_mboxq;
6063 
6064 retrieve_ppname:
6065 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
6066 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
6067 		sizeof(struct lpfc_mbx_get_port_name) -
6068 		sizeof(struct lpfc_sli4_cfg_mhdr),
6069 		LPFC_SLI4_MBX_EMBED);
6070 	get_port_name = &mboxq->u.mqe.un.get_port_name;
6071 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
6072 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
6073 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
6074 		phba->sli4_hba.lnk_info.lnk_tp);
6075 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6076 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6077 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6078 	if (shdr_status || shdr_add_status || rc) {
6079 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6080 				"3087 Mailbox x%x (x%x/x%x) failed: "
6081 				"rc:x%x, status:x%x, add_status:x%x\n",
6082 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6083 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6084 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6085 				rc, shdr_status, shdr_add_status);
6086 		rc = -ENXIO;
6087 		goto out_free_mboxq;
6088 	}
6089 	switch (phba->sli4_hba.lnk_info.lnk_no) {
6090 	case LPFC_LINK_NUMBER_0:
6091 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
6092 				&get_port_name->u.response);
6093 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6094 		break;
6095 	case LPFC_LINK_NUMBER_1:
6096 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
6097 				&get_port_name->u.response);
6098 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6099 		break;
6100 	case LPFC_LINK_NUMBER_2:
6101 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
6102 				&get_port_name->u.response);
6103 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6104 		break;
6105 	case LPFC_LINK_NUMBER_3:
6106 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
6107 				&get_port_name->u.response);
6108 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6109 		break;
6110 	default:
6111 		break;
6112 	}
6113 
6114 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
6115 		phba->Port[0] = cport_name;
6116 		phba->Port[1] = '\0';
6117 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6118 				"3091 SLI get port name: %s\n", phba->Port);
6119 	}
6120 
6121 out_free_mboxq:
6122 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6123 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6124 	else
6125 		mempool_free(mboxq, phba->mbox_mem_pool);
6126 	return rc;
6127 }
6128 
6129 /**
6130  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
6131  * @phba: pointer to lpfc hba data structure.
6132  *
6133  * This routine is called to explicitly arm the SLI4 device's completion and
6134  * event queues
6135  **/
6136 static void
6137 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
6138 {
6139 	int qidx;
6140 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
6141 	struct lpfc_sli4_hdw_queue *qp;
6142 	struct lpfc_queue *eq;
6143 
6144 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
6145 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
6146 	if (sli4_hba->nvmels_cq)
6147 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
6148 					   LPFC_QUEUE_REARM);
6149 
6150 	if (sli4_hba->hdwq) {
6151 		/* Loop thru all Hardware Queues */
6152 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
6153 			qp = &sli4_hba->hdwq[qidx];
6154 			/* ARM the corresponding CQ */
6155 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
6156 						LPFC_QUEUE_REARM);
6157 		}
6158 
6159 		/* Loop thru all IRQ vectors */
6160 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
6161 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
6162 			/* ARM the corresponding EQ */
6163 			sli4_hba->sli4_write_eq_db(phba, eq,
6164 						   0, LPFC_QUEUE_REARM);
6165 		}
6166 	}
6167 
6168 	if (phba->nvmet_support) {
6169 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
6170 			sli4_hba->sli4_write_cq_db(phba,
6171 				sli4_hba->nvmet_cqset[qidx], 0,
6172 				LPFC_QUEUE_REARM);
6173 		}
6174 	}
6175 }
6176 
6177 /**
6178  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
6179  * @phba: Pointer to HBA context object.
6180  * @type: The resource extent type.
6181  * @extnt_count: buffer to hold port available extent count.
6182  * @extnt_size: buffer to hold element count per extent.
6183  *
6184  * This function calls the port and retrievs the number of available
6185  * extents and their size for a particular extent type.
6186  *
6187  * Returns: 0 if successful.  Nonzero otherwise.
6188  **/
6189 int
6190 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
6191 			       uint16_t *extnt_count, uint16_t *extnt_size)
6192 {
6193 	int rc = 0;
6194 	uint32_t length;
6195 	uint32_t mbox_tmo;
6196 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
6197 	LPFC_MBOXQ_t *mbox;
6198 
6199 	*extnt_count = 0;
6200 	*extnt_size = 0;
6201 
6202 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6203 	if (!mbox)
6204 		return -ENOMEM;
6205 
6206 	/* Find out how many extents are available for this resource type */
6207 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
6208 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6209 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6210 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
6211 			 length, LPFC_SLI4_MBX_EMBED);
6212 
6213 	/* Send an extents count of 0 - the GET doesn't use it. */
6214 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6215 					LPFC_SLI4_MBX_EMBED);
6216 	if (unlikely(rc)) {
6217 		rc = -EIO;
6218 		goto err_exit;
6219 	}
6220 
6221 	if (!phba->sli4_hba.intr_enable)
6222 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6223 	else {
6224 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6225 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6226 	}
6227 	if (unlikely(rc)) {
6228 		rc = -EIO;
6229 		goto err_exit;
6230 	}
6231 
6232 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
6233 	if (bf_get(lpfc_mbox_hdr_status,
6234 		   &rsrc_info->header.cfg_shdr.response)) {
6235 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6236 				"2930 Failed to get resource extents "
6237 				"Status 0x%x Add'l Status 0x%x\n",
6238 				bf_get(lpfc_mbox_hdr_status,
6239 				       &rsrc_info->header.cfg_shdr.response),
6240 				bf_get(lpfc_mbox_hdr_add_status,
6241 				       &rsrc_info->header.cfg_shdr.response));
6242 		rc = -EIO;
6243 		goto err_exit;
6244 	}
6245 
6246 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
6247 			      &rsrc_info->u.rsp);
6248 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
6249 			     &rsrc_info->u.rsp);
6250 
6251 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6252 			"3162 Retrieved extents type-%d from port: count:%d, "
6253 			"size:%d\n", type, *extnt_count, *extnt_size);
6254 
6255 err_exit:
6256 	mempool_free(mbox, phba->mbox_mem_pool);
6257 	return rc;
6258 }
6259 
6260 /**
6261  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
6262  * @phba: Pointer to HBA context object.
6263  * @type: The extent type to check.
6264  *
6265  * This function reads the current available extents from the port and checks
6266  * if the extent count or extent size has changed since the last access.
6267  * Callers use this routine post port reset to understand if there is a
6268  * extent reprovisioning requirement.
6269  *
6270  * Returns:
6271  *   -Error: error indicates problem.
6272  *   1: Extent count or size has changed.
6273  *   0: No changes.
6274  **/
6275 static int
6276 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
6277 {
6278 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
6279 	uint16_t size_diff, rsrc_ext_size;
6280 	int rc = 0;
6281 	struct lpfc_rsrc_blks *rsrc_entry;
6282 	struct list_head *rsrc_blk_list = NULL;
6283 
6284 	size_diff = 0;
6285 	curr_ext_cnt = 0;
6286 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6287 					    &rsrc_ext_cnt,
6288 					    &rsrc_ext_size);
6289 	if (unlikely(rc))
6290 		return -EIO;
6291 
6292 	switch (type) {
6293 	case LPFC_RSC_TYPE_FCOE_RPI:
6294 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6295 		break;
6296 	case LPFC_RSC_TYPE_FCOE_VPI:
6297 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
6298 		break;
6299 	case LPFC_RSC_TYPE_FCOE_XRI:
6300 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6301 		break;
6302 	case LPFC_RSC_TYPE_FCOE_VFI:
6303 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6304 		break;
6305 	default:
6306 		break;
6307 	}
6308 
6309 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
6310 		curr_ext_cnt++;
6311 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
6312 			size_diff++;
6313 	}
6314 
6315 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
6316 		rc = 1;
6317 
6318 	return rc;
6319 }
6320 
6321 /**
6322  * lpfc_sli4_cfg_post_extnts -
6323  * @phba: Pointer to HBA context object.
6324  * @extnt_cnt: number of available extents.
6325  * @type: the extent type (rpi, xri, vfi, vpi).
6326  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
6327  * @mbox: pointer to the caller's allocated mailbox structure.
6328  *
6329  * This function executes the extents allocation request.  It also
6330  * takes care of the amount of memory needed to allocate or get the
6331  * allocated extents. It is the caller's responsibility to evaluate
6332  * the response.
6333  *
6334  * Returns:
6335  *   -Error:  Error value describes the condition found.
6336  *   0: if successful
6337  **/
6338 static int
6339 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6340 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6341 {
6342 	int rc = 0;
6343 	uint32_t req_len;
6344 	uint32_t emb_len;
6345 	uint32_t alloc_len, mbox_tmo;
6346 
6347 	/* Calculate the total requested length of the dma memory */
6348 	req_len = extnt_cnt * sizeof(uint16_t);
6349 
6350 	/*
6351 	 * Calculate the size of an embedded mailbox.  The uint32_t
6352 	 * accounts for extents-specific word.
6353 	 */
6354 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6355 		sizeof(uint32_t);
6356 
6357 	/*
6358 	 * Presume the allocation and response will fit into an embedded
6359 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6360 	 */
6361 	*emb = LPFC_SLI4_MBX_EMBED;
6362 	if (req_len > emb_len) {
6363 		req_len = extnt_cnt * sizeof(uint16_t) +
6364 			sizeof(union lpfc_sli4_cfg_shdr) +
6365 			sizeof(uint32_t);
6366 		*emb = LPFC_SLI4_MBX_NEMBED;
6367 	}
6368 
6369 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6370 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6371 				     req_len, *emb);
6372 	if (alloc_len < req_len) {
6373 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6374 			"2982 Allocated DMA memory size (x%x) is "
6375 			"less than the requested DMA memory "
6376 			"size (x%x)\n", alloc_len, req_len);
6377 		return -ENOMEM;
6378 	}
6379 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6380 	if (unlikely(rc))
6381 		return -EIO;
6382 
6383 	if (!phba->sli4_hba.intr_enable)
6384 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6385 	else {
6386 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6387 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6388 	}
6389 
6390 	if (unlikely(rc))
6391 		rc = -EIO;
6392 	return rc;
6393 }
6394 
6395 /**
6396  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6397  * @phba: Pointer to HBA context object.
6398  * @type:  The resource extent type to allocate.
6399  *
6400  * This function allocates the number of elements for the specified
6401  * resource type.
6402  **/
6403 static int
6404 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6405 {
6406 	bool emb = false;
6407 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6408 	uint16_t rsrc_id, rsrc_start, j, k;
6409 	uint16_t *ids;
6410 	int i, rc;
6411 	unsigned long longs;
6412 	unsigned long *bmask;
6413 	struct lpfc_rsrc_blks *rsrc_blks;
6414 	LPFC_MBOXQ_t *mbox;
6415 	uint32_t length;
6416 	struct lpfc_id_range *id_array = NULL;
6417 	void *virtaddr = NULL;
6418 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6419 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6420 	struct list_head *ext_blk_list;
6421 
6422 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6423 					    &rsrc_cnt,
6424 					    &rsrc_size);
6425 	if (unlikely(rc))
6426 		return -EIO;
6427 
6428 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6429 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6430 			"3009 No available Resource Extents "
6431 			"for resource type 0x%x: Count: 0x%x, "
6432 			"Size 0x%x\n", type, rsrc_cnt,
6433 			rsrc_size);
6434 		return -ENOMEM;
6435 	}
6436 
6437 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6438 			"2903 Post resource extents type-0x%x: "
6439 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6440 
6441 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6442 	if (!mbox)
6443 		return -ENOMEM;
6444 
6445 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6446 	if (unlikely(rc)) {
6447 		rc = -EIO;
6448 		goto err_exit;
6449 	}
6450 
6451 	/*
6452 	 * Figure out where the response is located.  Then get local pointers
6453 	 * to the response data.  The port does not guarantee to respond to
6454 	 * all extents counts request so update the local variable with the
6455 	 * allocated count from the port.
6456 	 */
6457 	if (emb == LPFC_SLI4_MBX_EMBED) {
6458 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6459 		id_array = &rsrc_ext->u.rsp.id[0];
6460 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6461 	} else {
6462 		virtaddr = mbox->sge_array->addr[0];
6463 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6464 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6465 		id_array = &n_rsrc->id;
6466 	}
6467 
6468 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6469 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6470 
6471 	/*
6472 	 * Based on the resource size and count, correct the base and max
6473 	 * resource values.
6474 	 */
6475 	length = sizeof(struct lpfc_rsrc_blks);
6476 	switch (type) {
6477 	case LPFC_RSC_TYPE_FCOE_RPI:
6478 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6479 						   sizeof(unsigned long),
6480 						   GFP_KERNEL);
6481 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6482 			rc = -ENOMEM;
6483 			goto err_exit;
6484 		}
6485 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6486 						 sizeof(uint16_t),
6487 						 GFP_KERNEL);
6488 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6489 			kfree(phba->sli4_hba.rpi_bmask);
6490 			rc = -ENOMEM;
6491 			goto err_exit;
6492 		}
6493 
6494 		/*
6495 		 * The next_rpi was initialized with the maximum available
6496 		 * count but the port may allocate a smaller number.  Catch
6497 		 * that case and update the next_rpi.
6498 		 */
6499 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6500 
6501 		/* Initialize local ptrs for common extent processing later. */
6502 		bmask = phba->sli4_hba.rpi_bmask;
6503 		ids = phba->sli4_hba.rpi_ids;
6504 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6505 		break;
6506 	case LPFC_RSC_TYPE_FCOE_VPI:
6507 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6508 					  GFP_KERNEL);
6509 		if (unlikely(!phba->vpi_bmask)) {
6510 			rc = -ENOMEM;
6511 			goto err_exit;
6512 		}
6513 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6514 					 GFP_KERNEL);
6515 		if (unlikely(!phba->vpi_ids)) {
6516 			kfree(phba->vpi_bmask);
6517 			rc = -ENOMEM;
6518 			goto err_exit;
6519 		}
6520 
6521 		/* Initialize local ptrs for common extent processing later. */
6522 		bmask = phba->vpi_bmask;
6523 		ids = phba->vpi_ids;
6524 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6525 		break;
6526 	case LPFC_RSC_TYPE_FCOE_XRI:
6527 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6528 						   sizeof(unsigned long),
6529 						   GFP_KERNEL);
6530 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6531 			rc = -ENOMEM;
6532 			goto err_exit;
6533 		}
6534 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6535 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6536 						 sizeof(uint16_t),
6537 						 GFP_KERNEL);
6538 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6539 			kfree(phba->sli4_hba.xri_bmask);
6540 			rc = -ENOMEM;
6541 			goto err_exit;
6542 		}
6543 
6544 		/* Initialize local ptrs for common extent processing later. */
6545 		bmask = phba->sli4_hba.xri_bmask;
6546 		ids = phba->sli4_hba.xri_ids;
6547 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6548 		break;
6549 	case LPFC_RSC_TYPE_FCOE_VFI:
6550 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6551 						   sizeof(unsigned long),
6552 						   GFP_KERNEL);
6553 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6554 			rc = -ENOMEM;
6555 			goto err_exit;
6556 		}
6557 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6558 						 sizeof(uint16_t),
6559 						 GFP_KERNEL);
6560 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6561 			kfree(phba->sli4_hba.vfi_bmask);
6562 			rc = -ENOMEM;
6563 			goto err_exit;
6564 		}
6565 
6566 		/* Initialize local ptrs for common extent processing later. */
6567 		bmask = phba->sli4_hba.vfi_bmask;
6568 		ids = phba->sli4_hba.vfi_ids;
6569 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6570 		break;
6571 	default:
6572 		/* Unsupported Opcode.  Fail call. */
6573 		id_array = NULL;
6574 		bmask = NULL;
6575 		ids = NULL;
6576 		ext_blk_list = NULL;
6577 		goto err_exit;
6578 	}
6579 
6580 	/*
6581 	 * Complete initializing the extent configuration with the
6582 	 * allocated ids assigned to this function.  The bitmask serves
6583 	 * as an index into the array and manages the available ids.  The
6584 	 * array just stores the ids communicated to the port via the wqes.
6585 	 */
6586 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6587 		if ((i % 2) == 0)
6588 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6589 					 &id_array[k]);
6590 		else
6591 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6592 					 &id_array[k]);
6593 
6594 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6595 		if (unlikely(!rsrc_blks)) {
6596 			rc = -ENOMEM;
6597 			kfree(bmask);
6598 			kfree(ids);
6599 			goto err_exit;
6600 		}
6601 		rsrc_blks->rsrc_start = rsrc_id;
6602 		rsrc_blks->rsrc_size = rsrc_size;
6603 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6604 		rsrc_start = rsrc_id;
6605 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6606 			phba->sli4_hba.io_xri_start = rsrc_start +
6607 				lpfc_sli4_get_iocb_cnt(phba);
6608 		}
6609 
6610 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6611 			ids[j] = rsrc_id;
6612 			rsrc_id++;
6613 			j++;
6614 		}
6615 		/* Entire word processed.  Get next word.*/
6616 		if ((i % 2) == 1)
6617 			k++;
6618 	}
6619  err_exit:
6620 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6621 	return rc;
6622 }
6623 
6624 
6625 
6626 /**
6627  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6628  * @phba: Pointer to HBA context object.
6629  * @type: the extent's type.
6630  *
6631  * This function deallocates all extents of a particular resource type.
6632  * SLI4 does not allow for deallocating a particular extent range.  It
6633  * is the caller's responsibility to release all kernel memory resources.
6634  **/
6635 static int
6636 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6637 {
6638 	int rc;
6639 	uint32_t length, mbox_tmo = 0;
6640 	LPFC_MBOXQ_t *mbox;
6641 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6642 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6643 
6644 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6645 	if (!mbox)
6646 		return -ENOMEM;
6647 
6648 	/*
6649 	 * This function sends an embedded mailbox because it only sends the
6650 	 * the resource type.  All extents of this type are released by the
6651 	 * port.
6652 	 */
6653 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6654 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6655 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6656 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6657 			 length, LPFC_SLI4_MBX_EMBED);
6658 
6659 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6660 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6661 					LPFC_SLI4_MBX_EMBED);
6662 	if (unlikely(rc)) {
6663 		rc = -EIO;
6664 		goto out_free_mbox;
6665 	}
6666 	if (!phba->sli4_hba.intr_enable)
6667 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6668 	else {
6669 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6670 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6671 	}
6672 	if (unlikely(rc)) {
6673 		rc = -EIO;
6674 		goto out_free_mbox;
6675 	}
6676 
6677 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6678 	if (bf_get(lpfc_mbox_hdr_status,
6679 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6680 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6681 				"2919 Failed to release resource extents "
6682 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6683 				"Resource memory not released.\n",
6684 				type,
6685 				bf_get(lpfc_mbox_hdr_status,
6686 				    &dealloc_rsrc->header.cfg_shdr.response),
6687 				bf_get(lpfc_mbox_hdr_add_status,
6688 				    &dealloc_rsrc->header.cfg_shdr.response));
6689 		rc = -EIO;
6690 		goto out_free_mbox;
6691 	}
6692 
6693 	/* Release kernel memory resources for the specific type. */
6694 	switch (type) {
6695 	case LPFC_RSC_TYPE_FCOE_VPI:
6696 		kfree(phba->vpi_bmask);
6697 		kfree(phba->vpi_ids);
6698 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6699 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6700 				    &phba->lpfc_vpi_blk_list, list) {
6701 			list_del_init(&rsrc_blk->list);
6702 			kfree(rsrc_blk);
6703 		}
6704 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6705 		break;
6706 	case LPFC_RSC_TYPE_FCOE_XRI:
6707 		kfree(phba->sli4_hba.xri_bmask);
6708 		kfree(phba->sli4_hba.xri_ids);
6709 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6710 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6711 			list_del_init(&rsrc_blk->list);
6712 			kfree(rsrc_blk);
6713 		}
6714 		break;
6715 	case LPFC_RSC_TYPE_FCOE_VFI:
6716 		kfree(phba->sli4_hba.vfi_bmask);
6717 		kfree(phba->sli4_hba.vfi_ids);
6718 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6719 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6720 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6721 			list_del_init(&rsrc_blk->list);
6722 			kfree(rsrc_blk);
6723 		}
6724 		break;
6725 	case LPFC_RSC_TYPE_FCOE_RPI:
6726 		/* RPI bitmask and physical id array are cleaned up earlier. */
6727 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6728 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6729 			list_del_init(&rsrc_blk->list);
6730 			kfree(rsrc_blk);
6731 		}
6732 		break;
6733 	default:
6734 		break;
6735 	}
6736 
6737 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6738 
6739  out_free_mbox:
6740 	mempool_free(mbox, phba->mbox_mem_pool);
6741 	return rc;
6742 }
6743 
6744 static void
6745 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6746 		  uint32_t feature)
6747 {
6748 	uint32_t len;
6749 	u32 sig_freq = 0;
6750 
6751 	len = sizeof(struct lpfc_mbx_set_feature) -
6752 		sizeof(struct lpfc_sli4_cfg_mhdr);
6753 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6754 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6755 			 LPFC_SLI4_MBX_EMBED);
6756 
6757 	switch (feature) {
6758 	case LPFC_SET_UE_RECOVERY:
6759 		bf_set(lpfc_mbx_set_feature_UER,
6760 		       &mbox->u.mqe.un.set_feature, 1);
6761 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6762 		mbox->u.mqe.un.set_feature.param_len = 8;
6763 		break;
6764 	case LPFC_SET_MDS_DIAGS:
6765 		bf_set(lpfc_mbx_set_feature_mds,
6766 		       &mbox->u.mqe.un.set_feature, 1);
6767 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6768 		       &mbox->u.mqe.un.set_feature, 1);
6769 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6770 		mbox->u.mqe.un.set_feature.param_len = 8;
6771 		break;
6772 	case LPFC_SET_CGN_SIGNAL:
6773 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6774 			sig_freq = 0;
6775 		else
6776 			sig_freq = phba->cgn_sig_freq;
6777 
6778 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6779 			bf_set(lpfc_mbx_set_feature_CGN_alarm_freq,
6780 			       &mbox->u.mqe.un.set_feature, sig_freq);
6781 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6782 			       &mbox->u.mqe.un.set_feature, sig_freq);
6783 		}
6784 
6785 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY)
6786 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6787 			       &mbox->u.mqe.un.set_feature, sig_freq);
6788 
6789 		if (phba->cmf_active_mode == LPFC_CFG_OFF ||
6790 		    phba->cgn_reg_signal == EDC_CG_SIG_NOTSUPPORTED)
6791 			sig_freq = 0;
6792 		else
6793 			sig_freq = lpfc_acqe_cgn_frequency;
6794 
6795 		bf_set(lpfc_mbx_set_feature_CGN_acqe_freq,
6796 		       &mbox->u.mqe.un.set_feature, sig_freq);
6797 
6798 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_CGN_SIGNAL;
6799 		mbox->u.mqe.un.set_feature.param_len = 12;
6800 		break;
6801 	case LPFC_SET_DUAL_DUMP:
6802 		bf_set(lpfc_mbx_set_feature_dd,
6803 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6804 		bf_set(lpfc_mbx_set_feature_ddquery,
6805 		       &mbox->u.mqe.un.set_feature, 0);
6806 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6807 		mbox->u.mqe.un.set_feature.param_len = 4;
6808 		break;
6809 	case LPFC_SET_ENABLE_MI:
6810 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_MI;
6811 		mbox->u.mqe.un.set_feature.param_len = 4;
6812 		bf_set(lpfc_mbx_set_feature_milunq, &mbox->u.mqe.un.set_feature,
6813 		       phba->pport->cfg_lun_queue_depth);
6814 		bf_set(lpfc_mbx_set_feature_mi, &mbox->u.mqe.un.set_feature,
6815 		       phba->sli4_hba.pc_sli4_params.mi_ver);
6816 		break;
6817 	case LPFC_SET_LD_SIGNAL:
6818 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_LD_SIGNAL;
6819 		mbox->u.mqe.un.set_feature.param_len = 16;
6820 		bf_set(lpfc_mbx_set_feature_lds_qry,
6821 		       &mbox->u.mqe.un.set_feature, LPFC_QUERY_LDS_OP);
6822 		break;
6823 	case LPFC_SET_ENABLE_CMF:
6824 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_CMF;
6825 		mbox->u.mqe.un.set_feature.param_len = 4;
6826 		bf_set(lpfc_mbx_set_feature_cmf,
6827 		       &mbox->u.mqe.un.set_feature, 1);
6828 		break;
6829 	}
6830 	return;
6831 }
6832 
6833 /**
6834  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6835  * @phba: Pointer to HBA context object.
6836  *
6837  * Disable FW logging into host memory on the adapter. To
6838  * be done before reading logs from the host memory.
6839  **/
6840 void
6841 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6842 {
6843 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6844 
6845 	spin_lock_irq(&phba->hbalock);
6846 	ras_fwlog->state = INACTIVE;
6847 	spin_unlock_irq(&phba->hbalock);
6848 
6849 	/* Disable FW logging to host memory */
6850 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6851 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6852 
6853 	/* Wait 10ms for firmware to stop using DMA buffer */
6854 	usleep_range(10 * 1000, 20 * 1000);
6855 }
6856 
6857 /**
6858  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6859  * @phba: Pointer to HBA context object.
6860  *
6861  * This function is called to free memory allocated for RAS FW logging
6862  * support in the driver.
6863  **/
6864 void
6865 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6866 {
6867 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6868 	struct lpfc_dmabuf *dmabuf, *next;
6869 
6870 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6871 		list_for_each_entry_safe(dmabuf, next,
6872 				    &ras_fwlog->fwlog_buff_list,
6873 				    list) {
6874 			list_del(&dmabuf->list);
6875 			dma_free_coherent(&phba->pcidev->dev,
6876 					  LPFC_RAS_MAX_ENTRY_SIZE,
6877 					  dmabuf->virt, dmabuf->phys);
6878 			kfree(dmabuf);
6879 		}
6880 	}
6881 
6882 	if (ras_fwlog->lwpd.virt) {
6883 		dma_free_coherent(&phba->pcidev->dev,
6884 				  sizeof(uint32_t) * 2,
6885 				  ras_fwlog->lwpd.virt,
6886 				  ras_fwlog->lwpd.phys);
6887 		ras_fwlog->lwpd.virt = NULL;
6888 	}
6889 
6890 	spin_lock_irq(&phba->hbalock);
6891 	ras_fwlog->state = INACTIVE;
6892 	spin_unlock_irq(&phba->hbalock);
6893 }
6894 
6895 /**
6896  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6897  * @phba: Pointer to HBA context object.
6898  * @fwlog_buff_count: Count of buffers to be created.
6899  *
6900  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6901  * to update FW log is posted to the adapter.
6902  * Buffer count is calculated based on module param ras_fwlog_buffsize
6903  * Size of each buffer posted to FW is 64K.
6904  **/
6905 
6906 static int
6907 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6908 			uint32_t fwlog_buff_count)
6909 {
6910 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6911 	struct lpfc_dmabuf *dmabuf;
6912 	int rc = 0, i = 0;
6913 
6914 	/* Initialize List */
6915 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6916 
6917 	/* Allocate memory for the LWPD */
6918 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6919 					    sizeof(uint32_t) * 2,
6920 					    &ras_fwlog->lwpd.phys,
6921 					    GFP_KERNEL);
6922 	if (!ras_fwlog->lwpd.virt) {
6923 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6924 				"6185 LWPD Memory Alloc Failed\n");
6925 
6926 		return -ENOMEM;
6927 	}
6928 
6929 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6930 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6931 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6932 				 GFP_KERNEL);
6933 		if (!dmabuf) {
6934 			rc = -ENOMEM;
6935 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6936 					"6186 Memory Alloc failed FW logging");
6937 			goto free_mem;
6938 		}
6939 
6940 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6941 						  LPFC_RAS_MAX_ENTRY_SIZE,
6942 						  &dmabuf->phys, GFP_KERNEL);
6943 		if (!dmabuf->virt) {
6944 			kfree(dmabuf);
6945 			rc = -ENOMEM;
6946 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6947 					"6187 DMA Alloc Failed FW logging");
6948 			goto free_mem;
6949 		}
6950 		dmabuf->buffer_tag = i;
6951 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6952 	}
6953 
6954 free_mem:
6955 	if (rc)
6956 		lpfc_sli4_ras_dma_free(phba);
6957 
6958 	return rc;
6959 }
6960 
6961 /**
6962  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6963  * @phba: pointer to lpfc hba data structure.
6964  * @pmb: pointer to the driver internal queue element for mailbox command.
6965  *
6966  * Completion handler for driver's RAS MBX command to the device.
6967  **/
6968 static void
6969 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6970 {
6971 	MAILBOX_t *mb;
6972 	union lpfc_sli4_cfg_shdr *shdr;
6973 	uint32_t shdr_status, shdr_add_status;
6974 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6975 
6976 	mb = &pmb->u.mb;
6977 
6978 	shdr = (union lpfc_sli4_cfg_shdr *)
6979 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6980 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6981 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6982 
6983 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6984 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6985 				"6188 FW LOG mailbox "
6986 				"completed with status x%x add_status x%x,"
6987 				" mbx status x%x\n",
6988 				shdr_status, shdr_add_status, mb->mbxStatus);
6989 
6990 		ras_fwlog->ras_hwsupport = false;
6991 		goto disable_ras;
6992 	}
6993 
6994 	spin_lock_irq(&phba->hbalock);
6995 	ras_fwlog->state = ACTIVE;
6996 	spin_unlock_irq(&phba->hbalock);
6997 	mempool_free(pmb, phba->mbox_mem_pool);
6998 
6999 	return;
7000 
7001 disable_ras:
7002 	/* Free RAS DMA memory */
7003 	lpfc_sli4_ras_dma_free(phba);
7004 	mempool_free(pmb, phba->mbox_mem_pool);
7005 }
7006 
7007 /**
7008  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
7009  * @phba: pointer to lpfc hba data structure.
7010  * @fwlog_level: Logging verbosity level.
7011  * @fwlog_enable: Enable/Disable logging.
7012  *
7013  * Initialize memory and post mailbox command to enable FW logging in host
7014  * memory.
7015  **/
7016 int
7017 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
7018 			 uint32_t fwlog_level,
7019 			 uint32_t fwlog_enable)
7020 {
7021 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
7022 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
7023 	struct lpfc_dmabuf *dmabuf;
7024 	LPFC_MBOXQ_t *mbox;
7025 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
7026 	int rc = 0;
7027 
7028 	spin_lock_irq(&phba->hbalock);
7029 	ras_fwlog->state = INACTIVE;
7030 	spin_unlock_irq(&phba->hbalock);
7031 
7032 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
7033 			  phba->cfg_ras_fwlog_buffsize);
7034 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
7035 
7036 	/*
7037 	 * If re-enabling FW logging support use earlier allocated
7038 	 * DMA buffers while posting MBX command.
7039 	 **/
7040 	if (!ras_fwlog->lwpd.virt) {
7041 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
7042 		if (rc) {
7043 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7044 					"6189 FW Log Memory Allocation Failed");
7045 			return rc;
7046 		}
7047 	}
7048 
7049 	/* Setup Mailbox command */
7050 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7051 	if (!mbox) {
7052 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7053 				"6190 RAS MBX Alloc Failed");
7054 		rc = -ENOMEM;
7055 		goto mem_free;
7056 	}
7057 
7058 	ras_fwlog->fw_loglevel = fwlog_level;
7059 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
7060 		sizeof(struct lpfc_sli4_cfg_mhdr));
7061 
7062 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
7063 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
7064 			 len, LPFC_SLI4_MBX_EMBED);
7065 
7066 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
7067 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
7068 	       fwlog_enable);
7069 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
7070 	       ras_fwlog->fw_loglevel);
7071 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
7072 	       ras_fwlog->fw_buffcount);
7073 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
7074 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
7075 
7076 	/* Update DMA buffer address */
7077 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
7078 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
7079 
7080 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
7081 			putPaddrLow(dmabuf->phys);
7082 
7083 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
7084 			putPaddrHigh(dmabuf->phys);
7085 	}
7086 
7087 	/* Update LPWD address */
7088 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
7089 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
7090 
7091 	spin_lock_irq(&phba->hbalock);
7092 	ras_fwlog->state = REG_INPROGRESS;
7093 	spin_unlock_irq(&phba->hbalock);
7094 	mbox->vport = phba->pport;
7095 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
7096 
7097 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
7098 
7099 	if (rc == MBX_NOT_FINISHED) {
7100 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7101 				"6191 FW-Log Mailbox failed. "
7102 				"status %d mbxStatus : x%x", rc,
7103 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
7104 		mempool_free(mbox, phba->mbox_mem_pool);
7105 		rc = -EIO;
7106 		goto mem_free;
7107 	} else
7108 		rc = 0;
7109 mem_free:
7110 	if (rc)
7111 		lpfc_sli4_ras_dma_free(phba);
7112 
7113 	return rc;
7114 }
7115 
7116 /**
7117  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
7118  * @phba: Pointer to HBA context object.
7119  *
7120  * Check if RAS is supported on the adapter and initialize it.
7121  **/
7122 void
7123 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
7124 {
7125 	/* Check RAS FW Log needs to be enabled or not */
7126 	if (lpfc_check_fwlog_support(phba))
7127 		return;
7128 
7129 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
7130 				 LPFC_RAS_ENABLE_LOGGING);
7131 }
7132 
7133 /**
7134  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
7135  * @phba: Pointer to HBA context object.
7136  *
7137  * This function allocates all SLI4 resource identifiers.
7138  **/
7139 int
7140 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
7141 {
7142 	int i, rc, error = 0;
7143 	uint16_t count, base;
7144 	unsigned long longs;
7145 
7146 	if (!phba->sli4_hba.rpi_hdrs_in_use)
7147 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
7148 	if (phba->sli4_hba.extents_in_use) {
7149 		/*
7150 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
7151 		 * resource extent count must be read and allocated before
7152 		 * provisioning the resource id arrays.
7153 		 */
7154 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7155 		    LPFC_IDX_RSRC_RDY) {
7156 			/*
7157 			 * Extent-based resources are set - the driver could
7158 			 * be in a port reset. Figure out if any corrective
7159 			 * actions need to be taken.
7160 			 */
7161 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7162 						 LPFC_RSC_TYPE_FCOE_VFI);
7163 			if (rc != 0)
7164 				error++;
7165 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7166 						 LPFC_RSC_TYPE_FCOE_VPI);
7167 			if (rc != 0)
7168 				error++;
7169 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7170 						 LPFC_RSC_TYPE_FCOE_XRI);
7171 			if (rc != 0)
7172 				error++;
7173 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7174 						 LPFC_RSC_TYPE_FCOE_RPI);
7175 			if (rc != 0)
7176 				error++;
7177 
7178 			/*
7179 			 * It's possible that the number of resources
7180 			 * provided to this port instance changed between
7181 			 * resets.  Detect this condition and reallocate
7182 			 * resources.  Otherwise, there is no action.
7183 			 */
7184 			if (error) {
7185 				lpfc_printf_log(phba, KERN_INFO,
7186 						LOG_MBOX | LOG_INIT,
7187 						"2931 Detected extent resource "
7188 						"change.  Reallocating all "
7189 						"extents.\n");
7190 				rc = lpfc_sli4_dealloc_extent(phba,
7191 						 LPFC_RSC_TYPE_FCOE_VFI);
7192 				rc = lpfc_sli4_dealloc_extent(phba,
7193 						 LPFC_RSC_TYPE_FCOE_VPI);
7194 				rc = lpfc_sli4_dealloc_extent(phba,
7195 						 LPFC_RSC_TYPE_FCOE_XRI);
7196 				rc = lpfc_sli4_dealloc_extent(phba,
7197 						 LPFC_RSC_TYPE_FCOE_RPI);
7198 			} else
7199 				return 0;
7200 		}
7201 
7202 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7203 		if (unlikely(rc))
7204 			goto err_exit;
7205 
7206 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7207 		if (unlikely(rc))
7208 			goto err_exit;
7209 
7210 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7211 		if (unlikely(rc))
7212 			goto err_exit;
7213 
7214 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7215 		if (unlikely(rc))
7216 			goto err_exit;
7217 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7218 		       LPFC_IDX_RSRC_RDY);
7219 		return rc;
7220 	} else {
7221 		/*
7222 		 * The port does not support resource extents.  The XRI, VPI,
7223 		 * VFI, RPI resource ids were determined from READ_CONFIG.
7224 		 * Just allocate the bitmasks and provision the resource id
7225 		 * arrays.  If a port reset is active, the resources don't
7226 		 * need any action - just exit.
7227 		 */
7228 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7229 		    LPFC_IDX_RSRC_RDY) {
7230 			lpfc_sli4_dealloc_resource_identifiers(phba);
7231 			lpfc_sli4_remove_rpis(phba);
7232 		}
7233 		/* RPIs. */
7234 		count = phba->sli4_hba.max_cfg_param.max_rpi;
7235 		if (count <= 0) {
7236 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7237 					"3279 Invalid provisioning of "
7238 					"rpi:%d\n", count);
7239 			rc = -EINVAL;
7240 			goto err_exit;
7241 		}
7242 		base = phba->sli4_hba.max_cfg_param.rpi_base;
7243 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7244 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
7245 						   sizeof(unsigned long),
7246 						   GFP_KERNEL);
7247 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
7248 			rc = -ENOMEM;
7249 			goto err_exit;
7250 		}
7251 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
7252 						 GFP_KERNEL);
7253 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
7254 			rc = -ENOMEM;
7255 			goto free_rpi_bmask;
7256 		}
7257 
7258 		for (i = 0; i < count; i++)
7259 			phba->sli4_hba.rpi_ids[i] = base + i;
7260 
7261 		/* VPIs. */
7262 		count = phba->sli4_hba.max_cfg_param.max_vpi;
7263 		if (count <= 0) {
7264 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7265 					"3280 Invalid provisioning of "
7266 					"vpi:%d\n", count);
7267 			rc = -EINVAL;
7268 			goto free_rpi_ids;
7269 		}
7270 		base = phba->sli4_hba.max_cfg_param.vpi_base;
7271 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7272 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
7273 					  GFP_KERNEL);
7274 		if (unlikely(!phba->vpi_bmask)) {
7275 			rc = -ENOMEM;
7276 			goto free_rpi_ids;
7277 		}
7278 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
7279 					GFP_KERNEL);
7280 		if (unlikely(!phba->vpi_ids)) {
7281 			rc = -ENOMEM;
7282 			goto free_vpi_bmask;
7283 		}
7284 
7285 		for (i = 0; i < count; i++)
7286 			phba->vpi_ids[i] = base + i;
7287 
7288 		/* XRIs. */
7289 		count = phba->sli4_hba.max_cfg_param.max_xri;
7290 		if (count <= 0) {
7291 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7292 					"3281 Invalid provisioning of "
7293 					"xri:%d\n", count);
7294 			rc = -EINVAL;
7295 			goto free_vpi_ids;
7296 		}
7297 		base = phba->sli4_hba.max_cfg_param.xri_base;
7298 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7299 		phba->sli4_hba.xri_bmask = kcalloc(longs,
7300 						   sizeof(unsigned long),
7301 						   GFP_KERNEL);
7302 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
7303 			rc = -ENOMEM;
7304 			goto free_vpi_ids;
7305 		}
7306 		phba->sli4_hba.max_cfg_param.xri_used = 0;
7307 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
7308 						 GFP_KERNEL);
7309 		if (unlikely(!phba->sli4_hba.xri_ids)) {
7310 			rc = -ENOMEM;
7311 			goto free_xri_bmask;
7312 		}
7313 
7314 		for (i = 0; i < count; i++)
7315 			phba->sli4_hba.xri_ids[i] = base + i;
7316 
7317 		/* VFIs. */
7318 		count = phba->sli4_hba.max_cfg_param.max_vfi;
7319 		if (count <= 0) {
7320 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7321 					"3282 Invalid provisioning of "
7322 					"vfi:%d\n", count);
7323 			rc = -EINVAL;
7324 			goto free_xri_ids;
7325 		}
7326 		base = phba->sli4_hba.max_cfg_param.vfi_base;
7327 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7328 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
7329 						   sizeof(unsigned long),
7330 						   GFP_KERNEL);
7331 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
7332 			rc = -ENOMEM;
7333 			goto free_xri_ids;
7334 		}
7335 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
7336 						 GFP_KERNEL);
7337 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
7338 			rc = -ENOMEM;
7339 			goto free_vfi_bmask;
7340 		}
7341 
7342 		for (i = 0; i < count; i++)
7343 			phba->sli4_hba.vfi_ids[i] = base + i;
7344 
7345 		/*
7346 		 * Mark all resources ready.  An HBA reset doesn't need
7347 		 * to reset the initialization.
7348 		 */
7349 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7350 		       LPFC_IDX_RSRC_RDY);
7351 		return 0;
7352 	}
7353 
7354  free_vfi_bmask:
7355 	kfree(phba->sli4_hba.vfi_bmask);
7356 	phba->sli4_hba.vfi_bmask = NULL;
7357  free_xri_ids:
7358 	kfree(phba->sli4_hba.xri_ids);
7359 	phba->sli4_hba.xri_ids = NULL;
7360  free_xri_bmask:
7361 	kfree(phba->sli4_hba.xri_bmask);
7362 	phba->sli4_hba.xri_bmask = NULL;
7363  free_vpi_ids:
7364 	kfree(phba->vpi_ids);
7365 	phba->vpi_ids = NULL;
7366  free_vpi_bmask:
7367 	kfree(phba->vpi_bmask);
7368 	phba->vpi_bmask = NULL;
7369  free_rpi_ids:
7370 	kfree(phba->sli4_hba.rpi_ids);
7371 	phba->sli4_hba.rpi_ids = NULL;
7372  free_rpi_bmask:
7373 	kfree(phba->sli4_hba.rpi_bmask);
7374 	phba->sli4_hba.rpi_bmask = NULL;
7375  err_exit:
7376 	return rc;
7377 }
7378 
7379 /**
7380  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
7381  * @phba: Pointer to HBA context object.
7382  *
7383  * This function allocates the number of elements for the specified
7384  * resource type.
7385  **/
7386 int
7387 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7388 {
7389 	if (phba->sli4_hba.extents_in_use) {
7390 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7391 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7392 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7393 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7394 	} else {
7395 		kfree(phba->vpi_bmask);
7396 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
7397 		kfree(phba->vpi_ids);
7398 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7399 		kfree(phba->sli4_hba.xri_bmask);
7400 		kfree(phba->sli4_hba.xri_ids);
7401 		kfree(phba->sli4_hba.vfi_bmask);
7402 		kfree(phba->sli4_hba.vfi_ids);
7403 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7404 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7405 	}
7406 
7407 	return 0;
7408 }
7409 
7410 /**
7411  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7412  * @phba: Pointer to HBA context object.
7413  * @type: The resource extent type.
7414  * @extnt_cnt: buffer to hold port extent count response
7415  * @extnt_size: buffer to hold port extent size response.
7416  *
7417  * This function calls the port to read the host allocated extents
7418  * for a particular type.
7419  **/
7420 int
7421 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7422 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
7423 {
7424 	bool emb;
7425 	int rc = 0;
7426 	uint16_t curr_blks = 0;
7427 	uint32_t req_len, emb_len;
7428 	uint32_t alloc_len, mbox_tmo;
7429 	struct list_head *blk_list_head;
7430 	struct lpfc_rsrc_blks *rsrc_blk;
7431 	LPFC_MBOXQ_t *mbox;
7432 	void *virtaddr = NULL;
7433 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7434 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7435 	union  lpfc_sli4_cfg_shdr *shdr;
7436 
7437 	switch (type) {
7438 	case LPFC_RSC_TYPE_FCOE_VPI:
7439 		blk_list_head = &phba->lpfc_vpi_blk_list;
7440 		break;
7441 	case LPFC_RSC_TYPE_FCOE_XRI:
7442 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7443 		break;
7444 	case LPFC_RSC_TYPE_FCOE_VFI:
7445 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7446 		break;
7447 	case LPFC_RSC_TYPE_FCOE_RPI:
7448 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7449 		break;
7450 	default:
7451 		return -EIO;
7452 	}
7453 
7454 	/* Count the number of extents currently allocatd for this type. */
7455 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
7456 		if (curr_blks == 0) {
7457 			/*
7458 			 * The GET_ALLOCATED mailbox does not return the size,
7459 			 * just the count.  The size should be just the size
7460 			 * stored in the current allocated block and all sizes
7461 			 * for an extent type are the same so set the return
7462 			 * value now.
7463 			 */
7464 			*extnt_size = rsrc_blk->rsrc_size;
7465 		}
7466 		curr_blks++;
7467 	}
7468 
7469 	/*
7470 	 * Calculate the size of an embedded mailbox.  The uint32_t
7471 	 * accounts for extents-specific word.
7472 	 */
7473 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7474 		sizeof(uint32_t);
7475 
7476 	/*
7477 	 * Presume the allocation and response will fit into an embedded
7478 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7479 	 */
7480 	emb = LPFC_SLI4_MBX_EMBED;
7481 	req_len = emb_len;
7482 	if (req_len > emb_len) {
7483 		req_len = curr_blks * sizeof(uint16_t) +
7484 			sizeof(union lpfc_sli4_cfg_shdr) +
7485 			sizeof(uint32_t);
7486 		emb = LPFC_SLI4_MBX_NEMBED;
7487 	}
7488 
7489 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7490 	if (!mbox)
7491 		return -ENOMEM;
7492 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7493 
7494 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7495 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7496 				     req_len, emb);
7497 	if (alloc_len < req_len) {
7498 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7499 			"2983 Allocated DMA memory size (x%x) is "
7500 			"less than the requested DMA memory "
7501 			"size (x%x)\n", alloc_len, req_len);
7502 		rc = -ENOMEM;
7503 		goto err_exit;
7504 	}
7505 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7506 	if (unlikely(rc)) {
7507 		rc = -EIO;
7508 		goto err_exit;
7509 	}
7510 
7511 	if (!phba->sli4_hba.intr_enable)
7512 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7513 	else {
7514 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7515 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7516 	}
7517 
7518 	if (unlikely(rc)) {
7519 		rc = -EIO;
7520 		goto err_exit;
7521 	}
7522 
7523 	/*
7524 	 * Figure out where the response is located.  Then get local pointers
7525 	 * to the response data.  The port does not guarantee to respond to
7526 	 * all extents counts request so update the local variable with the
7527 	 * allocated count from the port.
7528 	 */
7529 	if (emb == LPFC_SLI4_MBX_EMBED) {
7530 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7531 		shdr = &rsrc_ext->header.cfg_shdr;
7532 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7533 	} else {
7534 		virtaddr = mbox->sge_array->addr[0];
7535 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7536 		shdr = &n_rsrc->cfg_shdr;
7537 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7538 	}
7539 
7540 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7541 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7542 			"2984 Failed to read allocated resources "
7543 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7544 			type,
7545 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7546 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7547 		rc = -EIO;
7548 		goto err_exit;
7549 	}
7550  err_exit:
7551 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7552 	return rc;
7553 }
7554 
7555 /**
7556  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7557  * @phba: pointer to lpfc hba data structure.
7558  * @sgl_list: linked link of sgl buffers to post
7559  * @cnt: number of linked list buffers
7560  *
7561  * This routine walks the list of buffers that have been allocated and
7562  * repost them to the port by using SGL block post. This is needed after a
7563  * pci_function_reset/warm_start or start. It attempts to construct blocks
7564  * of buffer sgls which contains contiguous xris and uses the non-embedded
7565  * SGL block post mailbox commands to post them to the port. For single
7566  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7567  * mailbox command for posting.
7568  *
7569  * Returns: 0 = success, non-zero failure.
7570  **/
7571 static int
7572 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7573 			  struct list_head *sgl_list, int cnt)
7574 {
7575 	struct lpfc_sglq *sglq_entry = NULL;
7576 	struct lpfc_sglq *sglq_entry_next = NULL;
7577 	struct lpfc_sglq *sglq_entry_first = NULL;
7578 	int status, total_cnt;
7579 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7580 	int last_xritag = NO_XRI;
7581 	LIST_HEAD(prep_sgl_list);
7582 	LIST_HEAD(blck_sgl_list);
7583 	LIST_HEAD(allc_sgl_list);
7584 	LIST_HEAD(post_sgl_list);
7585 	LIST_HEAD(free_sgl_list);
7586 
7587 	spin_lock_irq(&phba->hbalock);
7588 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7589 	list_splice_init(sgl_list, &allc_sgl_list);
7590 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7591 	spin_unlock_irq(&phba->hbalock);
7592 
7593 	total_cnt = cnt;
7594 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7595 				 &allc_sgl_list, list) {
7596 		list_del_init(&sglq_entry->list);
7597 		block_cnt++;
7598 		if ((last_xritag != NO_XRI) &&
7599 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7600 			/* a hole in xri block, form a sgl posting block */
7601 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7602 			post_cnt = block_cnt - 1;
7603 			/* prepare list for next posting block */
7604 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7605 			block_cnt = 1;
7606 		} else {
7607 			/* prepare list for next posting block */
7608 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7609 			/* enough sgls for non-embed sgl mbox command */
7610 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7611 				list_splice_init(&prep_sgl_list,
7612 						 &blck_sgl_list);
7613 				post_cnt = block_cnt;
7614 				block_cnt = 0;
7615 			}
7616 		}
7617 		num_posted++;
7618 
7619 		/* keep track of last sgl's xritag */
7620 		last_xritag = sglq_entry->sli4_xritag;
7621 
7622 		/* end of repost sgl list condition for buffers */
7623 		if (num_posted == total_cnt) {
7624 			if (post_cnt == 0) {
7625 				list_splice_init(&prep_sgl_list,
7626 						 &blck_sgl_list);
7627 				post_cnt = block_cnt;
7628 			} else if (block_cnt == 1) {
7629 				status = lpfc_sli4_post_sgl(phba,
7630 						sglq_entry->phys, 0,
7631 						sglq_entry->sli4_xritag);
7632 				if (!status) {
7633 					/* successful, put sgl to posted list */
7634 					list_add_tail(&sglq_entry->list,
7635 						      &post_sgl_list);
7636 				} else {
7637 					/* Failure, put sgl to free list */
7638 					lpfc_printf_log(phba, KERN_WARNING,
7639 						LOG_SLI,
7640 						"3159 Failed to post "
7641 						"sgl, xritag:x%x\n",
7642 						sglq_entry->sli4_xritag);
7643 					list_add_tail(&sglq_entry->list,
7644 						      &free_sgl_list);
7645 					total_cnt--;
7646 				}
7647 			}
7648 		}
7649 
7650 		/* continue until a nembed page worth of sgls */
7651 		if (post_cnt == 0)
7652 			continue;
7653 
7654 		/* post the buffer list sgls as a block */
7655 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7656 						 post_cnt);
7657 
7658 		if (!status) {
7659 			/* success, put sgl list to posted sgl list */
7660 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7661 		} else {
7662 			/* Failure, put sgl list to free sgl list */
7663 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7664 							    struct lpfc_sglq,
7665 							    list);
7666 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7667 					"3160 Failed to post sgl-list, "
7668 					"xritag:x%x-x%x\n",
7669 					sglq_entry_first->sli4_xritag,
7670 					(sglq_entry_first->sli4_xritag +
7671 					 post_cnt - 1));
7672 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7673 			total_cnt -= post_cnt;
7674 		}
7675 
7676 		/* don't reset xirtag due to hole in xri block */
7677 		if (block_cnt == 0)
7678 			last_xritag = NO_XRI;
7679 
7680 		/* reset sgl post count for next round of posting */
7681 		post_cnt = 0;
7682 	}
7683 
7684 	/* free the sgls failed to post */
7685 	lpfc_free_sgl_list(phba, &free_sgl_list);
7686 
7687 	/* push sgls posted to the available list */
7688 	if (!list_empty(&post_sgl_list)) {
7689 		spin_lock_irq(&phba->hbalock);
7690 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7691 		list_splice_init(&post_sgl_list, sgl_list);
7692 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7693 		spin_unlock_irq(&phba->hbalock);
7694 	} else {
7695 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7696 				"3161 Failure to post sgl to port.\n");
7697 		return -EIO;
7698 	}
7699 
7700 	/* return the number of XRIs actually posted */
7701 	return total_cnt;
7702 }
7703 
7704 /**
7705  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7706  * @phba: pointer to lpfc hba data structure.
7707  *
7708  * This routine walks the list of nvme buffers that have been allocated and
7709  * repost them to the port by using SGL block post. This is needed after a
7710  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7711  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7712  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7713  *
7714  * Returns: 0 = success, non-zero failure.
7715  **/
7716 static int
7717 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7718 {
7719 	LIST_HEAD(post_nblist);
7720 	int num_posted, rc = 0;
7721 
7722 	/* get all NVME buffers need to repost to a local list */
7723 	lpfc_io_buf_flush(phba, &post_nblist);
7724 
7725 	/* post the list of nvme buffer sgls to port if available */
7726 	if (!list_empty(&post_nblist)) {
7727 		num_posted = lpfc_sli4_post_io_sgl_list(
7728 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7729 		/* failed to post any nvme buffer, return error */
7730 		if (num_posted == 0)
7731 			rc = -EIO;
7732 	}
7733 	return rc;
7734 }
7735 
7736 static void
7737 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7738 {
7739 	uint32_t len;
7740 
7741 	len = sizeof(struct lpfc_mbx_set_host_data) -
7742 		sizeof(struct lpfc_sli4_cfg_mhdr);
7743 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7744 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7745 			 LPFC_SLI4_MBX_EMBED);
7746 
7747 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7748 	mbox->u.mqe.un.set_host_data.param_len =
7749 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7750 	snprintf(mbox->u.mqe.un.set_host_data.un.data,
7751 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7752 		 "Linux %s v"LPFC_DRIVER_VERSION,
7753 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7754 }
7755 
7756 int
7757 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7758 		    struct lpfc_queue *drq, int count, int idx)
7759 {
7760 	int rc, i;
7761 	struct lpfc_rqe hrqe;
7762 	struct lpfc_rqe drqe;
7763 	struct lpfc_rqb *rqbp;
7764 	unsigned long flags;
7765 	struct rqb_dmabuf *rqb_buffer;
7766 	LIST_HEAD(rqb_buf_list);
7767 
7768 	rqbp = hrq->rqbp;
7769 	for (i = 0; i < count; i++) {
7770 		spin_lock_irqsave(&phba->hbalock, flags);
7771 		/* IF RQ is already full, don't bother */
7772 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7773 			spin_unlock_irqrestore(&phba->hbalock, flags);
7774 			break;
7775 		}
7776 		spin_unlock_irqrestore(&phba->hbalock, flags);
7777 
7778 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7779 		if (!rqb_buffer)
7780 			break;
7781 		rqb_buffer->hrq = hrq;
7782 		rqb_buffer->drq = drq;
7783 		rqb_buffer->idx = idx;
7784 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7785 	}
7786 
7787 	spin_lock_irqsave(&phba->hbalock, flags);
7788 	while (!list_empty(&rqb_buf_list)) {
7789 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7790 				 hbuf.list);
7791 
7792 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7793 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7794 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7795 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7796 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7797 		if (rc < 0) {
7798 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7799 					"6421 Cannot post to HRQ %d: %x %x %x "
7800 					"DRQ %x %x\n",
7801 					hrq->queue_id,
7802 					hrq->host_index,
7803 					hrq->hba_index,
7804 					hrq->entry_count,
7805 					drq->host_index,
7806 					drq->hba_index);
7807 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7808 		} else {
7809 			list_add_tail(&rqb_buffer->hbuf.list,
7810 				      &rqbp->rqb_buffer_list);
7811 			rqbp->buffer_count++;
7812 		}
7813 	}
7814 	spin_unlock_irqrestore(&phba->hbalock, flags);
7815 	return 1;
7816 }
7817 
7818 static void
7819 lpfc_mbx_cmpl_read_lds_params(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7820 {
7821 	union lpfc_sli4_cfg_shdr *shdr;
7822 	u32 shdr_status, shdr_add_status;
7823 
7824 	shdr = (union lpfc_sli4_cfg_shdr *)
7825 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7826 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7827 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7828 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7829 		lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT | LOG_MBOX,
7830 				"4622 SET_FEATURE (x%x) mbox failed, "
7831 				"status x%x add_status x%x, mbx status x%x\n",
7832 				LPFC_SET_LD_SIGNAL, shdr_status,
7833 				shdr_add_status, pmb->u.mb.mbxStatus);
7834 		phba->degrade_activate_threshold = 0;
7835 		phba->degrade_deactivate_threshold = 0;
7836 		phba->fec_degrade_interval = 0;
7837 		goto out;
7838 	}
7839 
7840 	phba->degrade_activate_threshold = pmb->u.mqe.un.set_feature.word7;
7841 	phba->degrade_deactivate_threshold = pmb->u.mqe.un.set_feature.word8;
7842 	phba->fec_degrade_interval = pmb->u.mqe.un.set_feature.word10;
7843 
7844 	lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT,
7845 			"4624 Success: da x%x dd x%x interval x%x\n",
7846 			phba->degrade_activate_threshold,
7847 			phba->degrade_deactivate_threshold,
7848 			phba->fec_degrade_interval);
7849 out:
7850 	mempool_free(pmb, phba->mbox_mem_pool);
7851 }
7852 
7853 int
7854 lpfc_read_lds_params(struct lpfc_hba *phba)
7855 {
7856 	LPFC_MBOXQ_t *mboxq;
7857 	int rc;
7858 
7859 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7860 	if (!mboxq)
7861 		return -ENOMEM;
7862 
7863 	lpfc_set_features(phba, mboxq, LPFC_SET_LD_SIGNAL);
7864 	mboxq->vport = phba->pport;
7865 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_lds_params;
7866 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7867 	if (rc == MBX_NOT_FINISHED) {
7868 		mempool_free(mboxq, phba->mbox_mem_pool);
7869 		return -EIO;
7870 	}
7871 	return 0;
7872 }
7873 
7874 static void
7875 lpfc_mbx_cmpl_cgn_set_ftrs(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7876 {
7877 	struct lpfc_vport *vport = pmb->vport;
7878 	union lpfc_sli4_cfg_shdr *shdr;
7879 	u32 shdr_status, shdr_add_status;
7880 	u32 sig, acqe;
7881 
7882 	/* Two outcomes. (1) Set featurs was successul and EDC negotiation
7883 	 * is done. (2) Mailbox failed and send FPIN support only.
7884 	 */
7885 	shdr = (union lpfc_sli4_cfg_shdr *)
7886 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7887 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7888 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7889 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7890 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
7891 				"2516 CGN SET_FEATURE mbox failed with "
7892 				"status x%x add_status x%x, mbx status x%x "
7893 				"Reset Congestion to FPINs only\n",
7894 				shdr_status, shdr_add_status,
7895 				pmb->u.mb.mbxStatus);
7896 		/* If there is a mbox error, move on to RDF */
7897 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7898 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7899 		goto out;
7900 	}
7901 
7902 	/* Zero out Congestion Signal ACQE counter */
7903 	phba->cgn_acqe_cnt = 0;
7904 
7905 	acqe = bf_get(lpfc_mbx_set_feature_CGN_acqe_freq,
7906 		      &pmb->u.mqe.un.set_feature);
7907 	sig = bf_get(lpfc_mbx_set_feature_CGN_warn_freq,
7908 		     &pmb->u.mqe.un.set_feature);
7909 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7910 			"4620 SET_FEATURES Success: Freq: %ds %dms "
7911 			" Reg: x%x x%x\n", acqe, sig,
7912 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7913 out:
7914 	mempool_free(pmb, phba->mbox_mem_pool);
7915 
7916 	/* Register for FPIN events from the fabric now that the
7917 	 * EDC common_set_features has completed.
7918 	 */
7919 	lpfc_issue_els_rdf(vport, 0);
7920 }
7921 
7922 int
7923 lpfc_config_cgn_signal(struct lpfc_hba *phba)
7924 {
7925 	LPFC_MBOXQ_t *mboxq;
7926 	u32 rc;
7927 
7928 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7929 	if (!mboxq)
7930 		goto out_rdf;
7931 
7932 	lpfc_set_features(phba, mboxq, LPFC_SET_CGN_SIGNAL);
7933 	mboxq->vport = phba->pport;
7934 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_cgn_set_ftrs;
7935 
7936 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7937 			"4621 SET_FEATURES: FREQ sig x%x acqe x%x: "
7938 			"Reg: x%x x%x\n",
7939 			phba->cgn_sig_freq, lpfc_acqe_cgn_frequency,
7940 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7941 
7942 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7943 	if (rc == MBX_NOT_FINISHED)
7944 		goto out;
7945 	return 0;
7946 
7947 out:
7948 	mempool_free(mboxq, phba->mbox_mem_pool);
7949 out_rdf:
7950 	/* If there is a mbox error, move on to RDF */
7951 	phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7952 	phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7953 	lpfc_issue_els_rdf(phba->pport, 0);
7954 	return -EIO;
7955 }
7956 
7957 /**
7958  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7959  * @phba: pointer to lpfc hba data structure.
7960  *
7961  * This routine initializes the per-eq idle_stat to dynamically dictate
7962  * polling decisions.
7963  *
7964  * Return codes:
7965  *   None
7966  **/
7967 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
7968 {
7969 	int i;
7970 	struct lpfc_sli4_hdw_queue *hdwq;
7971 	struct lpfc_queue *eq;
7972 	struct lpfc_idle_stat *idle_stat;
7973 	u64 wall;
7974 
7975 	for_each_present_cpu(i) {
7976 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
7977 		eq = hdwq->hba_eq;
7978 
7979 		/* Skip if we've already handled this eq's primary CPU */
7980 		if (eq->chann != i)
7981 			continue;
7982 
7983 		idle_stat = &phba->sli4_hba.idle_stat[i];
7984 
7985 		idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
7986 		idle_stat->prev_wall = wall;
7987 
7988 		if (phba->nvmet_support ||
7989 		    phba->cmf_active_mode != LPFC_CFG_OFF ||
7990 		    phba->intr_type != MSIX)
7991 			eq->poll_mode = LPFC_QUEUE_WORK;
7992 		else
7993 			eq->poll_mode = LPFC_THREADED_IRQ;
7994 	}
7995 
7996 	if (!phba->nvmet_support && phba->intr_type == MSIX)
7997 		schedule_delayed_work(&phba->idle_stat_delay_work,
7998 				      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
7999 }
8000 
8001 static void lpfc_sli4_dip(struct lpfc_hba *phba)
8002 {
8003 	uint32_t if_type;
8004 
8005 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
8006 	if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
8007 	    if_type == LPFC_SLI_INTF_IF_TYPE_6) {
8008 		struct lpfc_register reg_data;
8009 
8010 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
8011 			       &reg_data.word0))
8012 			return;
8013 
8014 		if (bf_get(lpfc_sliport_status_dip, &reg_data))
8015 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8016 					"2904 Firmware Dump Image Present"
8017 					" on Adapter");
8018 	}
8019 }
8020 
8021 /**
8022  * lpfc_rx_monitor_create_ring - Initialize ring buffer for rx_monitor
8023  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8024  * @entries: Number of rx_info_entry objects to allocate in ring
8025  *
8026  * Return:
8027  * 0 - Success
8028  * ENOMEM - Failure to kmalloc
8029  **/
8030 int lpfc_rx_monitor_create_ring(struct lpfc_rx_info_monitor *rx_monitor,
8031 				u32 entries)
8032 {
8033 	rx_monitor->ring = kmalloc_array(entries, sizeof(struct rx_info_entry),
8034 					 GFP_KERNEL);
8035 	if (!rx_monitor->ring)
8036 		return -ENOMEM;
8037 
8038 	rx_monitor->head_idx = 0;
8039 	rx_monitor->tail_idx = 0;
8040 	spin_lock_init(&rx_monitor->lock);
8041 	rx_monitor->entries = entries;
8042 
8043 	return 0;
8044 }
8045 
8046 /**
8047  * lpfc_rx_monitor_destroy_ring - Free ring buffer for rx_monitor
8048  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8049  *
8050  * Called after cancellation of cmf_timer.
8051  **/
8052 void lpfc_rx_monitor_destroy_ring(struct lpfc_rx_info_monitor *rx_monitor)
8053 {
8054 	kfree(rx_monitor->ring);
8055 	rx_monitor->ring = NULL;
8056 	rx_monitor->entries = 0;
8057 	rx_monitor->head_idx = 0;
8058 	rx_monitor->tail_idx = 0;
8059 }
8060 
8061 /**
8062  * lpfc_rx_monitor_record - Insert an entry into rx_monitor's ring
8063  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8064  * @entry: Pointer to rx_info_entry
8065  *
8066  * Used to insert an rx_info_entry into rx_monitor's ring.  Note that this is a
8067  * deep copy of rx_info_entry not a shallow copy of the rx_info_entry ptr.
8068  *
8069  * This is called from lpfc_cmf_timer, which is in timer/softirq context.
8070  *
8071  * In cases of old data overflow, we do a best effort of FIFO order.
8072  **/
8073 void lpfc_rx_monitor_record(struct lpfc_rx_info_monitor *rx_monitor,
8074 			    struct rx_info_entry *entry)
8075 {
8076 	struct rx_info_entry *ring = rx_monitor->ring;
8077 	u32 *head_idx = &rx_monitor->head_idx;
8078 	u32 *tail_idx = &rx_monitor->tail_idx;
8079 	spinlock_t *ring_lock = &rx_monitor->lock;
8080 	u32 ring_size = rx_monitor->entries;
8081 
8082 	spin_lock(ring_lock);
8083 	memcpy(&ring[*tail_idx], entry, sizeof(*entry));
8084 	*tail_idx = (*tail_idx + 1) % ring_size;
8085 
8086 	/* Best effort of FIFO saved data */
8087 	if (*tail_idx == *head_idx)
8088 		*head_idx = (*head_idx + 1) % ring_size;
8089 
8090 	spin_unlock(ring_lock);
8091 }
8092 
8093 /**
8094  * lpfc_rx_monitor_report - Read out rx_monitor's ring
8095  * @phba: Pointer to lpfc_hba object
8096  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8097  * @buf: Pointer to char buffer that will contain rx monitor info data
8098  * @buf_len: Length buf including null char
8099  * @max_read_entries: Maximum number of entries to read out of ring
8100  *
8101  * Used to dump/read what's in rx_monitor's ring buffer.
8102  *
8103  * If buf is NULL || buf_len == 0, then it is implied that we want to log the
8104  * information to kmsg instead of filling out buf.
8105  *
8106  * Return:
8107  * Number of entries read out of the ring
8108  **/
8109 u32 lpfc_rx_monitor_report(struct lpfc_hba *phba,
8110 			   struct lpfc_rx_info_monitor *rx_monitor, char *buf,
8111 			   u32 buf_len, u32 max_read_entries)
8112 {
8113 	struct rx_info_entry *ring = rx_monitor->ring;
8114 	struct rx_info_entry *entry;
8115 	u32 *head_idx = &rx_monitor->head_idx;
8116 	u32 *tail_idx = &rx_monitor->tail_idx;
8117 	spinlock_t *ring_lock = &rx_monitor->lock;
8118 	u32 ring_size = rx_monitor->entries;
8119 	u32 cnt = 0;
8120 	char tmp[DBG_LOG_STR_SZ] = {0};
8121 	bool log_to_kmsg = (!buf || !buf_len) ? true : false;
8122 
8123 	if (!log_to_kmsg) {
8124 		/* clear the buffer to be sure */
8125 		memset(buf, 0, buf_len);
8126 
8127 		scnprintf(buf, buf_len, "\t%-16s%-16s%-16s%-16s%-8s%-8s%-8s"
8128 					"%-8s%-8s%-8s%-16s\n",
8129 					"MaxBPI", "Tot_Data_CMF",
8130 					"Tot_Data_Cmd", "Tot_Data_Cmpl",
8131 					"Lat(us)", "Avg_IO", "Max_IO", "Bsy",
8132 					"IO_cnt", "Info", "BWutil(ms)");
8133 	}
8134 
8135 	/* Needs to be _irq because record is called from timer interrupt
8136 	 * context
8137 	 */
8138 	spin_lock_irq(ring_lock);
8139 	while (*head_idx != *tail_idx) {
8140 		entry = &ring[*head_idx];
8141 
8142 		/* Read out this entry's data. */
8143 		if (!log_to_kmsg) {
8144 			/* If !log_to_kmsg, then store to buf. */
8145 			scnprintf(tmp, sizeof(tmp),
8146 				  "%03d:\t%-16llu%-16llu%-16llu%-16llu%-8llu"
8147 				  "%-8llu%-8llu%-8u%-8u%-8u%u(%u)\n",
8148 				  *head_idx, entry->max_bytes_per_interval,
8149 				  entry->cmf_bytes, entry->total_bytes,
8150 				  entry->rcv_bytes, entry->avg_io_latency,
8151 				  entry->avg_io_size, entry->max_read_cnt,
8152 				  entry->cmf_busy, entry->io_cnt,
8153 				  entry->cmf_info, entry->timer_utilization,
8154 				  entry->timer_interval);
8155 
8156 			/* Check for buffer overflow */
8157 			if ((strlen(buf) + strlen(tmp)) >= buf_len)
8158 				break;
8159 
8160 			/* Append entry's data to buffer */
8161 			strlcat(buf, tmp, buf_len);
8162 		} else {
8163 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
8164 					"4410 %02u: MBPI %llu Xmit %llu "
8165 					"Cmpl %llu Lat %llu ASz %llu Info %02u "
8166 					"BWUtil %u Int %u slot %u\n",
8167 					cnt, entry->max_bytes_per_interval,
8168 					entry->total_bytes, entry->rcv_bytes,
8169 					entry->avg_io_latency,
8170 					entry->avg_io_size, entry->cmf_info,
8171 					entry->timer_utilization,
8172 					entry->timer_interval, *head_idx);
8173 		}
8174 
8175 		*head_idx = (*head_idx + 1) % ring_size;
8176 
8177 		/* Don't feed more than max_read_entries */
8178 		cnt++;
8179 		if (cnt >= max_read_entries)
8180 			break;
8181 	}
8182 	spin_unlock_irq(ring_lock);
8183 
8184 	return cnt;
8185 }
8186 
8187 /**
8188  * lpfc_cmf_setup - Initialize idle_stat tracking
8189  * @phba: Pointer to HBA context object.
8190  *
8191  * This is called from HBA setup during driver load or when the HBA
8192  * comes online. this does all the initialization to support CMF and MI.
8193  **/
8194 static int
8195 lpfc_cmf_setup(struct lpfc_hba *phba)
8196 {
8197 	LPFC_MBOXQ_t *mboxq;
8198 	struct lpfc_dmabuf *mp;
8199 	struct lpfc_pc_sli4_params *sli4_params;
8200 	int rc, cmf, mi_ver;
8201 
8202 	rc = lpfc_sli4_refresh_params(phba);
8203 	if (unlikely(rc))
8204 		return rc;
8205 
8206 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8207 	if (!mboxq)
8208 		return -ENOMEM;
8209 
8210 	sli4_params = &phba->sli4_hba.pc_sli4_params;
8211 
8212 	/* Always try to enable MI feature if we can */
8213 	if (sli4_params->mi_ver) {
8214 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_MI);
8215 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8216 		mi_ver = bf_get(lpfc_mbx_set_feature_mi,
8217 				 &mboxq->u.mqe.un.set_feature);
8218 
8219 		if (rc == MBX_SUCCESS) {
8220 			if (mi_ver) {
8221 				lpfc_printf_log(phba,
8222 						KERN_WARNING, LOG_CGN_MGMT,
8223 						"6215 MI is enabled\n");
8224 				sli4_params->mi_ver = mi_ver;
8225 			} else {
8226 				lpfc_printf_log(phba,
8227 						KERN_WARNING, LOG_CGN_MGMT,
8228 						"6338 MI is disabled\n");
8229 				sli4_params->mi_ver = 0;
8230 			}
8231 		} else {
8232 			/* mi_ver is already set from GET_SLI4_PARAMETERS */
8233 			lpfc_printf_log(phba, KERN_INFO,
8234 					LOG_CGN_MGMT | LOG_INIT,
8235 					"6245 Enable MI Mailbox x%x (x%x/x%x) "
8236 					"failed, rc:x%x mi:x%x\n",
8237 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8238 					lpfc_sli_config_mbox_subsys_get
8239 						(phba, mboxq),
8240 					lpfc_sli_config_mbox_opcode_get
8241 						(phba, mboxq),
8242 					rc, sli4_params->mi_ver);
8243 		}
8244 	} else {
8245 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8246 				"6217 MI is disabled\n");
8247 	}
8248 
8249 	/* Ensure FDMI is enabled for MI if enable_mi is set */
8250 	if (sli4_params->mi_ver)
8251 		phba->cfg_fdmi_on = LPFC_FDMI_SUPPORT;
8252 
8253 	/* Always try to enable CMF feature if we can */
8254 	if (sli4_params->cmf) {
8255 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_CMF);
8256 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8257 		cmf = bf_get(lpfc_mbx_set_feature_cmf,
8258 			     &mboxq->u.mqe.un.set_feature);
8259 		if (rc == MBX_SUCCESS && cmf) {
8260 			lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8261 					"6218 CMF is enabled: mode %d\n",
8262 					phba->cmf_active_mode);
8263 		} else {
8264 			lpfc_printf_log(phba, KERN_WARNING,
8265 					LOG_CGN_MGMT | LOG_INIT,
8266 					"6219 Enable CMF Mailbox x%x (x%x/x%x) "
8267 					"failed, rc:x%x dd:x%x\n",
8268 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8269 					lpfc_sli_config_mbox_subsys_get
8270 						(phba, mboxq),
8271 					lpfc_sli_config_mbox_opcode_get
8272 						(phba, mboxq),
8273 					rc, cmf);
8274 			sli4_params->cmf = 0;
8275 			phba->cmf_active_mode = LPFC_CFG_OFF;
8276 			goto no_cmf;
8277 		}
8278 
8279 		/* Allocate Congestion Information Buffer */
8280 		if (!phba->cgn_i) {
8281 			mp = kmalloc(sizeof(*mp), GFP_KERNEL);
8282 			if (mp)
8283 				mp->virt = dma_alloc_coherent
8284 						(&phba->pcidev->dev,
8285 						sizeof(struct lpfc_cgn_info),
8286 						&mp->phys, GFP_KERNEL);
8287 			if (!mp || !mp->virt) {
8288 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8289 						"2640 Failed to alloc memory "
8290 						"for Congestion Info\n");
8291 				kfree(mp);
8292 				sli4_params->cmf = 0;
8293 				phba->cmf_active_mode = LPFC_CFG_OFF;
8294 				goto no_cmf;
8295 			}
8296 			phba->cgn_i = mp;
8297 
8298 			/* initialize congestion buffer info */
8299 			lpfc_init_congestion_buf(phba);
8300 			lpfc_init_congestion_stat(phba);
8301 
8302 			/* Zero out Congestion Signal counters */
8303 			atomic64_set(&phba->cgn_acqe_stat.alarm, 0);
8304 			atomic64_set(&phba->cgn_acqe_stat.warn, 0);
8305 		}
8306 
8307 		rc = lpfc_sli4_cgn_params_read(phba);
8308 		if (rc < 0) {
8309 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8310 					"6242 Error reading Cgn Params (%d)\n",
8311 					rc);
8312 			/* Ensure CGN Mode is off */
8313 			sli4_params->cmf = 0;
8314 		} else if (!rc) {
8315 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8316 					"6243 CGN Event empty object.\n");
8317 			/* Ensure CGN Mode is off */
8318 			sli4_params->cmf = 0;
8319 		}
8320 	} else {
8321 no_cmf:
8322 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8323 				"6220 CMF is disabled\n");
8324 	}
8325 
8326 	/* Only register congestion buffer with firmware if BOTH
8327 	 * CMF and E2E are enabled.
8328 	 */
8329 	if (sli4_params->cmf && sli4_params->mi_ver) {
8330 		rc = lpfc_reg_congestion_buf(phba);
8331 		if (rc) {
8332 			dma_free_coherent(&phba->pcidev->dev,
8333 					  sizeof(struct lpfc_cgn_info),
8334 					  phba->cgn_i->virt, phba->cgn_i->phys);
8335 			kfree(phba->cgn_i);
8336 			phba->cgn_i = NULL;
8337 			/* Ensure CGN Mode is off */
8338 			phba->cmf_active_mode = LPFC_CFG_OFF;
8339 			sli4_params->cmf = 0;
8340 			return 0;
8341 		}
8342 	}
8343 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8344 			"6470 Setup MI version %d CMF %d mode %d\n",
8345 			sli4_params->mi_ver, sli4_params->cmf,
8346 			phba->cmf_active_mode);
8347 
8348 	mempool_free(mboxq, phba->mbox_mem_pool);
8349 
8350 	/* Initialize atomic counters */
8351 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
8352 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
8353 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
8354 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
8355 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
8356 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
8357 	atomic64_set(&phba->cgn_latency_evt, 0);
8358 
8359 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
8360 
8361 	/* Allocate RX Monitor Buffer */
8362 	if (!phba->rx_monitor) {
8363 		phba->rx_monitor = kzalloc(sizeof(*phba->rx_monitor),
8364 					   GFP_KERNEL);
8365 
8366 		if (!phba->rx_monitor) {
8367 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8368 					"2644 Failed to alloc memory "
8369 					"for RX Monitor Buffer\n");
8370 			return -ENOMEM;
8371 		}
8372 
8373 		/* Instruct the rx_monitor object to instantiate its ring */
8374 		if (lpfc_rx_monitor_create_ring(phba->rx_monitor,
8375 						LPFC_MAX_RXMONITOR_ENTRY)) {
8376 			kfree(phba->rx_monitor);
8377 			phba->rx_monitor = NULL;
8378 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8379 					"2645 Failed to alloc memory "
8380 					"for RX Monitor's Ring\n");
8381 			return -ENOMEM;
8382 		}
8383 	}
8384 
8385 	return 0;
8386 }
8387 
8388 static int
8389 lpfc_set_host_tm(struct lpfc_hba *phba)
8390 {
8391 	LPFC_MBOXQ_t *mboxq;
8392 	uint32_t len, rc;
8393 	struct timespec64 cur_time;
8394 	struct tm broken;
8395 	uint32_t month, day, year;
8396 	uint32_t hour, minute, second;
8397 	struct lpfc_mbx_set_host_date_time *tm;
8398 
8399 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8400 	if (!mboxq)
8401 		return -ENOMEM;
8402 
8403 	len = sizeof(struct lpfc_mbx_set_host_data) -
8404 		sizeof(struct lpfc_sli4_cfg_mhdr);
8405 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
8406 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
8407 			 LPFC_SLI4_MBX_EMBED);
8408 
8409 	mboxq->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_DATE_TIME;
8410 	mboxq->u.mqe.un.set_host_data.param_len =
8411 			sizeof(struct lpfc_mbx_set_host_date_time);
8412 	tm = &mboxq->u.mqe.un.set_host_data.un.tm;
8413 	ktime_get_real_ts64(&cur_time);
8414 	time64_to_tm(cur_time.tv_sec, 0, &broken);
8415 	month = broken.tm_mon + 1;
8416 	day = broken.tm_mday;
8417 	year = broken.tm_year - 100;
8418 	hour = broken.tm_hour;
8419 	minute = broken.tm_min;
8420 	second = broken.tm_sec;
8421 	bf_set(lpfc_mbx_set_host_month, tm, month);
8422 	bf_set(lpfc_mbx_set_host_day, tm, day);
8423 	bf_set(lpfc_mbx_set_host_year, tm, year);
8424 	bf_set(lpfc_mbx_set_host_hour, tm, hour);
8425 	bf_set(lpfc_mbx_set_host_min, tm, minute);
8426 	bf_set(lpfc_mbx_set_host_sec, tm, second);
8427 
8428 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8429 	mempool_free(mboxq, phba->mbox_mem_pool);
8430 	return rc;
8431 }
8432 
8433 /**
8434  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
8435  * @phba: Pointer to HBA context object.
8436  *
8437  * This function is the main SLI4 device initialization PCI function. This
8438  * function is called by the HBA initialization code, HBA reset code and
8439  * HBA error attention handler code. Caller is not required to hold any
8440  * locks.
8441  **/
8442 int
8443 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
8444 {
8445 	int rc, i, cnt, len, dd;
8446 	LPFC_MBOXQ_t *mboxq;
8447 	struct lpfc_mqe *mqe;
8448 	uint8_t *vpd;
8449 	uint32_t vpd_size;
8450 	uint32_t ftr_rsp = 0;
8451 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
8452 	struct lpfc_vport *vport = phba->pport;
8453 	struct lpfc_dmabuf *mp;
8454 	struct lpfc_rqb *rqbp;
8455 	u32 flg;
8456 
8457 	/* Perform a PCI function reset to start from clean */
8458 	rc = lpfc_pci_function_reset(phba);
8459 	if (unlikely(rc))
8460 		return -ENODEV;
8461 
8462 	/* Check the HBA Host Status Register for readyness */
8463 	rc = lpfc_sli4_post_status_check(phba);
8464 	if (unlikely(rc))
8465 		return -ENODEV;
8466 	else {
8467 		spin_lock_irq(&phba->hbalock);
8468 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
8469 		flg = phba->sli.sli_flag;
8470 		spin_unlock_irq(&phba->hbalock);
8471 		/* Allow a little time after setting SLI_ACTIVE for any polled
8472 		 * MBX commands to complete via BSG.
8473 		 */
8474 		for (i = 0; i < 50 && (flg & LPFC_SLI_MBOX_ACTIVE); i++) {
8475 			msleep(20);
8476 			spin_lock_irq(&phba->hbalock);
8477 			flg = phba->sli.sli_flag;
8478 			spin_unlock_irq(&phba->hbalock);
8479 		}
8480 	}
8481 
8482 	lpfc_sli4_dip(phba);
8483 
8484 	/*
8485 	 * Allocate a single mailbox container for initializing the
8486 	 * port.
8487 	 */
8488 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8489 	if (!mboxq)
8490 		return -ENOMEM;
8491 
8492 	/* Issue READ_REV to collect vpd and FW information. */
8493 	vpd_size = SLI4_PAGE_SIZE;
8494 	vpd = kzalloc(vpd_size, GFP_KERNEL);
8495 	if (!vpd) {
8496 		rc = -ENOMEM;
8497 		goto out_free_mbox;
8498 	}
8499 
8500 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
8501 	if (unlikely(rc)) {
8502 		kfree(vpd);
8503 		goto out_free_mbox;
8504 	}
8505 
8506 	mqe = &mboxq->u.mqe;
8507 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
8508 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
8509 		phba->hba_flag |= HBA_FCOE_MODE;
8510 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
8511 	} else {
8512 		phba->hba_flag &= ~HBA_FCOE_MODE;
8513 	}
8514 
8515 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
8516 		LPFC_DCBX_CEE_MODE)
8517 		phba->hba_flag |= HBA_FIP_SUPPORT;
8518 	else
8519 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
8520 
8521 	phba->hba_flag &= ~HBA_IOQ_FLUSH;
8522 
8523 	if (phba->sli_rev != LPFC_SLI_REV4) {
8524 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8525 			"0376 READ_REV Error. SLI Level %d "
8526 			"FCoE enabled %d\n",
8527 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
8528 		rc = -EIO;
8529 		kfree(vpd);
8530 		goto out_free_mbox;
8531 	}
8532 
8533 	rc = lpfc_set_host_tm(phba);
8534 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
8535 			"6468 Set host date / time: Status x%x:\n", rc);
8536 
8537 	/*
8538 	 * Continue initialization with default values even if driver failed
8539 	 * to read FCoE param config regions, only read parameters if the
8540 	 * board is FCoE
8541 	 */
8542 	if (phba->hba_flag & HBA_FCOE_MODE &&
8543 	    lpfc_sli4_read_fcoe_params(phba))
8544 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
8545 			"2570 Failed to read FCoE parameters\n");
8546 
8547 	/*
8548 	 * Retrieve sli4 device physical port name, failure of doing it
8549 	 * is considered as non-fatal.
8550 	 */
8551 	rc = lpfc_sli4_retrieve_pport_name(phba);
8552 	if (!rc)
8553 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8554 				"3080 Successful retrieving SLI4 device "
8555 				"physical port name: %s.\n", phba->Port);
8556 
8557 	rc = lpfc_sli4_get_ctl_attr(phba);
8558 	if (!rc)
8559 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8560 				"8351 Successful retrieving SLI4 device "
8561 				"CTL ATTR\n");
8562 
8563 	/*
8564 	 * Evaluate the read rev and vpd data. Populate the driver
8565 	 * state with the results. If this routine fails, the failure
8566 	 * is not fatal as the driver will use generic values.
8567 	 */
8568 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
8569 	if (unlikely(!rc)) {
8570 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8571 				"0377 Error %d parsing vpd. "
8572 				"Using defaults.\n", rc);
8573 		rc = 0;
8574 	}
8575 	kfree(vpd);
8576 
8577 	/* Save information as VPD data */
8578 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
8579 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
8580 
8581 	/*
8582 	 * This is because first G7 ASIC doesn't support the standard
8583 	 * 0x5a NVME cmd descriptor type/subtype
8584 	 */
8585 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8586 			LPFC_SLI_INTF_IF_TYPE_6) &&
8587 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
8588 	    (phba->vpd.rev.smRev == 0) &&
8589 	    (phba->cfg_nvme_embed_cmd == 1))
8590 		phba->cfg_nvme_embed_cmd = 0;
8591 
8592 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
8593 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
8594 					 &mqe->un.read_rev);
8595 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
8596 				       &mqe->un.read_rev);
8597 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
8598 					    &mqe->un.read_rev);
8599 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
8600 					   &mqe->un.read_rev);
8601 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
8602 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
8603 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
8604 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
8605 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
8606 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
8607 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8608 			"(%d):0380 READ_REV Status x%x "
8609 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
8610 			mboxq->vport ? mboxq->vport->vpi : 0,
8611 			bf_get(lpfc_mqe_status, mqe),
8612 			phba->vpd.rev.opFwName,
8613 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
8614 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
8615 
8616 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8617 	    LPFC_SLI_INTF_IF_TYPE_0) {
8618 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
8619 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8620 		if (rc == MBX_SUCCESS) {
8621 			phba->hba_flag |= HBA_RECOVERABLE_UE;
8622 			/* Set 1Sec interval to detect UE */
8623 			phba->eratt_poll_interval = 1;
8624 			phba->sli4_hba.ue_to_sr = bf_get(
8625 					lpfc_mbx_set_feature_UESR,
8626 					&mboxq->u.mqe.un.set_feature);
8627 			phba->sli4_hba.ue_to_rp = bf_get(
8628 					lpfc_mbx_set_feature_UERP,
8629 					&mboxq->u.mqe.un.set_feature);
8630 		}
8631 	}
8632 
8633 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
8634 		/* Enable MDS Diagnostics only if the SLI Port supports it */
8635 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
8636 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8637 		if (rc != MBX_SUCCESS)
8638 			phba->mds_diags_support = 0;
8639 	}
8640 
8641 	/*
8642 	 * Discover the port's supported feature set and match it against the
8643 	 * hosts requests.
8644 	 */
8645 	lpfc_request_features(phba, mboxq);
8646 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8647 	if (unlikely(rc)) {
8648 		rc = -EIO;
8649 		goto out_free_mbox;
8650 	}
8651 
8652 	/* Disable VMID if app header is not supported */
8653 	if (phba->cfg_vmid_app_header && !(bf_get(lpfc_mbx_rq_ftr_rsp_ashdr,
8654 						  &mqe->un.req_ftrs))) {
8655 		bf_set(lpfc_ftr_ashdr, &phba->sli4_hba.sli4_flags, 0);
8656 		phba->cfg_vmid_app_header = 0;
8657 		lpfc_printf_log(phba, KERN_DEBUG, LOG_SLI,
8658 				"1242 vmid feature not supported\n");
8659 	}
8660 
8661 	/*
8662 	 * The port must support FCP initiator mode as this is the
8663 	 * only mode running in the host.
8664 	 */
8665 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
8666 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8667 				"0378 No support for fcpi mode.\n");
8668 		ftr_rsp++;
8669 	}
8670 
8671 	/* Performance Hints are ONLY for FCoE */
8672 	if (phba->hba_flag & HBA_FCOE_MODE) {
8673 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
8674 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
8675 		else
8676 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
8677 	}
8678 
8679 	/*
8680 	 * If the port cannot support the host's requested features
8681 	 * then turn off the global config parameters to disable the
8682 	 * feature in the driver.  This is not a fatal error.
8683 	 */
8684 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8685 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
8686 			phba->cfg_enable_bg = 0;
8687 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
8688 			ftr_rsp++;
8689 		}
8690 	}
8691 
8692 	if (phba->max_vpi && phba->cfg_enable_npiv &&
8693 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8694 		ftr_rsp++;
8695 
8696 	if (ftr_rsp) {
8697 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8698 				"0379 Feature Mismatch Data: x%08x %08x "
8699 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
8700 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
8701 				phba->cfg_enable_npiv, phba->max_vpi);
8702 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
8703 			phba->cfg_enable_bg = 0;
8704 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8705 			phba->cfg_enable_npiv = 0;
8706 	}
8707 
8708 	/* These SLI3 features are assumed in SLI4 */
8709 	spin_lock_irq(&phba->hbalock);
8710 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
8711 	spin_unlock_irq(&phba->hbalock);
8712 
8713 	/* Always try to enable dual dump feature if we can */
8714 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
8715 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8716 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
8717 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
8718 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8719 				"6448 Dual Dump is enabled\n");
8720 	else
8721 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
8722 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
8723 				"rc:x%x dd:x%x\n",
8724 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8725 				lpfc_sli_config_mbox_subsys_get(
8726 					phba, mboxq),
8727 				lpfc_sli_config_mbox_opcode_get(
8728 					phba, mboxq),
8729 				rc, dd);
8730 	/*
8731 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
8732 	 * calls depends on these resources to complete port setup.
8733 	 */
8734 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
8735 	if (rc) {
8736 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8737 				"2920 Failed to alloc Resource IDs "
8738 				"rc = x%x\n", rc);
8739 		goto out_free_mbox;
8740 	}
8741 
8742 	lpfc_set_host_data(phba, mboxq);
8743 
8744 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8745 	if (rc) {
8746 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8747 				"2134 Failed to set host os driver version %x",
8748 				rc);
8749 	}
8750 
8751 	/* Read the port's service parameters. */
8752 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
8753 	if (rc) {
8754 		phba->link_state = LPFC_HBA_ERROR;
8755 		rc = -ENOMEM;
8756 		goto out_free_mbox;
8757 	}
8758 
8759 	mboxq->vport = vport;
8760 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8761 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
8762 	if (rc == MBX_SUCCESS) {
8763 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
8764 		rc = 0;
8765 	}
8766 
8767 	/*
8768 	 * This memory was allocated by the lpfc_read_sparam routine but is
8769 	 * no longer needed.  It is released and ctx_buf NULLed to prevent
8770 	 * unintended pointer access as the mbox is reused.
8771 	 */
8772 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
8773 	kfree(mp);
8774 	mboxq->ctx_buf = NULL;
8775 	if (unlikely(rc)) {
8776 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8777 				"0382 READ_SPARAM command failed "
8778 				"status %d, mbxStatus x%x\n",
8779 				rc, bf_get(lpfc_mqe_status, mqe));
8780 		phba->link_state = LPFC_HBA_ERROR;
8781 		rc = -EIO;
8782 		goto out_free_mbox;
8783 	}
8784 
8785 	lpfc_update_vport_wwn(vport);
8786 
8787 	/* Update the fc_host data structures with new wwn. */
8788 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
8789 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
8790 
8791 	/* Create all the SLI4 queues */
8792 	rc = lpfc_sli4_queue_create(phba);
8793 	if (rc) {
8794 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8795 				"3089 Failed to allocate queues\n");
8796 		rc = -ENODEV;
8797 		goto out_free_mbox;
8798 	}
8799 	/* Set up all the queues to the device */
8800 	rc = lpfc_sli4_queue_setup(phba);
8801 	if (unlikely(rc)) {
8802 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8803 				"0381 Error %d during queue setup.\n ", rc);
8804 		goto out_stop_timers;
8805 	}
8806 	/* Initialize the driver internal SLI layer lists. */
8807 	lpfc_sli4_setup(phba);
8808 	lpfc_sli4_queue_init(phba);
8809 
8810 	/* update host els xri-sgl sizes and mappings */
8811 	rc = lpfc_sli4_els_sgl_update(phba);
8812 	if (unlikely(rc)) {
8813 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8814 				"1400 Failed to update xri-sgl size and "
8815 				"mapping: %d\n", rc);
8816 		goto out_destroy_queue;
8817 	}
8818 
8819 	/* register the els sgl pool to the port */
8820 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
8821 				       phba->sli4_hba.els_xri_cnt);
8822 	if (unlikely(rc < 0)) {
8823 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8824 				"0582 Error %d during els sgl post "
8825 				"operation\n", rc);
8826 		rc = -ENODEV;
8827 		goto out_destroy_queue;
8828 	}
8829 	phba->sli4_hba.els_xri_cnt = rc;
8830 
8831 	if (phba->nvmet_support) {
8832 		/* update host nvmet xri-sgl sizes and mappings */
8833 		rc = lpfc_sli4_nvmet_sgl_update(phba);
8834 		if (unlikely(rc)) {
8835 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8836 					"6308 Failed to update nvmet-sgl size "
8837 					"and mapping: %d\n", rc);
8838 			goto out_destroy_queue;
8839 		}
8840 
8841 		/* register the nvmet sgl pool to the port */
8842 		rc = lpfc_sli4_repost_sgl_list(
8843 			phba,
8844 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
8845 			phba->sli4_hba.nvmet_xri_cnt);
8846 		if (unlikely(rc < 0)) {
8847 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8848 					"3117 Error %d during nvmet "
8849 					"sgl post\n", rc);
8850 			rc = -ENODEV;
8851 			goto out_destroy_queue;
8852 		}
8853 		phba->sli4_hba.nvmet_xri_cnt = rc;
8854 
8855 		/* We allocate an iocbq for every receive context SGL.
8856 		 * The additional allocation is for abort and ls handling.
8857 		 */
8858 		cnt = phba->sli4_hba.nvmet_xri_cnt +
8859 			phba->sli4_hba.max_cfg_param.max_xri;
8860 	} else {
8861 		/* update host common xri-sgl sizes and mappings */
8862 		rc = lpfc_sli4_io_sgl_update(phba);
8863 		if (unlikely(rc)) {
8864 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8865 					"6082 Failed to update nvme-sgl size "
8866 					"and mapping: %d\n", rc);
8867 			goto out_destroy_queue;
8868 		}
8869 
8870 		/* register the allocated common sgl pool to the port */
8871 		rc = lpfc_sli4_repost_io_sgl_list(phba);
8872 		if (unlikely(rc)) {
8873 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8874 					"6116 Error %d during nvme sgl post "
8875 					"operation\n", rc);
8876 			/* Some NVME buffers were moved to abort nvme list */
8877 			/* A pci function reset will repost them */
8878 			rc = -ENODEV;
8879 			goto out_destroy_queue;
8880 		}
8881 		/* Each lpfc_io_buf job structure has an iocbq element.
8882 		 * This cnt provides for abort, els, ct and ls requests.
8883 		 */
8884 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
8885 	}
8886 
8887 	if (!phba->sli.iocbq_lookup) {
8888 		/* Initialize and populate the iocb list per host */
8889 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8890 				"2821 initialize iocb list with %d entries\n",
8891 				cnt);
8892 		rc = lpfc_init_iocb_list(phba, cnt);
8893 		if (rc) {
8894 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8895 					"1413 Failed to init iocb list.\n");
8896 			goto out_destroy_queue;
8897 		}
8898 	}
8899 
8900 	if (phba->nvmet_support)
8901 		lpfc_nvmet_create_targetport(phba);
8902 
8903 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
8904 		/* Post initial buffers to all RQs created */
8905 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
8906 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
8907 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
8908 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
8909 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
8910 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
8911 			rqbp->buffer_count = 0;
8912 
8913 			lpfc_post_rq_buffer(
8914 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
8915 				phba->sli4_hba.nvmet_mrq_data[i],
8916 				phba->cfg_nvmet_mrq_post, i);
8917 		}
8918 	}
8919 
8920 	/* Post the rpi header region to the device. */
8921 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
8922 	if (unlikely(rc)) {
8923 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8924 				"0393 Error %d during rpi post operation\n",
8925 				rc);
8926 		rc = -ENODEV;
8927 		goto out_free_iocblist;
8928 	}
8929 	lpfc_sli4_node_prep(phba);
8930 
8931 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
8932 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
8933 			/*
8934 			 * The FC Port needs to register FCFI (index 0)
8935 			 */
8936 			lpfc_reg_fcfi(phba, mboxq);
8937 			mboxq->vport = phba->pport;
8938 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8939 			if (rc != MBX_SUCCESS)
8940 				goto out_unset_queue;
8941 			rc = 0;
8942 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
8943 						&mboxq->u.mqe.un.reg_fcfi);
8944 		} else {
8945 			/* We are a NVME Target mode with MRQ > 1 */
8946 
8947 			/* First register the FCFI */
8948 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
8949 			mboxq->vport = phba->pport;
8950 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8951 			if (rc != MBX_SUCCESS)
8952 				goto out_unset_queue;
8953 			rc = 0;
8954 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
8955 						&mboxq->u.mqe.un.reg_fcfi_mrq);
8956 
8957 			/* Next register the MRQs */
8958 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
8959 			mboxq->vport = phba->pport;
8960 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8961 			if (rc != MBX_SUCCESS)
8962 				goto out_unset_queue;
8963 			rc = 0;
8964 		}
8965 		/* Check if the port is configured to be disabled */
8966 		lpfc_sli_read_link_ste(phba);
8967 	}
8968 
8969 	/* Don't post more new bufs if repost already recovered
8970 	 * the nvme sgls.
8971 	 */
8972 	if (phba->nvmet_support == 0) {
8973 		if (phba->sli4_hba.io_xri_cnt == 0) {
8974 			len = lpfc_new_io_buf(
8975 					      phba, phba->sli4_hba.io_xri_max);
8976 			if (len == 0) {
8977 				rc = -ENOMEM;
8978 				goto out_unset_queue;
8979 			}
8980 
8981 			if (phba->cfg_xri_rebalancing)
8982 				lpfc_create_multixri_pools(phba);
8983 		}
8984 	} else {
8985 		phba->cfg_xri_rebalancing = 0;
8986 	}
8987 
8988 	/* Allow asynchronous mailbox command to go through */
8989 	spin_lock_irq(&phba->hbalock);
8990 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8991 	spin_unlock_irq(&phba->hbalock);
8992 
8993 	/* Post receive buffers to the device */
8994 	lpfc_sli4_rb_setup(phba);
8995 
8996 	/* Reset HBA FCF states after HBA reset */
8997 	phba->fcf.fcf_flag = 0;
8998 	phba->fcf.current_rec.flag = 0;
8999 
9000 	/* Start the ELS watchdog timer */
9001 	mod_timer(&vport->els_tmofunc,
9002 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
9003 
9004 	/* Start heart beat timer */
9005 	mod_timer(&phba->hb_tmofunc,
9006 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
9007 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
9008 	phba->last_completion_time = jiffies;
9009 
9010 	/* start eq_delay heartbeat */
9011 	if (phba->cfg_auto_imax)
9012 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
9013 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
9014 
9015 	/* start per phba idle_stat_delay heartbeat */
9016 	lpfc_init_idle_stat_hb(phba);
9017 
9018 	/* Start error attention (ERATT) polling timer */
9019 	mod_timer(&phba->eratt_poll,
9020 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
9021 
9022 	/*
9023 	 * The port is ready, set the host's link state to LINK_DOWN
9024 	 * in preparation for link interrupts.
9025 	 */
9026 	spin_lock_irq(&phba->hbalock);
9027 	phba->link_state = LPFC_LINK_DOWN;
9028 
9029 	/* Check if physical ports are trunked */
9030 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
9031 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
9032 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
9033 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
9034 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
9035 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
9036 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
9037 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
9038 	spin_unlock_irq(&phba->hbalock);
9039 
9040 	/* Arm the CQs and then EQs on device */
9041 	lpfc_sli4_arm_cqeq_intr(phba);
9042 
9043 	/* Indicate device interrupt mode */
9044 	phba->sli4_hba.intr_enable = 1;
9045 
9046 	/* Setup CMF after HBA is initialized */
9047 	lpfc_cmf_setup(phba);
9048 
9049 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
9050 	    (phba->hba_flag & LINK_DISABLED)) {
9051 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9052 				"3103 Adapter Link is disabled.\n");
9053 		lpfc_down_link(phba, mboxq);
9054 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9055 		if (rc != MBX_SUCCESS) {
9056 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9057 					"3104 Adapter failed to issue "
9058 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
9059 			goto out_io_buff_free;
9060 		}
9061 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
9062 		/* don't perform init_link on SLI4 FC port loopback test */
9063 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
9064 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
9065 			if (rc)
9066 				goto out_io_buff_free;
9067 		}
9068 	}
9069 	mempool_free(mboxq, phba->mbox_mem_pool);
9070 
9071 	/* Enable RAS FW log support */
9072 	lpfc_sli4_ras_setup(phba);
9073 
9074 	phba->hba_flag |= HBA_SETUP;
9075 	return rc;
9076 
9077 out_io_buff_free:
9078 	/* Free allocated IO Buffers */
9079 	lpfc_io_free(phba);
9080 out_unset_queue:
9081 	/* Unset all the queues set up in this routine when error out */
9082 	lpfc_sli4_queue_unset(phba);
9083 out_free_iocblist:
9084 	lpfc_free_iocb_list(phba);
9085 out_destroy_queue:
9086 	lpfc_sli4_queue_destroy(phba);
9087 out_stop_timers:
9088 	lpfc_stop_hba_timers(phba);
9089 out_free_mbox:
9090 	mempool_free(mboxq, phba->mbox_mem_pool);
9091 	return rc;
9092 }
9093 
9094 /**
9095  * lpfc_mbox_timeout - Timeout call back function for mbox timer
9096  * @t: Context to fetch pointer to hba structure from.
9097  *
9098  * This is the callback function for mailbox timer. The mailbox
9099  * timer is armed when a new mailbox command is issued and the timer
9100  * is deleted when the mailbox complete. The function is called by
9101  * the kernel timer code when a mailbox does not complete within
9102  * expected time. This function wakes up the worker thread to
9103  * process the mailbox timeout and returns. All the processing is
9104  * done by the worker thread function lpfc_mbox_timeout_handler.
9105  **/
9106 void
9107 lpfc_mbox_timeout(struct timer_list *t)
9108 {
9109 	struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
9110 	unsigned long iflag;
9111 	uint32_t tmo_posted;
9112 
9113 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
9114 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
9115 	if (!tmo_posted)
9116 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
9117 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
9118 
9119 	if (!tmo_posted)
9120 		lpfc_worker_wake_up(phba);
9121 	return;
9122 }
9123 
9124 /**
9125  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
9126  *                                    are pending
9127  * @phba: Pointer to HBA context object.
9128  *
9129  * This function checks if any mailbox completions are present on the mailbox
9130  * completion queue.
9131  **/
9132 static bool
9133 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
9134 {
9135 
9136 	uint32_t idx;
9137 	struct lpfc_queue *mcq;
9138 	struct lpfc_mcqe *mcqe;
9139 	bool pending_completions = false;
9140 	uint8_t	qe_valid;
9141 
9142 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9143 		return false;
9144 
9145 	/* Check for completions on mailbox completion queue */
9146 
9147 	mcq = phba->sli4_hba.mbx_cq;
9148 	idx = mcq->hba_index;
9149 	qe_valid = mcq->qe_valid;
9150 	while (bf_get_le32(lpfc_cqe_valid,
9151 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
9152 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
9153 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
9154 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
9155 			pending_completions = true;
9156 			break;
9157 		}
9158 		idx = (idx + 1) % mcq->entry_count;
9159 		if (mcq->hba_index == idx)
9160 			break;
9161 
9162 		/* if the index wrapped around, toggle the valid bit */
9163 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
9164 			qe_valid = (qe_valid) ? 0 : 1;
9165 	}
9166 	return pending_completions;
9167 
9168 }
9169 
9170 /**
9171  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
9172  *					      that were missed.
9173  * @phba: Pointer to HBA context object.
9174  *
9175  * For sli4, it is possible to miss an interrupt. As such mbox completions
9176  * maybe missed causing erroneous mailbox timeouts to occur. This function
9177  * checks to see if mbox completions are on the mailbox completion queue
9178  * and will process all the completions associated with the eq for the
9179  * mailbox completion queue.
9180  **/
9181 static bool
9182 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
9183 {
9184 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
9185 	uint32_t eqidx;
9186 	struct lpfc_queue *fpeq = NULL;
9187 	struct lpfc_queue *eq;
9188 	bool mbox_pending;
9189 
9190 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9191 		return false;
9192 
9193 	/* Find the EQ associated with the mbox CQ */
9194 	if (sli4_hba->hdwq) {
9195 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
9196 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
9197 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
9198 				fpeq = eq;
9199 				break;
9200 			}
9201 		}
9202 	}
9203 	if (!fpeq)
9204 		return false;
9205 
9206 	/* Turn off interrupts from this EQ */
9207 
9208 	sli4_hba->sli4_eq_clr_intr(fpeq);
9209 
9210 	/* Check to see if a mbox completion is pending */
9211 
9212 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
9213 
9214 	/*
9215 	 * If a mbox completion is pending, process all the events on EQ
9216 	 * associated with the mbox completion queue (this could include
9217 	 * mailbox commands, async events, els commands, receive queue data
9218 	 * and fcp commands)
9219 	 */
9220 
9221 	if (mbox_pending)
9222 		/* process and rearm the EQ */
9223 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
9224 				     LPFC_QUEUE_WORK);
9225 	else
9226 		/* Always clear and re-arm the EQ */
9227 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
9228 
9229 	return mbox_pending;
9230 
9231 }
9232 
9233 /**
9234  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
9235  * @phba: Pointer to HBA context object.
9236  *
9237  * This function is called from worker thread when a mailbox command times out.
9238  * The caller is not required to hold any locks. This function will reset the
9239  * HBA and recover all the pending commands.
9240  **/
9241 void
9242 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
9243 {
9244 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
9245 	MAILBOX_t *mb = NULL;
9246 
9247 	struct lpfc_sli *psli = &phba->sli;
9248 
9249 	/* If the mailbox completed, process the completion */
9250 	lpfc_sli4_process_missed_mbox_completions(phba);
9251 
9252 	if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
9253 		return;
9254 
9255 	if (pmbox != NULL)
9256 		mb = &pmbox->u.mb;
9257 	/* Check the pmbox pointer first.  There is a race condition
9258 	 * between the mbox timeout handler getting executed in the
9259 	 * worklist and the mailbox actually completing. When this
9260 	 * race condition occurs, the mbox_active will be NULL.
9261 	 */
9262 	spin_lock_irq(&phba->hbalock);
9263 	if (pmbox == NULL) {
9264 		lpfc_printf_log(phba, KERN_WARNING,
9265 				LOG_MBOX | LOG_SLI,
9266 				"0353 Active Mailbox cleared - mailbox timeout "
9267 				"exiting\n");
9268 		spin_unlock_irq(&phba->hbalock);
9269 		return;
9270 	}
9271 
9272 	/* Mbox cmd <mbxCommand> timeout */
9273 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9274 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
9275 			mb->mbxCommand,
9276 			phba->pport->port_state,
9277 			phba->sli.sli_flag,
9278 			phba->sli.mbox_active);
9279 	spin_unlock_irq(&phba->hbalock);
9280 
9281 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
9282 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
9283 	 * it to fail all outstanding SCSI IO.
9284 	 */
9285 	spin_lock_irq(&phba->pport->work_port_lock);
9286 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9287 	spin_unlock_irq(&phba->pport->work_port_lock);
9288 	spin_lock_irq(&phba->hbalock);
9289 	phba->link_state = LPFC_LINK_UNKNOWN;
9290 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
9291 	spin_unlock_irq(&phba->hbalock);
9292 
9293 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9294 			"0345 Resetting board due to mailbox timeout\n");
9295 
9296 	/* Reset the HBA device */
9297 	lpfc_reset_hba(phba);
9298 }
9299 
9300 /**
9301  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
9302  * @phba: Pointer to HBA context object.
9303  * @pmbox: Pointer to mailbox object.
9304  * @flag: Flag indicating how the mailbox need to be processed.
9305  *
9306  * This function is called by discovery code and HBA management code
9307  * to submit a mailbox command to firmware with SLI-3 interface spec. This
9308  * function gets the hbalock to protect the data structures.
9309  * The mailbox command can be submitted in polling mode, in which case
9310  * this function will wait in a polling loop for the completion of the
9311  * mailbox.
9312  * If the mailbox is submitted in no_wait mode (not polling) the
9313  * function will submit the command and returns immediately without waiting
9314  * for the mailbox completion. The no_wait is supported only when HBA
9315  * is in SLI2/SLI3 mode - interrupts are enabled.
9316  * The SLI interface allows only one mailbox pending at a time. If the
9317  * mailbox is issued in polling mode and there is already a mailbox
9318  * pending, then the function will return an error. If the mailbox is issued
9319  * in NO_WAIT mode and there is a mailbox pending already, the function
9320  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
9321  * The sli layer owns the mailbox object until the completion of mailbox
9322  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
9323  * return codes the caller owns the mailbox command after the return of
9324  * the function.
9325  **/
9326 static int
9327 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
9328 		       uint32_t flag)
9329 {
9330 	MAILBOX_t *mbx;
9331 	struct lpfc_sli *psli = &phba->sli;
9332 	uint32_t status, evtctr;
9333 	uint32_t ha_copy, hc_copy;
9334 	int i;
9335 	unsigned long timeout;
9336 	unsigned long drvr_flag = 0;
9337 	uint32_t word0, ldata;
9338 	void __iomem *to_slim;
9339 	int processing_queue = 0;
9340 
9341 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
9342 	if (!pmbox) {
9343 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9344 		/* processing mbox queue from intr_handler */
9345 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9346 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9347 			return MBX_SUCCESS;
9348 		}
9349 		processing_queue = 1;
9350 		pmbox = lpfc_mbox_get(phba);
9351 		if (!pmbox) {
9352 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9353 			return MBX_SUCCESS;
9354 		}
9355 	}
9356 
9357 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
9358 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
9359 		if(!pmbox->vport) {
9360 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9361 			lpfc_printf_log(phba, KERN_ERR,
9362 					LOG_MBOX | LOG_VPORT,
9363 					"1806 Mbox x%x failed. No vport\n",
9364 					pmbox->u.mb.mbxCommand);
9365 			dump_stack();
9366 			goto out_not_finished;
9367 		}
9368 	}
9369 
9370 	/* If the PCI channel is in offline state, do not post mbox. */
9371 	if (unlikely(pci_channel_offline(phba->pcidev))) {
9372 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9373 		goto out_not_finished;
9374 	}
9375 
9376 	/* If HBA has a deferred error attention, fail the iocb. */
9377 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
9378 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9379 		goto out_not_finished;
9380 	}
9381 
9382 	psli = &phba->sli;
9383 
9384 	mbx = &pmbox->u.mb;
9385 	status = MBX_SUCCESS;
9386 
9387 	if (phba->link_state == LPFC_HBA_ERROR) {
9388 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9389 
9390 		/* Mbox command <mbxCommand> cannot issue */
9391 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9392 				"(%d):0311 Mailbox command x%x cannot "
9393 				"issue Data: x%x x%x\n",
9394 				pmbox->vport ? pmbox->vport->vpi : 0,
9395 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9396 		goto out_not_finished;
9397 	}
9398 
9399 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
9400 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
9401 			!(hc_copy & HC_MBINT_ENA)) {
9402 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9403 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9404 				"(%d):2528 Mailbox command x%x cannot "
9405 				"issue Data: x%x x%x\n",
9406 				pmbox->vport ? pmbox->vport->vpi : 0,
9407 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9408 			goto out_not_finished;
9409 		}
9410 	}
9411 
9412 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9413 		/* Polling for a mbox command when another one is already active
9414 		 * is not allowed in SLI. Also, the driver must have established
9415 		 * SLI2 mode to queue and process multiple mbox commands.
9416 		 */
9417 
9418 		if (flag & MBX_POLL) {
9419 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9420 
9421 			/* Mbox command <mbxCommand> cannot issue */
9422 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9423 					"(%d):2529 Mailbox command x%x "
9424 					"cannot issue Data: x%x x%x\n",
9425 					pmbox->vport ? pmbox->vport->vpi : 0,
9426 					pmbox->u.mb.mbxCommand,
9427 					psli->sli_flag, flag);
9428 			goto out_not_finished;
9429 		}
9430 
9431 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
9432 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9433 			/* Mbox command <mbxCommand> cannot issue */
9434 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9435 					"(%d):2530 Mailbox command x%x "
9436 					"cannot issue Data: x%x x%x\n",
9437 					pmbox->vport ? pmbox->vport->vpi : 0,
9438 					pmbox->u.mb.mbxCommand,
9439 					psli->sli_flag, flag);
9440 			goto out_not_finished;
9441 		}
9442 
9443 		/* Another mailbox command is still being processed, queue this
9444 		 * command to be processed later.
9445 		 */
9446 		lpfc_mbox_put(phba, pmbox);
9447 
9448 		/* Mbox cmd issue - BUSY */
9449 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9450 				"(%d):0308 Mbox cmd issue - BUSY Data: "
9451 				"x%x x%x x%x x%x\n",
9452 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
9453 				mbx->mbxCommand,
9454 				phba->pport ? phba->pport->port_state : 0xff,
9455 				psli->sli_flag, flag);
9456 
9457 		psli->slistat.mbox_busy++;
9458 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9459 
9460 		if (pmbox->vport) {
9461 			lpfc_debugfs_disc_trc(pmbox->vport,
9462 				LPFC_DISC_TRC_MBOX_VPORT,
9463 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
9464 				(uint32_t)mbx->mbxCommand,
9465 				mbx->un.varWords[0], mbx->un.varWords[1]);
9466 		}
9467 		else {
9468 			lpfc_debugfs_disc_trc(phba->pport,
9469 				LPFC_DISC_TRC_MBOX,
9470 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
9471 				(uint32_t)mbx->mbxCommand,
9472 				mbx->un.varWords[0], mbx->un.varWords[1]);
9473 		}
9474 
9475 		return MBX_BUSY;
9476 	}
9477 
9478 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9479 
9480 	/* If we are not polling, we MUST be in SLI2 mode */
9481 	if (flag != MBX_POLL) {
9482 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
9483 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
9484 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9485 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9486 			/* Mbox command <mbxCommand> cannot issue */
9487 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9488 					"(%d):2531 Mailbox command x%x "
9489 					"cannot issue Data: x%x x%x\n",
9490 					pmbox->vport ? pmbox->vport->vpi : 0,
9491 					pmbox->u.mb.mbxCommand,
9492 					psli->sli_flag, flag);
9493 			goto out_not_finished;
9494 		}
9495 		/* timeout active mbox command */
9496 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9497 					   1000);
9498 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
9499 	}
9500 
9501 	/* Mailbox cmd <cmd> issue */
9502 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9503 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
9504 			"x%x\n",
9505 			pmbox->vport ? pmbox->vport->vpi : 0,
9506 			mbx->mbxCommand,
9507 			phba->pport ? phba->pport->port_state : 0xff,
9508 			psli->sli_flag, flag);
9509 
9510 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
9511 		if (pmbox->vport) {
9512 			lpfc_debugfs_disc_trc(pmbox->vport,
9513 				LPFC_DISC_TRC_MBOX_VPORT,
9514 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9515 				(uint32_t)mbx->mbxCommand,
9516 				mbx->un.varWords[0], mbx->un.varWords[1]);
9517 		}
9518 		else {
9519 			lpfc_debugfs_disc_trc(phba->pport,
9520 				LPFC_DISC_TRC_MBOX,
9521 				"MBOX Send:       cmd:x%x mb:x%x x%x",
9522 				(uint32_t)mbx->mbxCommand,
9523 				mbx->un.varWords[0], mbx->un.varWords[1]);
9524 		}
9525 	}
9526 
9527 	psli->slistat.mbox_cmd++;
9528 	evtctr = psli->slistat.mbox_event;
9529 
9530 	/* next set own bit for the adapter and copy over command word */
9531 	mbx->mbxOwner = OWN_CHIP;
9532 
9533 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9534 		/* Populate mbox extension offset word. */
9535 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
9536 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9537 				= (uint8_t *)phba->mbox_ext
9538 				  - (uint8_t *)phba->mbox;
9539 		}
9540 
9541 		/* Copy the mailbox extension data */
9542 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
9543 			lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
9544 					      (uint8_t *)phba->mbox_ext,
9545 					      pmbox->in_ext_byte_len);
9546 		}
9547 		/* Copy command data to host SLIM area */
9548 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
9549 	} else {
9550 		/* Populate mbox extension offset word. */
9551 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
9552 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9553 				= MAILBOX_HBA_EXT_OFFSET;
9554 
9555 		/* Copy the mailbox extension data */
9556 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
9557 			lpfc_memcpy_to_slim(phba->MBslimaddr +
9558 				MAILBOX_HBA_EXT_OFFSET,
9559 				pmbox->ctx_buf, pmbox->in_ext_byte_len);
9560 
9561 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9562 			/* copy command data into host mbox for cmpl */
9563 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
9564 					      MAILBOX_CMD_SIZE);
9565 
9566 		/* First copy mbox command data to HBA SLIM, skip past first
9567 		   word */
9568 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
9569 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
9570 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
9571 
9572 		/* Next copy over first word, with mbxOwner set */
9573 		ldata = *((uint32_t *)mbx);
9574 		to_slim = phba->MBslimaddr;
9575 		writel(ldata, to_slim);
9576 		readl(to_slim); /* flush */
9577 
9578 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9579 			/* switch over to host mailbox */
9580 			psli->sli_flag |= LPFC_SLI_ACTIVE;
9581 	}
9582 
9583 	wmb();
9584 
9585 	switch (flag) {
9586 	case MBX_NOWAIT:
9587 		/* Set up reference to mailbox command */
9588 		psli->mbox_active = pmbox;
9589 		/* Interrupt board to do it */
9590 		writel(CA_MBATT, phba->CAregaddr);
9591 		readl(phba->CAregaddr); /* flush */
9592 		/* Don't wait for it to finish, just return */
9593 		break;
9594 
9595 	case MBX_POLL:
9596 		/* Set up null reference to mailbox command */
9597 		psli->mbox_active = NULL;
9598 		/* Interrupt board to do it */
9599 		writel(CA_MBATT, phba->CAregaddr);
9600 		readl(phba->CAregaddr); /* flush */
9601 
9602 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9603 			/* First read mbox status word */
9604 			word0 = *((uint32_t *)phba->mbox);
9605 			word0 = le32_to_cpu(word0);
9606 		} else {
9607 			/* First read mbox status word */
9608 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
9609 				spin_unlock_irqrestore(&phba->hbalock,
9610 						       drvr_flag);
9611 				goto out_not_finished;
9612 			}
9613 		}
9614 
9615 		/* Read the HBA Host Attention Register */
9616 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9617 			spin_unlock_irqrestore(&phba->hbalock,
9618 						       drvr_flag);
9619 			goto out_not_finished;
9620 		}
9621 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9622 							1000) + jiffies;
9623 		i = 0;
9624 		/* Wait for command to complete */
9625 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
9626 		       (!(ha_copy & HA_MBATT) &&
9627 			(phba->link_state > LPFC_WARM_START))) {
9628 			if (time_after(jiffies, timeout)) {
9629 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9630 				spin_unlock_irqrestore(&phba->hbalock,
9631 						       drvr_flag);
9632 				goto out_not_finished;
9633 			}
9634 
9635 			/* Check if we took a mbox interrupt while we were
9636 			   polling */
9637 			if (((word0 & OWN_CHIP) != OWN_CHIP)
9638 			    && (evtctr != psli->slistat.mbox_event))
9639 				break;
9640 
9641 			if (i++ > 10) {
9642 				spin_unlock_irqrestore(&phba->hbalock,
9643 						       drvr_flag);
9644 				msleep(1);
9645 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
9646 			}
9647 
9648 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9649 				/* First copy command data */
9650 				word0 = *((uint32_t *)phba->mbox);
9651 				word0 = le32_to_cpu(word0);
9652 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
9653 					MAILBOX_t *slimmb;
9654 					uint32_t slimword0;
9655 					/* Check real SLIM for any errors */
9656 					slimword0 = readl(phba->MBslimaddr);
9657 					slimmb = (MAILBOX_t *) & slimword0;
9658 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
9659 					    && slimmb->mbxStatus) {
9660 						psli->sli_flag &=
9661 						    ~LPFC_SLI_ACTIVE;
9662 						word0 = slimword0;
9663 					}
9664 				}
9665 			} else {
9666 				/* First copy command data */
9667 				word0 = readl(phba->MBslimaddr);
9668 			}
9669 			/* Read the HBA Host Attention Register */
9670 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9671 				spin_unlock_irqrestore(&phba->hbalock,
9672 						       drvr_flag);
9673 				goto out_not_finished;
9674 			}
9675 		}
9676 
9677 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9678 			/* copy results back to user */
9679 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
9680 						MAILBOX_CMD_SIZE);
9681 			/* Copy the mailbox extension data */
9682 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9683 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
9684 						      pmbox->ctx_buf,
9685 						      pmbox->out_ext_byte_len);
9686 			}
9687 		} else {
9688 			/* First copy command data */
9689 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
9690 						MAILBOX_CMD_SIZE);
9691 			/* Copy the mailbox extension data */
9692 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9693 				lpfc_memcpy_from_slim(
9694 					pmbox->ctx_buf,
9695 					phba->MBslimaddr +
9696 					MAILBOX_HBA_EXT_OFFSET,
9697 					pmbox->out_ext_byte_len);
9698 			}
9699 		}
9700 
9701 		writel(HA_MBATT, phba->HAregaddr);
9702 		readl(phba->HAregaddr); /* flush */
9703 
9704 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9705 		status = mbx->mbxStatus;
9706 	}
9707 
9708 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9709 	return status;
9710 
9711 out_not_finished:
9712 	if (processing_queue) {
9713 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
9714 		lpfc_mbox_cmpl_put(phba, pmbox);
9715 	}
9716 	return MBX_NOT_FINISHED;
9717 }
9718 
9719 /**
9720  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
9721  * @phba: Pointer to HBA context object.
9722  *
9723  * The function blocks the posting of SLI4 asynchronous mailbox commands from
9724  * the driver internal pending mailbox queue. It will then try to wait out the
9725  * possible outstanding mailbox command before return.
9726  *
9727  * Returns:
9728  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
9729  * 	the outstanding mailbox command timed out.
9730  **/
9731 static int
9732 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
9733 {
9734 	struct lpfc_sli *psli = &phba->sli;
9735 	LPFC_MBOXQ_t *mboxq;
9736 	int rc = 0;
9737 	unsigned long timeout = 0;
9738 	u32 sli_flag;
9739 	u8 cmd, subsys, opcode;
9740 
9741 	/* Mark the asynchronous mailbox command posting as blocked */
9742 	spin_lock_irq(&phba->hbalock);
9743 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
9744 	/* Determine how long we might wait for the active mailbox
9745 	 * command to be gracefully completed by firmware.
9746 	 */
9747 	if (phba->sli.mbox_active)
9748 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
9749 						phba->sli.mbox_active) *
9750 						1000) + jiffies;
9751 	spin_unlock_irq(&phba->hbalock);
9752 
9753 	/* Make sure the mailbox is really active */
9754 	if (timeout)
9755 		lpfc_sli4_process_missed_mbox_completions(phba);
9756 
9757 	/* Wait for the outstanding mailbox command to complete */
9758 	while (phba->sli.mbox_active) {
9759 		/* Check active mailbox complete status every 2ms */
9760 		msleep(2);
9761 		if (time_after(jiffies, timeout)) {
9762 			/* Timeout, mark the outstanding cmd not complete */
9763 
9764 			/* Sanity check sli.mbox_active has not completed or
9765 			 * cancelled from another context during last 2ms sleep,
9766 			 * so take hbalock to be sure before logging.
9767 			 */
9768 			spin_lock_irq(&phba->hbalock);
9769 			if (phba->sli.mbox_active) {
9770 				mboxq = phba->sli.mbox_active;
9771 				cmd = mboxq->u.mb.mbxCommand;
9772 				subsys = lpfc_sli_config_mbox_subsys_get(phba,
9773 									 mboxq);
9774 				opcode = lpfc_sli_config_mbox_opcode_get(phba,
9775 									 mboxq);
9776 				sli_flag = psli->sli_flag;
9777 				spin_unlock_irq(&phba->hbalock);
9778 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9779 						"2352 Mailbox command x%x "
9780 						"(x%x/x%x) sli_flag x%x could "
9781 						"not complete\n",
9782 						cmd, subsys, opcode,
9783 						sli_flag);
9784 			} else {
9785 				spin_unlock_irq(&phba->hbalock);
9786 			}
9787 
9788 			rc = 1;
9789 			break;
9790 		}
9791 	}
9792 
9793 	/* Can not cleanly block async mailbox command, fails it */
9794 	if (rc) {
9795 		spin_lock_irq(&phba->hbalock);
9796 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9797 		spin_unlock_irq(&phba->hbalock);
9798 	}
9799 	return rc;
9800 }
9801 
9802 /**
9803  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
9804  * @phba: Pointer to HBA context object.
9805  *
9806  * The function unblocks and resume posting of SLI4 asynchronous mailbox
9807  * commands from the driver internal pending mailbox queue. It makes sure
9808  * that there is no outstanding mailbox command before resuming posting
9809  * asynchronous mailbox commands. If, for any reason, there is outstanding
9810  * mailbox command, it will try to wait it out before resuming asynchronous
9811  * mailbox command posting.
9812  **/
9813 static void
9814 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
9815 {
9816 	struct lpfc_sli *psli = &phba->sli;
9817 
9818 	spin_lock_irq(&phba->hbalock);
9819 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9820 		/* Asynchronous mailbox posting is not blocked, do nothing */
9821 		spin_unlock_irq(&phba->hbalock);
9822 		return;
9823 	}
9824 
9825 	/* Outstanding synchronous mailbox command is guaranteed to be done,
9826 	 * successful or timeout, after timing-out the outstanding mailbox
9827 	 * command shall always be removed, so just unblock posting async
9828 	 * mailbox command and resume
9829 	 */
9830 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9831 	spin_unlock_irq(&phba->hbalock);
9832 
9833 	/* wake up worker thread to post asynchronous mailbox command */
9834 	lpfc_worker_wake_up(phba);
9835 }
9836 
9837 /**
9838  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
9839  * @phba: Pointer to HBA context object.
9840  * @mboxq: Pointer to mailbox object.
9841  *
9842  * The function waits for the bootstrap mailbox register ready bit from
9843  * port for twice the regular mailbox command timeout value.
9844  *
9845  *      0 - no timeout on waiting for bootstrap mailbox register ready.
9846  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out or port
9847  *                     is in an unrecoverable state.
9848  **/
9849 static int
9850 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9851 {
9852 	uint32_t db_ready;
9853 	unsigned long timeout;
9854 	struct lpfc_register bmbx_reg;
9855 	struct lpfc_register portstat_reg = {-1};
9856 
9857 	/* Sanity check - there is no point to wait if the port is in an
9858 	 * unrecoverable state.
9859 	 */
9860 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
9861 	    LPFC_SLI_INTF_IF_TYPE_2) {
9862 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9863 			       &portstat_reg.word0) ||
9864 		    lpfc_sli4_unrecoverable_port(&portstat_reg)) {
9865 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9866 					"3858 Skipping bmbx ready because "
9867 					"Port Status x%x\n",
9868 					portstat_reg.word0);
9869 			return MBXERR_ERROR;
9870 		}
9871 	}
9872 
9873 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
9874 				   * 1000) + jiffies;
9875 
9876 	do {
9877 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
9878 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
9879 		if (!db_ready)
9880 			mdelay(2);
9881 
9882 		if (time_after(jiffies, timeout))
9883 			return MBXERR_ERROR;
9884 	} while (!db_ready);
9885 
9886 	return 0;
9887 }
9888 
9889 /**
9890  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
9891  * @phba: Pointer to HBA context object.
9892  * @mboxq: Pointer to mailbox object.
9893  *
9894  * The function posts a mailbox to the port.  The mailbox is expected
9895  * to be comletely filled in and ready for the port to operate on it.
9896  * This routine executes a synchronous completion operation on the
9897  * mailbox by polling for its completion.
9898  *
9899  * The caller must not be holding any locks when calling this routine.
9900  *
9901  * Returns:
9902  *	MBX_SUCCESS - mailbox posted successfully
9903  *	Any of the MBX error values.
9904  **/
9905 static int
9906 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9907 {
9908 	int rc = MBX_SUCCESS;
9909 	unsigned long iflag;
9910 	uint32_t mcqe_status;
9911 	uint32_t mbx_cmnd;
9912 	struct lpfc_sli *psli = &phba->sli;
9913 	struct lpfc_mqe *mb = &mboxq->u.mqe;
9914 	struct lpfc_bmbx_create *mbox_rgn;
9915 	struct dma_address *dma_address;
9916 
9917 	/*
9918 	 * Only one mailbox can be active to the bootstrap mailbox region
9919 	 * at a time and there is no queueing provided.
9920 	 */
9921 	spin_lock_irqsave(&phba->hbalock, iflag);
9922 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9923 		spin_unlock_irqrestore(&phba->hbalock, iflag);
9924 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9925 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
9926 				"cannot issue Data: x%x x%x\n",
9927 				mboxq->vport ? mboxq->vport->vpi : 0,
9928 				mboxq->u.mb.mbxCommand,
9929 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9930 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9931 				psli->sli_flag, MBX_POLL);
9932 		return MBXERR_ERROR;
9933 	}
9934 	/* The server grabs the token and owns it until release */
9935 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9936 	phba->sli.mbox_active = mboxq;
9937 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9938 
9939 	/* wait for bootstrap mbox register for readyness */
9940 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9941 	if (rc)
9942 		goto exit;
9943 	/*
9944 	 * Initialize the bootstrap memory region to avoid stale data areas
9945 	 * in the mailbox post.  Then copy the caller's mailbox contents to
9946 	 * the bmbx mailbox region.
9947 	 */
9948 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
9949 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
9950 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
9951 			       sizeof(struct lpfc_mqe));
9952 
9953 	/* Post the high mailbox dma address to the port and wait for ready. */
9954 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9955 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
9956 
9957 	/* wait for bootstrap mbox register for hi-address write done */
9958 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9959 	if (rc)
9960 		goto exit;
9961 
9962 	/* Post the low mailbox dma address to the port. */
9963 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
9964 
9965 	/* wait for bootstrap mbox register for low address write done */
9966 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9967 	if (rc)
9968 		goto exit;
9969 
9970 	/*
9971 	 * Read the CQ to ensure the mailbox has completed.
9972 	 * If so, update the mailbox status so that the upper layers
9973 	 * can complete the request normally.
9974 	 */
9975 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
9976 			       sizeof(struct lpfc_mqe));
9977 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
9978 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
9979 			       sizeof(struct lpfc_mcqe));
9980 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
9981 	/*
9982 	 * When the CQE status indicates a failure and the mailbox status
9983 	 * indicates success then copy the CQE status into the mailbox status
9984 	 * (and prefix it with x4000).
9985 	 */
9986 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
9987 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
9988 			bf_set(lpfc_mqe_status, mb,
9989 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
9990 		rc = MBXERR_ERROR;
9991 	} else
9992 		lpfc_sli4_swap_str(phba, mboxq);
9993 
9994 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9995 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
9996 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
9997 			" x%x x%x CQ: x%x x%x x%x x%x\n",
9998 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
9999 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10000 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10001 			bf_get(lpfc_mqe_status, mb),
10002 			mb->un.mb_words[0], mb->un.mb_words[1],
10003 			mb->un.mb_words[2], mb->un.mb_words[3],
10004 			mb->un.mb_words[4], mb->un.mb_words[5],
10005 			mb->un.mb_words[6], mb->un.mb_words[7],
10006 			mb->un.mb_words[8], mb->un.mb_words[9],
10007 			mb->un.mb_words[10], mb->un.mb_words[11],
10008 			mb->un.mb_words[12], mboxq->mcqe.word0,
10009 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
10010 			mboxq->mcqe.trailer);
10011 exit:
10012 	/* We are holding the token, no needed for lock when release */
10013 	spin_lock_irqsave(&phba->hbalock, iflag);
10014 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10015 	phba->sli.mbox_active = NULL;
10016 	spin_unlock_irqrestore(&phba->hbalock, iflag);
10017 	return rc;
10018 }
10019 
10020 /**
10021  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
10022  * @phba: Pointer to HBA context object.
10023  * @mboxq: Pointer to mailbox object.
10024  * @flag: Flag indicating how the mailbox need to be processed.
10025  *
10026  * This function is called by discovery code and HBA management code to submit
10027  * a mailbox command to firmware with SLI-4 interface spec.
10028  *
10029  * Return codes the caller owns the mailbox command after the return of the
10030  * function.
10031  **/
10032 static int
10033 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
10034 		       uint32_t flag)
10035 {
10036 	struct lpfc_sli *psli = &phba->sli;
10037 	unsigned long iflags;
10038 	int rc;
10039 
10040 	/* dump from issue mailbox command if setup */
10041 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
10042 
10043 	rc = lpfc_mbox_dev_check(phba);
10044 	if (unlikely(rc)) {
10045 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10046 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
10047 				"cannot issue Data: x%x x%x\n",
10048 				mboxq->vport ? mboxq->vport->vpi : 0,
10049 				mboxq->u.mb.mbxCommand,
10050 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10051 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10052 				psli->sli_flag, flag);
10053 		goto out_not_finished;
10054 	}
10055 
10056 	/* Detect polling mode and jump to a handler */
10057 	if (!phba->sli4_hba.intr_enable) {
10058 		if (flag == MBX_POLL)
10059 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10060 		else
10061 			rc = -EIO;
10062 		if (rc != MBX_SUCCESS)
10063 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10064 					"(%d):2541 Mailbox command x%x "
10065 					"(x%x/x%x) failure: "
10066 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
10067 					"Data: x%x x%x\n",
10068 					mboxq->vport ? mboxq->vport->vpi : 0,
10069 					mboxq->u.mb.mbxCommand,
10070 					lpfc_sli_config_mbox_subsys_get(phba,
10071 									mboxq),
10072 					lpfc_sli_config_mbox_opcode_get(phba,
10073 									mboxq),
10074 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10075 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10076 					bf_get(lpfc_mcqe_ext_status,
10077 					       &mboxq->mcqe),
10078 					psli->sli_flag, flag);
10079 		return rc;
10080 	} else if (flag == MBX_POLL) {
10081 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10082 				"(%d):2542 Try to issue mailbox command "
10083 				"x%x (x%x/x%x) synchronously ahead of async "
10084 				"mailbox command queue: x%x x%x\n",
10085 				mboxq->vport ? mboxq->vport->vpi : 0,
10086 				mboxq->u.mb.mbxCommand,
10087 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10088 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10089 				psli->sli_flag, flag);
10090 		/* Try to block the asynchronous mailbox posting */
10091 		rc = lpfc_sli4_async_mbox_block(phba);
10092 		if (!rc) {
10093 			/* Successfully blocked, now issue sync mbox cmd */
10094 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10095 			if (rc != MBX_SUCCESS)
10096 				lpfc_printf_log(phba, KERN_WARNING,
10097 					LOG_MBOX | LOG_SLI,
10098 					"(%d):2597 Sync Mailbox command "
10099 					"x%x (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 			/* Unblock the async mailbox posting afterward */
10114 			lpfc_sli4_async_mbox_unblock(phba);
10115 		}
10116 		return rc;
10117 	}
10118 
10119 	/* Now, interrupt mode asynchronous mailbox command */
10120 	rc = lpfc_mbox_cmd_check(phba, mboxq);
10121 	if (rc) {
10122 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10123 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
10124 				"cannot issue Data: x%x x%x\n",
10125 				mboxq->vport ? mboxq->vport->vpi : 0,
10126 				mboxq->u.mb.mbxCommand,
10127 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10128 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10129 				psli->sli_flag, flag);
10130 		goto out_not_finished;
10131 	}
10132 
10133 	/* Put the mailbox command to the driver internal FIFO */
10134 	psli->slistat.mbox_busy++;
10135 	spin_lock_irqsave(&phba->hbalock, iflags);
10136 	lpfc_mbox_put(phba, mboxq);
10137 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10138 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10139 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
10140 			"x%x (x%x/x%x) x%x x%x x%x\n",
10141 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
10142 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
10143 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10144 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10145 			phba->pport->port_state,
10146 			psli->sli_flag, MBX_NOWAIT);
10147 	/* Wake up worker thread to transport mailbox command from head */
10148 	lpfc_worker_wake_up(phba);
10149 
10150 	return MBX_BUSY;
10151 
10152 out_not_finished:
10153 	return MBX_NOT_FINISHED;
10154 }
10155 
10156 /**
10157  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
10158  * @phba: Pointer to HBA context object.
10159  *
10160  * This function is called by worker thread to send a mailbox command to
10161  * SLI4 HBA firmware.
10162  *
10163  **/
10164 int
10165 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
10166 {
10167 	struct lpfc_sli *psli = &phba->sli;
10168 	LPFC_MBOXQ_t *mboxq;
10169 	int rc = MBX_SUCCESS;
10170 	unsigned long iflags;
10171 	struct lpfc_mqe *mqe;
10172 	uint32_t mbx_cmnd;
10173 
10174 	/* Check interrupt mode before post async mailbox command */
10175 	if (unlikely(!phba->sli4_hba.intr_enable))
10176 		return MBX_NOT_FINISHED;
10177 
10178 	/* Check for mailbox command service token */
10179 	spin_lock_irqsave(&phba->hbalock, iflags);
10180 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
10181 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10182 		return MBX_NOT_FINISHED;
10183 	}
10184 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
10185 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10186 		return MBX_NOT_FINISHED;
10187 	}
10188 	if (unlikely(phba->sli.mbox_active)) {
10189 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10190 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10191 				"0384 There is pending active mailbox cmd\n");
10192 		return MBX_NOT_FINISHED;
10193 	}
10194 	/* Take the mailbox command service token */
10195 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
10196 
10197 	/* Get the next mailbox command from head of queue */
10198 	mboxq = lpfc_mbox_get(phba);
10199 
10200 	/* If no more mailbox command waiting for post, we're done */
10201 	if (!mboxq) {
10202 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10203 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10204 		return MBX_SUCCESS;
10205 	}
10206 	phba->sli.mbox_active = mboxq;
10207 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10208 
10209 	/* Check device readiness for posting mailbox command */
10210 	rc = lpfc_mbox_dev_check(phba);
10211 	if (unlikely(rc))
10212 		/* Driver clean routine will clean up pending mailbox */
10213 		goto out_not_finished;
10214 
10215 	/* Prepare the mbox command to be posted */
10216 	mqe = &mboxq->u.mqe;
10217 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
10218 
10219 	/* Start timer for the mbox_tmo and log some mailbox post messages */
10220 	mod_timer(&psli->mbox_tmo, (jiffies +
10221 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
10222 
10223 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10224 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
10225 			"x%x x%x\n",
10226 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10227 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10228 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10229 			phba->pport->port_state, psli->sli_flag);
10230 
10231 	if (mbx_cmnd != MBX_HEARTBEAT) {
10232 		if (mboxq->vport) {
10233 			lpfc_debugfs_disc_trc(mboxq->vport,
10234 				LPFC_DISC_TRC_MBOX_VPORT,
10235 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
10236 				mbx_cmnd, mqe->un.mb_words[0],
10237 				mqe->un.mb_words[1]);
10238 		} else {
10239 			lpfc_debugfs_disc_trc(phba->pport,
10240 				LPFC_DISC_TRC_MBOX,
10241 				"MBOX Send: cmd:x%x mb:x%x x%x",
10242 				mbx_cmnd, mqe->un.mb_words[0],
10243 				mqe->un.mb_words[1]);
10244 		}
10245 	}
10246 	psli->slistat.mbox_cmd++;
10247 
10248 	/* Post the mailbox command to the port */
10249 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
10250 	if (rc != MBX_SUCCESS) {
10251 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10252 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
10253 				"cannot issue Data: x%x x%x\n",
10254 				mboxq->vport ? mboxq->vport->vpi : 0,
10255 				mboxq->u.mb.mbxCommand,
10256 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10257 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10258 				psli->sli_flag, MBX_NOWAIT);
10259 		goto out_not_finished;
10260 	}
10261 
10262 	return rc;
10263 
10264 out_not_finished:
10265 	spin_lock_irqsave(&phba->hbalock, iflags);
10266 	if (phba->sli.mbox_active) {
10267 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
10268 		__lpfc_mbox_cmpl_put(phba, mboxq);
10269 		/* Release the token */
10270 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10271 		phba->sli.mbox_active = NULL;
10272 	}
10273 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10274 
10275 	return MBX_NOT_FINISHED;
10276 }
10277 
10278 /**
10279  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
10280  * @phba: Pointer to HBA context object.
10281  * @pmbox: Pointer to mailbox object.
10282  * @flag: Flag indicating how the mailbox need to be processed.
10283  *
10284  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
10285  * the API jump table function pointer from the lpfc_hba struct.
10286  *
10287  * Return codes the caller owns the mailbox command after the return of the
10288  * function.
10289  **/
10290 int
10291 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
10292 {
10293 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
10294 }
10295 
10296 /**
10297  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
10298  * @phba: The hba struct for which this call is being executed.
10299  * @dev_grp: The HBA PCI-Device group number.
10300  *
10301  * This routine sets up the mbox interface API function jump table in @phba
10302  * struct.
10303  * Returns: 0 - success, -ENODEV - failure.
10304  **/
10305 int
10306 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10307 {
10308 
10309 	switch (dev_grp) {
10310 	case LPFC_PCI_DEV_LP:
10311 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
10312 		phba->lpfc_sli_handle_slow_ring_event =
10313 				lpfc_sli_handle_slow_ring_event_s3;
10314 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
10315 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
10316 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
10317 		break;
10318 	case LPFC_PCI_DEV_OC:
10319 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
10320 		phba->lpfc_sli_handle_slow_ring_event =
10321 				lpfc_sli_handle_slow_ring_event_s4;
10322 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
10323 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
10324 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
10325 		break;
10326 	default:
10327 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10328 				"1420 Invalid HBA PCI-device group: 0x%x\n",
10329 				dev_grp);
10330 		return -ENODEV;
10331 	}
10332 	return 0;
10333 }
10334 
10335 /**
10336  * __lpfc_sli_ringtx_put - Add an iocb to the txq
10337  * @phba: Pointer to HBA context object.
10338  * @pring: Pointer to driver SLI ring object.
10339  * @piocb: Pointer to address of newly added command iocb.
10340  *
10341  * This function is called with hbalock held for SLI3 ports or
10342  * the ring lock held for SLI4 ports to add a command
10343  * iocb to the txq when SLI layer cannot submit the command iocb
10344  * to the ring.
10345  **/
10346 void
10347 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10348 		    struct lpfc_iocbq *piocb)
10349 {
10350 	if (phba->sli_rev == LPFC_SLI_REV4)
10351 		lockdep_assert_held(&pring->ring_lock);
10352 	else
10353 		lockdep_assert_held(&phba->hbalock);
10354 	/* Insert the caller's iocb in the txq tail for later processing. */
10355 	list_add_tail(&piocb->list, &pring->txq);
10356 }
10357 
10358 /**
10359  * lpfc_sli_next_iocb - Get the next iocb in the txq
10360  * @phba: Pointer to HBA context object.
10361  * @pring: Pointer to driver SLI ring object.
10362  * @piocb: Pointer to address of newly added command iocb.
10363  *
10364  * This function is called with hbalock held before a new
10365  * iocb is submitted to the firmware. This function checks
10366  * txq to flush the iocbs in txq to Firmware before
10367  * submitting new iocbs to the Firmware.
10368  * If there are iocbs in the txq which need to be submitted
10369  * to firmware, lpfc_sli_next_iocb returns the first element
10370  * of the txq after dequeuing it from txq.
10371  * If there is no iocb in the txq then the function will return
10372  * *piocb and *piocb is set to NULL. Caller needs to check
10373  * *piocb to find if there are more commands in the txq.
10374  **/
10375 static struct lpfc_iocbq *
10376 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10377 		   struct lpfc_iocbq **piocb)
10378 {
10379 	struct lpfc_iocbq * nextiocb;
10380 
10381 	lockdep_assert_held(&phba->hbalock);
10382 
10383 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
10384 	if (!nextiocb) {
10385 		nextiocb = *piocb;
10386 		*piocb = NULL;
10387 	}
10388 
10389 	return nextiocb;
10390 }
10391 
10392 /**
10393  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
10394  * @phba: Pointer to HBA context object.
10395  * @ring_number: SLI ring number to issue iocb on.
10396  * @piocb: Pointer to command iocb.
10397  * @flag: Flag indicating if this command can be put into txq.
10398  *
10399  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
10400  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
10401  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
10402  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
10403  * this function allows only iocbs for posting buffers. This function finds
10404  * next available slot in the command ring and posts the command to the
10405  * available slot and writes the port attention register to request HBA start
10406  * processing new iocb. If there is no slot available in the ring and
10407  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
10408  * the function returns IOCB_BUSY.
10409  *
10410  * This function is called with hbalock held. The function will return success
10411  * after it successfully submit the iocb to firmware or after adding to the
10412  * txq.
10413  **/
10414 static int
10415 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
10416 		    struct lpfc_iocbq *piocb, uint32_t flag)
10417 {
10418 	struct lpfc_iocbq *nextiocb;
10419 	IOCB_t *iocb;
10420 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
10421 
10422 	lockdep_assert_held(&phba->hbalock);
10423 
10424 	if (piocb->cmd_cmpl && (!piocb->vport) &&
10425 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
10426 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
10427 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10428 				"1807 IOCB x%x failed. No vport\n",
10429 				piocb->iocb.ulpCommand);
10430 		dump_stack();
10431 		return IOCB_ERROR;
10432 	}
10433 
10434 
10435 	/* If the PCI channel is in offline state, do not post iocbs. */
10436 	if (unlikely(pci_channel_offline(phba->pcidev)))
10437 		return IOCB_ERROR;
10438 
10439 	/* If HBA has a deferred error attention, fail the iocb. */
10440 	if (unlikely(phba->hba_flag & DEFER_ERATT))
10441 		return IOCB_ERROR;
10442 
10443 	/*
10444 	 * We should never get an IOCB if we are in a < LINK_DOWN state
10445 	 */
10446 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
10447 		return IOCB_ERROR;
10448 
10449 	/*
10450 	 * Check to see if we are blocking IOCB processing because of a
10451 	 * outstanding event.
10452 	 */
10453 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
10454 		goto iocb_busy;
10455 
10456 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
10457 		/*
10458 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
10459 		 * can be issued if the link is not up.
10460 		 */
10461 		switch (piocb->iocb.ulpCommand) {
10462 		case CMD_QUE_RING_BUF_CN:
10463 		case CMD_QUE_RING_BUF64_CN:
10464 			/*
10465 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
10466 			 * completion, cmd_cmpl MUST be 0.
10467 			 */
10468 			if (piocb->cmd_cmpl)
10469 				piocb->cmd_cmpl = NULL;
10470 			fallthrough;
10471 		case CMD_CREATE_XRI_CR:
10472 		case CMD_CLOSE_XRI_CN:
10473 		case CMD_CLOSE_XRI_CX:
10474 			break;
10475 		default:
10476 			goto iocb_busy;
10477 		}
10478 
10479 	/*
10480 	 * For FCP commands, we must be in a state where we can process link
10481 	 * attention events.
10482 	 */
10483 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
10484 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
10485 		goto iocb_busy;
10486 	}
10487 
10488 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
10489 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
10490 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
10491 
10492 	if (iocb)
10493 		lpfc_sli_update_ring(phba, pring);
10494 	else
10495 		lpfc_sli_update_full_ring(phba, pring);
10496 
10497 	if (!piocb)
10498 		return IOCB_SUCCESS;
10499 
10500 	goto out_busy;
10501 
10502  iocb_busy:
10503 	pring->stats.iocb_cmd_delay++;
10504 
10505  out_busy:
10506 
10507 	if (!(flag & SLI_IOCB_RET_IOCB)) {
10508 		__lpfc_sli_ringtx_put(phba, pring, piocb);
10509 		return IOCB_SUCCESS;
10510 	}
10511 
10512 	return IOCB_BUSY;
10513 }
10514 
10515 /**
10516  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10517  * @phba: Pointer to HBA context object.
10518  * @ring_number: SLI ring number to issue wqe on.
10519  * @piocb: Pointer to command iocb.
10520  * @flag: Flag indicating if this command can be put into txq.
10521  *
10522  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10523  * send  an iocb command to an HBA with SLI-3 interface spec.
10524  *
10525  * This function takes the hbalock before invoking the lockless version.
10526  * The function will return success after it successfully submit the wqe to
10527  * firmware or after adding to the txq.
10528  **/
10529 static int
10530 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10531 			   struct lpfc_iocbq *piocb, uint32_t flag)
10532 {
10533 	unsigned long iflags;
10534 	int rc;
10535 
10536 	spin_lock_irqsave(&phba->hbalock, iflags);
10537 	rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10538 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10539 
10540 	return rc;
10541 }
10542 
10543 /**
10544  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10545  * @phba: Pointer to HBA context object.
10546  * @ring_number: SLI ring number to issue wqe on.
10547  * @piocb: Pointer to command iocb.
10548  * @flag: Flag indicating if this command can be put into txq.
10549  *
10550  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10551  * an wqe command to an HBA with SLI-4 interface spec.
10552  *
10553  * This function is a lockless version. The function will return success
10554  * after it successfully submit the wqe to firmware or after adding to the
10555  * txq.
10556  **/
10557 static int
10558 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10559 			   struct lpfc_iocbq *piocb, uint32_t flag)
10560 {
10561 	struct lpfc_io_buf *lpfc_cmd = piocb->io_buf;
10562 
10563 	lpfc_prep_embed_io(phba, lpfc_cmd);
10564 	return lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
10565 }
10566 
10567 void
10568 lpfc_prep_embed_io(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
10569 {
10570 	struct lpfc_iocbq *piocb = &lpfc_cmd->cur_iocbq;
10571 	union lpfc_wqe128 *wqe = &lpfc_cmd->cur_iocbq.wqe;
10572 	struct sli4_sge *sgl;
10573 
10574 	/* 128 byte wqe support here */
10575 	sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10576 
10577 	if (phba->fcp_embed_io) {
10578 		struct fcp_cmnd *fcp_cmnd;
10579 		u32 *ptr;
10580 
10581 		fcp_cmnd = lpfc_cmd->fcp_cmnd;
10582 
10583 		/* Word 0-2 - FCP_CMND */
10584 		wqe->generic.bde.tus.f.bdeFlags =
10585 			BUFF_TYPE_BDE_IMMED;
10586 		wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10587 		wqe->generic.bde.addrHigh = 0;
10588 		wqe->generic.bde.addrLow =  88;  /* Word 22 */
10589 
10590 		bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10591 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10592 
10593 		/* Word 22-29  FCP CMND Payload */
10594 		ptr = &wqe->words[22];
10595 		memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10596 	} else {
10597 		/* Word 0-2 - Inline BDE */
10598 		wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
10599 		wqe->generic.bde.tus.f.bdeSize = sizeof(struct fcp_cmnd);
10600 		wqe->generic.bde.addrHigh = sgl->addr_hi;
10601 		wqe->generic.bde.addrLow =  sgl->addr_lo;
10602 
10603 		/* Word 10 */
10604 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10605 		bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
10606 	}
10607 
10608 	/* add the VMID tags as per switch response */
10609 	if (unlikely(piocb->cmd_flag & LPFC_IO_VMID)) {
10610 		if (phba->pport->vmid_flag & LPFC_VMID_TYPE_PRIO) {
10611 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
10612 			bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10613 					(piocb->vmid_tag.cs_ctl_vmid));
10614 		} else if (phba->cfg_vmid_app_header) {
10615 			bf_set(wqe_appid, &wqe->fcp_iwrite.wqe_com, 1);
10616 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10617 			wqe->words[31] = piocb->vmid_tag.app_id;
10618 		}
10619 	}
10620 }
10621 
10622 /**
10623  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10624  * @phba: Pointer to HBA context object.
10625  * @ring_number: SLI ring number to issue iocb on.
10626  * @piocb: Pointer to command iocb.
10627  * @flag: Flag indicating if this command can be put into txq.
10628  *
10629  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10630  * an iocb command to an HBA with SLI-4 interface spec.
10631  *
10632  * This function is called with ringlock held. The function will return success
10633  * after it successfully submit the iocb to firmware or after adding to the
10634  * txq.
10635  **/
10636 static int
10637 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10638 			 struct lpfc_iocbq *piocb, uint32_t flag)
10639 {
10640 	struct lpfc_sglq *sglq;
10641 	union lpfc_wqe128 *wqe;
10642 	struct lpfc_queue *wq;
10643 	struct lpfc_sli_ring *pring;
10644 	u32 ulp_command = get_job_cmnd(phba, piocb);
10645 
10646 	/* Get the WQ */
10647 	if ((piocb->cmd_flag & LPFC_IO_FCP) ||
10648 	    (piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
10649 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10650 	} else {
10651 		wq = phba->sli4_hba.els_wq;
10652 	}
10653 
10654 	/* Get corresponding ring */
10655 	pring = wq->pring;
10656 
10657 	/*
10658 	 * The WQE can be either 64 or 128 bytes,
10659 	 */
10660 
10661 	lockdep_assert_held(&pring->ring_lock);
10662 	wqe = &piocb->wqe;
10663 	if (piocb->sli4_xritag == NO_XRI) {
10664 		if (ulp_command == CMD_ABORT_XRI_CX)
10665 			sglq = NULL;
10666 		else {
10667 			sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10668 			if (!sglq) {
10669 				if (!(flag & SLI_IOCB_RET_IOCB)) {
10670 					__lpfc_sli_ringtx_put(phba,
10671 							pring,
10672 							piocb);
10673 					return IOCB_SUCCESS;
10674 				} else {
10675 					return IOCB_BUSY;
10676 				}
10677 			}
10678 		}
10679 	} else if (piocb->cmd_flag &  LPFC_IO_FCP) {
10680 		/* These IO's already have an XRI and a mapped sgl. */
10681 		sglq = NULL;
10682 	}
10683 	else {
10684 		/*
10685 		 * This is a continuation of a commandi,(CX) so this
10686 		 * sglq is on the active list
10687 		 */
10688 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10689 		if (!sglq)
10690 			return IOCB_ERROR;
10691 	}
10692 
10693 	if (sglq) {
10694 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10695 		piocb->sli4_xritag = sglq->sli4_xritag;
10696 
10697 		/* ABTS sent by initiator to CT exchange, the
10698 		 * RX_ID field will be filled with the newly
10699 		 * allocated responder XRI.
10700 		 */
10701 		if (ulp_command == CMD_XMIT_BLS_RSP64_CX &&
10702 		    piocb->abort_bls == LPFC_ABTS_UNSOL_INT)
10703 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10704 			       piocb->sli4_xritag);
10705 
10706 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com,
10707 		       piocb->sli4_xritag);
10708 
10709 		if (lpfc_wqe_bpl2sgl(phba, piocb, sglq) == NO_XRI)
10710 			return IOCB_ERROR;
10711 	}
10712 
10713 	if (lpfc_sli4_wq_put(wq, wqe))
10714 		return IOCB_ERROR;
10715 
10716 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10717 
10718 	return 0;
10719 }
10720 
10721 /*
10722  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
10723  *
10724  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
10725  * or IOCB for sli-3  function.
10726  * pointer from the lpfc_hba struct.
10727  *
10728  * Return codes:
10729  * IOCB_ERROR - Error
10730  * IOCB_SUCCESS - Success
10731  * IOCB_BUSY - Busy
10732  **/
10733 int
10734 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
10735 		      struct lpfc_iocbq *piocb, uint32_t flag)
10736 {
10737 	return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
10738 }
10739 
10740 /*
10741  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10742  *
10743  * This routine wraps the actual lockless version for issusing IOCB function
10744  * pointer from the lpfc_hba struct.
10745  *
10746  * Return codes:
10747  * IOCB_ERROR - Error
10748  * IOCB_SUCCESS - Success
10749  * IOCB_BUSY - Busy
10750  **/
10751 int
10752 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10753 		struct lpfc_iocbq *piocb, uint32_t flag)
10754 {
10755 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10756 }
10757 
10758 static void
10759 __lpfc_sli_prep_els_req_rsp_s3(struct lpfc_iocbq *cmdiocbq,
10760 			       struct lpfc_vport *vport,
10761 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10762 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10763 {
10764 	struct lpfc_hba *phba = vport->phba;
10765 	IOCB_t *cmd;
10766 
10767 	cmd = &cmdiocbq->iocb;
10768 	memset(cmd, 0, sizeof(*cmd));
10769 
10770 	cmd->un.elsreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10771 	cmd->un.elsreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10772 	cmd->un.elsreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10773 
10774 	if (expect_rsp) {
10775 		cmd->un.elsreq64.bdl.bdeSize = (2 * sizeof(struct ulp_bde64));
10776 		cmd->un.elsreq64.remoteID = did; /* DID */
10777 		cmd->ulpCommand = CMD_ELS_REQUEST64_CR;
10778 		cmd->ulpTimeout = tmo;
10779 	} else {
10780 		cmd->un.elsreq64.bdl.bdeSize = sizeof(struct ulp_bde64);
10781 		cmd->un.genreq64.xmit_els_remoteID = did; /* DID */
10782 		cmd->ulpCommand = CMD_XMIT_ELS_RSP64_CX;
10783 		cmd->ulpPU = PARM_NPIV_DID;
10784 	}
10785 	cmd->ulpBdeCount = 1;
10786 	cmd->ulpLe = 1;
10787 	cmd->ulpClass = CLASS3;
10788 
10789 	/* If we have NPIV enabled, we want to send ELS traffic by VPI. */
10790 	if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) {
10791 		if (expect_rsp) {
10792 			cmd->un.elsreq64.myID = vport->fc_myDID;
10793 
10794 			/* For ELS_REQUEST64_CR, use the VPI by default */
10795 			cmd->ulpContext = phba->vpi_ids[vport->vpi];
10796 		}
10797 
10798 		cmd->ulpCt_h = 0;
10799 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10800 		if (elscmd == ELS_CMD_ECHO)
10801 			cmd->ulpCt_l = 0; /* context = invalid RPI */
10802 		else
10803 			cmd->ulpCt_l = 1; /* context = VPI */
10804 	}
10805 }
10806 
10807 static void
10808 __lpfc_sli_prep_els_req_rsp_s4(struct lpfc_iocbq *cmdiocbq,
10809 			       struct lpfc_vport *vport,
10810 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10811 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10812 {
10813 	struct lpfc_hba  *phba = vport->phba;
10814 	union lpfc_wqe128 *wqe;
10815 	struct ulp_bde64_le *bde;
10816 	u8 els_id;
10817 
10818 	wqe = &cmdiocbq->wqe;
10819 	memset(wqe, 0, sizeof(*wqe));
10820 
10821 	/* Word 0 - 2 BDE */
10822 	bde = (struct ulp_bde64_le *)&wqe->generic.bde;
10823 	bde->addr_low = cpu_to_le32(putPaddrLow(bmp->phys));
10824 	bde->addr_high = cpu_to_le32(putPaddrHigh(bmp->phys));
10825 	bde->type_size = cpu_to_le32(cmd_size);
10826 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10827 
10828 	if (expect_rsp) {
10829 		bf_set(wqe_cmnd, &wqe->els_req.wqe_com, CMD_ELS_REQUEST64_WQE);
10830 
10831 		/* Transfer length */
10832 		wqe->els_req.payload_len = cmd_size;
10833 		wqe->els_req.max_response_payload_len = FCELSSIZE;
10834 
10835 		/* DID */
10836 		bf_set(wqe_els_did, &wqe->els_req.wqe_dest, did);
10837 
10838 		/* Word 11 - ELS_ID */
10839 		switch (elscmd) {
10840 		case ELS_CMD_PLOGI:
10841 			els_id = LPFC_ELS_ID_PLOGI;
10842 			break;
10843 		case ELS_CMD_FLOGI:
10844 			els_id = LPFC_ELS_ID_FLOGI;
10845 			break;
10846 		case ELS_CMD_LOGO:
10847 			els_id = LPFC_ELS_ID_LOGO;
10848 			break;
10849 		case ELS_CMD_FDISC:
10850 			if (!vport->fc_myDID) {
10851 				els_id = LPFC_ELS_ID_FDISC;
10852 				break;
10853 			}
10854 			fallthrough;
10855 		default:
10856 			els_id = LPFC_ELS_ID_DEFAULT;
10857 			break;
10858 		}
10859 
10860 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
10861 	} else {
10862 		/* DID */
10863 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest, did);
10864 
10865 		/* Transfer length */
10866 		wqe->xmit_els_rsp.response_payload_len = cmd_size;
10867 
10868 		bf_set(wqe_cmnd, &wqe->xmit_els_rsp.wqe_com,
10869 		       CMD_XMIT_ELS_RSP64_WQE);
10870 	}
10871 
10872 	bf_set(wqe_tmo, &wqe->generic.wqe_com, tmo);
10873 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, cmdiocbq->iotag);
10874 	bf_set(wqe_class, &wqe->generic.wqe_com, CLASS3);
10875 
10876 	/* If we have NPIV enabled, we want to send ELS traffic by VPI.
10877 	 * For SLI4, since the driver controls VPIs we also want to include
10878 	 * all ELS pt2pt protocol traffic as well.
10879 	 */
10880 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) ||
10881 	    (vport->fc_flag & FC_PT2PT)) {
10882 		if (expect_rsp) {
10883 			bf_set(els_req64_sid, &wqe->els_req, vport->fc_myDID);
10884 
10885 			/* For ELS_REQUEST64_WQE, use the VPI by default */
10886 			bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10887 			       phba->vpi_ids[vport->vpi]);
10888 		}
10889 
10890 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10891 		if (elscmd == ELS_CMD_ECHO)
10892 			bf_set(wqe_ct, &wqe->generic.wqe_com, 0);
10893 		else
10894 			bf_set(wqe_ct, &wqe->generic.wqe_com, 1);
10895 	}
10896 }
10897 
10898 void
10899 lpfc_sli_prep_els_req_rsp(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
10900 			  struct lpfc_vport *vport, struct lpfc_dmabuf *bmp,
10901 			  u16 cmd_size, u32 did, u32 elscmd, u8 tmo,
10902 			  u8 expect_rsp)
10903 {
10904 	phba->__lpfc_sli_prep_els_req_rsp(cmdiocbq, vport, bmp, cmd_size, did,
10905 					  elscmd, tmo, expect_rsp);
10906 }
10907 
10908 static void
10909 __lpfc_sli_prep_gen_req_s3(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10910 			   u16 rpi, u32 num_entry, u8 tmo)
10911 {
10912 	IOCB_t *cmd;
10913 
10914 	cmd = &cmdiocbq->iocb;
10915 	memset(cmd, 0, sizeof(*cmd));
10916 
10917 	cmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10918 	cmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10919 	cmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10920 	cmd->un.genreq64.bdl.bdeSize = num_entry * sizeof(struct ulp_bde64);
10921 
10922 	cmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
10923 	cmd->un.genreq64.w5.hcsw.Type = FC_TYPE_CT;
10924 	cmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
10925 
10926 	cmd->ulpContext = rpi;
10927 	cmd->ulpClass = CLASS3;
10928 	cmd->ulpCommand = CMD_GEN_REQUEST64_CR;
10929 	cmd->ulpBdeCount = 1;
10930 	cmd->ulpLe = 1;
10931 	cmd->ulpOwner = OWN_CHIP;
10932 	cmd->ulpTimeout = tmo;
10933 }
10934 
10935 static void
10936 __lpfc_sli_prep_gen_req_s4(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10937 			   u16 rpi, u32 num_entry, u8 tmo)
10938 {
10939 	union lpfc_wqe128 *cmdwqe;
10940 	struct ulp_bde64_le *bde, *bpl;
10941 	u32 xmit_len = 0, total_len = 0, size, type, i;
10942 
10943 	cmdwqe = &cmdiocbq->wqe;
10944 	memset(cmdwqe, 0, sizeof(*cmdwqe));
10945 
10946 	/* Calculate total_len and xmit_len */
10947 	bpl = (struct ulp_bde64_le *)bmp->virt;
10948 	for (i = 0; i < num_entry; i++) {
10949 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10950 		total_len += size;
10951 	}
10952 	for (i = 0; i < num_entry; i++) {
10953 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10954 		type = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_TYPE_MASK;
10955 		if (type != ULP_BDE64_TYPE_BDE_64)
10956 			break;
10957 		xmit_len += size;
10958 	}
10959 
10960 	/* Words 0 - 2 */
10961 	bde = (struct ulp_bde64_le *)&cmdwqe->generic.bde;
10962 	bde->addr_low = bpl->addr_low;
10963 	bde->addr_high = bpl->addr_high;
10964 	bde->type_size = cpu_to_le32(xmit_len);
10965 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10966 
10967 	/* Word 3 */
10968 	cmdwqe->gen_req.request_payload_len = xmit_len;
10969 
10970 	/* Word 5 */
10971 	bf_set(wqe_type, &cmdwqe->gen_req.wge_ctl, FC_TYPE_CT);
10972 	bf_set(wqe_rctl, &cmdwqe->gen_req.wge_ctl, FC_RCTL_DD_UNSOL_CTL);
10973 	bf_set(wqe_si, &cmdwqe->gen_req.wge_ctl, 1);
10974 	bf_set(wqe_la, &cmdwqe->gen_req.wge_ctl, 1);
10975 
10976 	/* Word 6 */
10977 	bf_set(wqe_ctxt_tag, &cmdwqe->gen_req.wqe_com, rpi);
10978 
10979 	/* Word 7 */
10980 	bf_set(wqe_tmo, &cmdwqe->gen_req.wqe_com, tmo);
10981 	bf_set(wqe_class, &cmdwqe->gen_req.wqe_com, CLASS3);
10982 	bf_set(wqe_cmnd, &cmdwqe->gen_req.wqe_com, CMD_GEN_REQUEST64_CR);
10983 	bf_set(wqe_ct, &cmdwqe->gen_req.wqe_com, SLI4_CT_RPI);
10984 
10985 	/* Word 12 */
10986 	cmdwqe->gen_req.max_response_payload_len = total_len - xmit_len;
10987 }
10988 
10989 void
10990 lpfc_sli_prep_gen_req(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
10991 		      struct lpfc_dmabuf *bmp, u16 rpi, u32 num_entry, u8 tmo)
10992 {
10993 	phba->__lpfc_sli_prep_gen_req(cmdiocbq, bmp, rpi, num_entry, tmo);
10994 }
10995 
10996 static void
10997 __lpfc_sli_prep_xmit_seq64_s3(struct lpfc_iocbq *cmdiocbq,
10998 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
10999 			      u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11000 {
11001 	IOCB_t *icmd;
11002 
11003 	icmd = &cmdiocbq->iocb;
11004 	memset(icmd, 0, sizeof(*icmd));
11005 
11006 	icmd->un.xseq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
11007 	icmd->un.xseq64.bdl.addrLow = putPaddrLow(bmp->phys);
11008 	icmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
11009 	icmd->un.xseq64.bdl.bdeSize = (num_entry * sizeof(struct ulp_bde64));
11010 	icmd->un.xseq64.w5.hcsw.Fctl = LA;
11011 	if (last_seq)
11012 		icmd->un.xseq64.w5.hcsw.Fctl |= LS;
11013 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
11014 	icmd->un.xseq64.w5.hcsw.Rctl = rctl;
11015 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
11016 
11017 	icmd->ulpBdeCount = 1;
11018 	icmd->ulpLe = 1;
11019 	icmd->ulpClass = CLASS3;
11020 
11021 	switch (cr_cx_cmd) {
11022 	case CMD_XMIT_SEQUENCE64_CR:
11023 		icmd->ulpContext = rpi;
11024 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CR;
11025 		break;
11026 	case CMD_XMIT_SEQUENCE64_CX:
11027 		icmd->ulpContext = ox_id;
11028 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CX;
11029 		break;
11030 	default:
11031 		break;
11032 	}
11033 }
11034 
11035 static void
11036 __lpfc_sli_prep_xmit_seq64_s4(struct lpfc_iocbq *cmdiocbq,
11037 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11038 			      u32 full_size, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11039 {
11040 	union lpfc_wqe128 *wqe;
11041 	struct ulp_bde64 *bpl;
11042 
11043 	wqe = &cmdiocbq->wqe;
11044 	memset(wqe, 0, sizeof(*wqe));
11045 
11046 	/* Words 0 - 2 */
11047 	bpl = (struct ulp_bde64 *)bmp->virt;
11048 	wqe->xmit_sequence.bde.addrHigh = bpl->addrHigh;
11049 	wqe->xmit_sequence.bde.addrLow = bpl->addrLow;
11050 	wqe->xmit_sequence.bde.tus.w = bpl->tus.w;
11051 
11052 	/* Word 5 */
11053 	bf_set(wqe_ls, &wqe->xmit_sequence.wge_ctl, last_seq);
11054 	bf_set(wqe_la, &wqe->xmit_sequence.wge_ctl, 1);
11055 	bf_set(wqe_dfctl, &wqe->xmit_sequence.wge_ctl, 0);
11056 	bf_set(wqe_rctl, &wqe->xmit_sequence.wge_ctl, rctl);
11057 	bf_set(wqe_type, &wqe->xmit_sequence.wge_ctl, FC_TYPE_CT);
11058 
11059 	/* Word 6 */
11060 	bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com, rpi);
11061 
11062 	bf_set(wqe_cmnd, &wqe->xmit_sequence.wqe_com,
11063 	       CMD_XMIT_SEQUENCE64_WQE);
11064 
11065 	/* Word 7 */
11066 	bf_set(wqe_class, &wqe->xmit_sequence.wqe_com, CLASS3);
11067 
11068 	/* Word 9 */
11069 	bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com, ox_id);
11070 
11071 	/* Word 12 */
11072 	if (cmdiocbq->cmd_flag & (LPFC_IO_LIBDFC | LPFC_IO_LOOPBACK))
11073 		wqe->xmit_sequence.xmit_len = full_size;
11074 	else
11075 		wqe->xmit_sequence.xmit_len =
11076 			wqe->xmit_sequence.bde.tus.f.bdeSize;
11077 }
11078 
11079 void
11080 lpfc_sli_prep_xmit_seq64(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11081 			 struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11082 			 u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11083 {
11084 	phba->__lpfc_sli_prep_xmit_seq64(cmdiocbq, bmp, rpi, ox_id, num_entry,
11085 					 rctl, last_seq, cr_cx_cmd);
11086 }
11087 
11088 static void
11089 __lpfc_sli_prep_abort_xri_s3(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11090 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11091 			     bool wqec)
11092 {
11093 	IOCB_t *icmd = NULL;
11094 
11095 	icmd = &cmdiocbq->iocb;
11096 	memset(icmd, 0, sizeof(*icmd));
11097 
11098 	/* Word 5 */
11099 	icmd->un.acxri.abortContextTag = ulp_context;
11100 	icmd->un.acxri.abortIoTag = iotag;
11101 
11102 	if (ia) {
11103 		/* Word 7 */
11104 		icmd->ulpCommand = CMD_CLOSE_XRI_CN;
11105 	} else {
11106 		/* Word 3 */
11107 		icmd->un.acxri.abortType = ABORT_TYPE_ABTS;
11108 
11109 		/* Word 7 */
11110 		icmd->ulpClass = ulp_class;
11111 		icmd->ulpCommand = CMD_ABORT_XRI_CN;
11112 	}
11113 
11114 	/* Word 7 */
11115 	icmd->ulpLe = 1;
11116 }
11117 
11118 static void
11119 __lpfc_sli_prep_abort_xri_s4(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11120 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11121 			     bool wqec)
11122 {
11123 	union lpfc_wqe128 *wqe;
11124 
11125 	wqe = &cmdiocbq->wqe;
11126 	memset(wqe, 0, sizeof(*wqe));
11127 
11128 	/* Word 3 */
11129 	bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
11130 	if (ia)
11131 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
11132 	else
11133 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
11134 
11135 	/* Word 7 */
11136 	bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_WQE);
11137 
11138 	/* Word 8 */
11139 	wqe->abort_cmd.wqe_com.abort_tag = ulp_context;
11140 
11141 	/* Word 9 */
11142 	bf_set(wqe_reqtag, &wqe->abort_cmd.wqe_com, iotag);
11143 
11144 	/* Word 10 */
11145 	bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
11146 
11147 	/* Word 11 */
11148 	if (wqec)
11149 		bf_set(wqe_wqec, &wqe->abort_cmd.wqe_com, 1);
11150 	bf_set(wqe_cqid, &wqe->abort_cmd.wqe_com, cqid);
11151 	bf_set(wqe_cmd_type, &wqe->abort_cmd.wqe_com, OTHER_COMMAND);
11152 }
11153 
11154 void
11155 lpfc_sli_prep_abort_xri(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11156 			u16 ulp_context, u16 iotag, u8 ulp_class, u16 cqid,
11157 			bool ia, bool wqec)
11158 {
11159 	phba->__lpfc_sli_prep_abort_xri(cmdiocbq, ulp_context, iotag, ulp_class,
11160 					cqid, ia, wqec);
11161 }
11162 
11163 /**
11164  * lpfc_sli_api_table_setup - Set up sli api function jump table
11165  * @phba: The hba struct for which this call is being executed.
11166  * @dev_grp: The HBA PCI-Device group number.
11167  *
11168  * This routine sets up the SLI interface API function jump table in @phba
11169  * struct.
11170  * Returns: 0 - success, -ENODEV - failure.
11171  **/
11172 int
11173 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
11174 {
11175 
11176 	switch (dev_grp) {
11177 	case LPFC_PCI_DEV_LP:
11178 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
11179 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
11180 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
11181 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s3;
11182 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s3;
11183 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s3;
11184 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s3;
11185 		break;
11186 	case LPFC_PCI_DEV_OC:
11187 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
11188 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
11189 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
11190 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s4;
11191 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s4;
11192 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s4;
11193 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s4;
11194 		break;
11195 	default:
11196 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11197 				"1419 Invalid HBA PCI-device group: 0x%x\n",
11198 				dev_grp);
11199 		return -ENODEV;
11200 	}
11201 	return 0;
11202 }
11203 
11204 /**
11205  * lpfc_sli4_calc_ring - Calculates which ring to use
11206  * @phba: Pointer to HBA context object.
11207  * @piocb: Pointer to command iocb.
11208  *
11209  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
11210  * hba_wqidx, thus we need to calculate the corresponding ring.
11211  * Since ABORTS must go on the same WQ of the command they are
11212  * aborting, we use command's hba_wqidx.
11213  */
11214 struct lpfc_sli_ring *
11215 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
11216 {
11217 	struct lpfc_io_buf *lpfc_cmd;
11218 
11219 	if (piocb->cmd_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
11220 		if (unlikely(!phba->sli4_hba.hdwq))
11221 			return NULL;
11222 		/*
11223 		 * for abort iocb hba_wqidx should already
11224 		 * be setup based on what work queue we used.
11225 		 */
11226 		if (!(piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
11227 			lpfc_cmd = piocb->io_buf;
11228 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
11229 		}
11230 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
11231 	} else {
11232 		if (unlikely(!phba->sli4_hba.els_wq))
11233 			return NULL;
11234 		piocb->hba_wqidx = 0;
11235 		return phba->sli4_hba.els_wq->pring;
11236 	}
11237 }
11238 
11239 inline void lpfc_sli4_poll_eq(struct lpfc_queue *eq)
11240 {
11241 	struct lpfc_hba *phba = eq->phba;
11242 
11243 	/*
11244 	 * Unlocking an irq is one of the entry point to check
11245 	 * for re-schedule, but we are good for io submission
11246 	 * path as midlayer does a get_cpu to glue us in. Flush
11247 	 * out the invalidate queue so we can see the updated
11248 	 * value for flag.
11249 	 */
11250 	smp_rmb();
11251 
11252 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
11253 		/* We will not likely get the completion for the caller
11254 		 * during this iteration but i guess that's fine.
11255 		 * Future io's coming on this eq should be able to
11256 		 * pick it up.  As for the case of single io's, they
11257 		 * will be handled through a sched from polling timer
11258 		 * function which is currently triggered every 1msec.
11259 		 */
11260 		lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM,
11261 				     LPFC_QUEUE_WORK);
11262 }
11263 
11264 /**
11265  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
11266  * @phba: Pointer to HBA context object.
11267  * @ring_number: Ring number
11268  * @piocb: Pointer to command iocb.
11269  * @flag: Flag indicating if this command can be put into txq.
11270  *
11271  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
11272  * function. This function gets the hbalock and calls
11273  * __lpfc_sli_issue_iocb function and will return the error returned
11274  * by __lpfc_sli_issue_iocb function. This wrapper is used by
11275  * functions which do not hold hbalock.
11276  **/
11277 int
11278 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
11279 		    struct lpfc_iocbq *piocb, uint32_t flag)
11280 {
11281 	struct lpfc_sli_ring *pring;
11282 	struct lpfc_queue *eq;
11283 	unsigned long iflags;
11284 	int rc;
11285 
11286 	/* If the PCI channel is in offline state, do not post iocbs. */
11287 	if (unlikely(pci_channel_offline(phba->pcidev)))
11288 		return IOCB_ERROR;
11289 
11290 	if (phba->sli_rev == LPFC_SLI_REV4) {
11291 		lpfc_sli_prep_wqe(phba, piocb);
11292 
11293 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
11294 
11295 		pring = lpfc_sli4_calc_ring(phba, piocb);
11296 		if (unlikely(pring == NULL))
11297 			return IOCB_ERROR;
11298 
11299 		spin_lock_irqsave(&pring->ring_lock, iflags);
11300 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11301 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11302 
11303 		lpfc_sli4_poll_eq(eq);
11304 	} else {
11305 		/* For now, SLI2/3 will still use hbalock */
11306 		spin_lock_irqsave(&phba->hbalock, iflags);
11307 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11308 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11309 	}
11310 	return rc;
11311 }
11312 
11313 /**
11314  * lpfc_extra_ring_setup - Extra ring setup function
11315  * @phba: Pointer to HBA context object.
11316  *
11317  * This function is called while driver attaches with the
11318  * HBA to setup the extra ring. The extra ring is used
11319  * only when driver needs to support target mode functionality
11320  * or IP over FC functionalities.
11321  *
11322  * This function is called with no lock held. SLI3 only.
11323  **/
11324 static int
11325 lpfc_extra_ring_setup( struct lpfc_hba *phba)
11326 {
11327 	struct lpfc_sli *psli;
11328 	struct lpfc_sli_ring *pring;
11329 
11330 	psli = &phba->sli;
11331 
11332 	/* Adjust cmd/rsp ring iocb entries more evenly */
11333 
11334 	/* Take some away from the FCP ring */
11335 	pring = &psli->sli3_ring[LPFC_FCP_RING];
11336 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11337 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11338 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11339 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11340 
11341 	/* and give them to the extra ring */
11342 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
11343 
11344 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11345 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11346 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11347 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11348 
11349 	/* Setup default profile for this ring */
11350 	pring->iotag_max = 4096;
11351 	pring->num_mask = 1;
11352 	pring->prt[0].profile = 0;      /* Mask 0 */
11353 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
11354 	pring->prt[0].type = phba->cfg_multi_ring_type;
11355 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
11356 	return 0;
11357 }
11358 
11359 static void
11360 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
11361 			     struct lpfc_nodelist *ndlp)
11362 {
11363 	unsigned long iflags;
11364 	struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
11365 
11366 	spin_lock_irqsave(&phba->hbalock, iflags);
11367 	if (!list_empty(&evtp->evt_listp)) {
11368 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11369 		return;
11370 	}
11371 
11372 	/* Incrementing the reference count until the queued work is done. */
11373 	evtp->evt_arg1  = lpfc_nlp_get(ndlp);
11374 	if (!evtp->evt_arg1) {
11375 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11376 		return;
11377 	}
11378 	evtp->evt = LPFC_EVT_RECOVER_PORT;
11379 	list_add_tail(&evtp->evt_listp, &phba->work_list);
11380 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11381 
11382 	lpfc_worker_wake_up(phba);
11383 }
11384 
11385 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
11386  * @phba: Pointer to HBA context object.
11387  * @iocbq: Pointer to iocb object.
11388  *
11389  * The async_event handler calls this routine when it receives
11390  * an ASYNC_STATUS_CN event from the port.  The port generates
11391  * this event when an Abort Sequence request to an rport fails
11392  * twice in succession.  The abort could be originated by the
11393  * driver or by the port.  The ABTS could have been for an ELS
11394  * or FCP IO.  The port only generates this event when an ABTS
11395  * fails to complete after one retry.
11396  */
11397 static void
11398 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
11399 			  struct lpfc_iocbq *iocbq)
11400 {
11401 	struct lpfc_nodelist *ndlp = NULL;
11402 	uint16_t rpi = 0, vpi = 0;
11403 	struct lpfc_vport *vport = NULL;
11404 
11405 	/* The rpi in the ulpContext is vport-sensitive. */
11406 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
11407 	rpi = iocbq->iocb.ulpContext;
11408 
11409 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11410 			"3092 Port generated ABTS async event "
11411 			"on vpi %d rpi %d status 0x%x\n",
11412 			vpi, rpi, iocbq->iocb.ulpStatus);
11413 
11414 	vport = lpfc_find_vport_by_vpid(phba, vpi);
11415 	if (!vport)
11416 		goto err_exit;
11417 	ndlp = lpfc_findnode_rpi(vport, rpi);
11418 	if (!ndlp)
11419 		goto err_exit;
11420 
11421 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
11422 		lpfc_sli_abts_recover_port(vport, ndlp);
11423 	return;
11424 
11425  err_exit:
11426 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11427 			"3095 Event Context not found, no "
11428 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
11429 			vpi, rpi, iocbq->iocb.ulpStatus,
11430 			iocbq->iocb.ulpContext);
11431 }
11432 
11433 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
11434  * @phba: pointer to HBA context object.
11435  * @ndlp: nodelist pointer for the impacted rport.
11436  * @axri: pointer to the wcqe containing the failed exchange.
11437  *
11438  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
11439  * port.  The port generates this event when an abort exchange request to an
11440  * rport fails twice in succession with no reply.  The abort could be originated
11441  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
11442  */
11443 void
11444 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
11445 			   struct lpfc_nodelist *ndlp,
11446 			   struct sli4_wcqe_xri_aborted *axri)
11447 {
11448 	uint32_t ext_status = 0;
11449 
11450 	if (!ndlp) {
11451 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11452 				"3115 Node Context not found, driver "
11453 				"ignoring abts err event\n");
11454 		return;
11455 	}
11456 
11457 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11458 			"3116 Port generated FCP XRI ABORT event on "
11459 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
11460 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
11461 			bf_get(lpfc_wcqe_xa_xri, axri),
11462 			bf_get(lpfc_wcqe_xa_status, axri),
11463 			axri->parameter);
11464 
11465 	/*
11466 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
11467 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
11468 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
11469 	 */
11470 	ext_status = axri->parameter & IOERR_PARAM_MASK;
11471 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
11472 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
11473 		lpfc_sli_post_recovery_event(phba, ndlp);
11474 }
11475 
11476 /**
11477  * lpfc_sli_async_event_handler - ASYNC iocb handler function
11478  * @phba: Pointer to HBA context object.
11479  * @pring: Pointer to driver SLI ring object.
11480  * @iocbq: Pointer to iocb object.
11481  *
11482  * This function is called by the slow ring event handler
11483  * function when there is an ASYNC event iocb in the ring.
11484  * This function is called with no lock held.
11485  * Currently this function handles only temperature related
11486  * ASYNC events. The function decodes the temperature sensor
11487  * event message and posts events for the management applications.
11488  **/
11489 static void
11490 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
11491 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
11492 {
11493 	IOCB_t *icmd;
11494 	uint16_t evt_code;
11495 	struct temp_event temp_event_data;
11496 	struct Scsi_Host *shost;
11497 	uint32_t *iocb_w;
11498 
11499 	icmd = &iocbq->iocb;
11500 	evt_code = icmd->un.asyncstat.evt_code;
11501 
11502 	switch (evt_code) {
11503 	case ASYNC_TEMP_WARN:
11504 	case ASYNC_TEMP_SAFE:
11505 		temp_event_data.data = (uint32_t) icmd->ulpContext;
11506 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
11507 		if (evt_code == ASYNC_TEMP_WARN) {
11508 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
11509 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11510 				"0347 Adapter is very hot, please take "
11511 				"corrective action. temperature : %d Celsius\n",
11512 				(uint32_t) icmd->ulpContext);
11513 		} else {
11514 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
11515 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11516 				"0340 Adapter temperature is OK now. "
11517 				"temperature : %d Celsius\n",
11518 				(uint32_t) icmd->ulpContext);
11519 		}
11520 
11521 		/* Send temperature change event to applications */
11522 		shost = lpfc_shost_from_vport(phba->pport);
11523 		fc_host_post_vendor_event(shost, fc_get_event_number(),
11524 			sizeof(temp_event_data), (char *) &temp_event_data,
11525 			LPFC_NL_VENDOR_ID);
11526 		break;
11527 	case ASYNC_STATUS_CN:
11528 		lpfc_sli_abts_err_handler(phba, iocbq);
11529 		break;
11530 	default:
11531 		iocb_w = (uint32_t *) icmd;
11532 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11533 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
11534 			" evt_code 0x%x\n"
11535 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
11536 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
11537 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
11538 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
11539 			pring->ringno, icmd->un.asyncstat.evt_code,
11540 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
11541 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
11542 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
11543 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
11544 
11545 		break;
11546 	}
11547 }
11548 
11549 
11550 /**
11551  * lpfc_sli4_setup - SLI ring setup function
11552  * @phba: Pointer to HBA context object.
11553  *
11554  * lpfc_sli_setup sets up rings of the SLI interface with
11555  * number of iocbs per ring and iotags. This function is
11556  * called while driver attach to the HBA and before the
11557  * interrupts are enabled. So there is no need for locking.
11558  *
11559  * This function always returns 0.
11560  **/
11561 int
11562 lpfc_sli4_setup(struct lpfc_hba *phba)
11563 {
11564 	struct lpfc_sli_ring *pring;
11565 
11566 	pring = phba->sli4_hba.els_wq->pring;
11567 	pring->num_mask = LPFC_MAX_RING_MASK;
11568 	pring->prt[0].profile = 0;	/* Mask 0 */
11569 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11570 	pring->prt[0].type = FC_TYPE_ELS;
11571 	pring->prt[0].lpfc_sli_rcv_unsol_event =
11572 	    lpfc_els_unsol_event;
11573 	pring->prt[1].profile = 0;	/* Mask 1 */
11574 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
11575 	pring->prt[1].type = FC_TYPE_ELS;
11576 	pring->prt[1].lpfc_sli_rcv_unsol_event =
11577 	    lpfc_els_unsol_event;
11578 	pring->prt[2].profile = 0;	/* Mask 2 */
11579 	/* NameServer Inquiry */
11580 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11581 	/* NameServer */
11582 	pring->prt[2].type = FC_TYPE_CT;
11583 	pring->prt[2].lpfc_sli_rcv_unsol_event =
11584 	    lpfc_ct_unsol_event;
11585 	pring->prt[3].profile = 0;	/* Mask 3 */
11586 	/* NameServer response */
11587 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11588 	/* NameServer */
11589 	pring->prt[3].type = FC_TYPE_CT;
11590 	pring->prt[3].lpfc_sli_rcv_unsol_event =
11591 	    lpfc_ct_unsol_event;
11592 	return 0;
11593 }
11594 
11595 /**
11596  * lpfc_sli_setup - SLI ring setup function
11597  * @phba: Pointer to HBA context object.
11598  *
11599  * lpfc_sli_setup sets up rings of the SLI interface with
11600  * number of iocbs per ring and iotags. This function is
11601  * called while driver attach to the HBA and before the
11602  * interrupts are enabled. So there is no need for locking.
11603  *
11604  * This function always returns 0. SLI3 only.
11605  **/
11606 int
11607 lpfc_sli_setup(struct lpfc_hba *phba)
11608 {
11609 	int i, totiocbsize = 0;
11610 	struct lpfc_sli *psli = &phba->sli;
11611 	struct lpfc_sli_ring *pring;
11612 
11613 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
11614 	psli->sli_flag = 0;
11615 
11616 	psli->iocbq_lookup = NULL;
11617 	psli->iocbq_lookup_len = 0;
11618 	psli->last_iotag = 0;
11619 
11620 	for (i = 0; i < psli->num_rings; i++) {
11621 		pring = &psli->sli3_ring[i];
11622 		switch (i) {
11623 		case LPFC_FCP_RING:	/* ring 0 - FCP */
11624 			/* numCiocb and numRiocb are used in config_port */
11625 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
11626 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
11627 			pring->sli.sli3.numCiocb +=
11628 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11629 			pring->sli.sli3.numRiocb +=
11630 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11631 			pring->sli.sli3.numCiocb +=
11632 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11633 			pring->sli.sli3.numRiocb +=
11634 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11635 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11636 							SLI3_IOCB_CMD_SIZE :
11637 							SLI2_IOCB_CMD_SIZE;
11638 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11639 							SLI3_IOCB_RSP_SIZE :
11640 							SLI2_IOCB_RSP_SIZE;
11641 			pring->iotag_ctr = 0;
11642 			pring->iotag_max =
11643 			    (phba->cfg_hba_queue_depth * 2);
11644 			pring->fast_iotag = pring->iotag_max;
11645 			pring->num_mask = 0;
11646 			break;
11647 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
11648 			/* numCiocb and numRiocb are used in config_port */
11649 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
11650 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
11651 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11652 							SLI3_IOCB_CMD_SIZE :
11653 							SLI2_IOCB_CMD_SIZE;
11654 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11655 							SLI3_IOCB_RSP_SIZE :
11656 							SLI2_IOCB_RSP_SIZE;
11657 			pring->iotag_max = phba->cfg_hba_queue_depth;
11658 			pring->num_mask = 0;
11659 			break;
11660 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
11661 			/* numCiocb and numRiocb are used in config_port */
11662 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
11663 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
11664 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11665 							SLI3_IOCB_CMD_SIZE :
11666 							SLI2_IOCB_CMD_SIZE;
11667 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11668 							SLI3_IOCB_RSP_SIZE :
11669 							SLI2_IOCB_RSP_SIZE;
11670 			pring->fast_iotag = 0;
11671 			pring->iotag_ctr = 0;
11672 			pring->iotag_max = 4096;
11673 			pring->lpfc_sli_rcv_async_status =
11674 				lpfc_sli_async_event_handler;
11675 			pring->num_mask = LPFC_MAX_RING_MASK;
11676 			pring->prt[0].profile = 0;	/* Mask 0 */
11677 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11678 			pring->prt[0].type = FC_TYPE_ELS;
11679 			pring->prt[0].lpfc_sli_rcv_unsol_event =
11680 			    lpfc_els_unsol_event;
11681 			pring->prt[1].profile = 0;	/* Mask 1 */
11682 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
11683 			pring->prt[1].type = FC_TYPE_ELS;
11684 			pring->prt[1].lpfc_sli_rcv_unsol_event =
11685 			    lpfc_els_unsol_event;
11686 			pring->prt[2].profile = 0;	/* Mask 2 */
11687 			/* NameServer Inquiry */
11688 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11689 			/* NameServer */
11690 			pring->prt[2].type = FC_TYPE_CT;
11691 			pring->prt[2].lpfc_sli_rcv_unsol_event =
11692 			    lpfc_ct_unsol_event;
11693 			pring->prt[3].profile = 0;	/* Mask 3 */
11694 			/* NameServer response */
11695 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11696 			/* NameServer */
11697 			pring->prt[3].type = FC_TYPE_CT;
11698 			pring->prt[3].lpfc_sli_rcv_unsol_event =
11699 			    lpfc_ct_unsol_event;
11700 			break;
11701 		}
11702 		totiocbsize += (pring->sli.sli3.numCiocb *
11703 			pring->sli.sli3.sizeCiocb) +
11704 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
11705 	}
11706 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
11707 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
11708 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
11709 		       "SLI2 SLIM Data: x%x x%lx\n",
11710 		       phba->brd_no, totiocbsize,
11711 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
11712 	}
11713 	if (phba->cfg_multi_ring_support == 2)
11714 		lpfc_extra_ring_setup(phba);
11715 
11716 	return 0;
11717 }
11718 
11719 /**
11720  * lpfc_sli4_queue_init - Queue initialization function
11721  * @phba: Pointer to HBA context object.
11722  *
11723  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
11724  * ring. This function also initializes ring indices of each ring.
11725  * This function is called during the initialization of the SLI
11726  * interface of an HBA.
11727  * This function is called with no lock held and always returns
11728  * 1.
11729  **/
11730 void
11731 lpfc_sli4_queue_init(struct lpfc_hba *phba)
11732 {
11733 	struct lpfc_sli *psli;
11734 	struct lpfc_sli_ring *pring;
11735 	int i;
11736 
11737 	psli = &phba->sli;
11738 	spin_lock_irq(&phba->hbalock);
11739 	INIT_LIST_HEAD(&psli->mboxq);
11740 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11741 	/* Initialize list headers for txq and txcmplq as double linked lists */
11742 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
11743 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
11744 		pring->flag = 0;
11745 		pring->ringno = LPFC_FCP_RING;
11746 		pring->txcmplq_cnt = 0;
11747 		INIT_LIST_HEAD(&pring->txq);
11748 		INIT_LIST_HEAD(&pring->txcmplq);
11749 		INIT_LIST_HEAD(&pring->iocb_continueq);
11750 		spin_lock_init(&pring->ring_lock);
11751 	}
11752 	pring = phba->sli4_hba.els_wq->pring;
11753 	pring->flag = 0;
11754 	pring->ringno = LPFC_ELS_RING;
11755 	pring->txcmplq_cnt = 0;
11756 	INIT_LIST_HEAD(&pring->txq);
11757 	INIT_LIST_HEAD(&pring->txcmplq);
11758 	INIT_LIST_HEAD(&pring->iocb_continueq);
11759 	spin_lock_init(&pring->ring_lock);
11760 
11761 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11762 		pring = phba->sli4_hba.nvmels_wq->pring;
11763 		pring->flag = 0;
11764 		pring->ringno = LPFC_ELS_RING;
11765 		pring->txcmplq_cnt = 0;
11766 		INIT_LIST_HEAD(&pring->txq);
11767 		INIT_LIST_HEAD(&pring->txcmplq);
11768 		INIT_LIST_HEAD(&pring->iocb_continueq);
11769 		spin_lock_init(&pring->ring_lock);
11770 	}
11771 
11772 	spin_unlock_irq(&phba->hbalock);
11773 }
11774 
11775 /**
11776  * lpfc_sli_queue_init - Queue initialization function
11777  * @phba: Pointer to HBA context object.
11778  *
11779  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11780  * ring. This function also initializes ring indices of each ring.
11781  * This function is called during the initialization of the SLI
11782  * interface of an HBA.
11783  * This function is called with no lock held and always returns
11784  * 1.
11785  **/
11786 void
11787 lpfc_sli_queue_init(struct lpfc_hba *phba)
11788 {
11789 	struct lpfc_sli *psli;
11790 	struct lpfc_sli_ring *pring;
11791 	int i;
11792 
11793 	psli = &phba->sli;
11794 	spin_lock_irq(&phba->hbalock);
11795 	INIT_LIST_HEAD(&psli->mboxq);
11796 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11797 	/* Initialize list headers for txq and txcmplq as double linked lists */
11798 	for (i = 0; i < psli->num_rings; i++) {
11799 		pring = &psli->sli3_ring[i];
11800 		pring->ringno = i;
11801 		pring->sli.sli3.next_cmdidx  = 0;
11802 		pring->sli.sli3.local_getidx = 0;
11803 		pring->sli.sli3.cmdidx = 0;
11804 		INIT_LIST_HEAD(&pring->iocb_continueq);
11805 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11806 		INIT_LIST_HEAD(&pring->postbufq);
11807 		pring->flag = 0;
11808 		INIT_LIST_HEAD(&pring->txq);
11809 		INIT_LIST_HEAD(&pring->txcmplq);
11810 		spin_lock_init(&pring->ring_lock);
11811 	}
11812 	spin_unlock_irq(&phba->hbalock);
11813 }
11814 
11815 /**
11816  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11817  * @phba: Pointer to HBA context object.
11818  *
11819  * This routine flushes the mailbox command subsystem. It will unconditionally
11820  * flush all the mailbox commands in the three possible stages in the mailbox
11821  * command sub-system: pending mailbox command queue; the outstanding mailbox
11822  * command; and completed mailbox command queue. It is caller's responsibility
11823  * to make sure that the driver is in the proper state to flush the mailbox
11824  * command sub-system. Namely, the posting of mailbox commands into the
11825  * pending mailbox command queue from the various clients must be stopped;
11826  * either the HBA is in a state that it will never works on the outstanding
11827  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11828  * mailbox command has been completed.
11829  **/
11830 static void
11831 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11832 {
11833 	LIST_HEAD(completions);
11834 	struct lpfc_sli *psli = &phba->sli;
11835 	LPFC_MBOXQ_t *pmb;
11836 	unsigned long iflag;
11837 
11838 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11839 	local_bh_disable();
11840 
11841 	/* Flush all the mailbox commands in the mbox system */
11842 	spin_lock_irqsave(&phba->hbalock, iflag);
11843 
11844 	/* The pending mailbox command queue */
11845 	list_splice_init(&phba->sli.mboxq, &completions);
11846 	/* The outstanding active mailbox command */
11847 	if (psli->mbox_active) {
11848 		list_add_tail(&psli->mbox_active->list, &completions);
11849 		psli->mbox_active = NULL;
11850 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11851 	}
11852 	/* The completed mailbox command queue */
11853 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11854 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11855 
11856 	/* Enable softirqs again, done with phba->hbalock */
11857 	local_bh_enable();
11858 
11859 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11860 	while (!list_empty(&completions)) {
11861 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11862 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11863 		if (pmb->mbox_cmpl)
11864 			pmb->mbox_cmpl(phba, pmb);
11865 	}
11866 }
11867 
11868 /**
11869  * lpfc_sli_host_down - Vport cleanup function
11870  * @vport: Pointer to virtual port object.
11871  *
11872  * lpfc_sli_host_down is called to clean up the resources
11873  * associated with a vport before destroying virtual
11874  * port data structures.
11875  * This function does following operations:
11876  * - Free discovery resources associated with this virtual
11877  *   port.
11878  * - Free iocbs associated with this virtual port in
11879  *   the txq.
11880  * - Send abort for all iocb commands associated with this
11881  *   vport in txcmplq.
11882  *
11883  * This function is called with no lock held and always returns 1.
11884  **/
11885 int
11886 lpfc_sli_host_down(struct lpfc_vport *vport)
11887 {
11888 	LIST_HEAD(completions);
11889 	struct lpfc_hba *phba = vport->phba;
11890 	struct lpfc_sli *psli = &phba->sli;
11891 	struct lpfc_queue *qp = NULL;
11892 	struct lpfc_sli_ring *pring;
11893 	struct lpfc_iocbq *iocb, *next_iocb;
11894 	int i;
11895 	unsigned long flags = 0;
11896 	uint16_t prev_pring_flag;
11897 
11898 	lpfc_cleanup_discovery_resources(vport);
11899 
11900 	spin_lock_irqsave(&phba->hbalock, flags);
11901 
11902 	/*
11903 	 * Error everything on the txq since these iocbs
11904 	 * have not been given to the FW yet.
11905 	 * Also issue ABTS for everything on the txcmplq
11906 	 */
11907 	if (phba->sli_rev != LPFC_SLI_REV4) {
11908 		for (i = 0; i < psli->num_rings; i++) {
11909 			pring = &psli->sli3_ring[i];
11910 			prev_pring_flag = pring->flag;
11911 			/* Only slow rings */
11912 			if (pring->ringno == LPFC_ELS_RING) {
11913 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11914 				/* Set the lpfc data pending flag */
11915 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11916 			}
11917 			list_for_each_entry_safe(iocb, next_iocb,
11918 						 &pring->txq, list) {
11919 				if (iocb->vport != vport)
11920 					continue;
11921 				list_move_tail(&iocb->list, &completions);
11922 			}
11923 			list_for_each_entry_safe(iocb, next_iocb,
11924 						 &pring->txcmplq, list) {
11925 				if (iocb->vport != vport)
11926 					continue;
11927 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11928 							   NULL);
11929 			}
11930 			pring->flag = prev_pring_flag;
11931 		}
11932 	} else {
11933 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11934 			pring = qp->pring;
11935 			if (!pring)
11936 				continue;
11937 			if (pring == phba->sli4_hba.els_wq->pring) {
11938 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11939 				/* Set the lpfc data pending flag */
11940 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11941 			}
11942 			prev_pring_flag = pring->flag;
11943 			spin_lock(&pring->ring_lock);
11944 			list_for_each_entry_safe(iocb, next_iocb,
11945 						 &pring->txq, list) {
11946 				if (iocb->vport != vport)
11947 					continue;
11948 				list_move_tail(&iocb->list, &completions);
11949 			}
11950 			spin_unlock(&pring->ring_lock);
11951 			list_for_each_entry_safe(iocb, next_iocb,
11952 						 &pring->txcmplq, list) {
11953 				if (iocb->vport != vport)
11954 					continue;
11955 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11956 							   NULL);
11957 			}
11958 			pring->flag = prev_pring_flag;
11959 		}
11960 	}
11961 	spin_unlock_irqrestore(&phba->hbalock, flags);
11962 
11963 	/* Make sure HBA is alive */
11964 	lpfc_issue_hb_tmo(phba);
11965 
11966 	/* Cancel all the IOCBs from the completions list */
11967 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11968 			      IOERR_SLI_DOWN);
11969 	return 1;
11970 }
11971 
11972 /**
11973  * lpfc_sli_hba_down - Resource cleanup function for the HBA
11974  * @phba: Pointer to HBA context object.
11975  *
11976  * This function cleans up all iocb, buffers, mailbox commands
11977  * while shutting down the HBA. This function is called with no
11978  * lock held and always returns 1.
11979  * This function does the following to cleanup driver resources:
11980  * - Free discovery resources for each virtual port
11981  * - Cleanup any pending fabric iocbs
11982  * - Iterate through the iocb txq and free each entry
11983  *   in the list.
11984  * - Free up any buffer posted to the HBA
11985  * - Free mailbox commands in the mailbox queue.
11986  **/
11987 int
11988 lpfc_sli_hba_down(struct lpfc_hba *phba)
11989 {
11990 	LIST_HEAD(completions);
11991 	struct lpfc_sli *psli = &phba->sli;
11992 	struct lpfc_queue *qp = NULL;
11993 	struct lpfc_sli_ring *pring;
11994 	struct lpfc_dmabuf *buf_ptr;
11995 	unsigned long flags = 0;
11996 	int i;
11997 
11998 	/* Shutdown the mailbox command sub-system */
11999 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
12000 
12001 	lpfc_hba_down_prep(phba);
12002 
12003 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12004 	local_bh_disable();
12005 
12006 	lpfc_fabric_abort_hba(phba);
12007 
12008 	spin_lock_irqsave(&phba->hbalock, flags);
12009 
12010 	/*
12011 	 * Error everything on the txq since these iocbs
12012 	 * have not been given to the FW yet.
12013 	 */
12014 	if (phba->sli_rev != LPFC_SLI_REV4) {
12015 		for (i = 0; i < psli->num_rings; i++) {
12016 			pring = &psli->sli3_ring[i];
12017 			/* Only slow rings */
12018 			if (pring->ringno == LPFC_ELS_RING) {
12019 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12020 				/* Set the lpfc data pending flag */
12021 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12022 			}
12023 			list_splice_init(&pring->txq, &completions);
12024 		}
12025 	} else {
12026 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12027 			pring = qp->pring;
12028 			if (!pring)
12029 				continue;
12030 			spin_lock(&pring->ring_lock);
12031 			list_splice_init(&pring->txq, &completions);
12032 			spin_unlock(&pring->ring_lock);
12033 			if (pring == phba->sli4_hba.els_wq->pring) {
12034 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12035 				/* Set the lpfc data pending flag */
12036 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12037 			}
12038 		}
12039 	}
12040 	spin_unlock_irqrestore(&phba->hbalock, flags);
12041 
12042 	/* Cancel all the IOCBs from the completions list */
12043 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
12044 			      IOERR_SLI_DOWN);
12045 
12046 	spin_lock_irqsave(&phba->hbalock, flags);
12047 	list_splice_init(&phba->elsbuf, &completions);
12048 	phba->elsbuf_cnt = 0;
12049 	phba->elsbuf_prev_cnt = 0;
12050 	spin_unlock_irqrestore(&phba->hbalock, flags);
12051 
12052 	while (!list_empty(&completions)) {
12053 		list_remove_head(&completions, buf_ptr,
12054 			struct lpfc_dmabuf, list);
12055 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
12056 		kfree(buf_ptr);
12057 	}
12058 
12059 	/* Enable softirqs again, done with phba->hbalock */
12060 	local_bh_enable();
12061 
12062 	/* Return any active mbox cmds */
12063 	del_timer_sync(&psli->mbox_tmo);
12064 
12065 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
12066 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
12067 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
12068 
12069 	return 1;
12070 }
12071 
12072 /**
12073  * lpfc_sli_pcimem_bcopy - SLI memory copy function
12074  * @srcp: Source memory pointer.
12075  * @destp: Destination memory pointer.
12076  * @cnt: Number of words required to be copied.
12077  *
12078  * This function is used for copying data between driver memory
12079  * and the SLI memory. This function also changes the endianness
12080  * of each word if native endianness is different from SLI
12081  * endianness. This function can be called with or without
12082  * lock.
12083  **/
12084 void
12085 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
12086 {
12087 	uint32_t *src = srcp;
12088 	uint32_t *dest = destp;
12089 	uint32_t ldata;
12090 	int i;
12091 
12092 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
12093 		ldata = *src;
12094 		ldata = le32_to_cpu(ldata);
12095 		*dest = ldata;
12096 		src++;
12097 		dest++;
12098 	}
12099 }
12100 
12101 
12102 /**
12103  * lpfc_sli_bemem_bcopy - SLI memory copy function
12104  * @srcp: Source memory pointer.
12105  * @destp: Destination memory pointer.
12106  * @cnt: Number of words required to be copied.
12107  *
12108  * This function is used for copying data between a data structure
12109  * with big endian representation to local endianness.
12110  * This function can be called with or without lock.
12111  **/
12112 void
12113 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
12114 {
12115 	uint32_t *src = srcp;
12116 	uint32_t *dest = destp;
12117 	uint32_t ldata;
12118 	int i;
12119 
12120 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
12121 		ldata = *src;
12122 		ldata = be32_to_cpu(ldata);
12123 		*dest = ldata;
12124 		src++;
12125 		dest++;
12126 	}
12127 }
12128 
12129 /**
12130  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
12131  * @phba: Pointer to HBA context object.
12132  * @pring: Pointer to driver SLI ring object.
12133  * @mp: Pointer to driver buffer object.
12134  *
12135  * This function is called with no lock held.
12136  * It always return zero after adding the buffer to the postbufq
12137  * buffer list.
12138  **/
12139 int
12140 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12141 			 struct lpfc_dmabuf *mp)
12142 {
12143 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
12144 	   later */
12145 	spin_lock_irq(&phba->hbalock);
12146 	list_add_tail(&mp->list, &pring->postbufq);
12147 	pring->postbufq_cnt++;
12148 	spin_unlock_irq(&phba->hbalock);
12149 	return 0;
12150 }
12151 
12152 /**
12153  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
12154  * @phba: Pointer to HBA context object.
12155  *
12156  * When HBQ is enabled, buffers are searched based on tags. This function
12157  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
12158  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
12159  * does not conflict with tags of buffer posted for unsolicited events.
12160  * The function returns the allocated tag. The function is called with
12161  * no locks held.
12162  **/
12163 uint32_t
12164 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
12165 {
12166 	spin_lock_irq(&phba->hbalock);
12167 	phba->buffer_tag_count++;
12168 	/*
12169 	 * Always set the QUE_BUFTAG_BIT to distiguish between
12170 	 * a tag assigned by HBQ.
12171 	 */
12172 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
12173 	spin_unlock_irq(&phba->hbalock);
12174 	return phba->buffer_tag_count;
12175 }
12176 
12177 /**
12178  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
12179  * @phba: Pointer to HBA context object.
12180  * @pring: Pointer to driver SLI ring object.
12181  * @tag: Buffer tag.
12182  *
12183  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
12184  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
12185  * iocb is posted to the response ring with the tag of the buffer.
12186  * This function searches the pring->postbufq list using the tag
12187  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
12188  * iocb. If the buffer is found then lpfc_dmabuf object of the
12189  * buffer is returned to the caller else NULL is returned.
12190  * This function is called with no lock held.
12191  **/
12192 struct lpfc_dmabuf *
12193 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12194 			uint32_t tag)
12195 {
12196 	struct lpfc_dmabuf *mp, *next_mp;
12197 	struct list_head *slp = &pring->postbufq;
12198 
12199 	/* Search postbufq, from the beginning, looking for a match on tag */
12200 	spin_lock_irq(&phba->hbalock);
12201 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12202 		if (mp->buffer_tag == tag) {
12203 			list_del_init(&mp->list);
12204 			pring->postbufq_cnt--;
12205 			spin_unlock_irq(&phba->hbalock);
12206 			return mp;
12207 		}
12208 	}
12209 
12210 	spin_unlock_irq(&phba->hbalock);
12211 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12212 			"0402 Cannot find virtual addr for buffer tag on "
12213 			"ring %d Data x%lx x%px x%px x%x\n",
12214 			pring->ringno, (unsigned long) tag,
12215 			slp->next, slp->prev, pring->postbufq_cnt);
12216 
12217 	return NULL;
12218 }
12219 
12220 /**
12221  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
12222  * @phba: Pointer to HBA context object.
12223  * @pring: Pointer to driver SLI ring object.
12224  * @phys: DMA address of the buffer.
12225  *
12226  * This function searches the buffer list using the dma_address
12227  * of unsolicited event to find the driver's lpfc_dmabuf object
12228  * corresponding to the dma_address. The function returns the
12229  * lpfc_dmabuf object if a buffer is found else it returns NULL.
12230  * This function is called by the ct and els unsolicited event
12231  * handlers to get the buffer associated with the unsolicited
12232  * event.
12233  *
12234  * This function is called with no lock held.
12235  **/
12236 struct lpfc_dmabuf *
12237 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12238 			 dma_addr_t phys)
12239 {
12240 	struct lpfc_dmabuf *mp, *next_mp;
12241 	struct list_head *slp = &pring->postbufq;
12242 
12243 	/* Search postbufq, from the beginning, looking for a match on phys */
12244 	spin_lock_irq(&phba->hbalock);
12245 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12246 		if (mp->phys == phys) {
12247 			list_del_init(&mp->list);
12248 			pring->postbufq_cnt--;
12249 			spin_unlock_irq(&phba->hbalock);
12250 			return mp;
12251 		}
12252 	}
12253 
12254 	spin_unlock_irq(&phba->hbalock);
12255 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12256 			"0410 Cannot find virtual addr for mapped buf on "
12257 			"ring %d Data x%llx x%px x%px x%x\n",
12258 			pring->ringno, (unsigned long long)phys,
12259 			slp->next, slp->prev, pring->postbufq_cnt);
12260 	return NULL;
12261 }
12262 
12263 /**
12264  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
12265  * @phba: Pointer to HBA context object.
12266  * @cmdiocb: Pointer to driver command iocb object.
12267  * @rspiocb: Pointer to driver response iocb object.
12268  *
12269  * This function is the completion handler for the abort iocbs for
12270  * ELS commands. This function is called from the ELS ring event
12271  * handler with no lock held. This function frees memory resources
12272  * associated with the abort iocb.
12273  **/
12274 static void
12275 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12276 			struct lpfc_iocbq *rspiocb)
12277 {
12278 	u32 ulp_status = get_job_ulpstatus(phba, rspiocb);
12279 	u32 ulp_word4 = get_job_word4(phba, rspiocb);
12280 	u8 cmnd = get_job_cmnd(phba, cmdiocb);
12281 
12282 	if (ulp_status) {
12283 		/*
12284 		 * Assume that the port already completed and returned, or
12285 		 * will return the iocb. Just Log the message.
12286 		 */
12287 		if (phba->sli_rev < LPFC_SLI_REV4) {
12288 			if (cmnd == CMD_ABORT_XRI_CX &&
12289 			    ulp_status == IOSTAT_LOCAL_REJECT &&
12290 			    ulp_word4 == IOERR_ABORT_REQUESTED) {
12291 				goto release_iocb;
12292 			}
12293 		}
12294 
12295 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
12296 				"0327 Cannot abort els iocb x%px "
12297 				"with io cmd xri %x abort tag : x%x, "
12298 				"abort status %x abort code %x\n",
12299 				cmdiocb, get_job_abtsiotag(phba, cmdiocb),
12300 				(phba->sli_rev == LPFC_SLI_REV4) ?
12301 				get_wqe_reqtag(cmdiocb) :
12302 				cmdiocb->iocb.un.acxri.abortContextTag,
12303 				ulp_status, ulp_word4);
12304 
12305 	}
12306 release_iocb:
12307 	lpfc_sli_release_iocbq(phba, cmdiocb);
12308 	return;
12309 }
12310 
12311 /**
12312  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
12313  * @phba: Pointer to HBA context object.
12314  * @cmdiocb: Pointer to driver command iocb object.
12315  * @rspiocb: Pointer to driver response iocb object.
12316  *
12317  * The function is called from SLI ring event handler with no
12318  * lock held. This function is the completion handler for ELS commands
12319  * which are aborted. The function frees memory resources used for
12320  * the aborted ELS commands.
12321  **/
12322 void
12323 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12324 		     struct lpfc_iocbq *rspiocb)
12325 {
12326 	struct lpfc_nodelist *ndlp = cmdiocb->ndlp;
12327 	IOCB_t *irsp;
12328 	LPFC_MBOXQ_t *mbox;
12329 	u32 ulp_command, ulp_status, ulp_word4, iotag;
12330 
12331 	ulp_command = get_job_cmnd(phba, cmdiocb);
12332 	ulp_status = get_job_ulpstatus(phba, rspiocb);
12333 	ulp_word4 = get_job_word4(phba, rspiocb);
12334 
12335 	if (phba->sli_rev == LPFC_SLI_REV4) {
12336 		iotag = get_wqe_reqtag(cmdiocb);
12337 	} else {
12338 		irsp = &rspiocb->iocb;
12339 		iotag = irsp->ulpIoTag;
12340 
12341 		/* It is possible a PLOGI_RJT for NPIV ports to get aborted.
12342 		 * The MBX_REG_LOGIN64 mbox command is freed back to the
12343 		 * mbox_mem_pool here.
12344 		 */
12345 		if (cmdiocb->context_un.mbox) {
12346 			mbox = cmdiocb->context_un.mbox;
12347 			lpfc_mbox_rsrc_cleanup(phba, mbox, MBOX_THD_UNLOCKED);
12348 			cmdiocb->context_un.mbox = NULL;
12349 		}
12350 	}
12351 
12352 	/* ELS cmd tag <ulpIoTag> completes */
12353 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
12354 			"0139 Ignoring ELS cmd code x%x completion Data: "
12355 			"x%x x%x x%x x%px\n",
12356 			ulp_command, ulp_status, ulp_word4, iotag,
12357 			cmdiocb->ndlp);
12358 	/*
12359 	 * Deref the ndlp after free_iocb. sli_release_iocb will access the ndlp
12360 	 * if exchange is busy.
12361 	 */
12362 	if (ulp_command == CMD_GEN_REQUEST64_CR)
12363 		lpfc_ct_free_iocb(phba, cmdiocb);
12364 	else
12365 		lpfc_els_free_iocb(phba, cmdiocb);
12366 
12367 	lpfc_nlp_put(ndlp);
12368 }
12369 
12370 /**
12371  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
12372  * @phba: Pointer to HBA context object.
12373  * @pring: Pointer to driver SLI ring object.
12374  * @cmdiocb: Pointer to driver command iocb object.
12375  * @cmpl: completion function.
12376  *
12377  * This function issues an abort iocb for the provided command iocb. In case
12378  * of unloading, the abort iocb will not be issued to commands on the ELS
12379  * ring. Instead, the callback function shall be changed to those commands
12380  * so that nothing happens when them finishes. This function is called with
12381  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
12382  * when the command iocb is an abort request.
12383  *
12384  **/
12385 int
12386 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12387 			   struct lpfc_iocbq *cmdiocb, void *cmpl)
12388 {
12389 	struct lpfc_vport *vport = cmdiocb->vport;
12390 	struct lpfc_iocbq *abtsiocbp;
12391 	int retval = IOCB_ERROR;
12392 	unsigned long iflags;
12393 	struct lpfc_nodelist *ndlp = NULL;
12394 	u32 ulp_command = get_job_cmnd(phba, cmdiocb);
12395 	u16 ulp_context, iotag;
12396 	bool ia;
12397 
12398 	/*
12399 	 * There are certain command types we don't want to abort.  And we
12400 	 * don't want to abort commands that are already in the process of
12401 	 * being aborted.
12402 	 */
12403 	if (ulp_command == CMD_ABORT_XRI_WQE ||
12404 	    ulp_command == CMD_ABORT_XRI_CN ||
12405 	    ulp_command == CMD_CLOSE_XRI_CN ||
12406 	    cmdiocb->cmd_flag & LPFC_DRIVER_ABORTED)
12407 		return IOCB_ABORTING;
12408 
12409 	if (!pring) {
12410 		if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12411 			cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12412 		else
12413 			cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12414 		return retval;
12415 	}
12416 
12417 	/*
12418 	 * If we're unloading, don't abort iocb on the ELS ring, but change
12419 	 * the callback so that nothing happens when it finishes.
12420 	 */
12421 	if ((vport->load_flag & FC_UNLOADING) &&
12422 	    pring->ringno == LPFC_ELS_RING) {
12423 		if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12424 			cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12425 		else
12426 			cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12427 		return retval;
12428 	}
12429 
12430 	/* issue ABTS for this IOCB based on iotag */
12431 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
12432 	if (abtsiocbp == NULL)
12433 		return IOCB_NORESOURCE;
12434 
12435 	/* This signals the response to set the correct status
12436 	 * before calling the completion handler
12437 	 */
12438 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
12439 
12440 	if (phba->sli_rev == LPFC_SLI_REV4) {
12441 		ulp_context = cmdiocb->sli4_xritag;
12442 		iotag = abtsiocbp->iotag;
12443 	} else {
12444 		iotag = cmdiocb->iocb.ulpIoTag;
12445 		if (pring->ringno == LPFC_ELS_RING) {
12446 			ndlp = cmdiocb->ndlp;
12447 			ulp_context = ndlp->nlp_rpi;
12448 		} else {
12449 			ulp_context = cmdiocb->iocb.ulpContext;
12450 		}
12451 	}
12452 
12453 	if (phba->link_state < LPFC_LINK_UP ||
12454 	    (phba->sli_rev == LPFC_SLI_REV4 &&
12455 	     phba->sli4_hba.link_state.status == LPFC_FC_LA_TYPE_LINK_DOWN) ||
12456 	    (phba->link_flag & LS_EXTERNAL_LOOPBACK))
12457 		ia = true;
12458 	else
12459 		ia = false;
12460 
12461 	lpfc_sli_prep_abort_xri(phba, abtsiocbp, ulp_context, iotag,
12462 				cmdiocb->iocb.ulpClass,
12463 				LPFC_WQE_CQ_ID_DEFAULT, ia, false);
12464 
12465 	abtsiocbp->vport = vport;
12466 
12467 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12468 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
12469 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
12470 		abtsiocbp->cmd_flag |= (LPFC_IO_FCP | LPFC_USE_FCPWQIDX);
12471 
12472 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
12473 		abtsiocbp->cmd_flag |= LPFC_IO_FOF;
12474 
12475 	if (cmpl)
12476 		abtsiocbp->cmd_cmpl = cmpl;
12477 	else
12478 		abtsiocbp->cmd_cmpl = lpfc_sli_abort_els_cmpl;
12479 	abtsiocbp->vport = vport;
12480 
12481 	if (phba->sli_rev == LPFC_SLI_REV4) {
12482 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
12483 		if (unlikely(pring == NULL))
12484 			goto abort_iotag_exit;
12485 		/* Note: both hbalock and ring_lock need to be set here */
12486 		spin_lock_irqsave(&pring->ring_lock, iflags);
12487 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12488 			abtsiocbp, 0);
12489 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
12490 	} else {
12491 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12492 			abtsiocbp, 0);
12493 	}
12494 
12495 abort_iotag_exit:
12496 
12497 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
12498 			 "0339 Abort IO XRI x%x, Original iotag x%x, "
12499 			 "abort tag x%x Cmdjob : x%px Abortjob : x%px "
12500 			 "retval x%x\n",
12501 			 ulp_context, (phba->sli_rev == LPFC_SLI_REV4) ?
12502 			 cmdiocb->iotag : iotag, iotag, cmdiocb, abtsiocbp,
12503 			 retval);
12504 	if (retval) {
12505 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
12506 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
12507 	}
12508 
12509 	/*
12510 	 * Caller to this routine should check for IOCB_ERROR
12511 	 * and handle it properly.  This routine no longer removes
12512 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
12513 	 */
12514 	return retval;
12515 }
12516 
12517 /**
12518  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
12519  * @phba: pointer to lpfc HBA data structure.
12520  *
12521  * This routine will abort all pending and outstanding iocbs to an HBA.
12522  **/
12523 void
12524 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
12525 {
12526 	struct lpfc_sli *psli = &phba->sli;
12527 	struct lpfc_sli_ring *pring;
12528 	struct lpfc_queue *qp = NULL;
12529 	int i;
12530 
12531 	if (phba->sli_rev != LPFC_SLI_REV4) {
12532 		for (i = 0; i < psli->num_rings; i++) {
12533 			pring = &psli->sli3_ring[i];
12534 			lpfc_sli_abort_iocb_ring(phba, pring);
12535 		}
12536 		return;
12537 	}
12538 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12539 		pring = qp->pring;
12540 		if (!pring)
12541 			continue;
12542 		lpfc_sli_abort_iocb_ring(phba, pring);
12543 	}
12544 }
12545 
12546 /**
12547  * lpfc_sli_validate_fcp_iocb_for_abort - filter iocbs appropriate for FCP aborts
12548  * @iocbq: Pointer to iocb object.
12549  * @vport: Pointer to driver virtual port object.
12550  *
12551  * This function acts as an iocb filter for functions which abort FCP iocbs.
12552  *
12553  * Return values
12554  * -ENODEV, if a null iocb or vport ptr is encountered
12555  * -EINVAL, if the iocb is not an FCP I/O, not on the TX cmpl queue, premarked as
12556  *          driver already started the abort process, or is an abort iocb itself
12557  * 0, passes criteria for aborting the FCP I/O iocb
12558  **/
12559 static int
12560 lpfc_sli_validate_fcp_iocb_for_abort(struct lpfc_iocbq *iocbq,
12561 				     struct lpfc_vport *vport)
12562 {
12563 	u8 ulp_command;
12564 
12565 	/* No null ptr vports */
12566 	if (!iocbq || iocbq->vport != vport)
12567 		return -ENODEV;
12568 
12569 	/* iocb must be for FCP IO, already exists on the TX cmpl queue,
12570 	 * can't be premarked as driver aborted, nor be an ABORT iocb itself
12571 	 */
12572 	ulp_command = get_job_cmnd(vport->phba, iocbq);
12573 	if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12574 	    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ) ||
12575 	    (iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12576 	    (ulp_command == CMD_ABORT_XRI_CN ||
12577 	     ulp_command == CMD_CLOSE_XRI_CN ||
12578 	     ulp_command == CMD_ABORT_XRI_WQE))
12579 		return -EINVAL;
12580 
12581 	return 0;
12582 }
12583 
12584 /**
12585  * lpfc_sli_validate_fcp_iocb - validate commands associated with a SCSI target
12586  * @iocbq: Pointer to driver iocb object.
12587  * @vport: Pointer to driver virtual port object.
12588  * @tgt_id: SCSI ID of the target.
12589  * @lun_id: LUN ID of the scsi device.
12590  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
12591  *
12592  * This function acts as an iocb filter for validating a lun/SCSI target/SCSI
12593  * host.
12594  *
12595  * It will return
12596  * 0 if the filtering criteria is met for the given iocb and will return
12597  * 1 if the filtering criteria is not met.
12598  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
12599  * given iocb is for the SCSI device specified by vport, tgt_id and
12600  * lun_id parameter.
12601  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
12602  * given iocb is for the SCSI target specified by vport and tgt_id
12603  * parameters.
12604  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
12605  * given iocb is for the SCSI host associated with the given vport.
12606  * This function is called with no locks held.
12607  **/
12608 static int
12609 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
12610 			   uint16_t tgt_id, uint64_t lun_id,
12611 			   lpfc_ctx_cmd ctx_cmd)
12612 {
12613 	struct lpfc_io_buf *lpfc_cmd;
12614 	int rc = 1;
12615 
12616 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12617 
12618 	if (lpfc_cmd->pCmd == NULL)
12619 		return rc;
12620 
12621 	switch (ctx_cmd) {
12622 	case LPFC_CTX_LUN:
12623 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12624 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
12625 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
12626 			rc = 0;
12627 		break;
12628 	case LPFC_CTX_TGT:
12629 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12630 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
12631 			rc = 0;
12632 		break;
12633 	case LPFC_CTX_HOST:
12634 		rc = 0;
12635 		break;
12636 	default:
12637 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
12638 			__func__, ctx_cmd);
12639 		break;
12640 	}
12641 
12642 	return rc;
12643 }
12644 
12645 /**
12646  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
12647  * @vport: Pointer to virtual port.
12648  * @tgt_id: SCSI ID of the target.
12649  * @lun_id: LUN ID of the scsi device.
12650  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12651  *
12652  * This function returns number of FCP commands pending for the vport.
12653  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
12654  * commands pending on the vport associated with SCSI device specified
12655  * by tgt_id and lun_id parameters.
12656  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
12657  * commands pending on the vport associated with SCSI target specified
12658  * by tgt_id parameter.
12659  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
12660  * commands pending on the vport.
12661  * This function returns the number of iocbs which satisfy the filter.
12662  * This function is called without any lock held.
12663  **/
12664 int
12665 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
12666 		  lpfc_ctx_cmd ctx_cmd)
12667 {
12668 	struct lpfc_hba *phba = vport->phba;
12669 	struct lpfc_iocbq *iocbq;
12670 	int sum, i;
12671 	unsigned long iflags;
12672 	u8 ulp_command;
12673 
12674 	spin_lock_irqsave(&phba->hbalock, iflags);
12675 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
12676 		iocbq = phba->sli.iocbq_lookup[i];
12677 
12678 		if (!iocbq || iocbq->vport != vport)
12679 			continue;
12680 		if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12681 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ))
12682 			continue;
12683 
12684 		/* Include counting outstanding aborts */
12685 		ulp_command = get_job_cmnd(phba, iocbq);
12686 		if (ulp_command == CMD_ABORT_XRI_CN ||
12687 		    ulp_command == CMD_CLOSE_XRI_CN ||
12688 		    ulp_command == CMD_ABORT_XRI_WQE) {
12689 			sum++;
12690 			continue;
12691 		}
12692 
12693 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12694 					       ctx_cmd) == 0)
12695 			sum++;
12696 	}
12697 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12698 
12699 	return sum;
12700 }
12701 
12702 /**
12703  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
12704  * @phba: Pointer to HBA context object
12705  * @cmdiocb: Pointer to command iocb object.
12706  * @rspiocb: Pointer to response iocb object.
12707  *
12708  * This function is called when an aborted FCP iocb completes. This
12709  * function is called by the ring event handler with no lock held.
12710  * This function frees the iocb.
12711  **/
12712 void
12713 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12714 			struct lpfc_iocbq *rspiocb)
12715 {
12716 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12717 			"3096 ABORT_XRI_CX completing on rpi x%x "
12718 			"original iotag x%x, abort cmd iotag x%x "
12719 			"status 0x%x, reason 0x%x\n",
12720 			(phba->sli_rev == LPFC_SLI_REV4) ?
12721 			cmdiocb->sli4_xritag :
12722 			cmdiocb->iocb.un.acxri.abortContextTag,
12723 			get_job_abtsiotag(phba, cmdiocb),
12724 			cmdiocb->iotag, get_job_ulpstatus(phba, rspiocb),
12725 			get_job_word4(phba, rspiocb));
12726 	lpfc_sli_release_iocbq(phba, cmdiocb);
12727 	return;
12728 }
12729 
12730 /**
12731  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
12732  * @vport: Pointer to virtual port.
12733  * @tgt_id: SCSI ID of the target.
12734  * @lun_id: LUN ID of the scsi device.
12735  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12736  *
12737  * This function sends an abort command for every SCSI command
12738  * associated with the given virtual port pending on the ring
12739  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12740  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12741  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12742  * followed by lpfc_sli_validate_fcp_iocb.
12743  *
12744  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
12745  * FCP iocbs associated with lun specified by tgt_id and lun_id
12746  * parameters
12747  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
12748  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12749  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
12750  * FCP iocbs associated with virtual port.
12751  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
12752  * lpfc_sli4_calc_ring is used.
12753  * This function returns number of iocbs it failed to abort.
12754  * This function is called with no locks held.
12755  **/
12756 int
12757 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
12758 		    lpfc_ctx_cmd abort_cmd)
12759 {
12760 	struct lpfc_hba *phba = vport->phba;
12761 	struct lpfc_sli_ring *pring = NULL;
12762 	struct lpfc_iocbq *iocbq;
12763 	int errcnt = 0, ret_val = 0;
12764 	unsigned long iflags;
12765 	int i;
12766 
12767 	/* all I/Os are in process of being flushed */
12768 	if (phba->hba_flag & HBA_IOQ_FLUSH)
12769 		return errcnt;
12770 
12771 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12772 		iocbq = phba->sli.iocbq_lookup[i];
12773 
12774 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12775 			continue;
12776 
12777 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12778 					       abort_cmd) != 0)
12779 			continue;
12780 
12781 		spin_lock_irqsave(&phba->hbalock, iflags);
12782 		if (phba->sli_rev == LPFC_SLI_REV3) {
12783 			pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12784 		} else if (phba->sli_rev == LPFC_SLI_REV4) {
12785 			pring = lpfc_sli4_calc_ring(phba, iocbq);
12786 		}
12787 		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
12788 						     lpfc_sli_abort_fcp_cmpl);
12789 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12790 		if (ret_val != IOCB_SUCCESS)
12791 			errcnt++;
12792 	}
12793 
12794 	return errcnt;
12795 }
12796 
12797 /**
12798  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12799  * @vport: Pointer to virtual port.
12800  * @pring: Pointer to driver SLI ring object.
12801  * @tgt_id: SCSI ID of the target.
12802  * @lun_id: LUN ID of the scsi device.
12803  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12804  *
12805  * This function sends an abort command for every SCSI command
12806  * associated with the given virtual port pending on the ring
12807  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12808  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12809  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12810  * followed by lpfc_sli_validate_fcp_iocb.
12811  *
12812  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12813  * FCP iocbs associated with lun specified by tgt_id and lun_id
12814  * parameters
12815  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12816  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12817  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12818  * FCP iocbs associated with virtual port.
12819  * This function returns number of iocbs it aborted .
12820  * This function is called with no locks held right after a taskmgmt
12821  * command is sent.
12822  **/
12823 int
12824 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12825 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12826 {
12827 	struct lpfc_hba *phba = vport->phba;
12828 	struct lpfc_io_buf *lpfc_cmd;
12829 	struct lpfc_iocbq *abtsiocbq;
12830 	struct lpfc_nodelist *ndlp = NULL;
12831 	struct lpfc_iocbq *iocbq;
12832 	int sum, i, ret_val;
12833 	unsigned long iflags;
12834 	struct lpfc_sli_ring *pring_s4 = NULL;
12835 	u16 ulp_context, iotag, cqid = LPFC_WQE_CQ_ID_DEFAULT;
12836 	bool ia;
12837 
12838 	spin_lock_irqsave(&phba->hbalock, iflags);
12839 
12840 	/* all I/Os are in process of being flushed */
12841 	if (phba->hba_flag & HBA_IOQ_FLUSH) {
12842 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12843 		return 0;
12844 	}
12845 	sum = 0;
12846 
12847 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12848 		iocbq = phba->sli.iocbq_lookup[i];
12849 
12850 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12851 			continue;
12852 
12853 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12854 					       cmd) != 0)
12855 			continue;
12856 
12857 		/* Guard against IO completion being called at same time */
12858 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12859 		spin_lock(&lpfc_cmd->buf_lock);
12860 
12861 		if (!lpfc_cmd->pCmd) {
12862 			spin_unlock(&lpfc_cmd->buf_lock);
12863 			continue;
12864 		}
12865 
12866 		if (phba->sli_rev == LPFC_SLI_REV4) {
12867 			pring_s4 =
12868 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12869 			if (!pring_s4) {
12870 				spin_unlock(&lpfc_cmd->buf_lock);
12871 				continue;
12872 			}
12873 			/* Note: both hbalock and ring_lock must be set here */
12874 			spin_lock(&pring_s4->ring_lock);
12875 		}
12876 
12877 		/*
12878 		 * If the iocbq is already being aborted, don't take a second
12879 		 * action, but do count it.
12880 		 */
12881 		if ((iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12882 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ)) {
12883 			if (phba->sli_rev == LPFC_SLI_REV4)
12884 				spin_unlock(&pring_s4->ring_lock);
12885 			spin_unlock(&lpfc_cmd->buf_lock);
12886 			continue;
12887 		}
12888 
12889 		/* issue ABTS for this IOCB based on iotag */
12890 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
12891 		if (!abtsiocbq) {
12892 			if (phba->sli_rev == LPFC_SLI_REV4)
12893 				spin_unlock(&pring_s4->ring_lock);
12894 			spin_unlock(&lpfc_cmd->buf_lock);
12895 			continue;
12896 		}
12897 
12898 		if (phba->sli_rev == LPFC_SLI_REV4) {
12899 			iotag = abtsiocbq->iotag;
12900 			ulp_context = iocbq->sli4_xritag;
12901 			cqid = lpfc_cmd->hdwq->io_cq_map;
12902 		} else {
12903 			iotag = iocbq->iocb.ulpIoTag;
12904 			if (pring->ringno == LPFC_ELS_RING) {
12905 				ndlp = iocbq->ndlp;
12906 				ulp_context = ndlp->nlp_rpi;
12907 			} else {
12908 				ulp_context = iocbq->iocb.ulpContext;
12909 			}
12910 		}
12911 
12912 		ndlp = lpfc_cmd->rdata->pnode;
12913 
12914 		if (lpfc_is_link_up(phba) &&
12915 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE) &&
12916 		    !(phba->link_flag & LS_EXTERNAL_LOOPBACK))
12917 			ia = false;
12918 		else
12919 			ia = true;
12920 
12921 		lpfc_sli_prep_abort_xri(phba, abtsiocbq, ulp_context, iotag,
12922 					iocbq->iocb.ulpClass, cqid,
12923 					ia, false);
12924 
12925 		abtsiocbq->vport = vport;
12926 
12927 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12928 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12929 		if (iocbq->cmd_flag & LPFC_IO_FCP)
12930 			abtsiocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
12931 		if (iocbq->cmd_flag & LPFC_IO_FOF)
12932 			abtsiocbq->cmd_flag |= LPFC_IO_FOF;
12933 
12934 		/* Setup callback routine and issue the command. */
12935 		abtsiocbq->cmd_cmpl = lpfc_sli_abort_fcp_cmpl;
12936 
12937 		/*
12938 		 * Indicate the IO is being aborted by the driver and set
12939 		 * the caller's flag into the aborted IO.
12940 		 */
12941 		iocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
12942 
12943 		if (phba->sli_rev == LPFC_SLI_REV4) {
12944 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
12945 							abtsiocbq, 0);
12946 			spin_unlock(&pring_s4->ring_lock);
12947 		} else {
12948 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
12949 							abtsiocbq, 0);
12950 		}
12951 
12952 		spin_unlock(&lpfc_cmd->buf_lock);
12953 
12954 		if (ret_val == IOCB_ERROR)
12955 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
12956 		else
12957 			sum++;
12958 	}
12959 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12960 	return sum;
12961 }
12962 
12963 /**
12964  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
12965  * @phba: Pointer to HBA context object.
12966  * @cmdiocbq: Pointer to command iocb.
12967  * @rspiocbq: Pointer to response iocb.
12968  *
12969  * This function is the completion handler for iocbs issued using
12970  * lpfc_sli_issue_iocb_wait function. This function is called by the
12971  * ring event handler function without any lock held. This function
12972  * can be called from both worker thread context and interrupt
12973  * context. This function also can be called from other thread which
12974  * cleans up the SLI layer objects.
12975  * This function copy the contents of the response iocb to the
12976  * response iocb memory object provided by the caller of
12977  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
12978  * sleeps for the iocb completion.
12979  **/
12980 static void
12981 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
12982 			struct lpfc_iocbq *cmdiocbq,
12983 			struct lpfc_iocbq *rspiocbq)
12984 {
12985 	wait_queue_head_t *pdone_q;
12986 	unsigned long iflags;
12987 	struct lpfc_io_buf *lpfc_cmd;
12988 	size_t offset = offsetof(struct lpfc_iocbq, wqe);
12989 
12990 	spin_lock_irqsave(&phba->hbalock, iflags);
12991 	if (cmdiocbq->cmd_flag & LPFC_IO_WAKE_TMO) {
12992 
12993 		/*
12994 		 * A time out has occurred for the iocb.  If a time out
12995 		 * completion handler has been supplied, call it.  Otherwise,
12996 		 * just free the iocbq.
12997 		 */
12998 
12999 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13000 		cmdiocbq->cmd_cmpl = cmdiocbq->wait_cmd_cmpl;
13001 		cmdiocbq->wait_cmd_cmpl = NULL;
13002 		if (cmdiocbq->cmd_cmpl)
13003 			cmdiocbq->cmd_cmpl(phba, cmdiocbq, NULL);
13004 		else
13005 			lpfc_sli_release_iocbq(phba, cmdiocbq);
13006 		return;
13007 	}
13008 
13009 	/* Copy the contents of the local rspiocb into the caller's buffer. */
13010 	cmdiocbq->cmd_flag |= LPFC_IO_WAKE;
13011 	if (cmdiocbq->rsp_iocb && rspiocbq)
13012 		memcpy((char *)cmdiocbq->rsp_iocb + offset,
13013 		       (char *)rspiocbq + offset, sizeof(*rspiocbq) - offset);
13014 
13015 	/* Set the exchange busy flag for task management commands */
13016 	if ((cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
13017 	    !(cmdiocbq->cmd_flag & LPFC_IO_LIBDFC)) {
13018 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
13019 					cur_iocbq);
13020 		if (rspiocbq && (rspiocbq->cmd_flag & LPFC_EXCHANGE_BUSY))
13021 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
13022 		else
13023 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
13024 	}
13025 
13026 	pdone_q = cmdiocbq->context_un.wait_queue;
13027 	if (pdone_q)
13028 		wake_up(pdone_q);
13029 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13030 	return;
13031 }
13032 
13033 /**
13034  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
13035  * @phba: Pointer to HBA context object..
13036  * @piocbq: Pointer to command iocb.
13037  * @flag: Flag to test.
13038  *
13039  * This routine grabs the hbalock and then test the cmd_flag to
13040  * see if the passed in flag is set.
13041  * Returns:
13042  * 1 if flag is set.
13043  * 0 if flag is not set.
13044  **/
13045 static int
13046 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
13047 		 struct lpfc_iocbq *piocbq, uint32_t flag)
13048 {
13049 	unsigned long iflags;
13050 	int ret;
13051 
13052 	spin_lock_irqsave(&phba->hbalock, iflags);
13053 	ret = piocbq->cmd_flag & flag;
13054 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13055 	return ret;
13056 
13057 }
13058 
13059 /**
13060  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
13061  * @phba: Pointer to HBA context object..
13062  * @ring_number: Ring number
13063  * @piocb: Pointer to command iocb.
13064  * @prspiocbq: Pointer to response iocb.
13065  * @timeout: Timeout in number of seconds.
13066  *
13067  * This function issues the iocb to firmware and waits for the
13068  * iocb to complete. The cmd_cmpl field of the shall be used
13069  * to handle iocbs which time out. If the field is NULL, the
13070  * function shall free the iocbq structure.  If more clean up is
13071  * needed, the caller is expected to provide a completion function
13072  * that will provide the needed clean up.  If the iocb command is
13073  * not completed within timeout seconds, the function will either
13074  * free the iocbq structure (if cmd_cmpl == NULL) or execute the
13075  * completion function set in the cmd_cmpl field and then return
13076  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
13077  * resources if this function returns IOCB_TIMEDOUT.
13078  * The function waits for the iocb completion using an
13079  * non-interruptible wait.
13080  * This function will sleep while waiting for iocb completion.
13081  * So, this function should not be called from any context which
13082  * does not allow sleeping. Due to the same reason, this function
13083  * cannot be called with interrupt disabled.
13084  * This function assumes that the iocb completions occur while
13085  * this function sleep. So, this function cannot be called from
13086  * the thread which process iocb completion for this ring.
13087  * This function clears the cmd_flag of the iocb object before
13088  * issuing the iocb and the iocb completion handler sets this
13089  * flag and wakes this thread when the iocb completes.
13090  * The contents of the response iocb will be copied to prspiocbq
13091  * by the completion handler when the command completes.
13092  * This function returns IOCB_SUCCESS when success.
13093  * This function is called with no lock held.
13094  **/
13095 int
13096 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
13097 			 uint32_t ring_number,
13098 			 struct lpfc_iocbq *piocb,
13099 			 struct lpfc_iocbq *prspiocbq,
13100 			 uint32_t timeout)
13101 {
13102 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
13103 	long timeleft, timeout_req = 0;
13104 	int retval = IOCB_SUCCESS;
13105 	uint32_t creg_val;
13106 	struct lpfc_iocbq *iocb;
13107 	int txq_cnt = 0;
13108 	int txcmplq_cnt = 0;
13109 	struct lpfc_sli_ring *pring;
13110 	unsigned long iflags;
13111 	bool iocb_completed = true;
13112 
13113 	if (phba->sli_rev >= LPFC_SLI_REV4) {
13114 		lpfc_sli_prep_wqe(phba, piocb);
13115 
13116 		pring = lpfc_sli4_calc_ring(phba, piocb);
13117 	} else
13118 		pring = &phba->sli.sli3_ring[ring_number];
13119 	/*
13120 	 * If the caller has provided a response iocbq buffer, then rsp_iocb
13121 	 * is NULL or its an error.
13122 	 */
13123 	if (prspiocbq) {
13124 		if (piocb->rsp_iocb)
13125 			return IOCB_ERROR;
13126 		piocb->rsp_iocb = prspiocbq;
13127 	}
13128 
13129 	piocb->wait_cmd_cmpl = piocb->cmd_cmpl;
13130 	piocb->cmd_cmpl = lpfc_sli_wake_iocb_wait;
13131 	piocb->context_un.wait_queue = &done_q;
13132 	piocb->cmd_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
13133 
13134 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13135 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13136 			return IOCB_ERROR;
13137 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
13138 		writel(creg_val, phba->HCregaddr);
13139 		readl(phba->HCregaddr); /* flush */
13140 	}
13141 
13142 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
13143 				     SLI_IOCB_RET_IOCB);
13144 	if (retval == IOCB_SUCCESS) {
13145 		timeout_req = msecs_to_jiffies(timeout * 1000);
13146 		timeleft = wait_event_timeout(done_q,
13147 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
13148 				timeout_req);
13149 		spin_lock_irqsave(&phba->hbalock, iflags);
13150 		if (!(piocb->cmd_flag & LPFC_IO_WAKE)) {
13151 
13152 			/*
13153 			 * IOCB timed out.  Inform the wake iocb wait
13154 			 * completion function and set local status
13155 			 */
13156 
13157 			iocb_completed = false;
13158 			piocb->cmd_flag |= LPFC_IO_WAKE_TMO;
13159 		}
13160 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13161 		if (iocb_completed) {
13162 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13163 					"0331 IOCB wake signaled\n");
13164 			/* Note: we are not indicating if the IOCB has a success
13165 			 * status or not - that's for the caller to check.
13166 			 * IOCB_SUCCESS means just that the command was sent and
13167 			 * completed. Not that it completed successfully.
13168 			 * */
13169 		} else if (timeleft == 0) {
13170 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13171 					"0338 IOCB wait timeout error - no "
13172 					"wake response Data x%x\n", timeout);
13173 			retval = IOCB_TIMEDOUT;
13174 		} else {
13175 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13176 					"0330 IOCB wake NOT set, "
13177 					"Data x%x x%lx\n",
13178 					timeout, (timeleft / jiffies));
13179 			retval = IOCB_TIMEDOUT;
13180 		}
13181 	} else if (retval == IOCB_BUSY) {
13182 		if (phba->cfg_log_verbose & LOG_SLI) {
13183 			list_for_each_entry(iocb, &pring->txq, list) {
13184 				txq_cnt++;
13185 			}
13186 			list_for_each_entry(iocb, &pring->txcmplq, list) {
13187 				txcmplq_cnt++;
13188 			}
13189 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13190 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
13191 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
13192 		}
13193 		return retval;
13194 	} else {
13195 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13196 				"0332 IOCB wait issue failed, Data x%x\n",
13197 				retval);
13198 		retval = IOCB_ERROR;
13199 	}
13200 
13201 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13202 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13203 			return IOCB_ERROR;
13204 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
13205 		writel(creg_val, phba->HCregaddr);
13206 		readl(phba->HCregaddr); /* flush */
13207 	}
13208 
13209 	if (prspiocbq)
13210 		piocb->rsp_iocb = NULL;
13211 
13212 	piocb->context_un.wait_queue = NULL;
13213 	piocb->cmd_cmpl = NULL;
13214 	return retval;
13215 }
13216 
13217 /**
13218  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
13219  * @phba: Pointer to HBA context object.
13220  * @pmboxq: Pointer to driver mailbox object.
13221  * @timeout: Timeout in number of seconds.
13222  *
13223  * This function issues the mailbox to firmware and waits for the
13224  * mailbox command to complete. If the mailbox command is not
13225  * completed within timeout seconds, it returns MBX_TIMEOUT.
13226  * The function waits for the mailbox completion using an
13227  * interruptible wait. If the thread is woken up due to a
13228  * signal, MBX_TIMEOUT error is returned to the caller. Caller
13229  * should not free the mailbox resources, if this function returns
13230  * MBX_TIMEOUT.
13231  * This function will sleep while waiting for mailbox completion.
13232  * So, this function should not be called from any context which
13233  * does not allow sleeping. Due to the same reason, this function
13234  * cannot be called with interrupt disabled.
13235  * This function assumes that the mailbox completion occurs while
13236  * this function sleep. So, this function cannot be called from
13237  * the worker thread which processes mailbox completion.
13238  * This function is called in the context of HBA management
13239  * applications.
13240  * This function returns MBX_SUCCESS when successful.
13241  * This function is called with no lock held.
13242  **/
13243 int
13244 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
13245 			 uint32_t timeout)
13246 {
13247 	struct completion mbox_done;
13248 	int retval;
13249 	unsigned long flag;
13250 
13251 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
13252 	/* setup wake call as IOCB callback */
13253 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
13254 
13255 	/* setup context3 field to pass wait_queue pointer to wake function  */
13256 	init_completion(&mbox_done);
13257 	pmboxq->context3 = &mbox_done;
13258 	/* now issue the command */
13259 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
13260 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
13261 		wait_for_completion_timeout(&mbox_done,
13262 					    msecs_to_jiffies(timeout * 1000));
13263 
13264 		spin_lock_irqsave(&phba->hbalock, flag);
13265 		pmboxq->context3 = NULL;
13266 		/*
13267 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
13268 		 * else do not free the resources.
13269 		 */
13270 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
13271 			retval = MBX_SUCCESS;
13272 		} else {
13273 			retval = MBX_TIMEOUT;
13274 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13275 		}
13276 		spin_unlock_irqrestore(&phba->hbalock, flag);
13277 	}
13278 	return retval;
13279 }
13280 
13281 /**
13282  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
13283  * @phba: Pointer to HBA context.
13284  * @mbx_action: Mailbox shutdown options.
13285  *
13286  * This function is called to shutdown the driver's mailbox sub-system.
13287  * It first marks the mailbox sub-system is in a block state to prevent
13288  * the asynchronous mailbox command from issued off the pending mailbox
13289  * command queue. If the mailbox command sub-system shutdown is due to
13290  * HBA error conditions such as EEH or ERATT, this routine shall invoke
13291  * the mailbox sub-system flush routine to forcefully bring down the
13292  * mailbox sub-system. Otherwise, if it is due to normal condition (such
13293  * as with offline or HBA function reset), this routine will wait for the
13294  * outstanding mailbox command to complete before invoking the mailbox
13295  * sub-system flush routine to gracefully bring down mailbox sub-system.
13296  **/
13297 void
13298 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
13299 {
13300 	struct lpfc_sli *psli = &phba->sli;
13301 	unsigned long timeout;
13302 
13303 	if (mbx_action == LPFC_MBX_NO_WAIT) {
13304 		/* delay 100ms for port state */
13305 		msleep(100);
13306 		lpfc_sli_mbox_sys_flush(phba);
13307 		return;
13308 	}
13309 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
13310 
13311 	/* Disable softirqs, including timers from obtaining phba->hbalock */
13312 	local_bh_disable();
13313 
13314 	spin_lock_irq(&phba->hbalock);
13315 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13316 
13317 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
13318 		/* Determine how long we might wait for the active mailbox
13319 		 * command to be gracefully completed by firmware.
13320 		 */
13321 		if (phba->sli.mbox_active)
13322 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
13323 						phba->sli.mbox_active) *
13324 						1000) + jiffies;
13325 		spin_unlock_irq(&phba->hbalock);
13326 
13327 		/* Enable softirqs again, done with phba->hbalock */
13328 		local_bh_enable();
13329 
13330 		while (phba->sli.mbox_active) {
13331 			/* Check active mailbox complete status every 2ms */
13332 			msleep(2);
13333 			if (time_after(jiffies, timeout))
13334 				/* Timeout, let the mailbox flush routine to
13335 				 * forcefully release active mailbox command
13336 				 */
13337 				break;
13338 		}
13339 	} else {
13340 		spin_unlock_irq(&phba->hbalock);
13341 
13342 		/* Enable softirqs again, done with phba->hbalock */
13343 		local_bh_enable();
13344 	}
13345 
13346 	lpfc_sli_mbox_sys_flush(phba);
13347 }
13348 
13349 /**
13350  * lpfc_sli_eratt_read - read sli-3 error attention events
13351  * @phba: Pointer to HBA context.
13352  *
13353  * This function is called to read the SLI3 device error attention registers
13354  * for possible error attention events. The caller must hold the hostlock
13355  * with spin_lock_irq().
13356  *
13357  * This function returns 1 when there is Error Attention in the Host Attention
13358  * Register and returns 0 otherwise.
13359  **/
13360 static int
13361 lpfc_sli_eratt_read(struct lpfc_hba *phba)
13362 {
13363 	uint32_t ha_copy;
13364 
13365 	/* Read chip Host Attention (HA) register */
13366 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
13367 		goto unplug_err;
13368 
13369 	if (ha_copy & HA_ERATT) {
13370 		/* Read host status register to retrieve error event */
13371 		if (lpfc_sli_read_hs(phba))
13372 			goto unplug_err;
13373 
13374 		/* Check if there is a deferred error condition is active */
13375 		if ((HS_FFER1 & phba->work_hs) &&
13376 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13377 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
13378 			phba->hba_flag |= DEFER_ERATT;
13379 			/* Clear all interrupt enable conditions */
13380 			writel(0, phba->HCregaddr);
13381 			readl(phba->HCregaddr);
13382 		}
13383 
13384 		/* Set the driver HA work bitmap */
13385 		phba->work_ha |= HA_ERATT;
13386 		/* Indicate polling handles this ERATT */
13387 		phba->hba_flag |= HBA_ERATT_HANDLED;
13388 		return 1;
13389 	}
13390 	return 0;
13391 
13392 unplug_err:
13393 	/* Set the driver HS work bitmap */
13394 	phba->work_hs |= UNPLUG_ERR;
13395 	/* Set the driver HA work bitmap */
13396 	phba->work_ha |= HA_ERATT;
13397 	/* Indicate polling handles this ERATT */
13398 	phba->hba_flag |= HBA_ERATT_HANDLED;
13399 	return 1;
13400 }
13401 
13402 /**
13403  * lpfc_sli4_eratt_read - read sli-4 error attention events
13404  * @phba: Pointer to HBA context.
13405  *
13406  * This function is called to read the SLI4 device error attention registers
13407  * for possible error attention events. The caller must hold the hostlock
13408  * with spin_lock_irq().
13409  *
13410  * This function returns 1 when there is Error Attention in the Host Attention
13411  * Register and returns 0 otherwise.
13412  **/
13413 static int
13414 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
13415 {
13416 	uint32_t uerr_sta_hi, uerr_sta_lo;
13417 	uint32_t if_type, portsmphr;
13418 	struct lpfc_register portstat_reg;
13419 	u32 logmask;
13420 
13421 	/*
13422 	 * For now, use the SLI4 device internal unrecoverable error
13423 	 * registers for error attention. This can be changed later.
13424 	 */
13425 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
13426 	switch (if_type) {
13427 	case LPFC_SLI_INTF_IF_TYPE_0:
13428 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
13429 			&uerr_sta_lo) ||
13430 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
13431 			&uerr_sta_hi)) {
13432 			phba->work_hs |= UNPLUG_ERR;
13433 			phba->work_ha |= HA_ERATT;
13434 			phba->hba_flag |= HBA_ERATT_HANDLED;
13435 			return 1;
13436 		}
13437 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
13438 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
13439 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13440 					"1423 HBA Unrecoverable error: "
13441 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
13442 					"ue_mask_lo_reg=0x%x, "
13443 					"ue_mask_hi_reg=0x%x\n",
13444 					uerr_sta_lo, uerr_sta_hi,
13445 					phba->sli4_hba.ue_mask_lo,
13446 					phba->sli4_hba.ue_mask_hi);
13447 			phba->work_status[0] = uerr_sta_lo;
13448 			phba->work_status[1] = uerr_sta_hi;
13449 			phba->work_ha |= HA_ERATT;
13450 			phba->hba_flag |= HBA_ERATT_HANDLED;
13451 			return 1;
13452 		}
13453 		break;
13454 	case LPFC_SLI_INTF_IF_TYPE_2:
13455 	case LPFC_SLI_INTF_IF_TYPE_6:
13456 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
13457 			&portstat_reg.word0) ||
13458 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
13459 			&portsmphr)){
13460 			phba->work_hs |= UNPLUG_ERR;
13461 			phba->work_ha |= HA_ERATT;
13462 			phba->hba_flag |= HBA_ERATT_HANDLED;
13463 			return 1;
13464 		}
13465 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
13466 			phba->work_status[0] =
13467 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
13468 			phba->work_status[1] =
13469 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
13470 			logmask = LOG_TRACE_EVENT;
13471 			if (phba->work_status[0] ==
13472 				SLIPORT_ERR1_REG_ERR_CODE_2 &&
13473 			    phba->work_status[1] == SLIPORT_ERR2_REG_FW_RESTART)
13474 				logmask = LOG_SLI;
13475 			lpfc_printf_log(phba, KERN_ERR, logmask,
13476 					"2885 Port Status Event: "
13477 					"port status reg 0x%x, "
13478 					"port smphr reg 0x%x, "
13479 					"error 1=0x%x, error 2=0x%x\n",
13480 					portstat_reg.word0,
13481 					portsmphr,
13482 					phba->work_status[0],
13483 					phba->work_status[1]);
13484 			phba->work_ha |= HA_ERATT;
13485 			phba->hba_flag |= HBA_ERATT_HANDLED;
13486 			return 1;
13487 		}
13488 		break;
13489 	case LPFC_SLI_INTF_IF_TYPE_1:
13490 	default:
13491 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13492 				"2886 HBA Error Attention on unsupported "
13493 				"if type %d.", if_type);
13494 		return 1;
13495 	}
13496 
13497 	return 0;
13498 }
13499 
13500 /**
13501  * lpfc_sli_check_eratt - check error attention events
13502  * @phba: Pointer to HBA context.
13503  *
13504  * This function is called from timer soft interrupt context to check HBA's
13505  * error attention register bit for error attention events.
13506  *
13507  * This function returns 1 when there is Error Attention in the Host Attention
13508  * Register and returns 0 otherwise.
13509  **/
13510 int
13511 lpfc_sli_check_eratt(struct lpfc_hba *phba)
13512 {
13513 	uint32_t ha_copy;
13514 
13515 	/* If somebody is waiting to handle an eratt, don't process it
13516 	 * here. The brdkill function will do this.
13517 	 */
13518 	if (phba->link_flag & LS_IGNORE_ERATT)
13519 		return 0;
13520 
13521 	/* Check if interrupt handler handles this ERATT */
13522 	spin_lock_irq(&phba->hbalock);
13523 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
13524 		/* Interrupt handler has handled ERATT */
13525 		spin_unlock_irq(&phba->hbalock);
13526 		return 0;
13527 	}
13528 
13529 	/*
13530 	 * If there is deferred error attention, do not check for error
13531 	 * attention
13532 	 */
13533 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13534 		spin_unlock_irq(&phba->hbalock);
13535 		return 0;
13536 	}
13537 
13538 	/* If PCI channel is offline, don't process it */
13539 	if (unlikely(pci_channel_offline(phba->pcidev))) {
13540 		spin_unlock_irq(&phba->hbalock);
13541 		return 0;
13542 	}
13543 
13544 	switch (phba->sli_rev) {
13545 	case LPFC_SLI_REV2:
13546 	case LPFC_SLI_REV3:
13547 		/* Read chip Host Attention (HA) register */
13548 		ha_copy = lpfc_sli_eratt_read(phba);
13549 		break;
13550 	case LPFC_SLI_REV4:
13551 		/* Read device Uncoverable Error (UERR) registers */
13552 		ha_copy = lpfc_sli4_eratt_read(phba);
13553 		break;
13554 	default:
13555 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13556 				"0299 Invalid SLI revision (%d)\n",
13557 				phba->sli_rev);
13558 		ha_copy = 0;
13559 		break;
13560 	}
13561 	spin_unlock_irq(&phba->hbalock);
13562 
13563 	return ha_copy;
13564 }
13565 
13566 /**
13567  * lpfc_intr_state_check - Check device state for interrupt handling
13568  * @phba: Pointer to HBA context.
13569  *
13570  * This inline routine checks whether a device or its PCI slot is in a state
13571  * that the interrupt should be handled.
13572  *
13573  * This function returns 0 if the device or the PCI slot is in a state that
13574  * interrupt should be handled, otherwise -EIO.
13575  */
13576 static inline int
13577 lpfc_intr_state_check(struct lpfc_hba *phba)
13578 {
13579 	/* If the pci channel is offline, ignore all the interrupts */
13580 	if (unlikely(pci_channel_offline(phba->pcidev)))
13581 		return -EIO;
13582 
13583 	/* Update device level interrupt statistics */
13584 	phba->sli.slistat.sli_intr++;
13585 
13586 	/* Ignore all interrupts during initialization. */
13587 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
13588 		return -EIO;
13589 
13590 	return 0;
13591 }
13592 
13593 /**
13594  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
13595  * @irq: Interrupt number.
13596  * @dev_id: The device context pointer.
13597  *
13598  * This function is directly called from the PCI layer as an interrupt
13599  * service routine when device with SLI-3 interface spec is enabled with
13600  * MSI-X multi-message interrupt mode and there are slow-path events in
13601  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
13602  * interrupt mode, this function is called as part of the device-level
13603  * interrupt handler. When the PCI slot is in error recovery or the HBA
13604  * is undergoing initialization, the interrupt handler will not process
13605  * the interrupt. The link attention and ELS ring attention events are
13606  * handled by the worker thread. The interrupt handler signals the worker
13607  * thread and returns for these events. This function is called without
13608  * any lock held. It gets the hbalock to access and update SLI data
13609  * structures.
13610  *
13611  * This function returns IRQ_HANDLED when interrupt is handled else it
13612  * returns IRQ_NONE.
13613  **/
13614 irqreturn_t
13615 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
13616 {
13617 	struct lpfc_hba  *phba;
13618 	uint32_t ha_copy, hc_copy;
13619 	uint32_t work_ha_copy;
13620 	unsigned long status;
13621 	unsigned long iflag;
13622 	uint32_t control;
13623 
13624 	MAILBOX_t *mbox, *pmbox;
13625 	struct lpfc_vport *vport;
13626 	struct lpfc_nodelist *ndlp;
13627 	struct lpfc_dmabuf *mp;
13628 	LPFC_MBOXQ_t *pmb;
13629 	int rc;
13630 
13631 	/*
13632 	 * Get the driver's phba structure from the dev_id and
13633 	 * assume the HBA is not interrupting.
13634 	 */
13635 	phba = (struct lpfc_hba *)dev_id;
13636 
13637 	if (unlikely(!phba))
13638 		return IRQ_NONE;
13639 
13640 	/*
13641 	 * Stuff needs to be attented to when this function is invoked as an
13642 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13643 	 */
13644 	if (phba->intr_type == MSIX) {
13645 		/* Check device state for handling interrupt */
13646 		if (lpfc_intr_state_check(phba))
13647 			return IRQ_NONE;
13648 		/* Need to read HA REG for slow-path events */
13649 		spin_lock_irqsave(&phba->hbalock, iflag);
13650 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13651 			goto unplug_error;
13652 		/* If somebody is waiting to handle an eratt don't process it
13653 		 * here. The brdkill function will do this.
13654 		 */
13655 		if (phba->link_flag & LS_IGNORE_ERATT)
13656 			ha_copy &= ~HA_ERATT;
13657 		/* Check the need for handling ERATT in interrupt handler */
13658 		if (ha_copy & HA_ERATT) {
13659 			if (phba->hba_flag & HBA_ERATT_HANDLED)
13660 				/* ERATT polling has handled ERATT */
13661 				ha_copy &= ~HA_ERATT;
13662 			else
13663 				/* Indicate interrupt handler handles ERATT */
13664 				phba->hba_flag |= HBA_ERATT_HANDLED;
13665 		}
13666 
13667 		/*
13668 		 * If there is deferred error attention, do not check for any
13669 		 * interrupt.
13670 		 */
13671 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13672 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13673 			return IRQ_NONE;
13674 		}
13675 
13676 		/* Clear up only attention source related to slow-path */
13677 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
13678 			goto unplug_error;
13679 
13680 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
13681 			HC_LAINT_ENA | HC_ERINT_ENA),
13682 			phba->HCregaddr);
13683 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
13684 			phba->HAregaddr);
13685 		writel(hc_copy, phba->HCregaddr);
13686 		readl(phba->HAregaddr); /* flush */
13687 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13688 	} else
13689 		ha_copy = phba->ha_copy;
13690 
13691 	work_ha_copy = ha_copy & phba->work_ha_mask;
13692 
13693 	if (work_ha_copy) {
13694 		if (work_ha_copy & HA_LATT) {
13695 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
13696 				/*
13697 				 * Turn off Link Attention interrupts
13698 				 * until CLEAR_LA done
13699 				 */
13700 				spin_lock_irqsave(&phba->hbalock, iflag);
13701 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
13702 				if (lpfc_readl(phba->HCregaddr, &control))
13703 					goto unplug_error;
13704 				control &= ~HC_LAINT_ENA;
13705 				writel(control, phba->HCregaddr);
13706 				readl(phba->HCregaddr); /* flush */
13707 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13708 			}
13709 			else
13710 				work_ha_copy &= ~HA_LATT;
13711 		}
13712 
13713 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
13714 			/*
13715 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
13716 			 * the only slow ring.
13717 			 */
13718 			status = (work_ha_copy &
13719 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
13720 			status >>= (4*LPFC_ELS_RING);
13721 			if (status & HA_RXMASK) {
13722 				spin_lock_irqsave(&phba->hbalock, iflag);
13723 				if (lpfc_readl(phba->HCregaddr, &control))
13724 					goto unplug_error;
13725 
13726 				lpfc_debugfs_slow_ring_trc(phba,
13727 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
13728 				control, status,
13729 				(uint32_t)phba->sli.slistat.sli_intr);
13730 
13731 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
13732 					lpfc_debugfs_slow_ring_trc(phba,
13733 						"ISR Disable ring:"
13734 						"pwork:x%x hawork:x%x wait:x%x",
13735 						phba->work_ha, work_ha_copy,
13736 						(uint32_t)((unsigned long)
13737 						&phba->work_waitq));
13738 
13739 					control &=
13740 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
13741 					writel(control, phba->HCregaddr);
13742 					readl(phba->HCregaddr); /* flush */
13743 				}
13744 				else {
13745 					lpfc_debugfs_slow_ring_trc(phba,
13746 						"ISR slow ring:   pwork:"
13747 						"x%x hawork:x%x wait:x%x",
13748 						phba->work_ha, work_ha_copy,
13749 						(uint32_t)((unsigned long)
13750 						&phba->work_waitq));
13751 				}
13752 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13753 			}
13754 		}
13755 		spin_lock_irqsave(&phba->hbalock, iflag);
13756 		if (work_ha_copy & HA_ERATT) {
13757 			if (lpfc_sli_read_hs(phba))
13758 				goto unplug_error;
13759 			/*
13760 			 * Check if there is a deferred error condition
13761 			 * is active
13762 			 */
13763 			if ((HS_FFER1 & phba->work_hs) &&
13764 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13765 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
13766 				  phba->work_hs)) {
13767 				phba->hba_flag |= DEFER_ERATT;
13768 				/* Clear all interrupt enable conditions */
13769 				writel(0, phba->HCregaddr);
13770 				readl(phba->HCregaddr);
13771 			}
13772 		}
13773 
13774 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
13775 			pmb = phba->sli.mbox_active;
13776 			pmbox = &pmb->u.mb;
13777 			mbox = phba->mbox;
13778 			vport = pmb->vport;
13779 
13780 			/* First check out the status word */
13781 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
13782 			if (pmbox->mbxOwner != OWN_HOST) {
13783 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13784 				/*
13785 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
13786 				 * mbxStatus <status>
13787 				 */
13788 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13789 						"(%d):0304 Stray Mailbox "
13790 						"Interrupt mbxCommand x%x "
13791 						"mbxStatus x%x\n",
13792 						(vport ? vport->vpi : 0),
13793 						pmbox->mbxCommand,
13794 						pmbox->mbxStatus);
13795 				/* clear mailbox attention bit */
13796 				work_ha_copy &= ~HA_MBATT;
13797 			} else {
13798 				phba->sli.mbox_active = NULL;
13799 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13800 				phba->last_completion_time = jiffies;
13801 				del_timer(&phba->sli.mbox_tmo);
13802 				if (pmb->mbox_cmpl) {
13803 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
13804 							MAILBOX_CMD_SIZE);
13805 					if (pmb->out_ext_byte_len &&
13806 						pmb->ctx_buf)
13807 						lpfc_sli_pcimem_bcopy(
13808 						phba->mbox_ext,
13809 						pmb->ctx_buf,
13810 						pmb->out_ext_byte_len);
13811 				}
13812 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13813 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13814 
13815 					lpfc_debugfs_disc_trc(vport,
13816 						LPFC_DISC_TRC_MBOX_VPORT,
13817 						"MBOX dflt rpi: : "
13818 						"status:x%x rpi:x%x",
13819 						(uint32_t)pmbox->mbxStatus,
13820 						pmbox->un.varWords[0], 0);
13821 
13822 					if (!pmbox->mbxStatus) {
13823 						mp = (struct lpfc_dmabuf *)
13824 							(pmb->ctx_buf);
13825 						ndlp = (struct lpfc_nodelist *)
13826 							pmb->ctx_ndlp;
13827 
13828 						/* Reg_LOGIN of dflt RPI was
13829 						 * successful. new lets get
13830 						 * rid of the RPI using the
13831 						 * same mbox buffer.
13832 						 */
13833 						lpfc_unreg_login(phba,
13834 							vport->vpi,
13835 							pmbox->un.varWords[0],
13836 							pmb);
13837 						pmb->mbox_cmpl =
13838 							lpfc_mbx_cmpl_dflt_rpi;
13839 						pmb->ctx_buf = mp;
13840 						pmb->ctx_ndlp = ndlp;
13841 						pmb->vport = vport;
13842 						rc = lpfc_sli_issue_mbox(phba,
13843 								pmb,
13844 								MBX_NOWAIT);
13845 						if (rc != MBX_BUSY)
13846 							lpfc_printf_log(phba,
13847 							KERN_ERR,
13848 							LOG_TRACE_EVENT,
13849 							"0350 rc should have"
13850 							"been MBX_BUSY\n");
13851 						if (rc != MBX_NOT_FINISHED)
13852 							goto send_current_mbox;
13853 					}
13854 				}
13855 				spin_lock_irqsave(
13856 						&phba->pport->work_port_lock,
13857 						iflag);
13858 				phba->pport->work_port_events &=
13859 					~WORKER_MBOX_TMO;
13860 				spin_unlock_irqrestore(
13861 						&phba->pport->work_port_lock,
13862 						iflag);
13863 
13864 				/* Do NOT queue MBX_HEARTBEAT to the worker
13865 				 * thread for processing.
13866 				 */
13867 				if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13868 					/* Process mbox now */
13869 					phba->sli.mbox_active = NULL;
13870 					phba->sli.sli_flag &=
13871 						~LPFC_SLI_MBOX_ACTIVE;
13872 					if (pmb->mbox_cmpl)
13873 						pmb->mbox_cmpl(phba, pmb);
13874 				} else {
13875 					/* Queue to worker thread to process */
13876 					lpfc_mbox_cmpl_put(phba, pmb);
13877 				}
13878 			}
13879 		} else
13880 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13881 
13882 		if ((work_ha_copy & HA_MBATT) &&
13883 		    (phba->sli.mbox_active == NULL)) {
13884 send_current_mbox:
13885 			/* Process next mailbox command if there is one */
13886 			do {
13887 				rc = lpfc_sli_issue_mbox(phba, NULL,
13888 							 MBX_NOWAIT);
13889 			} while (rc == MBX_NOT_FINISHED);
13890 			if (rc != MBX_SUCCESS)
13891 				lpfc_printf_log(phba, KERN_ERR,
13892 						LOG_TRACE_EVENT,
13893 						"0349 rc should be "
13894 						"MBX_SUCCESS\n");
13895 		}
13896 
13897 		spin_lock_irqsave(&phba->hbalock, iflag);
13898 		phba->work_ha |= work_ha_copy;
13899 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13900 		lpfc_worker_wake_up(phba);
13901 	}
13902 	return IRQ_HANDLED;
13903 unplug_error:
13904 	spin_unlock_irqrestore(&phba->hbalock, iflag);
13905 	return IRQ_HANDLED;
13906 
13907 } /* lpfc_sli_sp_intr_handler */
13908 
13909 /**
13910  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13911  * @irq: Interrupt number.
13912  * @dev_id: The device context pointer.
13913  *
13914  * This function is directly called from the PCI layer as an interrupt
13915  * service routine when device with SLI-3 interface spec is enabled with
13916  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13917  * ring event in the HBA. However, when the device is enabled with either
13918  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13919  * device-level interrupt handler. When the PCI slot is in error recovery
13920  * or the HBA is undergoing initialization, the interrupt handler will not
13921  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13922  * the intrrupt context. This function is called without any lock held.
13923  * It gets the hbalock to access and update SLI data structures.
13924  *
13925  * This function returns IRQ_HANDLED when interrupt is handled else it
13926  * returns IRQ_NONE.
13927  **/
13928 irqreturn_t
13929 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13930 {
13931 	struct lpfc_hba  *phba;
13932 	uint32_t ha_copy;
13933 	unsigned long status;
13934 	unsigned long iflag;
13935 	struct lpfc_sli_ring *pring;
13936 
13937 	/* Get the driver's phba structure from the dev_id and
13938 	 * assume the HBA is not interrupting.
13939 	 */
13940 	phba = (struct lpfc_hba *) dev_id;
13941 
13942 	if (unlikely(!phba))
13943 		return IRQ_NONE;
13944 
13945 	/*
13946 	 * Stuff needs to be attented to when this function is invoked as an
13947 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13948 	 */
13949 	if (phba->intr_type == MSIX) {
13950 		/* Check device state for handling interrupt */
13951 		if (lpfc_intr_state_check(phba))
13952 			return IRQ_NONE;
13953 		/* Need to read HA REG for FCP ring and other ring events */
13954 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13955 			return IRQ_HANDLED;
13956 		/* Clear up only attention source related to fast-path */
13957 		spin_lock_irqsave(&phba->hbalock, iflag);
13958 		/*
13959 		 * If there is deferred error attention, do not check for
13960 		 * any interrupt.
13961 		 */
13962 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13963 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13964 			return IRQ_NONE;
13965 		}
13966 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
13967 			phba->HAregaddr);
13968 		readl(phba->HAregaddr); /* flush */
13969 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13970 	} else
13971 		ha_copy = phba->ha_copy;
13972 
13973 	/*
13974 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
13975 	 */
13976 	ha_copy &= ~(phba->work_ha_mask);
13977 
13978 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13979 	status >>= (4*LPFC_FCP_RING);
13980 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
13981 	if (status & HA_RXMASK)
13982 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
13983 
13984 	if (phba->cfg_multi_ring_support == 2) {
13985 		/*
13986 		 * Process all events on extra ring. Take the optimized path
13987 		 * for extra ring IO.
13988 		 */
13989 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13990 		status >>= (4*LPFC_EXTRA_RING);
13991 		if (status & HA_RXMASK) {
13992 			lpfc_sli_handle_fast_ring_event(phba,
13993 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
13994 					status);
13995 		}
13996 	}
13997 	return IRQ_HANDLED;
13998 }  /* lpfc_sli_fp_intr_handler */
13999 
14000 /**
14001  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
14002  * @irq: Interrupt number.
14003  * @dev_id: The device context pointer.
14004  *
14005  * This function is the HBA device-level interrupt handler to device with
14006  * SLI-3 interface spec, called from the PCI layer when either MSI or
14007  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
14008  * requires driver attention. This function invokes the slow-path interrupt
14009  * attention handling function and fast-path interrupt attention handling
14010  * function in turn to process the relevant HBA attention events. This
14011  * function is called without any lock held. It gets the hbalock to access
14012  * and update SLI data structures.
14013  *
14014  * This function returns IRQ_HANDLED when interrupt is handled, else it
14015  * returns IRQ_NONE.
14016  **/
14017 irqreturn_t
14018 lpfc_sli_intr_handler(int irq, void *dev_id)
14019 {
14020 	struct lpfc_hba  *phba;
14021 	irqreturn_t sp_irq_rc, fp_irq_rc;
14022 	unsigned long status1, status2;
14023 	uint32_t hc_copy;
14024 
14025 	/*
14026 	 * Get the driver's phba structure from the dev_id and
14027 	 * assume the HBA is not interrupting.
14028 	 */
14029 	phba = (struct lpfc_hba *) dev_id;
14030 
14031 	if (unlikely(!phba))
14032 		return IRQ_NONE;
14033 
14034 	/* Check device state for handling interrupt */
14035 	if (lpfc_intr_state_check(phba))
14036 		return IRQ_NONE;
14037 
14038 	spin_lock(&phba->hbalock);
14039 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
14040 		spin_unlock(&phba->hbalock);
14041 		return IRQ_HANDLED;
14042 	}
14043 
14044 	if (unlikely(!phba->ha_copy)) {
14045 		spin_unlock(&phba->hbalock);
14046 		return IRQ_NONE;
14047 	} else if (phba->ha_copy & HA_ERATT) {
14048 		if (phba->hba_flag & HBA_ERATT_HANDLED)
14049 			/* ERATT polling has handled ERATT */
14050 			phba->ha_copy &= ~HA_ERATT;
14051 		else
14052 			/* Indicate interrupt handler handles ERATT */
14053 			phba->hba_flag |= HBA_ERATT_HANDLED;
14054 	}
14055 
14056 	/*
14057 	 * If there is deferred error attention, do not check for any interrupt.
14058 	 */
14059 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
14060 		spin_unlock(&phba->hbalock);
14061 		return IRQ_NONE;
14062 	}
14063 
14064 	/* Clear attention sources except link and error attentions */
14065 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
14066 		spin_unlock(&phba->hbalock);
14067 		return IRQ_HANDLED;
14068 	}
14069 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
14070 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
14071 		phba->HCregaddr);
14072 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
14073 	writel(hc_copy, phba->HCregaddr);
14074 	readl(phba->HAregaddr); /* flush */
14075 	spin_unlock(&phba->hbalock);
14076 
14077 	/*
14078 	 * Invokes slow-path host attention interrupt handling as appropriate.
14079 	 */
14080 
14081 	/* status of events with mailbox and link attention */
14082 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
14083 
14084 	/* status of events with ELS ring */
14085 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
14086 	status2 >>= (4*LPFC_ELS_RING);
14087 
14088 	if (status1 || (status2 & HA_RXMASK))
14089 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
14090 	else
14091 		sp_irq_rc = IRQ_NONE;
14092 
14093 	/*
14094 	 * Invoke fast-path host attention interrupt handling as appropriate.
14095 	 */
14096 
14097 	/* status of events with FCP ring */
14098 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
14099 	status1 >>= (4*LPFC_FCP_RING);
14100 
14101 	/* status of events with extra ring */
14102 	if (phba->cfg_multi_ring_support == 2) {
14103 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14104 		status2 >>= (4*LPFC_EXTRA_RING);
14105 	} else
14106 		status2 = 0;
14107 
14108 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
14109 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
14110 	else
14111 		fp_irq_rc = IRQ_NONE;
14112 
14113 	/* Return device-level interrupt handling status */
14114 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
14115 }  /* lpfc_sli_intr_handler */
14116 
14117 /**
14118  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
14119  * @phba: pointer to lpfc hba data structure.
14120  *
14121  * This routine is invoked by the worker thread to process all the pending
14122  * SLI4 els abort xri events.
14123  **/
14124 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
14125 {
14126 	struct lpfc_cq_event *cq_event;
14127 	unsigned long iflags;
14128 
14129 	/* First, declare the els xri abort event has been handled */
14130 	spin_lock_irqsave(&phba->hbalock, iflags);
14131 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
14132 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14133 
14134 	/* Now, handle all the els xri abort events */
14135 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14136 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
14137 		/* Get the first event from the head of the event queue */
14138 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
14139 				 cq_event, struct lpfc_cq_event, list);
14140 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14141 				       iflags);
14142 		/* Notify aborted XRI for ELS work queue */
14143 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
14144 
14145 		/* Free the event processed back to the free pool */
14146 		lpfc_sli4_cq_event_release(phba, cq_event);
14147 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14148 				  iflags);
14149 	}
14150 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14151 }
14152 
14153 /**
14154  * lpfc_sli4_els_preprocess_rspiocbq - Get response iocbq from els wcqe
14155  * @phba: Pointer to HBA context object.
14156  * @irspiocbq: Pointer to work-queue completion queue entry.
14157  *
14158  * This routine handles an ELS work-queue completion event and construct
14159  * a pseudo response ELS IOCBQ from the SLI4 ELS WCQE for the common
14160  * discovery engine to handle.
14161  *
14162  * Return: Pointer to the receive IOCBQ, NULL otherwise.
14163  **/
14164 static struct lpfc_iocbq *
14165 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
14166 				  struct lpfc_iocbq *irspiocbq)
14167 {
14168 	struct lpfc_sli_ring *pring;
14169 	struct lpfc_iocbq *cmdiocbq;
14170 	struct lpfc_wcqe_complete *wcqe;
14171 	unsigned long iflags;
14172 
14173 	pring = lpfc_phba_elsring(phba);
14174 	if (unlikely(!pring))
14175 		return NULL;
14176 
14177 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
14178 	spin_lock_irqsave(&pring->ring_lock, iflags);
14179 	pring->stats.iocb_event++;
14180 	/* Look up the ELS command IOCB and create pseudo response IOCB */
14181 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14182 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14183 	if (unlikely(!cmdiocbq)) {
14184 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
14185 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14186 				"0386 ELS complete with no corresponding "
14187 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
14188 				wcqe->word0, wcqe->total_data_placed,
14189 				wcqe->parameter, wcqe->word3);
14190 		lpfc_sli_release_iocbq(phba, irspiocbq);
14191 		return NULL;
14192 	}
14193 
14194 	memcpy(&irspiocbq->wqe, &cmdiocbq->wqe, sizeof(union lpfc_wqe128));
14195 	memcpy(&irspiocbq->wcqe_cmpl, wcqe, sizeof(*wcqe));
14196 
14197 	/* Put the iocb back on the txcmplq */
14198 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
14199 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
14200 
14201 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
14202 		spin_lock_irqsave(&phba->hbalock, iflags);
14203 		irspiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
14204 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14205 	}
14206 
14207 	return irspiocbq;
14208 }
14209 
14210 inline struct lpfc_cq_event *
14211 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
14212 {
14213 	struct lpfc_cq_event *cq_event;
14214 
14215 	/* Allocate a new internal CQ_EVENT entry */
14216 	cq_event = lpfc_sli4_cq_event_alloc(phba);
14217 	if (!cq_event) {
14218 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14219 				"0602 Failed to alloc CQ_EVENT entry\n");
14220 		return NULL;
14221 	}
14222 
14223 	/* Move the CQE into the event */
14224 	memcpy(&cq_event->cqe, entry, size);
14225 	return cq_event;
14226 }
14227 
14228 /**
14229  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
14230  * @phba: Pointer to HBA context object.
14231  * @mcqe: Pointer to mailbox completion queue entry.
14232  *
14233  * This routine process a mailbox completion queue entry with asynchronous
14234  * event.
14235  *
14236  * Return: true if work posted to worker thread, otherwise false.
14237  **/
14238 static bool
14239 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14240 {
14241 	struct lpfc_cq_event *cq_event;
14242 	unsigned long iflags;
14243 
14244 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14245 			"0392 Async Event: word0:x%x, word1:x%x, "
14246 			"word2:x%x, word3:x%x\n", mcqe->word0,
14247 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
14248 
14249 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
14250 	if (!cq_event)
14251 		return false;
14252 
14253 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
14254 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
14255 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
14256 
14257 	/* Set the async event flag */
14258 	spin_lock_irqsave(&phba->hbalock, iflags);
14259 	phba->hba_flag |= ASYNC_EVENT;
14260 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14261 
14262 	return true;
14263 }
14264 
14265 /**
14266  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
14267  * @phba: Pointer to HBA context object.
14268  * @mcqe: Pointer to mailbox completion queue entry.
14269  *
14270  * This routine process a mailbox completion queue entry with mailbox
14271  * completion event.
14272  *
14273  * Return: true if work posted to worker thread, otherwise false.
14274  **/
14275 static bool
14276 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14277 {
14278 	uint32_t mcqe_status;
14279 	MAILBOX_t *mbox, *pmbox;
14280 	struct lpfc_mqe *mqe;
14281 	struct lpfc_vport *vport;
14282 	struct lpfc_nodelist *ndlp;
14283 	struct lpfc_dmabuf *mp;
14284 	unsigned long iflags;
14285 	LPFC_MBOXQ_t *pmb;
14286 	bool workposted = false;
14287 	int rc;
14288 
14289 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
14290 	if (!bf_get(lpfc_trailer_completed, mcqe))
14291 		goto out_no_mqe_complete;
14292 
14293 	/* Get the reference to the active mbox command */
14294 	spin_lock_irqsave(&phba->hbalock, iflags);
14295 	pmb = phba->sli.mbox_active;
14296 	if (unlikely(!pmb)) {
14297 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14298 				"1832 No pending MBOX command to handle\n");
14299 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14300 		goto out_no_mqe_complete;
14301 	}
14302 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14303 	mqe = &pmb->u.mqe;
14304 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
14305 	mbox = phba->mbox;
14306 	vport = pmb->vport;
14307 
14308 	/* Reset heartbeat timer */
14309 	phba->last_completion_time = jiffies;
14310 	del_timer(&phba->sli.mbox_tmo);
14311 
14312 	/* Move mbox data to caller's mailbox region, do endian swapping */
14313 	if (pmb->mbox_cmpl && mbox)
14314 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
14315 
14316 	/*
14317 	 * For mcqe errors, conditionally move a modified error code to
14318 	 * the mbox so that the error will not be missed.
14319 	 */
14320 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
14321 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
14322 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
14323 			bf_set(lpfc_mqe_status, mqe,
14324 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
14325 	}
14326 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
14327 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
14328 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
14329 				      "MBOX dflt rpi: status:x%x rpi:x%x",
14330 				      mcqe_status,
14331 				      pmbox->un.varWords[0], 0);
14332 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
14333 			mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
14334 			ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
14335 
14336 			/* Reg_LOGIN of dflt RPI was successful. Mark the
14337 			 * node as having an UNREG_LOGIN in progress to stop
14338 			 * an unsolicited PLOGI from the same NPortId from
14339 			 * starting another mailbox transaction.
14340 			 */
14341 			spin_lock_irqsave(&ndlp->lock, iflags);
14342 			ndlp->nlp_flag |= NLP_UNREG_INP;
14343 			spin_unlock_irqrestore(&ndlp->lock, iflags);
14344 			lpfc_unreg_login(phba, vport->vpi,
14345 					 pmbox->un.varWords[0], pmb);
14346 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
14347 			pmb->ctx_buf = mp;
14348 
14349 			/* No reference taken here.  This is a default
14350 			 * RPI reg/immediate unreg cycle. The reference was
14351 			 * taken in the reg rpi path and is released when
14352 			 * this mailbox completes.
14353 			 */
14354 			pmb->ctx_ndlp = ndlp;
14355 			pmb->vport = vport;
14356 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
14357 			if (rc != MBX_BUSY)
14358 				lpfc_printf_log(phba, KERN_ERR,
14359 						LOG_TRACE_EVENT,
14360 						"0385 rc should "
14361 						"have been MBX_BUSY\n");
14362 			if (rc != MBX_NOT_FINISHED)
14363 				goto send_current_mbox;
14364 		}
14365 	}
14366 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
14367 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
14368 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
14369 
14370 	/* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
14371 	if (pmbox->mbxCommand == MBX_HEARTBEAT) {
14372 		spin_lock_irqsave(&phba->hbalock, iflags);
14373 		/* Release the mailbox command posting token */
14374 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14375 		phba->sli.mbox_active = NULL;
14376 		if (bf_get(lpfc_trailer_consumed, mcqe))
14377 			lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14378 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14379 
14380 		/* Post the next mbox command, if there is one */
14381 		lpfc_sli4_post_async_mbox(phba);
14382 
14383 		/* Process cmpl now */
14384 		if (pmb->mbox_cmpl)
14385 			pmb->mbox_cmpl(phba, pmb);
14386 		return false;
14387 	}
14388 
14389 	/* There is mailbox completion work to queue to the worker thread */
14390 	spin_lock_irqsave(&phba->hbalock, iflags);
14391 	__lpfc_mbox_cmpl_put(phba, pmb);
14392 	phba->work_ha |= HA_MBATT;
14393 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14394 	workposted = true;
14395 
14396 send_current_mbox:
14397 	spin_lock_irqsave(&phba->hbalock, iflags);
14398 	/* Release the mailbox command posting token */
14399 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14400 	/* Setting active mailbox pointer need to be in sync to flag clear */
14401 	phba->sli.mbox_active = NULL;
14402 	if (bf_get(lpfc_trailer_consumed, mcqe))
14403 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14404 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14405 	/* Wake up worker thread to post the next pending mailbox command */
14406 	lpfc_worker_wake_up(phba);
14407 	return workposted;
14408 
14409 out_no_mqe_complete:
14410 	spin_lock_irqsave(&phba->hbalock, iflags);
14411 	if (bf_get(lpfc_trailer_consumed, mcqe))
14412 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14413 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14414 	return false;
14415 }
14416 
14417 /**
14418  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
14419  * @phba: Pointer to HBA context object.
14420  * @cq: Pointer to associated CQ
14421  * @cqe: Pointer to mailbox completion queue entry.
14422  *
14423  * This routine process a mailbox completion queue entry, it invokes the
14424  * proper mailbox complete handling or asynchronous event handling routine
14425  * according to the MCQE's async bit.
14426  *
14427  * Return: true if work posted to worker thread, otherwise false.
14428  **/
14429 static bool
14430 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14431 			 struct lpfc_cqe *cqe)
14432 {
14433 	struct lpfc_mcqe mcqe;
14434 	bool workposted;
14435 
14436 	cq->CQ_mbox++;
14437 
14438 	/* Copy the mailbox MCQE and convert endian order as needed */
14439 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
14440 
14441 	/* Invoke the proper event handling routine */
14442 	if (!bf_get(lpfc_trailer_async, &mcqe))
14443 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
14444 	else
14445 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
14446 	return workposted;
14447 }
14448 
14449 /**
14450  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
14451  * @phba: Pointer to HBA context object.
14452  * @cq: Pointer to associated CQ
14453  * @wcqe: Pointer to work-queue completion queue entry.
14454  *
14455  * This routine handles an ELS work-queue completion event.
14456  *
14457  * Return: true if work posted to worker thread, otherwise false.
14458  **/
14459 static bool
14460 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14461 			     struct lpfc_wcqe_complete *wcqe)
14462 {
14463 	struct lpfc_iocbq *irspiocbq;
14464 	unsigned long iflags;
14465 	struct lpfc_sli_ring *pring = cq->pring;
14466 	int txq_cnt = 0;
14467 	int txcmplq_cnt = 0;
14468 
14469 	/* Check for response status */
14470 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14471 		/* Log the error status */
14472 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14473 				"0357 ELS CQE error: status=x%x: "
14474 				"CQE: %08x %08x %08x %08x\n",
14475 				bf_get(lpfc_wcqe_c_status, wcqe),
14476 				wcqe->word0, wcqe->total_data_placed,
14477 				wcqe->parameter, wcqe->word3);
14478 	}
14479 
14480 	/* Get an irspiocbq for later ELS response processing use */
14481 	irspiocbq = lpfc_sli_get_iocbq(phba);
14482 	if (!irspiocbq) {
14483 		if (!list_empty(&pring->txq))
14484 			txq_cnt++;
14485 		if (!list_empty(&pring->txcmplq))
14486 			txcmplq_cnt++;
14487 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14488 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
14489 			"els_txcmplq_cnt=%d\n",
14490 			txq_cnt, phba->iocb_cnt,
14491 			txcmplq_cnt);
14492 		return false;
14493 	}
14494 
14495 	/* Save off the slow-path queue event for work thread to process */
14496 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
14497 	spin_lock_irqsave(&phba->hbalock, iflags);
14498 	list_add_tail(&irspiocbq->cq_event.list,
14499 		      &phba->sli4_hba.sp_queue_event);
14500 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
14501 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14502 
14503 	return true;
14504 }
14505 
14506 /**
14507  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
14508  * @phba: Pointer to HBA context object.
14509  * @wcqe: Pointer to work-queue completion queue entry.
14510  *
14511  * This routine handles slow-path WQ entry consumed event by invoking the
14512  * proper WQ release routine to the slow-path WQ.
14513  **/
14514 static void
14515 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
14516 			     struct lpfc_wcqe_release *wcqe)
14517 {
14518 	/* sanity check on queue memory */
14519 	if (unlikely(!phba->sli4_hba.els_wq))
14520 		return;
14521 	/* Check for the slow-path ELS work queue */
14522 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
14523 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
14524 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14525 	else
14526 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14527 				"2579 Slow-path wqe consume event carries "
14528 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
14529 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
14530 				phba->sli4_hba.els_wq->queue_id);
14531 }
14532 
14533 /**
14534  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
14535  * @phba: Pointer to HBA context object.
14536  * @cq: Pointer to a WQ completion queue.
14537  * @wcqe: Pointer to work-queue completion queue entry.
14538  *
14539  * This routine handles an XRI abort event.
14540  *
14541  * Return: true if work posted to worker thread, otherwise false.
14542  **/
14543 static bool
14544 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
14545 				   struct lpfc_queue *cq,
14546 				   struct sli4_wcqe_xri_aborted *wcqe)
14547 {
14548 	bool workposted = false;
14549 	struct lpfc_cq_event *cq_event;
14550 	unsigned long iflags;
14551 
14552 	switch (cq->subtype) {
14553 	case LPFC_IO:
14554 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
14555 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14556 			/* Notify aborted XRI for NVME work queue */
14557 			if (phba->nvmet_support)
14558 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
14559 		}
14560 		workposted = false;
14561 		break;
14562 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
14563 	case LPFC_ELS:
14564 		cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
14565 		if (!cq_event) {
14566 			workposted = false;
14567 			break;
14568 		}
14569 		cq_event->hdwq = cq->hdwq;
14570 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14571 				  iflags);
14572 		list_add_tail(&cq_event->list,
14573 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
14574 		/* Set the els xri abort event flag */
14575 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
14576 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14577 				       iflags);
14578 		workposted = true;
14579 		break;
14580 	default:
14581 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14582 				"0603 Invalid CQ subtype %d: "
14583 				"%08x %08x %08x %08x\n",
14584 				cq->subtype, wcqe->word0, wcqe->parameter,
14585 				wcqe->word2, wcqe->word3);
14586 		workposted = false;
14587 		break;
14588 	}
14589 	return workposted;
14590 }
14591 
14592 #define FC_RCTL_MDS_DIAGS	0xF4
14593 
14594 /**
14595  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
14596  * @phba: Pointer to HBA context object.
14597  * @rcqe: Pointer to receive-queue completion queue entry.
14598  *
14599  * This routine process a receive-queue completion queue entry.
14600  *
14601  * Return: true if work posted to worker thread, otherwise false.
14602  **/
14603 static bool
14604 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
14605 {
14606 	bool workposted = false;
14607 	struct fc_frame_header *fc_hdr;
14608 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
14609 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
14610 	struct lpfc_nvmet_tgtport *tgtp;
14611 	struct hbq_dmabuf *dma_buf;
14612 	uint32_t status, rq_id;
14613 	unsigned long iflags;
14614 
14615 	/* sanity check on queue memory */
14616 	if (unlikely(!hrq) || unlikely(!drq))
14617 		return workposted;
14618 
14619 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14620 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14621 	else
14622 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14623 	if (rq_id != hrq->queue_id)
14624 		goto out;
14625 
14626 	status = bf_get(lpfc_rcqe_status, rcqe);
14627 	switch (status) {
14628 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14629 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14630 				"2537 Receive Frame Truncated!!\n");
14631 		fallthrough;
14632 	case FC_STATUS_RQ_SUCCESS:
14633 		spin_lock_irqsave(&phba->hbalock, iflags);
14634 		lpfc_sli4_rq_release(hrq, drq);
14635 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14636 		if (!dma_buf) {
14637 			hrq->RQ_no_buf_found++;
14638 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14639 			goto out;
14640 		}
14641 		hrq->RQ_rcv_buf++;
14642 		hrq->RQ_buf_posted--;
14643 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
14644 
14645 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14646 
14647 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
14648 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
14649 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14650 			/* Handle MDS Loopback frames */
14651 			if  (!(phba->pport->load_flag & FC_UNLOADING))
14652 				lpfc_sli4_handle_mds_loopback(phba->pport,
14653 							      dma_buf);
14654 			else
14655 				lpfc_in_buf_free(phba, &dma_buf->dbuf);
14656 			break;
14657 		}
14658 
14659 		/* save off the frame for the work thread to process */
14660 		list_add_tail(&dma_buf->cq_event.list,
14661 			      &phba->sli4_hba.sp_queue_event);
14662 		/* Frame received */
14663 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
14664 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14665 		workposted = true;
14666 		break;
14667 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14668 		if (phba->nvmet_support) {
14669 			tgtp = phba->targetport->private;
14670 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14671 					"6402 RQE Error x%x, posted %d err_cnt "
14672 					"%d: %x %x %x\n",
14673 					status, hrq->RQ_buf_posted,
14674 					hrq->RQ_no_posted_buf,
14675 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14676 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14677 					atomic_read(&tgtp->xmt_fcp_release));
14678 		}
14679 		fallthrough;
14680 
14681 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14682 		hrq->RQ_no_posted_buf++;
14683 		/* Post more buffers if possible */
14684 		spin_lock_irqsave(&phba->hbalock, iflags);
14685 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
14686 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14687 		workposted = true;
14688 		break;
14689 	case FC_STATUS_RQ_DMA_FAILURE:
14690 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14691 				"2564 RQE DMA Error x%x, x%08x x%08x x%08x "
14692 				"x%08x\n",
14693 				status, rcqe->word0, rcqe->word1,
14694 				rcqe->word2, rcqe->word3);
14695 
14696 		/* If IV set, no further recovery */
14697 		if (bf_get(lpfc_rcqe_iv, rcqe))
14698 			break;
14699 
14700 		/* recycle consumed resource */
14701 		spin_lock_irqsave(&phba->hbalock, iflags);
14702 		lpfc_sli4_rq_release(hrq, drq);
14703 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14704 		if (!dma_buf) {
14705 			hrq->RQ_no_buf_found++;
14706 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14707 			break;
14708 		}
14709 		hrq->RQ_rcv_buf++;
14710 		hrq->RQ_buf_posted--;
14711 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14712 		lpfc_in_buf_free(phba, &dma_buf->dbuf);
14713 		break;
14714 	default:
14715 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14716 				"2565 Unexpected RQE Status x%x, w0-3 x%08x "
14717 				"x%08x x%08x x%08x\n",
14718 				status, rcqe->word0, rcqe->word1,
14719 				rcqe->word2, rcqe->word3);
14720 		break;
14721 	}
14722 out:
14723 	return workposted;
14724 }
14725 
14726 /**
14727  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
14728  * @phba: Pointer to HBA context object.
14729  * @cq: Pointer to the completion queue.
14730  * @cqe: Pointer to a completion queue entry.
14731  *
14732  * This routine process a slow-path work-queue or receive queue completion queue
14733  * entry.
14734  *
14735  * Return: true if work posted to worker thread, otherwise false.
14736  **/
14737 static bool
14738 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14739 			 struct lpfc_cqe *cqe)
14740 {
14741 	struct lpfc_cqe cqevt;
14742 	bool workposted = false;
14743 
14744 	/* Copy the work queue CQE and convert endian order if needed */
14745 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14746 
14747 	/* Check and process for different type of WCQE and dispatch */
14748 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
14749 	case CQE_CODE_COMPL_WQE:
14750 		/* Process the WQ/RQ complete event */
14751 		phba->last_completion_time = jiffies;
14752 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14753 				(struct lpfc_wcqe_complete *)&cqevt);
14754 		break;
14755 	case CQE_CODE_RELEASE_WQE:
14756 		/* Process the WQ release event */
14757 		lpfc_sli4_sp_handle_rel_wcqe(phba,
14758 				(struct lpfc_wcqe_release *)&cqevt);
14759 		break;
14760 	case CQE_CODE_XRI_ABORTED:
14761 		/* Process the WQ XRI abort event */
14762 		phba->last_completion_time = jiffies;
14763 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14764 				(struct sli4_wcqe_xri_aborted *)&cqevt);
14765 		break;
14766 	case CQE_CODE_RECEIVE:
14767 	case CQE_CODE_RECEIVE_V1:
14768 		/* Process the RQ event */
14769 		phba->last_completion_time = jiffies;
14770 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
14771 				(struct lpfc_rcqe *)&cqevt);
14772 		break;
14773 	default:
14774 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14775 				"0388 Not a valid WCQE code: x%x\n",
14776 				bf_get(lpfc_cqe_code, &cqevt));
14777 		break;
14778 	}
14779 	return workposted;
14780 }
14781 
14782 /**
14783  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14784  * @phba: Pointer to HBA context object.
14785  * @eqe: Pointer to fast-path event queue entry.
14786  * @speq: Pointer to slow-path event queue.
14787  *
14788  * This routine process a event queue entry from the slow-path event queue.
14789  * It will check the MajorCode and MinorCode to determine this is for a
14790  * completion event on a completion queue, if not, an error shall be logged
14791  * and just return. Otherwise, it will get to the corresponding completion
14792  * queue and process all the entries on that completion queue, rearm the
14793  * completion queue, and then return.
14794  *
14795  **/
14796 static void
14797 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14798 	struct lpfc_queue *speq)
14799 {
14800 	struct lpfc_queue *cq = NULL, *childq;
14801 	uint16_t cqid;
14802 	int ret = 0;
14803 
14804 	/* Get the reference to the corresponding CQ */
14805 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14806 
14807 	list_for_each_entry(childq, &speq->child_list, list) {
14808 		if (childq->queue_id == cqid) {
14809 			cq = childq;
14810 			break;
14811 		}
14812 	}
14813 	if (unlikely(!cq)) {
14814 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14815 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14816 					"0365 Slow-path CQ identifier "
14817 					"(%d) does not exist\n", cqid);
14818 		return;
14819 	}
14820 
14821 	/* Save EQ associated with this CQ */
14822 	cq->assoc_qp = speq;
14823 
14824 	if (is_kdump_kernel())
14825 		ret = queue_work(phba->wq, &cq->spwork);
14826 	else
14827 		ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14828 
14829 	if (!ret)
14830 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14831 				"0390 Cannot schedule queue work "
14832 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14833 				cqid, cq->queue_id, raw_smp_processor_id());
14834 }
14835 
14836 /**
14837  * __lpfc_sli4_process_cq - Process elements of a CQ
14838  * @phba: Pointer to HBA context object.
14839  * @cq: Pointer to CQ to be processed
14840  * @handler: Routine to process each cqe
14841  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14842  *
14843  * This routine processes completion queue entries in a CQ. While a valid
14844  * queue element is found, the handler is called. During processing checks
14845  * are made for periodic doorbell writes to let the hardware know of
14846  * element consumption.
14847  *
14848  * If the max limit on cqes to process is hit, or there are no more valid
14849  * entries, the loop stops. If we processed a sufficient number of elements,
14850  * meaning there is sufficient load, rather than rearming and generating
14851  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14852  * indicates no rescheduling.
14853  *
14854  * Returns True if work scheduled, False otherwise.
14855  **/
14856 static bool
14857 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14858 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14859 			struct lpfc_cqe *), unsigned long *delay)
14860 {
14861 	struct lpfc_cqe *cqe;
14862 	bool workposted = false;
14863 	int count = 0, consumed = 0;
14864 	bool arm = true;
14865 
14866 	/* default - no reschedule */
14867 	*delay = 0;
14868 
14869 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14870 		goto rearm_and_exit;
14871 
14872 	/* Process all the entries to the CQ */
14873 	cq->q_flag = 0;
14874 	cqe = lpfc_sli4_cq_get(cq);
14875 	while (cqe) {
14876 		workposted |= handler(phba, cq, cqe);
14877 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
14878 
14879 		consumed++;
14880 		if (!(++count % cq->max_proc_limit))
14881 			break;
14882 
14883 		if (!(count % cq->notify_interval)) {
14884 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14885 						LPFC_QUEUE_NOARM);
14886 			consumed = 0;
14887 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14888 		}
14889 
14890 		if (count == LPFC_NVMET_CQ_NOTIFY)
14891 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14892 
14893 		cqe = lpfc_sli4_cq_get(cq);
14894 	}
14895 	if (count >= phba->cfg_cq_poll_threshold) {
14896 		*delay = 1;
14897 		arm = false;
14898 	}
14899 
14900 	/* Track the max number of CQEs processed in 1 EQ */
14901 	if (count > cq->CQ_max_cqe)
14902 		cq->CQ_max_cqe = count;
14903 
14904 	cq->assoc_qp->EQ_cqe_cnt += count;
14905 
14906 	/* Catch the no cq entry condition */
14907 	if (unlikely(count == 0))
14908 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14909 				"0369 No entry from completion queue "
14910 				"qid=%d\n", cq->queue_id);
14911 
14912 	xchg(&cq->queue_claimed, 0);
14913 
14914 rearm_and_exit:
14915 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14916 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14917 
14918 	return workposted;
14919 }
14920 
14921 /**
14922  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14923  * @cq: pointer to CQ to process
14924  *
14925  * This routine calls the cq processing routine with a handler specific
14926  * to the type of queue bound to it.
14927  *
14928  * The CQ routine returns two values: the first is the calling status,
14929  * which indicates whether work was queued to the  background discovery
14930  * thread. If true, the routine should wakeup the discovery thread;
14931  * the second is the delay parameter. If non-zero, rather than rearming
14932  * the CQ and yet another interrupt, the CQ handler should be queued so
14933  * that it is processed in a subsequent polling action. The value of
14934  * the delay indicates when to reschedule it.
14935  **/
14936 static void
14937 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14938 {
14939 	struct lpfc_hba *phba = cq->phba;
14940 	unsigned long delay;
14941 	bool workposted = false;
14942 	int ret = 0;
14943 
14944 	/* Process and rearm the CQ */
14945 	switch (cq->type) {
14946 	case LPFC_MCQ:
14947 		workposted |= __lpfc_sli4_process_cq(phba, cq,
14948 						lpfc_sli4_sp_handle_mcqe,
14949 						&delay);
14950 		break;
14951 	case LPFC_WCQ:
14952 		if (cq->subtype == LPFC_IO)
14953 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14954 						lpfc_sli4_fp_handle_cqe,
14955 						&delay);
14956 		else
14957 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14958 						lpfc_sli4_sp_handle_cqe,
14959 						&delay);
14960 		break;
14961 	default:
14962 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14963 				"0370 Invalid completion queue type (%d)\n",
14964 				cq->type);
14965 		return;
14966 	}
14967 
14968 	if (delay) {
14969 		if (is_kdump_kernel())
14970 			ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
14971 						delay);
14972 		else
14973 			ret = queue_delayed_work_on(cq->chann, phba->wq,
14974 						&cq->sched_spwork, delay);
14975 		if (!ret)
14976 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14977 				"0394 Cannot schedule queue work "
14978 				"for cqid=%d on CPU %d\n",
14979 				cq->queue_id, cq->chann);
14980 	}
14981 
14982 	/* wake up worker thread if there are works to be done */
14983 	if (workposted)
14984 		lpfc_worker_wake_up(phba);
14985 }
14986 
14987 /**
14988  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
14989  *   interrupt
14990  * @work: pointer to work element
14991  *
14992  * translates from the work handler and calls the slow-path handler.
14993  **/
14994 static void
14995 lpfc_sli4_sp_process_cq(struct work_struct *work)
14996 {
14997 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
14998 
14999 	__lpfc_sli4_sp_process_cq(cq);
15000 }
15001 
15002 /**
15003  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
15004  * @work: pointer to work element
15005  *
15006  * translates from the work handler and calls the slow-path handler.
15007  **/
15008 static void
15009 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
15010 {
15011 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15012 					struct lpfc_queue, sched_spwork);
15013 
15014 	__lpfc_sli4_sp_process_cq(cq);
15015 }
15016 
15017 /**
15018  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
15019  * @phba: Pointer to HBA context object.
15020  * @cq: Pointer to associated CQ
15021  * @wcqe: Pointer to work-queue completion queue entry.
15022  *
15023  * This routine process a fast-path work queue completion entry from fast-path
15024  * event queue for FCP command response completion.
15025  **/
15026 static void
15027 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15028 			     struct lpfc_wcqe_complete *wcqe)
15029 {
15030 	struct lpfc_sli_ring *pring = cq->pring;
15031 	struct lpfc_iocbq *cmdiocbq;
15032 	unsigned long iflags;
15033 
15034 	/* Check for response status */
15035 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
15036 		/* If resource errors reported from HBA, reduce queue
15037 		 * depth of the SCSI device.
15038 		 */
15039 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
15040 		     IOSTAT_LOCAL_REJECT)) &&
15041 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
15042 		     IOERR_NO_RESOURCES))
15043 			phba->lpfc_rampdown_queue_depth(phba);
15044 
15045 		/* Log the cmpl status */
15046 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15047 				"0373 FCP CQE cmpl: status=x%x: "
15048 				"CQE: %08x %08x %08x %08x\n",
15049 				bf_get(lpfc_wcqe_c_status, wcqe),
15050 				wcqe->word0, wcqe->total_data_placed,
15051 				wcqe->parameter, wcqe->word3);
15052 	}
15053 
15054 	/* Look up the FCP command IOCB and create pseudo response IOCB */
15055 	spin_lock_irqsave(&pring->ring_lock, iflags);
15056 	pring->stats.iocb_event++;
15057 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
15058 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15059 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
15060 	if (unlikely(!cmdiocbq)) {
15061 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15062 				"0374 FCP complete with no corresponding "
15063 				"cmdiocb: iotag (%d)\n",
15064 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15065 		return;
15066 	}
15067 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
15068 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
15069 #endif
15070 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
15071 		spin_lock_irqsave(&phba->hbalock, iflags);
15072 		cmdiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
15073 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15074 	}
15075 
15076 	if (cmdiocbq->cmd_cmpl) {
15077 		/* For FCP the flag is cleared in cmd_cmpl */
15078 		if (!(cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
15079 		    cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED) {
15080 			spin_lock_irqsave(&phba->hbalock, iflags);
15081 			cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
15082 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15083 		}
15084 
15085 		/* Pass the cmd_iocb and the wcqe to the upper layer */
15086 		memcpy(&cmdiocbq->wcqe_cmpl, wcqe,
15087 		       sizeof(struct lpfc_wcqe_complete));
15088 		cmdiocbq->cmd_cmpl(phba, cmdiocbq, cmdiocbq);
15089 	} else {
15090 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15091 				"0375 FCP cmdiocb not callback function "
15092 				"iotag: (%d)\n",
15093 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15094 	}
15095 }
15096 
15097 /**
15098  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
15099  * @phba: Pointer to HBA context object.
15100  * @cq: Pointer to completion queue.
15101  * @wcqe: Pointer to work-queue completion queue entry.
15102  *
15103  * This routine handles an fast-path WQ entry consumed event by invoking the
15104  * proper WQ release routine to the slow-path WQ.
15105  **/
15106 static void
15107 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15108 			     struct lpfc_wcqe_release *wcqe)
15109 {
15110 	struct lpfc_queue *childwq;
15111 	bool wqid_matched = false;
15112 	uint16_t hba_wqid;
15113 
15114 	/* Check for fast-path FCP work queue release */
15115 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
15116 	list_for_each_entry(childwq, &cq->child_list, list) {
15117 		if (childwq->queue_id == hba_wqid) {
15118 			lpfc_sli4_wq_release(childwq,
15119 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
15120 			if (childwq->q_flag & HBA_NVMET_WQFULL)
15121 				lpfc_nvmet_wqfull_process(phba, childwq);
15122 			wqid_matched = true;
15123 			break;
15124 		}
15125 	}
15126 	/* Report warning log message if no match found */
15127 	if (wqid_matched != true)
15128 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15129 				"2580 Fast-path wqe consume event carries "
15130 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
15131 }
15132 
15133 /**
15134  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
15135  * @phba: Pointer to HBA context object.
15136  * @cq: Pointer to completion queue.
15137  * @rcqe: Pointer to receive-queue completion queue entry.
15138  *
15139  * This routine process a receive-queue completion queue entry.
15140  *
15141  * Return: true if work posted to worker thread, otherwise false.
15142  **/
15143 static bool
15144 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15145 			    struct lpfc_rcqe *rcqe)
15146 {
15147 	bool workposted = false;
15148 	struct lpfc_queue *hrq;
15149 	struct lpfc_queue *drq;
15150 	struct rqb_dmabuf *dma_buf;
15151 	struct fc_frame_header *fc_hdr;
15152 	struct lpfc_nvmet_tgtport *tgtp;
15153 	uint32_t status, rq_id;
15154 	unsigned long iflags;
15155 	uint32_t fctl, idx;
15156 
15157 	if ((phba->nvmet_support == 0) ||
15158 	    (phba->sli4_hba.nvmet_cqset == NULL))
15159 		return workposted;
15160 
15161 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
15162 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
15163 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
15164 
15165 	/* sanity check on queue memory */
15166 	if (unlikely(!hrq) || unlikely(!drq))
15167 		return workposted;
15168 
15169 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
15170 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
15171 	else
15172 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
15173 
15174 	if ((phba->nvmet_support == 0) ||
15175 	    (rq_id != hrq->queue_id))
15176 		return workposted;
15177 
15178 	status = bf_get(lpfc_rcqe_status, rcqe);
15179 	switch (status) {
15180 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
15181 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15182 				"6126 Receive Frame Truncated!!\n");
15183 		fallthrough;
15184 	case FC_STATUS_RQ_SUCCESS:
15185 		spin_lock_irqsave(&phba->hbalock, iflags);
15186 		lpfc_sli4_rq_release(hrq, drq);
15187 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15188 		if (!dma_buf) {
15189 			hrq->RQ_no_buf_found++;
15190 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15191 			goto out;
15192 		}
15193 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15194 		hrq->RQ_rcv_buf++;
15195 		hrq->RQ_buf_posted--;
15196 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
15197 
15198 		/* Just some basic sanity checks on FCP Command frame */
15199 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
15200 			fc_hdr->fh_f_ctl[1] << 8 |
15201 			fc_hdr->fh_f_ctl[2]);
15202 		if (((fctl &
15203 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
15204 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
15205 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
15206 			goto drop;
15207 
15208 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
15209 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
15210 			lpfc_nvmet_unsol_fcp_event(
15211 				phba, idx, dma_buf, cq->isr_timestamp,
15212 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
15213 			return false;
15214 		}
15215 drop:
15216 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15217 		break;
15218 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
15219 		if (phba->nvmet_support) {
15220 			tgtp = phba->targetport->private;
15221 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15222 					"6401 RQE Error x%x, posted %d err_cnt "
15223 					"%d: %x %x %x\n",
15224 					status, hrq->RQ_buf_posted,
15225 					hrq->RQ_no_posted_buf,
15226 					atomic_read(&tgtp->rcv_fcp_cmd_in),
15227 					atomic_read(&tgtp->rcv_fcp_cmd_out),
15228 					atomic_read(&tgtp->xmt_fcp_release));
15229 		}
15230 		fallthrough;
15231 
15232 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
15233 		hrq->RQ_no_posted_buf++;
15234 		/* Post more buffers if possible */
15235 		break;
15236 	case FC_STATUS_RQ_DMA_FAILURE:
15237 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15238 				"2575 RQE DMA Error x%x, x%08x x%08x x%08x "
15239 				"x%08x\n",
15240 				status, rcqe->word0, rcqe->word1,
15241 				rcqe->word2, rcqe->word3);
15242 
15243 		/* If IV set, no further recovery */
15244 		if (bf_get(lpfc_rcqe_iv, rcqe))
15245 			break;
15246 
15247 		/* recycle consumed resource */
15248 		spin_lock_irqsave(&phba->hbalock, iflags);
15249 		lpfc_sli4_rq_release(hrq, drq);
15250 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15251 		if (!dma_buf) {
15252 			hrq->RQ_no_buf_found++;
15253 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15254 			break;
15255 		}
15256 		hrq->RQ_rcv_buf++;
15257 		hrq->RQ_buf_posted--;
15258 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15259 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15260 		break;
15261 	default:
15262 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15263 				"2576 Unexpected RQE Status x%x, w0-3 x%08x "
15264 				"x%08x x%08x x%08x\n",
15265 				status, rcqe->word0, rcqe->word1,
15266 				rcqe->word2, rcqe->word3);
15267 		break;
15268 	}
15269 out:
15270 	return workposted;
15271 }
15272 
15273 /**
15274  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
15275  * @phba: adapter with cq
15276  * @cq: Pointer to the completion queue.
15277  * @cqe: Pointer to fast-path completion queue entry.
15278  *
15279  * This routine process a fast-path work queue completion entry from fast-path
15280  * event queue for FCP command response completion.
15281  *
15282  * Return: true if work posted to worker thread, otherwise false.
15283  **/
15284 static bool
15285 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15286 			 struct lpfc_cqe *cqe)
15287 {
15288 	struct lpfc_wcqe_release wcqe;
15289 	bool workposted = false;
15290 
15291 	/* Copy the work queue CQE and convert endian order if needed */
15292 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
15293 
15294 	/* Check and process for different type of WCQE and dispatch */
15295 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
15296 	case CQE_CODE_COMPL_WQE:
15297 	case CQE_CODE_NVME_ERSP:
15298 		cq->CQ_wq++;
15299 		/* Process the WQ complete event */
15300 		phba->last_completion_time = jiffies;
15301 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
15302 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
15303 				(struct lpfc_wcqe_complete *)&wcqe);
15304 		break;
15305 	case CQE_CODE_RELEASE_WQE:
15306 		cq->CQ_release_wqe++;
15307 		/* Process the WQ release event */
15308 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
15309 				(struct lpfc_wcqe_release *)&wcqe);
15310 		break;
15311 	case CQE_CODE_XRI_ABORTED:
15312 		cq->CQ_xri_aborted++;
15313 		/* Process the WQ XRI abort event */
15314 		phba->last_completion_time = jiffies;
15315 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
15316 				(struct sli4_wcqe_xri_aborted *)&wcqe);
15317 		break;
15318 	case CQE_CODE_RECEIVE_V1:
15319 	case CQE_CODE_RECEIVE:
15320 		phba->last_completion_time = jiffies;
15321 		if (cq->subtype == LPFC_NVMET) {
15322 			workposted = lpfc_sli4_nvmet_handle_rcqe(
15323 				phba, cq, (struct lpfc_rcqe *)&wcqe);
15324 		}
15325 		break;
15326 	default:
15327 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15328 				"0144 Not a valid CQE code: x%x\n",
15329 				bf_get(lpfc_wcqe_c_code, &wcqe));
15330 		break;
15331 	}
15332 	return workposted;
15333 }
15334 
15335 /**
15336  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
15337  * @cq: Pointer to CQ to be processed
15338  *
15339  * This routine calls the cq processing routine with the handler for
15340  * fast path CQEs.
15341  *
15342  * The CQ routine returns two values: the first is the calling status,
15343  * which indicates whether work was queued to the  background discovery
15344  * thread. If true, the routine should wakeup the discovery thread;
15345  * the second is the delay parameter. If non-zero, rather than rearming
15346  * the CQ and yet another interrupt, the CQ handler should be queued so
15347  * that it is processed in a subsequent polling action. The value of
15348  * the delay indicates when to reschedule it.
15349  **/
15350 static void
15351 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq)
15352 {
15353 	struct lpfc_hba *phba = cq->phba;
15354 	unsigned long delay;
15355 	bool workposted = false;
15356 	int ret;
15357 
15358 	/* process and rearm the CQ */
15359 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
15360 					     &delay);
15361 
15362 	if (delay) {
15363 		if (is_kdump_kernel())
15364 			ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
15365 						delay);
15366 		else
15367 			ret = queue_delayed_work_on(cq->chann, phba->wq,
15368 						&cq->sched_irqwork, delay);
15369 		if (!ret)
15370 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15371 					"0367 Cannot schedule queue work "
15372 					"for cqid=%d on CPU %d\n",
15373 					cq->queue_id, cq->chann);
15374 	}
15375 
15376 	/* wake up worker thread if there are works to be done */
15377 	if (workposted)
15378 		lpfc_worker_wake_up(phba);
15379 }
15380 
15381 /**
15382  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
15383  *   interrupt
15384  * @work: pointer to work element
15385  *
15386  * translates from the work handler and calls the fast-path handler.
15387  **/
15388 static void
15389 lpfc_sli4_hba_process_cq(struct work_struct *work)
15390 {
15391 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
15392 
15393 	__lpfc_sli4_hba_process_cq(cq);
15394 }
15395 
15396 /**
15397  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
15398  * @phba: Pointer to HBA context object.
15399  * @eq: Pointer to the queue structure.
15400  * @eqe: Pointer to fast-path event queue entry.
15401  * @poll_mode: poll_mode to execute processing the cq.
15402  *
15403  * This routine process a event queue entry from the fast-path event queue.
15404  * It will check the MajorCode and MinorCode to determine this is for a
15405  * completion event on a completion queue, if not, an error shall be logged
15406  * and just return. Otherwise, it will get to the corresponding completion
15407  * queue and process all the entries on the completion queue, rearm the
15408  * completion queue, and then return.
15409  **/
15410 static void
15411 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
15412 			 struct lpfc_eqe *eqe, enum lpfc_poll_mode poll_mode)
15413 {
15414 	struct lpfc_queue *cq = NULL;
15415 	uint32_t qidx = eq->hdwq;
15416 	uint16_t cqid, id;
15417 	int ret;
15418 
15419 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
15420 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15421 				"0366 Not a valid completion "
15422 				"event: majorcode=x%x, minorcode=x%x\n",
15423 				bf_get_le32(lpfc_eqe_major_code, eqe),
15424 				bf_get_le32(lpfc_eqe_minor_code, eqe));
15425 		return;
15426 	}
15427 
15428 	/* Get the reference to the corresponding CQ */
15429 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
15430 
15431 	/* Use the fast lookup method first */
15432 	if (cqid <= phba->sli4_hba.cq_max) {
15433 		cq = phba->sli4_hba.cq_lookup[cqid];
15434 		if (cq)
15435 			goto  work_cq;
15436 	}
15437 
15438 	/* Next check for NVMET completion */
15439 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
15440 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
15441 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
15442 			/* Process NVMET unsol rcv */
15443 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
15444 			goto  process_cq;
15445 		}
15446 	}
15447 
15448 	if (phba->sli4_hba.nvmels_cq &&
15449 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
15450 		/* Process NVME unsol rcv */
15451 		cq = phba->sli4_hba.nvmels_cq;
15452 	}
15453 
15454 	/* Otherwise this is a Slow path event */
15455 	if (cq == NULL) {
15456 		lpfc_sli4_sp_handle_eqe(phba, eqe,
15457 					phba->sli4_hba.hdwq[qidx].hba_eq);
15458 		return;
15459 	}
15460 
15461 process_cq:
15462 	if (unlikely(cqid != cq->queue_id)) {
15463 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15464 				"0368 Miss-matched fast-path completion "
15465 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
15466 				cqid, cq->queue_id);
15467 		return;
15468 	}
15469 
15470 work_cq:
15471 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
15472 	if (phba->ktime_on)
15473 		cq->isr_timestamp = ktime_get_ns();
15474 	else
15475 		cq->isr_timestamp = 0;
15476 #endif
15477 
15478 	switch (poll_mode) {
15479 	case LPFC_THREADED_IRQ:
15480 		__lpfc_sli4_hba_process_cq(cq);
15481 		break;
15482 	case LPFC_QUEUE_WORK:
15483 	default:
15484 		if (is_kdump_kernel())
15485 			ret = queue_work(phba->wq, &cq->irqwork);
15486 		else
15487 			ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
15488 		if (!ret)
15489 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15490 					"0383 Cannot schedule queue work "
15491 					"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
15492 					cqid, cq->queue_id,
15493 					raw_smp_processor_id());
15494 		break;
15495 	}
15496 }
15497 
15498 /**
15499  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
15500  * @work: pointer to work element
15501  *
15502  * translates from the work handler and calls the fast-path handler.
15503  **/
15504 static void
15505 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
15506 {
15507 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15508 					struct lpfc_queue, sched_irqwork);
15509 
15510 	__lpfc_sli4_hba_process_cq(cq);
15511 }
15512 
15513 /**
15514  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
15515  * @irq: Interrupt number.
15516  * @dev_id: The device context pointer.
15517  *
15518  * This function is directly called from the PCI layer as an interrupt
15519  * service routine when device with SLI-4 interface spec is enabled with
15520  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
15521  * ring event in the HBA. However, when the device is enabled with either
15522  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
15523  * device-level interrupt handler. When the PCI slot is in error recovery
15524  * or the HBA is undergoing initialization, the interrupt handler will not
15525  * process the interrupt. The SCSI FCP fast-path ring event are handled in
15526  * the intrrupt context. This function is called without any lock held.
15527  * It gets the hbalock to access and update SLI data structures. Note that,
15528  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
15529  * equal to that of FCP CQ index.
15530  *
15531  * The link attention and ELS ring attention events are handled
15532  * by the worker thread. The interrupt handler signals the worker thread
15533  * and returns for these events. This function is called without any lock
15534  * held. It gets the hbalock to access and update SLI data structures.
15535  *
15536  * This function returns IRQ_HANDLED when interrupt is handled, IRQ_WAKE_THREAD
15537  * when interrupt is scheduled to be handled from a threaded irq context, or
15538  * else returns IRQ_NONE.
15539  **/
15540 irqreturn_t
15541 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
15542 {
15543 	struct lpfc_hba *phba;
15544 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
15545 	struct lpfc_queue *fpeq;
15546 	unsigned long iflag;
15547 	int hba_eqidx;
15548 	int ecount = 0;
15549 	struct lpfc_eq_intr_info *eqi;
15550 
15551 	/* Get the driver's phba structure from the dev_id */
15552 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
15553 	phba = hba_eq_hdl->phba;
15554 	hba_eqidx = hba_eq_hdl->idx;
15555 
15556 	if (unlikely(!phba))
15557 		return IRQ_NONE;
15558 	if (unlikely(!phba->sli4_hba.hdwq))
15559 		return IRQ_NONE;
15560 
15561 	/* Get to the EQ struct associated with this vector */
15562 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
15563 	if (unlikely(!fpeq))
15564 		return IRQ_NONE;
15565 
15566 	/* Check device state for handling interrupt */
15567 	if (unlikely(lpfc_intr_state_check(phba))) {
15568 		/* Check again for link_state with lock held */
15569 		spin_lock_irqsave(&phba->hbalock, iflag);
15570 		if (phba->link_state < LPFC_LINK_DOWN)
15571 			/* Flush, clear interrupt, and rearm the EQ */
15572 			lpfc_sli4_eqcq_flush(phba, fpeq);
15573 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15574 		return IRQ_NONE;
15575 	}
15576 
15577 	switch (fpeq->poll_mode) {
15578 	case LPFC_THREADED_IRQ:
15579 		/* CGN mgmt is mutually exclusive from irq processing */
15580 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
15581 			return IRQ_WAKE_THREAD;
15582 		fallthrough;
15583 	case LPFC_QUEUE_WORK:
15584 	default:
15585 		eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
15586 		eqi->icnt++;
15587 
15588 		fpeq->last_cpu = raw_smp_processor_id();
15589 
15590 		if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
15591 		    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
15592 		    phba->cfg_auto_imax &&
15593 		    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
15594 		    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
15595 			lpfc_sli4_mod_hba_eq_delay(phba, fpeq,
15596 						   LPFC_MAX_AUTO_EQ_DELAY);
15597 
15598 		/* process and rearm the EQ */
15599 		ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
15600 					      LPFC_QUEUE_WORK);
15601 
15602 		if (unlikely(ecount == 0)) {
15603 			fpeq->EQ_no_entry++;
15604 			if (phba->intr_type == MSIX)
15605 				/* MSI-X treated interrupt served as no EQ share INT */
15606 				lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15607 						"0358 MSI-X interrupt with no EQE\n");
15608 			else
15609 				/* Non MSI-X treated on interrupt as EQ share INT */
15610 				return IRQ_NONE;
15611 		}
15612 	}
15613 
15614 	return IRQ_HANDLED;
15615 } /* lpfc_sli4_hba_intr_handler */
15616 
15617 /**
15618  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
15619  * @irq: Interrupt number.
15620  * @dev_id: The device context pointer.
15621  *
15622  * This function is the device-level interrupt handler to device with SLI-4
15623  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
15624  * interrupt mode is enabled and there is an event in the HBA which requires
15625  * driver attention. This function invokes the slow-path interrupt attention
15626  * handling function and fast-path interrupt attention handling function in
15627  * turn to process the relevant HBA attention events. This function is called
15628  * without any lock held. It gets the hbalock to access and update SLI data
15629  * structures.
15630  *
15631  * This function returns IRQ_HANDLED when interrupt is handled, else it
15632  * returns IRQ_NONE.
15633  **/
15634 irqreturn_t
15635 lpfc_sli4_intr_handler(int irq, void *dev_id)
15636 {
15637 	struct lpfc_hba  *phba;
15638 	irqreturn_t hba_irq_rc;
15639 	bool hba_handled = false;
15640 	int qidx;
15641 
15642 	/* Get the driver's phba structure from the dev_id */
15643 	phba = (struct lpfc_hba *)dev_id;
15644 
15645 	if (unlikely(!phba))
15646 		return IRQ_NONE;
15647 
15648 	/*
15649 	 * Invoke fast-path host attention interrupt handling as appropriate.
15650 	 */
15651 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
15652 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
15653 					&phba->sli4_hba.hba_eq_hdl[qidx]);
15654 		if (hba_irq_rc == IRQ_HANDLED)
15655 			hba_handled |= true;
15656 	}
15657 
15658 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
15659 } /* lpfc_sli4_intr_handler */
15660 
15661 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
15662 {
15663 	struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
15664 	struct lpfc_queue *eq;
15665 
15666 	rcu_read_lock();
15667 
15668 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
15669 		lpfc_sli4_poll_eq(eq);
15670 	if (!list_empty(&phba->poll_list))
15671 		mod_timer(&phba->cpuhp_poll_timer,
15672 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15673 
15674 	rcu_read_unlock();
15675 }
15676 
15677 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
15678 {
15679 	struct lpfc_hba *phba = eq->phba;
15680 
15681 	/* kickstart slowpath processing if needed */
15682 	if (list_empty(&phba->poll_list))
15683 		mod_timer(&phba->cpuhp_poll_timer,
15684 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15685 
15686 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
15687 	synchronize_rcu();
15688 }
15689 
15690 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
15691 {
15692 	struct lpfc_hba *phba = eq->phba;
15693 
15694 	/* Disable slowpath processing for this eq.  Kick start the eq
15695 	 * by RE-ARMING the eq's ASAP
15696 	 */
15697 	list_del_rcu(&eq->_poll_list);
15698 	synchronize_rcu();
15699 
15700 	if (list_empty(&phba->poll_list))
15701 		del_timer_sync(&phba->cpuhp_poll_timer);
15702 }
15703 
15704 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
15705 {
15706 	struct lpfc_queue *eq, *next;
15707 
15708 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
15709 		list_del(&eq->_poll_list);
15710 
15711 	INIT_LIST_HEAD(&phba->poll_list);
15712 	synchronize_rcu();
15713 }
15714 
15715 static inline void
15716 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
15717 {
15718 	if (mode == eq->mode)
15719 		return;
15720 	/*
15721 	 * currently this function is only called during a hotplug
15722 	 * event and the cpu on which this function is executing
15723 	 * is going offline.  By now the hotplug has instructed
15724 	 * the scheduler to remove this cpu from cpu active mask.
15725 	 * So we don't need to work about being put aside by the
15726 	 * scheduler for a high priority process.  Yes, the inte-
15727 	 * rrupts could come but they are known to retire ASAP.
15728 	 */
15729 
15730 	/* Disable polling in the fastpath */
15731 	WRITE_ONCE(eq->mode, mode);
15732 	/* flush out the store buffer */
15733 	smp_wmb();
15734 
15735 	/*
15736 	 * Add this eq to the polling list and start polling. For
15737 	 * a grace period both interrupt handler and poller will
15738 	 * try to process the eq _but_ that's fine.  We have a
15739 	 * synchronization mechanism in place (queue_claimed) to
15740 	 * deal with it.  This is just a draining phase for int-
15741 	 * errupt handler (not eq's) as we have guranteed through
15742 	 * barrier that all the CPUs have seen the new CQ_POLLED
15743 	 * state. which will effectively disable the REARMING of
15744 	 * the EQ.  The whole idea is eq's die off eventually as
15745 	 * we are not rearming EQ's anymore.
15746 	 */
15747 	mode ? lpfc_sli4_add_to_poll_list(eq) :
15748 	       lpfc_sli4_remove_from_poll_list(eq);
15749 }
15750 
15751 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15752 {
15753 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15754 }
15755 
15756 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15757 {
15758 	struct lpfc_hba *phba = eq->phba;
15759 
15760 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15761 
15762 	/* Kick start for the pending io's in h/w.
15763 	 * Once we switch back to interrupt processing on a eq
15764 	 * the io path completion will only arm eq's when it
15765 	 * receives a completion.  But since eq's are in disa-
15766 	 * rmed state it doesn't receive a completion.  This
15767 	 * creates a deadlock scenaro.
15768 	 */
15769 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15770 }
15771 
15772 /**
15773  * lpfc_sli4_queue_free - free a queue structure and associated memory
15774  * @queue: The queue structure to free.
15775  *
15776  * This function frees a queue structure and the DMAable memory used for
15777  * the host resident queue. This function must be called after destroying the
15778  * queue on the HBA.
15779  **/
15780 void
15781 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15782 {
15783 	struct lpfc_dmabuf *dmabuf;
15784 
15785 	if (!queue)
15786 		return;
15787 
15788 	if (!list_empty(&queue->wq_list))
15789 		list_del(&queue->wq_list);
15790 
15791 	while (!list_empty(&queue->page_list)) {
15792 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15793 				 list);
15794 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15795 				  dmabuf->virt, dmabuf->phys);
15796 		kfree(dmabuf);
15797 	}
15798 	if (queue->rqbp) {
15799 		lpfc_free_rq_buffer(queue->phba, queue);
15800 		kfree(queue->rqbp);
15801 	}
15802 
15803 	if (!list_empty(&queue->cpu_list))
15804 		list_del(&queue->cpu_list);
15805 
15806 	kfree(queue);
15807 	return;
15808 }
15809 
15810 /**
15811  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15812  * @phba: The HBA that this queue is being created on.
15813  * @page_size: The size of a queue page
15814  * @entry_size: The size of each queue entry for this queue.
15815  * @entry_count: The number of entries that this queue will handle.
15816  * @cpu: The cpu that will primarily utilize this queue.
15817  *
15818  * This function allocates a queue structure and the DMAable memory used for
15819  * the host resident queue. This function must be called before creating the
15820  * queue on the HBA.
15821  **/
15822 struct lpfc_queue *
15823 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15824 		      uint32_t entry_size, uint32_t entry_count, int cpu)
15825 {
15826 	struct lpfc_queue *queue;
15827 	struct lpfc_dmabuf *dmabuf;
15828 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15829 	uint16_t x, pgcnt;
15830 
15831 	if (!phba->sli4_hba.pc_sli4_params.supported)
15832 		hw_page_size = page_size;
15833 
15834 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15835 
15836 	/* If needed, Adjust page count to match the max the adapter supports */
15837 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15838 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15839 
15840 	queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
15841 			     GFP_KERNEL, cpu_to_node(cpu));
15842 	if (!queue)
15843 		return NULL;
15844 
15845 	INIT_LIST_HEAD(&queue->list);
15846 	INIT_LIST_HEAD(&queue->_poll_list);
15847 	INIT_LIST_HEAD(&queue->wq_list);
15848 	INIT_LIST_HEAD(&queue->wqfull_list);
15849 	INIT_LIST_HEAD(&queue->page_list);
15850 	INIT_LIST_HEAD(&queue->child_list);
15851 	INIT_LIST_HEAD(&queue->cpu_list);
15852 
15853 	/* Set queue parameters now.  If the system cannot provide memory
15854 	 * resources, the free routine needs to know what was allocated.
15855 	 */
15856 	queue->page_count = pgcnt;
15857 	queue->q_pgs = (void **)&queue[1];
15858 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
15859 	queue->entry_size = entry_size;
15860 	queue->entry_count = entry_count;
15861 	queue->page_size = hw_page_size;
15862 	queue->phba = phba;
15863 
15864 	for (x = 0; x < queue->page_count; x++) {
15865 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15866 				      dev_to_node(&phba->pcidev->dev));
15867 		if (!dmabuf)
15868 			goto out_fail;
15869 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15870 						  hw_page_size, &dmabuf->phys,
15871 						  GFP_KERNEL);
15872 		if (!dmabuf->virt) {
15873 			kfree(dmabuf);
15874 			goto out_fail;
15875 		}
15876 		dmabuf->buffer_tag = x;
15877 		list_add_tail(&dmabuf->list, &queue->page_list);
15878 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
15879 		queue->q_pgs[x] = dmabuf->virt;
15880 	}
15881 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15882 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15883 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15884 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15885 
15886 	/* notify_interval will be set during q creation */
15887 
15888 	return queue;
15889 out_fail:
15890 	lpfc_sli4_queue_free(queue);
15891 	return NULL;
15892 }
15893 
15894 /**
15895  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15896  * @phba: HBA structure that indicates port to create a queue on.
15897  * @pci_barset: PCI BAR set flag.
15898  *
15899  * This function shall perform iomap of the specified PCI BAR address to host
15900  * memory address if not already done so and return it. The returned host
15901  * memory address can be NULL.
15902  */
15903 static void __iomem *
15904 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15905 {
15906 	if (!phba->pcidev)
15907 		return NULL;
15908 
15909 	switch (pci_barset) {
15910 	case WQ_PCI_BAR_0_AND_1:
15911 		return phba->pci_bar0_memmap_p;
15912 	case WQ_PCI_BAR_2_AND_3:
15913 		return phba->pci_bar2_memmap_p;
15914 	case WQ_PCI_BAR_4_AND_5:
15915 		return phba->pci_bar4_memmap_p;
15916 	default:
15917 		break;
15918 	}
15919 	return NULL;
15920 }
15921 
15922 /**
15923  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
15924  * @phba: HBA structure that EQs are on.
15925  * @startq: The starting EQ index to modify
15926  * @numq: The number of EQs (consecutive indexes) to modify
15927  * @usdelay: amount of delay
15928  *
15929  * This function revises the EQ delay on 1 or more EQs. The EQ delay
15930  * is set either by writing to a register (if supported by the SLI Port)
15931  * or by mailbox command. The mailbox command allows several EQs to be
15932  * updated at once.
15933  *
15934  * The @phba struct is used to send a mailbox command to HBA. The @startq
15935  * is used to get the starting EQ index to change. The @numq value is
15936  * used to specify how many consecutive EQ indexes, starting at EQ index,
15937  * are to be changed. This function is asynchronous and will wait for any
15938  * mailbox commands to finish before returning.
15939  *
15940  * On success this function will return a zero. If unable to allocate
15941  * enough memory this function will return -ENOMEM. If a mailbox command
15942  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
15943  * have had their delay multipler changed.
15944  **/
15945 void
15946 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
15947 			 uint32_t numq, uint32_t usdelay)
15948 {
15949 	struct lpfc_mbx_modify_eq_delay *eq_delay;
15950 	LPFC_MBOXQ_t *mbox;
15951 	struct lpfc_queue *eq;
15952 	int cnt = 0, rc, length;
15953 	uint32_t shdr_status, shdr_add_status;
15954 	uint32_t dmult;
15955 	int qidx;
15956 	union lpfc_sli4_cfg_shdr *shdr;
15957 
15958 	if (startq >= phba->cfg_irq_chann)
15959 		return;
15960 
15961 	if (usdelay > 0xFFFF) {
15962 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
15963 				"6429 usdelay %d too large. Scaled down to "
15964 				"0xFFFF.\n", usdelay);
15965 		usdelay = 0xFFFF;
15966 	}
15967 
15968 	/* set values by EQ_DELAY register if supported */
15969 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
15970 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15971 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15972 			if (!eq)
15973 				continue;
15974 
15975 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
15976 
15977 			if (++cnt >= numq)
15978 				break;
15979 		}
15980 		return;
15981 	}
15982 
15983 	/* Otherwise, set values by mailbox cmd */
15984 
15985 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15986 	if (!mbox) {
15987 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15988 				"6428 Failed allocating mailbox cmd buffer."
15989 				" EQ delay was not set.\n");
15990 		return;
15991 	}
15992 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
15993 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15994 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15995 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
15996 			 length, LPFC_SLI4_MBX_EMBED);
15997 	eq_delay = &mbox->u.mqe.un.eq_delay;
15998 
15999 	/* Calculate delay multiper from maximum interrupt per second */
16000 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
16001 	if (dmult)
16002 		dmult--;
16003 	if (dmult > LPFC_DMULT_MAX)
16004 		dmult = LPFC_DMULT_MAX;
16005 
16006 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
16007 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
16008 		if (!eq)
16009 			continue;
16010 		eq->q_mode = usdelay;
16011 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
16012 		eq_delay->u.request.eq[cnt].phase = 0;
16013 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
16014 
16015 		if (++cnt >= numq)
16016 			break;
16017 	}
16018 	eq_delay->u.request.num_eq = cnt;
16019 
16020 	mbox->vport = phba->pport;
16021 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16022 	mbox->ctx_ndlp = NULL;
16023 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16024 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
16025 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16026 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16027 	if (shdr_status || shdr_add_status || rc) {
16028 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16029 				"2512 MODIFY_EQ_DELAY mailbox failed with "
16030 				"status x%x add_status x%x, mbx status x%x\n",
16031 				shdr_status, shdr_add_status, rc);
16032 	}
16033 	mempool_free(mbox, phba->mbox_mem_pool);
16034 	return;
16035 }
16036 
16037 /**
16038  * lpfc_eq_create - Create an Event Queue on the HBA
16039  * @phba: HBA structure that indicates port to create a queue on.
16040  * @eq: The queue structure to use to create the event queue.
16041  * @imax: The maximum interrupt per second limit.
16042  *
16043  * This function creates an event queue, as detailed in @eq, on a port,
16044  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
16045  *
16046  * The @phba struct is used to send mailbox command to HBA. The @eq struct
16047  * is used to get the entry count and entry size that are necessary to
16048  * determine the number of pages to allocate and use for this queue. This
16049  * function will send the EQ_CREATE mailbox command to the HBA to setup the
16050  * event queue. This function is asynchronous and will wait for the mailbox
16051  * command to finish before continuing.
16052  *
16053  * On success this function will return a zero. If unable to allocate enough
16054  * memory this function will return -ENOMEM. If the queue create mailbox command
16055  * fails this function will return -ENXIO.
16056  **/
16057 int
16058 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
16059 {
16060 	struct lpfc_mbx_eq_create *eq_create;
16061 	LPFC_MBOXQ_t *mbox;
16062 	int rc, length, status = 0;
16063 	struct lpfc_dmabuf *dmabuf;
16064 	uint32_t shdr_status, shdr_add_status;
16065 	union lpfc_sli4_cfg_shdr *shdr;
16066 	uint16_t dmult;
16067 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16068 
16069 	/* sanity check on queue memory */
16070 	if (!eq)
16071 		return -ENODEV;
16072 	if (!phba->sli4_hba.pc_sli4_params.supported)
16073 		hw_page_size = SLI4_PAGE_SIZE;
16074 
16075 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16076 	if (!mbox)
16077 		return -ENOMEM;
16078 	length = (sizeof(struct lpfc_mbx_eq_create) -
16079 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16080 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16081 			 LPFC_MBOX_OPCODE_EQ_CREATE,
16082 			 length, LPFC_SLI4_MBX_EMBED);
16083 	eq_create = &mbox->u.mqe.un.eq_create;
16084 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
16085 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
16086 	       eq->page_count);
16087 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
16088 	       LPFC_EQE_SIZE);
16089 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
16090 
16091 	/* Use version 2 of CREATE_EQ if eqav is set */
16092 	if (phba->sli4_hba.pc_sli4_params.eqav) {
16093 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16094 		       LPFC_Q_CREATE_VERSION_2);
16095 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
16096 		       phba->sli4_hba.pc_sli4_params.eqav);
16097 	}
16098 
16099 	/* don't setup delay multiplier using EQ_CREATE */
16100 	dmult = 0;
16101 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
16102 	       dmult);
16103 	switch (eq->entry_count) {
16104 	default:
16105 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16106 				"0360 Unsupported EQ count. (%d)\n",
16107 				eq->entry_count);
16108 		if (eq->entry_count < 256) {
16109 			status = -EINVAL;
16110 			goto out;
16111 		}
16112 		fallthrough;	/* otherwise default to smallest count */
16113 	case 256:
16114 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16115 		       LPFC_EQ_CNT_256);
16116 		break;
16117 	case 512:
16118 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16119 		       LPFC_EQ_CNT_512);
16120 		break;
16121 	case 1024:
16122 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16123 		       LPFC_EQ_CNT_1024);
16124 		break;
16125 	case 2048:
16126 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16127 		       LPFC_EQ_CNT_2048);
16128 		break;
16129 	case 4096:
16130 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16131 		       LPFC_EQ_CNT_4096);
16132 		break;
16133 	}
16134 	list_for_each_entry(dmabuf, &eq->page_list, list) {
16135 		memset(dmabuf->virt, 0, hw_page_size);
16136 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16137 					putPaddrLow(dmabuf->phys);
16138 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16139 					putPaddrHigh(dmabuf->phys);
16140 	}
16141 	mbox->vport = phba->pport;
16142 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16143 	mbox->ctx_buf = NULL;
16144 	mbox->ctx_ndlp = NULL;
16145 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16146 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16147 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16148 	if (shdr_status || shdr_add_status || rc) {
16149 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16150 				"2500 EQ_CREATE mailbox failed with "
16151 				"status x%x add_status x%x, mbx status x%x\n",
16152 				shdr_status, shdr_add_status, rc);
16153 		status = -ENXIO;
16154 	}
16155 	eq->type = LPFC_EQ;
16156 	eq->subtype = LPFC_NONE;
16157 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
16158 	if (eq->queue_id == 0xFFFF)
16159 		status = -ENXIO;
16160 	eq->host_index = 0;
16161 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
16162 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
16163 out:
16164 	mempool_free(mbox, phba->mbox_mem_pool);
16165 	return status;
16166 }
16167 
16168 /**
16169  * lpfc_sli4_hba_intr_handler_th - SLI4 HBA threaded interrupt handler
16170  * @irq: Interrupt number.
16171  * @dev_id: The device context pointer.
16172  *
16173  * This routine is a mirror of lpfc_sli4_hba_intr_handler, but executed within
16174  * threaded irq context.
16175  *
16176  * Returns
16177  * IRQ_HANDLED - interrupt is handled
16178  * IRQ_NONE - otherwise
16179  **/
16180 irqreturn_t lpfc_sli4_hba_intr_handler_th(int irq, void *dev_id)
16181 {
16182 	struct lpfc_hba *phba;
16183 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
16184 	struct lpfc_queue *fpeq;
16185 	int ecount = 0;
16186 	int hba_eqidx;
16187 	struct lpfc_eq_intr_info *eqi;
16188 
16189 	/* Get the driver's phba structure from the dev_id */
16190 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
16191 	phba = hba_eq_hdl->phba;
16192 	hba_eqidx = hba_eq_hdl->idx;
16193 
16194 	if (unlikely(!phba))
16195 		return IRQ_NONE;
16196 	if (unlikely(!phba->sli4_hba.hdwq))
16197 		return IRQ_NONE;
16198 
16199 	/* Get to the EQ struct associated with this vector */
16200 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
16201 	if (unlikely(!fpeq))
16202 		return IRQ_NONE;
16203 
16204 	eqi = per_cpu_ptr(phba->sli4_hba.eq_info, raw_smp_processor_id());
16205 	eqi->icnt++;
16206 
16207 	fpeq->last_cpu = raw_smp_processor_id();
16208 
16209 	if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
16210 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
16211 	    phba->cfg_auto_imax &&
16212 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
16213 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
16214 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
16215 
16216 	/* process and rearm the EQ */
16217 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
16218 				      LPFC_THREADED_IRQ);
16219 
16220 	if (unlikely(ecount == 0)) {
16221 		fpeq->EQ_no_entry++;
16222 		if (phba->intr_type == MSIX)
16223 			/* MSI-X treated interrupt served as no EQ share INT */
16224 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
16225 					"3358 MSI-X interrupt with no EQE\n");
16226 		else
16227 			/* Non MSI-X treated on interrupt as EQ share INT */
16228 			return IRQ_NONE;
16229 	}
16230 	return IRQ_HANDLED;
16231 }
16232 
16233 /**
16234  * lpfc_cq_create - Create a Completion Queue on the HBA
16235  * @phba: HBA structure that indicates port to create a queue on.
16236  * @cq: The queue structure to use to create the completion queue.
16237  * @eq: The event queue to bind this completion queue to.
16238  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16239  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16240  *
16241  * This function creates a completion queue, as detailed in @wq, on a port,
16242  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
16243  *
16244  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16245  * is used to get the entry count and entry size that are necessary to
16246  * determine the number of pages to allocate and use for this queue. The @eq
16247  * is used to indicate which event queue to bind this completion queue to. This
16248  * function will send the CQ_CREATE mailbox command to the HBA to setup the
16249  * completion queue. This function is asynchronous and will wait for the mailbox
16250  * command to finish before continuing.
16251  *
16252  * On success this function will return a zero. If unable to allocate enough
16253  * memory this function will return -ENOMEM. If the queue create mailbox command
16254  * fails this function will return -ENXIO.
16255  **/
16256 int
16257 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
16258 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
16259 {
16260 	struct lpfc_mbx_cq_create *cq_create;
16261 	struct lpfc_dmabuf *dmabuf;
16262 	LPFC_MBOXQ_t *mbox;
16263 	int rc, length, status = 0;
16264 	uint32_t shdr_status, shdr_add_status;
16265 	union lpfc_sli4_cfg_shdr *shdr;
16266 
16267 	/* sanity check on queue memory */
16268 	if (!cq || !eq)
16269 		return -ENODEV;
16270 
16271 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16272 	if (!mbox)
16273 		return -ENOMEM;
16274 	length = (sizeof(struct lpfc_mbx_cq_create) -
16275 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16276 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16277 			 LPFC_MBOX_OPCODE_CQ_CREATE,
16278 			 length, LPFC_SLI4_MBX_EMBED);
16279 	cq_create = &mbox->u.mqe.un.cq_create;
16280 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
16281 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
16282 		    cq->page_count);
16283 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
16284 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
16285 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16286 	       phba->sli4_hba.pc_sli4_params.cqv);
16287 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
16288 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
16289 		       (cq->page_size / SLI4_PAGE_SIZE));
16290 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
16291 		       eq->queue_id);
16292 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
16293 		       phba->sli4_hba.pc_sli4_params.cqav);
16294 	} else {
16295 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
16296 		       eq->queue_id);
16297 	}
16298 	switch (cq->entry_count) {
16299 	case 2048:
16300 	case 4096:
16301 		if (phba->sli4_hba.pc_sli4_params.cqv ==
16302 		    LPFC_Q_CREATE_VERSION_2) {
16303 			cq_create->u.request.context.lpfc_cq_context_count =
16304 				cq->entry_count;
16305 			bf_set(lpfc_cq_context_count,
16306 			       &cq_create->u.request.context,
16307 			       LPFC_CQ_CNT_WORD7);
16308 			break;
16309 		}
16310 		fallthrough;
16311 	default:
16312 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16313 				"0361 Unsupported CQ count: "
16314 				"entry cnt %d sz %d pg cnt %d\n",
16315 				cq->entry_count, cq->entry_size,
16316 				cq->page_count);
16317 		if (cq->entry_count < 256) {
16318 			status = -EINVAL;
16319 			goto out;
16320 		}
16321 		fallthrough;	/* otherwise default to smallest count */
16322 	case 256:
16323 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16324 		       LPFC_CQ_CNT_256);
16325 		break;
16326 	case 512:
16327 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16328 		       LPFC_CQ_CNT_512);
16329 		break;
16330 	case 1024:
16331 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16332 		       LPFC_CQ_CNT_1024);
16333 		break;
16334 	}
16335 	list_for_each_entry(dmabuf, &cq->page_list, list) {
16336 		memset(dmabuf->virt, 0, cq->page_size);
16337 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16338 					putPaddrLow(dmabuf->phys);
16339 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16340 					putPaddrHigh(dmabuf->phys);
16341 	}
16342 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16343 
16344 	/* The IOCTL status is embedded in the mailbox subheader. */
16345 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16346 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16347 	if (shdr_status || shdr_add_status || rc) {
16348 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16349 				"2501 CQ_CREATE mailbox failed with "
16350 				"status x%x add_status x%x, mbx status x%x\n",
16351 				shdr_status, shdr_add_status, rc);
16352 		status = -ENXIO;
16353 		goto out;
16354 	}
16355 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16356 	if (cq->queue_id == 0xFFFF) {
16357 		status = -ENXIO;
16358 		goto out;
16359 	}
16360 	/* link the cq onto the parent eq child list */
16361 	list_add_tail(&cq->list, &eq->child_list);
16362 	/* Set up completion queue's type and subtype */
16363 	cq->type = type;
16364 	cq->subtype = subtype;
16365 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16366 	cq->assoc_qid = eq->queue_id;
16367 	cq->assoc_qp = eq;
16368 	cq->host_index = 0;
16369 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16370 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
16371 
16372 	if (cq->queue_id > phba->sli4_hba.cq_max)
16373 		phba->sli4_hba.cq_max = cq->queue_id;
16374 out:
16375 	mempool_free(mbox, phba->mbox_mem_pool);
16376 	return status;
16377 }
16378 
16379 /**
16380  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
16381  * @phba: HBA structure that indicates port to create a queue on.
16382  * @cqp: The queue structure array to use to create the completion queues.
16383  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
16384  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16385  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16386  *
16387  * This function creates a set of  completion queue, s to support MRQ
16388  * as detailed in @cqp, on a port,
16389  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
16390  *
16391  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16392  * is used to get the entry count and entry size that are necessary to
16393  * determine the number of pages to allocate and use for this queue. The @eq
16394  * is used to indicate which event queue to bind this completion queue to. This
16395  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
16396  * completion queue. This function is asynchronous and will wait for the mailbox
16397  * command to finish before continuing.
16398  *
16399  * On success this function will return a zero. If unable to allocate enough
16400  * memory this function will return -ENOMEM. If the queue create mailbox command
16401  * fails this function will return -ENXIO.
16402  **/
16403 int
16404 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
16405 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
16406 		   uint32_t subtype)
16407 {
16408 	struct lpfc_queue *cq;
16409 	struct lpfc_queue *eq;
16410 	struct lpfc_mbx_cq_create_set *cq_set;
16411 	struct lpfc_dmabuf *dmabuf;
16412 	LPFC_MBOXQ_t *mbox;
16413 	int rc, length, alloclen, status = 0;
16414 	int cnt, idx, numcq, page_idx = 0;
16415 	uint32_t shdr_status, shdr_add_status;
16416 	union lpfc_sli4_cfg_shdr *shdr;
16417 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16418 
16419 	/* sanity check on queue memory */
16420 	numcq = phba->cfg_nvmet_mrq;
16421 	if (!cqp || !hdwq || !numcq)
16422 		return -ENODEV;
16423 
16424 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16425 	if (!mbox)
16426 		return -ENOMEM;
16427 
16428 	length = sizeof(struct lpfc_mbx_cq_create_set);
16429 	length += ((numcq * cqp[0]->page_count) *
16430 		   sizeof(struct dma_address));
16431 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16432 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
16433 			LPFC_SLI4_MBX_NEMBED);
16434 	if (alloclen < length) {
16435 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16436 				"3098 Allocated DMA memory size (%d) is "
16437 				"less than the requested DMA memory size "
16438 				"(%d)\n", alloclen, length);
16439 		status = -ENOMEM;
16440 		goto out;
16441 	}
16442 	cq_set = mbox->sge_array->addr[0];
16443 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
16444 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
16445 
16446 	for (idx = 0; idx < numcq; idx++) {
16447 		cq = cqp[idx];
16448 		eq = hdwq[idx].hba_eq;
16449 		if (!cq || !eq) {
16450 			status = -ENOMEM;
16451 			goto out;
16452 		}
16453 		if (!phba->sli4_hba.pc_sli4_params.supported)
16454 			hw_page_size = cq->page_size;
16455 
16456 		switch (idx) {
16457 		case 0:
16458 			bf_set(lpfc_mbx_cq_create_set_page_size,
16459 			       &cq_set->u.request,
16460 			       (hw_page_size / SLI4_PAGE_SIZE));
16461 			bf_set(lpfc_mbx_cq_create_set_num_pages,
16462 			       &cq_set->u.request, cq->page_count);
16463 			bf_set(lpfc_mbx_cq_create_set_evt,
16464 			       &cq_set->u.request, 1);
16465 			bf_set(lpfc_mbx_cq_create_set_valid,
16466 			       &cq_set->u.request, 1);
16467 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
16468 			       &cq_set->u.request, 0);
16469 			bf_set(lpfc_mbx_cq_create_set_num_cq,
16470 			       &cq_set->u.request, numcq);
16471 			bf_set(lpfc_mbx_cq_create_set_autovalid,
16472 			       &cq_set->u.request,
16473 			       phba->sli4_hba.pc_sli4_params.cqav);
16474 			switch (cq->entry_count) {
16475 			case 2048:
16476 			case 4096:
16477 				if (phba->sli4_hba.pc_sli4_params.cqv ==
16478 				    LPFC_Q_CREATE_VERSION_2) {
16479 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16480 					       &cq_set->u.request,
16481 						cq->entry_count);
16482 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16483 					       &cq_set->u.request,
16484 					       LPFC_CQ_CNT_WORD7);
16485 					break;
16486 				}
16487 				fallthrough;
16488 			default:
16489 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16490 						"3118 Bad CQ count. (%d)\n",
16491 						cq->entry_count);
16492 				if (cq->entry_count < 256) {
16493 					status = -EINVAL;
16494 					goto out;
16495 				}
16496 				fallthrough;	/* otherwise default to smallest */
16497 			case 256:
16498 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16499 				       &cq_set->u.request, LPFC_CQ_CNT_256);
16500 				break;
16501 			case 512:
16502 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16503 				       &cq_set->u.request, LPFC_CQ_CNT_512);
16504 				break;
16505 			case 1024:
16506 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16507 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
16508 				break;
16509 			}
16510 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
16511 			       &cq_set->u.request, eq->queue_id);
16512 			break;
16513 		case 1:
16514 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
16515 			       &cq_set->u.request, eq->queue_id);
16516 			break;
16517 		case 2:
16518 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
16519 			       &cq_set->u.request, eq->queue_id);
16520 			break;
16521 		case 3:
16522 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
16523 			       &cq_set->u.request, eq->queue_id);
16524 			break;
16525 		case 4:
16526 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
16527 			       &cq_set->u.request, eq->queue_id);
16528 			break;
16529 		case 5:
16530 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
16531 			       &cq_set->u.request, eq->queue_id);
16532 			break;
16533 		case 6:
16534 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
16535 			       &cq_set->u.request, eq->queue_id);
16536 			break;
16537 		case 7:
16538 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
16539 			       &cq_set->u.request, eq->queue_id);
16540 			break;
16541 		case 8:
16542 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
16543 			       &cq_set->u.request, eq->queue_id);
16544 			break;
16545 		case 9:
16546 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
16547 			       &cq_set->u.request, eq->queue_id);
16548 			break;
16549 		case 10:
16550 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
16551 			       &cq_set->u.request, eq->queue_id);
16552 			break;
16553 		case 11:
16554 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
16555 			       &cq_set->u.request, eq->queue_id);
16556 			break;
16557 		case 12:
16558 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
16559 			       &cq_set->u.request, eq->queue_id);
16560 			break;
16561 		case 13:
16562 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
16563 			       &cq_set->u.request, eq->queue_id);
16564 			break;
16565 		case 14:
16566 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
16567 			       &cq_set->u.request, eq->queue_id);
16568 			break;
16569 		case 15:
16570 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
16571 			       &cq_set->u.request, eq->queue_id);
16572 			break;
16573 		}
16574 
16575 		/* link the cq onto the parent eq child list */
16576 		list_add_tail(&cq->list, &eq->child_list);
16577 		/* Set up completion queue's type and subtype */
16578 		cq->type = type;
16579 		cq->subtype = subtype;
16580 		cq->assoc_qid = eq->queue_id;
16581 		cq->assoc_qp = eq;
16582 		cq->host_index = 0;
16583 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16584 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
16585 					 cq->entry_count);
16586 		cq->chann = idx;
16587 
16588 		rc = 0;
16589 		list_for_each_entry(dmabuf, &cq->page_list, list) {
16590 			memset(dmabuf->virt, 0, hw_page_size);
16591 			cnt = page_idx + dmabuf->buffer_tag;
16592 			cq_set->u.request.page[cnt].addr_lo =
16593 					putPaddrLow(dmabuf->phys);
16594 			cq_set->u.request.page[cnt].addr_hi =
16595 					putPaddrHigh(dmabuf->phys);
16596 			rc++;
16597 		}
16598 		page_idx += rc;
16599 	}
16600 
16601 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16602 
16603 	/* The IOCTL status is embedded in the mailbox subheader. */
16604 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16605 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16606 	if (shdr_status || shdr_add_status || rc) {
16607 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16608 				"3119 CQ_CREATE_SET mailbox failed with "
16609 				"status x%x add_status x%x, mbx status x%x\n",
16610 				shdr_status, shdr_add_status, rc);
16611 		status = -ENXIO;
16612 		goto out;
16613 	}
16614 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
16615 	if (rc == 0xFFFF) {
16616 		status = -ENXIO;
16617 		goto out;
16618 	}
16619 
16620 	for (idx = 0; idx < numcq; idx++) {
16621 		cq = cqp[idx];
16622 		cq->queue_id = rc + idx;
16623 		if (cq->queue_id > phba->sli4_hba.cq_max)
16624 			phba->sli4_hba.cq_max = cq->queue_id;
16625 	}
16626 
16627 out:
16628 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16629 	return status;
16630 }
16631 
16632 /**
16633  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
16634  * @phba: HBA structure that indicates port to create a queue on.
16635  * @mq: The queue structure to use to create the mailbox queue.
16636  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
16637  * @cq: The completion queue to associate with this cq.
16638  *
16639  * This function provides failback (fb) functionality when the
16640  * mq_create_ext fails on older FW generations.  It's purpose is identical
16641  * to mq_create_ext otherwise.
16642  *
16643  * This routine cannot fail as all attributes were previously accessed and
16644  * initialized in mq_create_ext.
16645  **/
16646 static void
16647 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
16648 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
16649 {
16650 	struct lpfc_mbx_mq_create *mq_create;
16651 	struct lpfc_dmabuf *dmabuf;
16652 	int length;
16653 
16654 	length = (sizeof(struct lpfc_mbx_mq_create) -
16655 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16656 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16657 			 LPFC_MBOX_OPCODE_MQ_CREATE,
16658 			 length, LPFC_SLI4_MBX_EMBED);
16659 	mq_create = &mbox->u.mqe.un.mq_create;
16660 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
16661 	       mq->page_count);
16662 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
16663 	       cq->queue_id);
16664 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
16665 	switch (mq->entry_count) {
16666 	case 16:
16667 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16668 		       LPFC_MQ_RING_SIZE_16);
16669 		break;
16670 	case 32:
16671 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16672 		       LPFC_MQ_RING_SIZE_32);
16673 		break;
16674 	case 64:
16675 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16676 		       LPFC_MQ_RING_SIZE_64);
16677 		break;
16678 	case 128:
16679 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16680 		       LPFC_MQ_RING_SIZE_128);
16681 		break;
16682 	}
16683 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16684 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16685 			putPaddrLow(dmabuf->phys);
16686 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16687 			putPaddrHigh(dmabuf->phys);
16688 	}
16689 }
16690 
16691 /**
16692  * lpfc_mq_create - Create a mailbox Queue on the HBA
16693  * @phba: HBA structure that indicates port to create a queue on.
16694  * @mq: The queue structure to use to create the mailbox queue.
16695  * @cq: The completion queue to associate with this cq.
16696  * @subtype: The queue's subtype.
16697  *
16698  * This function creates a mailbox queue, as detailed in @mq, on a port,
16699  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
16700  *
16701  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16702  * is used to get the entry count and entry size that are necessary to
16703  * determine the number of pages to allocate and use for this queue. This
16704  * function will send the MQ_CREATE mailbox command to the HBA to setup the
16705  * mailbox queue. This function is asynchronous and will wait for the mailbox
16706  * command to finish before continuing.
16707  *
16708  * On success this function will return a zero. If unable to allocate enough
16709  * memory this function will return -ENOMEM. If the queue create mailbox command
16710  * fails this function will return -ENXIO.
16711  **/
16712 int32_t
16713 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
16714 	       struct lpfc_queue *cq, uint32_t subtype)
16715 {
16716 	struct lpfc_mbx_mq_create *mq_create;
16717 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
16718 	struct lpfc_dmabuf *dmabuf;
16719 	LPFC_MBOXQ_t *mbox;
16720 	int rc, length, status = 0;
16721 	uint32_t shdr_status, shdr_add_status;
16722 	union lpfc_sli4_cfg_shdr *shdr;
16723 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16724 
16725 	/* sanity check on queue memory */
16726 	if (!mq || !cq)
16727 		return -ENODEV;
16728 	if (!phba->sli4_hba.pc_sli4_params.supported)
16729 		hw_page_size = SLI4_PAGE_SIZE;
16730 
16731 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16732 	if (!mbox)
16733 		return -ENOMEM;
16734 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
16735 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16736 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16737 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
16738 			 length, LPFC_SLI4_MBX_EMBED);
16739 
16740 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
16741 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
16742 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
16743 	       &mq_create_ext->u.request, mq->page_count);
16744 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
16745 	       &mq_create_ext->u.request, 1);
16746 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
16747 	       &mq_create_ext->u.request, 1);
16748 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
16749 	       &mq_create_ext->u.request, 1);
16750 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
16751 	       &mq_create_ext->u.request, 1);
16752 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
16753 	       &mq_create_ext->u.request, 1);
16754 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
16755 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16756 	       phba->sli4_hba.pc_sli4_params.mqv);
16757 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
16758 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
16759 		       cq->queue_id);
16760 	else
16761 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
16762 		       cq->queue_id);
16763 	switch (mq->entry_count) {
16764 	default:
16765 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16766 				"0362 Unsupported MQ count. (%d)\n",
16767 				mq->entry_count);
16768 		if (mq->entry_count < 16) {
16769 			status = -EINVAL;
16770 			goto out;
16771 		}
16772 		fallthrough;	/* otherwise default to smallest count */
16773 	case 16:
16774 		bf_set(lpfc_mq_context_ring_size,
16775 		       &mq_create_ext->u.request.context,
16776 		       LPFC_MQ_RING_SIZE_16);
16777 		break;
16778 	case 32:
16779 		bf_set(lpfc_mq_context_ring_size,
16780 		       &mq_create_ext->u.request.context,
16781 		       LPFC_MQ_RING_SIZE_32);
16782 		break;
16783 	case 64:
16784 		bf_set(lpfc_mq_context_ring_size,
16785 		       &mq_create_ext->u.request.context,
16786 		       LPFC_MQ_RING_SIZE_64);
16787 		break;
16788 	case 128:
16789 		bf_set(lpfc_mq_context_ring_size,
16790 		       &mq_create_ext->u.request.context,
16791 		       LPFC_MQ_RING_SIZE_128);
16792 		break;
16793 	}
16794 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16795 		memset(dmabuf->virt, 0, hw_page_size);
16796 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16797 					putPaddrLow(dmabuf->phys);
16798 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16799 					putPaddrHigh(dmabuf->phys);
16800 	}
16801 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16802 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16803 			      &mq_create_ext->u.response);
16804 	if (rc != MBX_SUCCESS) {
16805 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16806 				"2795 MQ_CREATE_EXT failed with "
16807 				"status x%x. Failback to MQ_CREATE.\n",
16808 				rc);
16809 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16810 		mq_create = &mbox->u.mqe.un.mq_create;
16811 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16812 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16813 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16814 				      &mq_create->u.response);
16815 	}
16816 
16817 	/* The IOCTL status is embedded in the mailbox subheader. */
16818 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16819 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16820 	if (shdr_status || shdr_add_status || rc) {
16821 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16822 				"2502 MQ_CREATE mailbox failed with "
16823 				"status x%x add_status x%x, mbx status x%x\n",
16824 				shdr_status, shdr_add_status, rc);
16825 		status = -ENXIO;
16826 		goto out;
16827 	}
16828 	if (mq->queue_id == 0xFFFF) {
16829 		status = -ENXIO;
16830 		goto out;
16831 	}
16832 	mq->type = LPFC_MQ;
16833 	mq->assoc_qid = cq->queue_id;
16834 	mq->subtype = subtype;
16835 	mq->host_index = 0;
16836 	mq->hba_index = 0;
16837 
16838 	/* link the mq onto the parent cq child list */
16839 	list_add_tail(&mq->list, &cq->child_list);
16840 out:
16841 	mempool_free(mbox, phba->mbox_mem_pool);
16842 	return status;
16843 }
16844 
16845 /**
16846  * lpfc_wq_create - Create a Work Queue on the HBA
16847  * @phba: HBA structure that indicates port to create a queue on.
16848  * @wq: The queue structure to use to create the work queue.
16849  * @cq: The completion queue to bind this work queue to.
16850  * @subtype: The subtype of the work queue indicating its functionality.
16851  *
16852  * This function creates a work queue, as detailed in @wq, on a port, described
16853  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16854  *
16855  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16856  * is used to get the entry count and entry size that are necessary to
16857  * determine the number of pages to allocate and use for this queue. The @cq
16858  * is used to indicate which completion queue to bind this work queue to. This
16859  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16860  * work queue. This function is asynchronous and will wait for the mailbox
16861  * command to finish before continuing.
16862  *
16863  * On success this function will return a zero. If unable to allocate enough
16864  * memory this function will return -ENOMEM. If the queue create mailbox command
16865  * fails this function will return -ENXIO.
16866  **/
16867 int
16868 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16869 	       struct lpfc_queue *cq, uint32_t subtype)
16870 {
16871 	struct lpfc_mbx_wq_create *wq_create;
16872 	struct lpfc_dmabuf *dmabuf;
16873 	LPFC_MBOXQ_t *mbox;
16874 	int rc, length, status = 0;
16875 	uint32_t shdr_status, shdr_add_status;
16876 	union lpfc_sli4_cfg_shdr *shdr;
16877 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16878 	struct dma_address *page;
16879 	void __iomem *bar_memmap_p;
16880 	uint32_t db_offset;
16881 	uint16_t pci_barset;
16882 	uint8_t dpp_barset;
16883 	uint32_t dpp_offset;
16884 	uint8_t wq_create_version;
16885 #ifdef CONFIG_X86
16886 	unsigned long pg_addr;
16887 #endif
16888 
16889 	/* sanity check on queue memory */
16890 	if (!wq || !cq)
16891 		return -ENODEV;
16892 	if (!phba->sli4_hba.pc_sli4_params.supported)
16893 		hw_page_size = wq->page_size;
16894 
16895 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16896 	if (!mbox)
16897 		return -ENOMEM;
16898 	length = (sizeof(struct lpfc_mbx_wq_create) -
16899 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16900 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16901 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16902 			 length, LPFC_SLI4_MBX_EMBED);
16903 	wq_create = &mbox->u.mqe.un.wq_create;
16904 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16905 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16906 		    wq->page_count);
16907 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16908 		    cq->queue_id);
16909 
16910 	/* wqv is the earliest version supported, NOT the latest */
16911 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16912 	       phba->sli4_hba.pc_sli4_params.wqv);
16913 
16914 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16915 	    (wq->page_size > SLI4_PAGE_SIZE))
16916 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
16917 	else
16918 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
16919 
16920 	switch (wq_create_version) {
16921 	case LPFC_Q_CREATE_VERSION_1:
16922 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
16923 		       wq->entry_count);
16924 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16925 		       LPFC_Q_CREATE_VERSION_1);
16926 
16927 		switch (wq->entry_size) {
16928 		default:
16929 		case 64:
16930 			bf_set(lpfc_mbx_wq_create_wqe_size,
16931 			       &wq_create->u.request_1,
16932 			       LPFC_WQ_WQE_SIZE_64);
16933 			break;
16934 		case 128:
16935 			bf_set(lpfc_mbx_wq_create_wqe_size,
16936 			       &wq_create->u.request_1,
16937 			       LPFC_WQ_WQE_SIZE_128);
16938 			break;
16939 		}
16940 		/* Request DPP by default */
16941 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
16942 		bf_set(lpfc_mbx_wq_create_page_size,
16943 		       &wq_create->u.request_1,
16944 		       (wq->page_size / SLI4_PAGE_SIZE));
16945 		page = wq_create->u.request_1.page;
16946 		break;
16947 	default:
16948 		page = wq_create->u.request.page;
16949 		break;
16950 	}
16951 
16952 	list_for_each_entry(dmabuf, &wq->page_list, list) {
16953 		memset(dmabuf->virt, 0, hw_page_size);
16954 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
16955 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
16956 	}
16957 
16958 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16959 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
16960 
16961 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16962 	/* The IOCTL status is embedded in the mailbox subheader. */
16963 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16964 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16965 	if (shdr_status || shdr_add_status || rc) {
16966 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16967 				"2503 WQ_CREATE mailbox failed with "
16968 				"status x%x add_status x%x, mbx status x%x\n",
16969 				shdr_status, shdr_add_status, rc);
16970 		status = -ENXIO;
16971 		goto out;
16972 	}
16973 
16974 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
16975 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
16976 					&wq_create->u.response);
16977 	else
16978 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
16979 					&wq_create->u.response_1);
16980 
16981 	if (wq->queue_id == 0xFFFF) {
16982 		status = -ENXIO;
16983 		goto out;
16984 	}
16985 
16986 	wq->db_format = LPFC_DB_LIST_FORMAT;
16987 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
16988 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16989 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
16990 					       &wq_create->u.response);
16991 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
16992 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
16993 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16994 						"3265 WQ[%d] doorbell format "
16995 						"not supported: x%x\n",
16996 						wq->queue_id, wq->db_format);
16997 				status = -EINVAL;
16998 				goto out;
16999 			}
17000 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
17001 					    &wq_create->u.response);
17002 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17003 								   pci_barset);
17004 			if (!bar_memmap_p) {
17005 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17006 						"3263 WQ[%d] failed to memmap "
17007 						"pci barset:x%x\n",
17008 						wq->queue_id, pci_barset);
17009 				status = -ENOMEM;
17010 				goto out;
17011 			}
17012 			db_offset = wq_create->u.response.doorbell_offset;
17013 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
17014 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
17015 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17016 						"3252 WQ[%d] doorbell offset "
17017 						"not supported: x%x\n",
17018 						wq->queue_id, db_offset);
17019 				status = -EINVAL;
17020 				goto out;
17021 			}
17022 			wq->db_regaddr = bar_memmap_p + db_offset;
17023 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17024 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
17025 					"format:x%x\n", wq->queue_id,
17026 					pci_barset, db_offset, wq->db_format);
17027 		} else
17028 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17029 	} else {
17030 		/* Check if DPP was honored by the firmware */
17031 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
17032 				    &wq_create->u.response_1);
17033 		if (wq->dpp_enable) {
17034 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
17035 					    &wq_create->u.response_1);
17036 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17037 								   pci_barset);
17038 			if (!bar_memmap_p) {
17039 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17040 						"3267 WQ[%d] failed to memmap "
17041 						"pci barset:x%x\n",
17042 						wq->queue_id, pci_barset);
17043 				status = -ENOMEM;
17044 				goto out;
17045 			}
17046 			db_offset = wq_create->u.response_1.doorbell_offset;
17047 			wq->db_regaddr = bar_memmap_p + db_offset;
17048 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
17049 					    &wq_create->u.response_1);
17050 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
17051 					    &wq_create->u.response_1);
17052 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17053 								   dpp_barset);
17054 			if (!bar_memmap_p) {
17055 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17056 						"3268 WQ[%d] failed to memmap "
17057 						"pci barset:x%x\n",
17058 						wq->queue_id, dpp_barset);
17059 				status = -ENOMEM;
17060 				goto out;
17061 			}
17062 			dpp_offset = wq_create->u.response_1.dpp_offset;
17063 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
17064 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17065 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
17066 					"dpp_id:x%x dpp_barset:x%x "
17067 					"dpp_offset:x%x\n",
17068 					wq->queue_id, pci_barset, db_offset,
17069 					wq->dpp_id, dpp_barset, dpp_offset);
17070 
17071 #ifdef CONFIG_X86
17072 			/* Enable combined writes for DPP aperture */
17073 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
17074 			rc = set_memory_wc(pg_addr, 1);
17075 			if (rc) {
17076 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17077 					"3272 Cannot setup Combined "
17078 					"Write on WQ[%d] - disable DPP\n",
17079 					wq->queue_id);
17080 				phba->cfg_enable_dpp = 0;
17081 			}
17082 #else
17083 			phba->cfg_enable_dpp = 0;
17084 #endif
17085 		} else
17086 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17087 	}
17088 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
17089 	if (wq->pring == NULL) {
17090 		status = -ENOMEM;
17091 		goto out;
17092 	}
17093 	wq->type = LPFC_WQ;
17094 	wq->assoc_qid = cq->queue_id;
17095 	wq->subtype = subtype;
17096 	wq->host_index = 0;
17097 	wq->hba_index = 0;
17098 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
17099 
17100 	/* link the wq onto the parent cq child list */
17101 	list_add_tail(&wq->list, &cq->child_list);
17102 out:
17103 	mempool_free(mbox, phba->mbox_mem_pool);
17104 	return status;
17105 }
17106 
17107 /**
17108  * lpfc_rq_create - Create a Receive Queue on the HBA
17109  * @phba: HBA structure that indicates port to create a queue on.
17110  * @hrq: The queue structure to use to create the header receive queue.
17111  * @drq: The queue structure to use to create the data receive queue.
17112  * @cq: The completion queue to bind this work queue to.
17113  * @subtype: The subtype of the work queue indicating its functionality.
17114  *
17115  * This function creates a receive buffer queue pair , as detailed in @hrq and
17116  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17117  * to the HBA.
17118  *
17119  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17120  * struct is used to get the entry count that is necessary to determine the
17121  * number of pages to use for this queue. The @cq is used to indicate which
17122  * completion queue to bind received buffers that are posted to these queues to.
17123  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17124  * receive queue pair. This function is asynchronous and will wait for the
17125  * mailbox command to finish before continuing.
17126  *
17127  * On success this function will return a zero. If unable to allocate enough
17128  * memory this function will return -ENOMEM. If the queue create mailbox command
17129  * fails this function will return -ENXIO.
17130  **/
17131 int
17132 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17133 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
17134 {
17135 	struct lpfc_mbx_rq_create *rq_create;
17136 	struct lpfc_dmabuf *dmabuf;
17137 	LPFC_MBOXQ_t *mbox;
17138 	int rc, length, status = 0;
17139 	uint32_t shdr_status, shdr_add_status;
17140 	union lpfc_sli4_cfg_shdr *shdr;
17141 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17142 	void __iomem *bar_memmap_p;
17143 	uint32_t db_offset;
17144 	uint16_t pci_barset;
17145 
17146 	/* sanity check on queue memory */
17147 	if (!hrq || !drq || !cq)
17148 		return -ENODEV;
17149 	if (!phba->sli4_hba.pc_sli4_params.supported)
17150 		hw_page_size = SLI4_PAGE_SIZE;
17151 
17152 	if (hrq->entry_count != drq->entry_count)
17153 		return -EINVAL;
17154 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17155 	if (!mbox)
17156 		return -ENOMEM;
17157 	length = (sizeof(struct lpfc_mbx_rq_create) -
17158 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17159 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17160 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17161 			 length, LPFC_SLI4_MBX_EMBED);
17162 	rq_create = &mbox->u.mqe.un.rq_create;
17163 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17164 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17165 	       phba->sli4_hba.pc_sli4_params.rqv);
17166 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17167 		bf_set(lpfc_rq_context_rqe_count_1,
17168 		       &rq_create->u.request.context,
17169 		       hrq->entry_count);
17170 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
17171 		bf_set(lpfc_rq_context_rqe_size,
17172 		       &rq_create->u.request.context,
17173 		       LPFC_RQE_SIZE_8);
17174 		bf_set(lpfc_rq_context_page_size,
17175 		       &rq_create->u.request.context,
17176 		       LPFC_RQ_PAGE_SIZE_4096);
17177 	} else {
17178 		switch (hrq->entry_count) {
17179 		default:
17180 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17181 					"2535 Unsupported RQ count. (%d)\n",
17182 					hrq->entry_count);
17183 			if (hrq->entry_count < 512) {
17184 				status = -EINVAL;
17185 				goto out;
17186 			}
17187 			fallthrough;	/* otherwise default to smallest count */
17188 		case 512:
17189 			bf_set(lpfc_rq_context_rqe_count,
17190 			       &rq_create->u.request.context,
17191 			       LPFC_RQ_RING_SIZE_512);
17192 			break;
17193 		case 1024:
17194 			bf_set(lpfc_rq_context_rqe_count,
17195 			       &rq_create->u.request.context,
17196 			       LPFC_RQ_RING_SIZE_1024);
17197 			break;
17198 		case 2048:
17199 			bf_set(lpfc_rq_context_rqe_count,
17200 			       &rq_create->u.request.context,
17201 			       LPFC_RQ_RING_SIZE_2048);
17202 			break;
17203 		case 4096:
17204 			bf_set(lpfc_rq_context_rqe_count,
17205 			       &rq_create->u.request.context,
17206 			       LPFC_RQ_RING_SIZE_4096);
17207 			break;
17208 		}
17209 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
17210 		       LPFC_HDR_BUF_SIZE);
17211 	}
17212 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17213 	       cq->queue_id);
17214 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17215 	       hrq->page_count);
17216 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
17217 		memset(dmabuf->virt, 0, hw_page_size);
17218 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17219 					putPaddrLow(dmabuf->phys);
17220 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17221 					putPaddrHigh(dmabuf->phys);
17222 	}
17223 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17224 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17225 
17226 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17227 	/* The IOCTL status is embedded in the mailbox subheader. */
17228 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17229 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17230 	if (shdr_status || shdr_add_status || rc) {
17231 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17232 				"2504 RQ_CREATE mailbox failed with "
17233 				"status x%x add_status x%x, mbx status x%x\n",
17234 				shdr_status, shdr_add_status, rc);
17235 		status = -ENXIO;
17236 		goto out;
17237 	}
17238 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17239 	if (hrq->queue_id == 0xFFFF) {
17240 		status = -ENXIO;
17241 		goto out;
17242 	}
17243 
17244 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
17245 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
17246 					&rq_create->u.response);
17247 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
17248 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
17249 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17250 					"3262 RQ [%d] doorbell format not "
17251 					"supported: x%x\n", hrq->queue_id,
17252 					hrq->db_format);
17253 			status = -EINVAL;
17254 			goto out;
17255 		}
17256 
17257 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
17258 				    &rq_create->u.response);
17259 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
17260 		if (!bar_memmap_p) {
17261 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17262 					"3269 RQ[%d] failed to memmap pci "
17263 					"barset:x%x\n", hrq->queue_id,
17264 					pci_barset);
17265 			status = -ENOMEM;
17266 			goto out;
17267 		}
17268 
17269 		db_offset = rq_create->u.response.doorbell_offset;
17270 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
17271 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
17272 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17273 					"3270 RQ[%d] doorbell offset not "
17274 					"supported: x%x\n", hrq->queue_id,
17275 					db_offset);
17276 			status = -EINVAL;
17277 			goto out;
17278 		}
17279 		hrq->db_regaddr = bar_memmap_p + db_offset;
17280 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17281 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
17282 				"format:x%x\n", hrq->queue_id, pci_barset,
17283 				db_offset, hrq->db_format);
17284 	} else {
17285 		hrq->db_format = LPFC_DB_RING_FORMAT;
17286 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17287 	}
17288 	hrq->type = LPFC_HRQ;
17289 	hrq->assoc_qid = cq->queue_id;
17290 	hrq->subtype = subtype;
17291 	hrq->host_index = 0;
17292 	hrq->hba_index = 0;
17293 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17294 
17295 	/* now create the data queue */
17296 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17297 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17298 			 length, LPFC_SLI4_MBX_EMBED);
17299 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17300 	       phba->sli4_hba.pc_sli4_params.rqv);
17301 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17302 		bf_set(lpfc_rq_context_rqe_count_1,
17303 		       &rq_create->u.request.context, hrq->entry_count);
17304 		if (subtype == LPFC_NVMET)
17305 			rq_create->u.request.context.buffer_size =
17306 				LPFC_NVMET_DATA_BUF_SIZE;
17307 		else
17308 			rq_create->u.request.context.buffer_size =
17309 				LPFC_DATA_BUF_SIZE;
17310 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
17311 		       LPFC_RQE_SIZE_8);
17312 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
17313 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
17314 	} else {
17315 		switch (drq->entry_count) {
17316 		default:
17317 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17318 					"2536 Unsupported RQ count. (%d)\n",
17319 					drq->entry_count);
17320 			if (drq->entry_count < 512) {
17321 				status = -EINVAL;
17322 				goto out;
17323 			}
17324 			fallthrough;	/* otherwise default to smallest count */
17325 		case 512:
17326 			bf_set(lpfc_rq_context_rqe_count,
17327 			       &rq_create->u.request.context,
17328 			       LPFC_RQ_RING_SIZE_512);
17329 			break;
17330 		case 1024:
17331 			bf_set(lpfc_rq_context_rqe_count,
17332 			       &rq_create->u.request.context,
17333 			       LPFC_RQ_RING_SIZE_1024);
17334 			break;
17335 		case 2048:
17336 			bf_set(lpfc_rq_context_rqe_count,
17337 			       &rq_create->u.request.context,
17338 			       LPFC_RQ_RING_SIZE_2048);
17339 			break;
17340 		case 4096:
17341 			bf_set(lpfc_rq_context_rqe_count,
17342 			       &rq_create->u.request.context,
17343 			       LPFC_RQ_RING_SIZE_4096);
17344 			break;
17345 		}
17346 		if (subtype == LPFC_NVMET)
17347 			bf_set(lpfc_rq_context_buf_size,
17348 			       &rq_create->u.request.context,
17349 			       LPFC_NVMET_DATA_BUF_SIZE);
17350 		else
17351 			bf_set(lpfc_rq_context_buf_size,
17352 			       &rq_create->u.request.context,
17353 			       LPFC_DATA_BUF_SIZE);
17354 	}
17355 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17356 	       cq->queue_id);
17357 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17358 	       drq->page_count);
17359 	list_for_each_entry(dmabuf, &drq->page_list, list) {
17360 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17361 					putPaddrLow(dmabuf->phys);
17362 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17363 					putPaddrHigh(dmabuf->phys);
17364 	}
17365 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17366 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17367 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17368 	/* The IOCTL status is embedded in the mailbox subheader. */
17369 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17370 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17371 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17372 	if (shdr_status || shdr_add_status || rc) {
17373 		status = -ENXIO;
17374 		goto out;
17375 	}
17376 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17377 	if (drq->queue_id == 0xFFFF) {
17378 		status = -ENXIO;
17379 		goto out;
17380 	}
17381 	drq->type = LPFC_DRQ;
17382 	drq->assoc_qid = cq->queue_id;
17383 	drq->subtype = subtype;
17384 	drq->host_index = 0;
17385 	drq->hba_index = 0;
17386 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17387 
17388 	/* link the header and data RQs onto the parent cq child list */
17389 	list_add_tail(&hrq->list, &cq->child_list);
17390 	list_add_tail(&drq->list, &cq->child_list);
17391 
17392 out:
17393 	mempool_free(mbox, phba->mbox_mem_pool);
17394 	return status;
17395 }
17396 
17397 /**
17398  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
17399  * @phba: HBA structure that indicates port to create a queue on.
17400  * @hrqp: The queue structure array to use to create the header receive queues.
17401  * @drqp: The queue structure array to use to create the data receive queues.
17402  * @cqp: The completion queue array to bind these receive queues to.
17403  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
17404  *
17405  * This function creates a receive buffer queue pair , as detailed in @hrq and
17406  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17407  * to the HBA.
17408  *
17409  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17410  * struct is used to get the entry count that is necessary to determine the
17411  * number of pages to use for this queue. The @cq is used to indicate which
17412  * completion queue to bind received buffers that are posted to these queues to.
17413  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17414  * receive queue pair. This function is asynchronous and will wait for the
17415  * mailbox command to finish before continuing.
17416  *
17417  * On success this function will return a zero. If unable to allocate enough
17418  * memory this function will return -ENOMEM. If the queue create mailbox command
17419  * fails this function will return -ENXIO.
17420  **/
17421 int
17422 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
17423 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
17424 		uint32_t subtype)
17425 {
17426 	struct lpfc_queue *hrq, *drq, *cq;
17427 	struct lpfc_mbx_rq_create_v2 *rq_create;
17428 	struct lpfc_dmabuf *dmabuf;
17429 	LPFC_MBOXQ_t *mbox;
17430 	int rc, length, alloclen, status = 0;
17431 	int cnt, idx, numrq, page_idx = 0;
17432 	uint32_t shdr_status, shdr_add_status;
17433 	union lpfc_sli4_cfg_shdr *shdr;
17434 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17435 
17436 	numrq = phba->cfg_nvmet_mrq;
17437 	/* sanity check on array memory */
17438 	if (!hrqp || !drqp || !cqp || !numrq)
17439 		return -ENODEV;
17440 	if (!phba->sli4_hba.pc_sli4_params.supported)
17441 		hw_page_size = SLI4_PAGE_SIZE;
17442 
17443 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17444 	if (!mbox)
17445 		return -ENOMEM;
17446 
17447 	length = sizeof(struct lpfc_mbx_rq_create_v2);
17448 	length += ((2 * numrq * hrqp[0]->page_count) *
17449 		   sizeof(struct dma_address));
17450 
17451 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17452 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
17453 				    LPFC_SLI4_MBX_NEMBED);
17454 	if (alloclen < length) {
17455 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17456 				"3099 Allocated DMA memory size (%d) is "
17457 				"less than the requested DMA memory size "
17458 				"(%d)\n", alloclen, length);
17459 		status = -ENOMEM;
17460 		goto out;
17461 	}
17462 
17463 
17464 
17465 	rq_create = mbox->sge_array->addr[0];
17466 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
17467 
17468 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
17469 	cnt = 0;
17470 
17471 	for (idx = 0; idx < numrq; idx++) {
17472 		hrq = hrqp[idx];
17473 		drq = drqp[idx];
17474 		cq  = cqp[idx];
17475 
17476 		/* sanity check on queue memory */
17477 		if (!hrq || !drq || !cq) {
17478 			status = -ENODEV;
17479 			goto out;
17480 		}
17481 
17482 		if (hrq->entry_count != drq->entry_count) {
17483 			status = -EINVAL;
17484 			goto out;
17485 		}
17486 
17487 		if (idx == 0) {
17488 			bf_set(lpfc_mbx_rq_create_num_pages,
17489 			       &rq_create->u.request,
17490 			       hrq->page_count);
17491 			bf_set(lpfc_mbx_rq_create_rq_cnt,
17492 			       &rq_create->u.request, (numrq * 2));
17493 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
17494 			       1);
17495 			bf_set(lpfc_rq_context_base_cq,
17496 			       &rq_create->u.request.context,
17497 			       cq->queue_id);
17498 			bf_set(lpfc_rq_context_data_size,
17499 			       &rq_create->u.request.context,
17500 			       LPFC_NVMET_DATA_BUF_SIZE);
17501 			bf_set(lpfc_rq_context_hdr_size,
17502 			       &rq_create->u.request.context,
17503 			       LPFC_HDR_BUF_SIZE);
17504 			bf_set(lpfc_rq_context_rqe_count_1,
17505 			       &rq_create->u.request.context,
17506 			       hrq->entry_count);
17507 			bf_set(lpfc_rq_context_rqe_size,
17508 			       &rq_create->u.request.context,
17509 			       LPFC_RQE_SIZE_8);
17510 			bf_set(lpfc_rq_context_page_size,
17511 			       &rq_create->u.request.context,
17512 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
17513 		}
17514 		rc = 0;
17515 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
17516 			memset(dmabuf->virt, 0, hw_page_size);
17517 			cnt = page_idx + dmabuf->buffer_tag;
17518 			rq_create->u.request.page[cnt].addr_lo =
17519 					putPaddrLow(dmabuf->phys);
17520 			rq_create->u.request.page[cnt].addr_hi =
17521 					putPaddrHigh(dmabuf->phys);
17522 			rc++;
17523 		}
17524 		page_idx += rc;
17525 
17526 		rc = 0;
17527 		list_for_each_entry(dmabuf, &drq->page_list, list) {
17528 			memset(dmabuf->virt, 0, hw_page_size);
17529 			cnt = page_idx + dmabuf->buffer_tag;
17530 			rq_create->u.request.page[cnt].addr_lo =
17531 					putPaddrLow(dmabuf->phys);
17532 			rq_create->u.request.page[cnt].addr_hi =
17533 					putPaddrHigh(dmabuf->phys);
17534 			rc++;
17535 		}
17536 		page_idx += rc;
17537 
17538 		hrq->db_format = LPFC_DB_RING_FORMAT;
17539 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17540 		hrq->type = LPFC_HRQ;
17541 		hrq->assoc_qid = cq->queue_id;
17542 		hrq->subtype = subtype;
17543 		hrq->host_index = 0;
17544 		hrq->hba_index = 0;
17545 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17546 
17547 		drq->db_format = LPFC_DB_RING_FORMAT;
17548 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17549 		drq->type = LPFC_DRQ;
17550 		drq->assoc_qid = cq->queue_id;
17551 		drq->subtype = subtype;
17552 		drq->host_index = 0;
17553 		drq->hba_index = 0;
17554 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17555 
17556 		list_add_tail(&hrq->list, &cq->child_list);
17557 		list_add_tail(&drq->list, &cq->child_list);
17558 	}
17559 
17560 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17561 	/* The IOCTL status is embedded in the mailbox subheader. */
17562 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17563 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17564 	if (shdr_status || shdr_add_status || rc) {
17565 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17566 				"3120 RQ_CREATE mailbox failed with "
17567 				"status x%x add_status x%x, mbx status x%x\n",
17568 				shdr_status, shdr_add_status, rc);
17569 		status = -ENXIO;
17570 		goto out;
17571 	}
17572 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17573 	if (rc == 0xFFFF) {
17574 		status = -ENXIO;
17575 		goto out;
17576 	}
17577 
17578 	/* Initialize all RQs with associated queue id */
17579 	for (idx = 0; idx < numrq; idx++) {
17580 		hrq = hrqp[idx];
17581 		hrq->queue_id = rc + (2 * idx);
17582 		drq = drqp[idx];
17583 		drq->queue_id = rc + (2 * idx) + 1;
17584 	}
17585 
17586 out:
17587 	lpfc_sli4_mbox_cmd_free(phba, mbox);
17588 	return status;
17589 }
17590 
17591 /**
17592  * lpfc_eq_destroy - Destroy an event Queue on the HBA
17593  * @phba: HBA structure that indicates port to destroy a queue on.
17594  * @eq: The queue structure associated with the queue to destroy.
17595  *
17596  * This function destroys a queue, as detailed in @eq by sending an mailbox
17597  * command, specific to the type of queue, to the HBA.
17598  *
17599  * The @eq struct is used to get the queue ID of the queue to destroy.
17600  *
17601  * On success this function will return a zero. If the queue destroy mailbox
17602  * command fails this function will return -ENXIO.
17603  **/
17604 int
17605 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
17606 {
17607 	LPFC_MBOXQ_t *mbox;
17608 	int rc, length, status = 0;
17609 	uint32_t shdr_status, shdr_add_status;
17610 	union lpfc_sli4_cfg_shdr *shdr;
17611 
17612 	/* sanity check on queue memory */
17613 	if (!eq)
17614 		return -ENODEV;
17615 
17616 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
17617 	if (!mbox)
17618 		return -ENOMEM;
17619 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
17620 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17621 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17622 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
17623 			 length, LPFC_SLI4_MBX_EMBED);
17624 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
17625 	       eq->queue_id);
17626 	mbox->vport = eq->phba->pport;
17627 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17628 
17629 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
17630 	/* The IOCTL status is embedded in the mailbox subheader. */
17631 	shdr = (union lpfc_sli4_cfg_shdr *)
17632 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
17633 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17634 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17635 	if (shdr_status || shdr_add_status || rc) {
17636 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17637 				"2505 EQ_DESTROY mailbox failed with "
17638 				"status x%x add_status x%x, mbx status x%x\n",
17639 				shdr_status, shdr_add_status, rc);
17640 		status = -ENXIO;
17641 	}
17642 
17643 	/* Remove eq from any list */
17644 	list_del_init(&eq->list);
17645 	mempool_free(mbox, eq->phba->mbox_mem_pool);
17646 	return status;
17647 }
17648 
17649 /**
17650  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
17651  * @phba: HBA structure that indicates port to destroy a queue on.
17652  * @cq: The queue structure associated with the queue to destroy.
17653  *
17654  * This function destroys a queue, as detailed in @cq by sending an mailbox
17655  * command, specific to the type of queue, to the HBA.
17656  *
17657  * The @cq struct is used to get the queue ID of the queue to destroy.
17658  *
17659  * On success this function will return a zero. If the queue destroy mailbox
17660  * command fails this function will return -ENXIO.
17661  **/
17662 int
17663 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
17664 {
17665 	LPFC_MBOXQ_t *mbox;
17666 	int rc, length, status = 0;
17667 	uint32_t shdr_status, shdr_add_status;
17668 	union lpfc_sli4_cfg_shdr *shdr;
17669 
17670 	/* sanity check on queue memory */
17671 	if (!cq)
17672 		return -ENODEV;
17673 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
17674 	if (!mbox)
17675 		return -ENOMEM;
17676 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
17677 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17678 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17679 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
17680 			 length, LPFC_SLI4_MBX_EMBED);
17681 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
17682 	       cq->queue_id);
17683 	mbox->vport = cq->phba->pport;
17684 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17685 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
17686 	/* The IOCTL status is embedded in the mailbox subheader. */
17687 	shdr = (union lpfc_sli4_cfg_shdr *)
17688 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
17689 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17690 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17691 	if (shdr_status || shdr_add_status || rc) {
17692 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17693 				"2506 CQ_DESTROY mailbox failed with "
17694 				"status x%x add_status x%x, mbx status x%x\n",
17695 				shdr_status, shdr_add_status, rc);
17696 		status = -ENXIO;
17697 	}
17698 	/* Remove cq from any list */
17699 	list_del_init(&cq->list);
17700 	mempool_free(mbox, cq->phba->mbox_mem_pool);
17701 	return status;
17702 }
17703 
17704 /**
17705  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
17706  * @phba: HBA structure that indicates port to destroy a queue on.
17707  * @mq: The queue structure associated with the queue to destroy.
17708  *
17709  * This function destroys a queue, as detailed in @mq by sending an mailbox
17710  * command, specific to the type of queue, to the HBA.
17711  *
17712  * The @mq struct is used to get the queue ID of the queue to destroy.
17713  *
17714  * On success this function will return a zero. If the queue destroy mailbox
17715  * command fails this function will return -ENXIO.
17716  **/
17717 int
17718 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
17719 {
17720 	LPFC_MBOXQ_t *mbox;
17721 	int rc, length, status = 0;
17722 	uint32_t shdr_status, shdr_add_status;
17723 	union lpfc_sli4_cfg_shdr *shdr;
17724 
17725 	/* sanity check on queue memory */
17726 	if (!mq)
17727 		return -ENODEV;
17728 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
17729 	if (!mbox)
17730 		return -ENOMEM;
17731 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
17732 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17733 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17734 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
17735 			 length, LPFC_SLI4_MBX_EMBED);
17736 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
17737 	       mq->queue_id);
17738 	mbox->vport = mq->phba->pport;
17739 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17740 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
17741 	/* The IOCTL status is embedded in the mailbox subheader. */
17742 	shdr = (union lpfc_sli4_cfg_shdr *)
17743 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
17744 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17745 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17746 	if (shdr_status || shdr_add_status || rc) {
17747 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17748 				"2507 MQ_DESTROY mailbox failed with "
17749 				"status x%x add_status x%x, mbx status x%x\n",
17750 				shdr_status, shdr_add_status, rc);
17751 		status = -ENXIO;
17752 	}
17753 	/* Remove mq from any list */
17754 	list_del_init(&mq->list);
17755 	mempool_free(mbox, mq->phba->mbox_mem_pool);
17756 	return status;
17757 }
17758 
17759 /**
17760  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
17761  * @phba: HBA structure that indicates port to destroy a queue on.
17762  * @wq: The queue structure associated with the queue to destroy.
17763  *
17764  * This function destroys a queue, as detailed in @wq by sending an mailbox
17765  * command, specific to the type of queue, to the HBA.
17766  *
17767  * The @wq struct is used to get the queue ID of the queue to destroy.
17768  *
17769  * On success this function will return a zero. If the queue destroy mailbox
17770  * command fails this function will return -ENXIO.
17771  **/
17772 int
17773 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
17774 {
17775 	LPFC_MBOXQ_t *mbox;
17776 	int rc, length, status = 0;
17777 	uint32_t shdr_status, shdr_add_status;
17778 	union lpfc_sli4_cfg_shdr *shdr;
17779 
17780 	/* sanity check on queue memory */
17781 	if (!wq)
17782 		return -ENODEV;
17783 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17784 	if (!mbox)
17785 		return -ENOMEM;
17786 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
17787 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17788 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17789 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17790 			 length, LPFC_SLI4_MBX_EMBED);
17791 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17792 	       wq->queue_id);
17793 	mbox->vport = wq->phba->pport;
17794 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17795 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17796 	shdr = (union lpfc_sli4_cfg_shdr *)
17797 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17798 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17799 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17800 	if (shdr_status || shdr_add_status || rc) {
17801 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17802 				"2508 WQ_DESTROY mailbox failed with "
17803 				"status x%x add_status x%x, mbx status x%x\n",
17804 				shdr_status, shdr_add_status, rc);
17805 		status = -ENXIO;
17806 	}
17807 	/* Remove wq from any list */
17808 	list_del_init(&wq->list);
17809 	kfree(wq->pring);
17810 	wq->pring = NULL;
17811 	mempool_free(mbox, wq->phba->mbox_mem_pool);
17812 	return status;
17813 }
17814 
17815 /**
17816  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17817  * @phba: HBA structure that indicates port to destroy a queue on.
17818  * @hrq: The queue structure associated with the queue to destroy.
17819  * @drq: The queue structure associated with the queue to destroy.
17820  *
17821  * This function destroys a queue, as detailed in @rq by sending an mailbox
17822  * command, specific to the type of queue, to the HBA.
17823  *
17824  * The @rq struct is used to get the queue ID of the queue to destroy.
17825  *
17826  * On success this function will return a zero. If the queue destroy mailbox
17827  * command fails this function will return -ENXIO.
17828  **/
17829 int
17830 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17831 		struct lpfc_queue *drq)
17832 {
17833 	LPFC_MBOXQ_t *mbox;
17834 	int rc, length, status = 0;
17835 	uint32_t shdr_status, shdr_add_status;
17836 	union lpfc_sli4_cfg_shdr *shdr;
17837 
17838 	/* sanity check on queue memory */
17839 	if (!hrq || !drq)
17840 		return -ENODEV;
17841 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17842 	if (!mbox)
17843 		return -ENOMEM;
17844 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
17845 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17846 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17847 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17848 			 length, LPFC_SLI4_MBX_EMBED);
17849 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17850 	       hrq->queue_id);
17851 	mbox->vport = hrq->phba->pport;
17852 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17853 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17854 	/* The IOCTL status is embedded in the mailbox subheader. */
17855 	shdr = (union lpfc_sli4_cfg_shdr *)
17856 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17857 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17858 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17859 	if (shdr_status || shdr_add_status || rc) {
17860 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17861 				"2509 RQ_DESTROY mailbox failed with "
17862 				"status x%x add_status x%x, mbx status x%x\n",
17863 				shdr_status, shdr_add_status, rc);
17864 		mempool_free(mbox, hrq->phba->mbox_mem_pool);
17865 		return -ENXIO;
17866 	}
17867 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17868 	       drq->queue_id);
17869 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17870 	shdr = (union lpfc_sli4_cfg_shdr *)
17871 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17872 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17873 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17874 	if (shdr_status || shdr_add_status || rc) {
17875 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17876 				"2510 RQ_DESTROY mailbox failed with "
17877 				"status x%x add_status x%x, mbx status x%x\n",
17878 				shdr_status, shdr_add_status, rc);
17879 		status = -ENXIO;
17880 	}
17881 	list_del_init(&hrq->list);
17882 	list_del_init(&drq->list);
17883 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
17884 	return status;
17885 }
17886 
17887 /**
17888  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17889  * @phba: The virtual port for which this call being executed.
17890  * @pdma_phys_addr0: Physical address of the 1st SGL page.
17891  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
17892  * @xritag: the xritag that ties this io to the SGL pages.
17893  *
17894  * This routine will post the sgl pages for the IO that has the xritag
17895  * that is in the iocbq structure. The xritag is assigned during iocbq
17896  * creation and persists for as long as the driver is loaded.
17897  * if the caller has fewer than 256 scatter gather segments to map then
17898  * pdma_phys_addr1 should be 0.
17899  * If the caller needs to map more than 256 scatter gather segment then
17900  * pdma_phys_addr1 should be a valid physical address.
17901  * physical address for SGLs must be 64 byte aligned.
17902  * If you are going to map 2 SGL's then the first one must have 256 entries
17903  * the second sgl can have between 1 and 256 entries.
17904  *
17905  * Return codes:
17906  * 	0 - Success
17907  * 	-ENXIO, -ENOMEM - Failure
17908  **/
17909 int
17910 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
17911 		dma_addr_t pdma_phys_addr0,
17912 		dma_addr_t pdma_phys_addr1,
17913 		uint16_t xritag)
17914 {
17915 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
17916 	LPFC_MBOXQ_t *mbox;
17917 	int rc;
17918 	uint32_t shdr_status, shdr_add_status;
17919 	uint32_t mbox_tmo;
17920 	union lpfc_sli4_cfg_shdr *shdr;
17921 
17922 	if (xritag == NO_XRI) {
17923 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17924 				"0364 Invalid param:\n");
17925 		return -EINVAL;
17926 	}
17927 
17928 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17929 	if (!mbox)
17930 		return -ENOMEM;
17931 
17932 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17933 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17934 			sizeof(struct lpfc_mbx_post_sgl_pages) -
17935 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17936 
17937 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
17938 				&mbox->u.mqe.un.post_sgl_pages;
17939 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
17940 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
17941 
17942 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
17943 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
17944 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
17945 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
17946 
17947 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
17948 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
17949 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
17950 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
17951 	if (!phba->sli4_hba.intr_enable)
17952 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17953 	else {
17954 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17955 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17956 	}
17957 	/* The IOCTL status is embedded in the mailbox subheader. */
17958 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
17959 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17960 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17961 	if (!phba->sli4_hba.intr_enable)
17962 		mempool_free(mbox, phba->mbox_mem_pool);
17963 	else if (rc != MBX_TIMEOUT)
17964 		mempool_free(mbox, phba->mbox_mem_pool);
17965 	if (shdr_status || shdr_add_status || rc) {
17966 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17967 				"2511 POST_SGL mailbox failed with "
17968 				"status x%x add_status x%x, mbx status x%x\n",
17969 				shdr_status, shdr_add_status, rc);
17970 	}
17971 	return 0;
17972 }
17973 
17974 /**
17975  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
17976  * @phba: pointer to lpfc hba data structure.
17977  *
17978  * This routine is invoked to post rpi header templates to the
17979  * HBA consistent with the SLI-4 interface spec.  This routine
17980  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
17981  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
17982  *
17983  * Returns
17984  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
17985  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
17986  **/
17987 static uint16_t
17988 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
17989 {
17990 	unsigned long xri;
17991 
17992 	/*
17993 	 * Fetch the next logical xri.  Because this index is logical,
17994 	 * the driver starts at 0 each time.
17995 	 */
17996 	spin_lock_irq(&phba->hbalock);
17997 	xri = find_first_zero_bit(phba->sli4_hba.xri_bmask,
17998 				 phba->sli4_hba.max_cfg_param.max_xri);
17999 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
18000 		spin_unlock_irq(&phba->hbalock);
18001 		return NO_XRI;
18002 	} else {
18003 		set_bit(xri, phba->sli4_hba.xri_bmask);
18004 		phba->sli4_hba.max_cfg_param.xri_used++;
18005 	}
18006 	spin_unlock_irq(&phba->hbalock);
18007 	return xri;
18008 }
18009 
18010 /**
18011  * __lpfc_sli4_free_xri - Release an xri for reuse.
18012  * @phba: pointer to lpfc hba data structure.
18013  * @xri: xri to release.
18014  *
18015  * This routine is invoked to release an xri to the pool of
18016  * available rpis maintained by the driver.
18017  **/
18018 static void
18019 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18020 {
18021 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
18022 		phba->sli4_hba.max_cfg_param.xri_used--;
18023 	}
18024 }
18025 
18026 /**
18027  * lpfc_sli4_free_xri - Release an xri for reuse.
18028  * @phba: pointer to lpfc hba data structure.
18029  * @xri: xri to release.
18030  *
18031  * This routine is invoked to release an xri to the pool of
18032  * available rpis maintained by the driver.
18033  **/
18034 void
18035 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18036 {
18037 	spin_lock_irq(&phba->hbalock);
18038 	__lpfc_sli4_free_xri(phba, xri);
18039 	spin_unlock_irq(&phba->hbalock);
18040 }
18041 
18042 /**
18043  * lpfc_sli4_next_xritag - Get an xritag for the io
18044  * @phba: Pointer to HBA context object.
18045  *
18046  * This function gets an xritag for the iocb. If there is no unused xritag
18047  * it will return 0xffff.
18048  * The function returns the allocated xritag if successful, else returns zero.
18049  * Zero is not a valid xritag.
18050  * The caller is not required to hold any lock.
18051  **/
18052 uint16_t
18053 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
18054 {
18055 	uint16_t xri_index;
18056 
18057 	xri_index = lpfc_sli4_alloc_xri(phba);
18058 	if (xri_index == NO_XRI)
18059 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18060 				"2004 Failed to allocate XRI.last XRITAG is %d"
18061 				" Max XRI is %d, Used XRI is %d\n",
18062 				xri_index,
18063 				phba->sli4_hba.max_cfg_param.max_xri,
18064 				phba->sli4_hba.max_cfg_param.xri_used);
18065 	return xri_index;
18066 }
18067 
18068 /**
18069  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
18070  * @phba: pointer to lpfc hba data structure.
18071  * @post_sgl_list: pointer to els sgl entry list.
18072  * @post_cnt: number of els sgl entries on the list.
18073  *
18074  * This routine is invoked to post a block of driver's sgl pages to the
18075  * HBA using non-embedded mailbox command. No Lock is held. This routine
18076  * is only called when the driver is loading and after all IO has been
18077  * stopped.
18078  **/
18079 static int
18080 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
18081 			    struct list_head *post_sgl_list,
18082 			    int post_cnt)
18083 {
18084 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
18085 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18086 	struct sgl_page_pairs *sgl_pg_pairs;
18087 	void *viraddr;
18088 	LPFC_MBOXQ_t *mbox;
18089 	uint32_t reqlen, alloclen, pg_pairs;
18090 	uint32_t mbox_tmo;
18091 	uint16_t xritag_start = 0;
18092 	int rc = 0;
18093 	uint32_t shdr_status, shdr_add_status;
18094 	union lpfc_sli4_cfg_shdr *shdr;
18095 
18096 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
18097 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18098 	if (reqlen > SLI4_PAGE_SIZE) {
18099 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18100 				"2559 Block sgl registration required DMA "
18101 				"size (%d) great than a page\n", reqlen);
18102 		return -ENOMEM;
18103 	}
18104 
18105 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18106 	if (!mbox)
18107 		return -ENOMEM;
18108 
18109 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18110 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18111 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
18112 			 LPFC_SLI4_MBX_NEMBED);
18113 
18114 	if (alloclen < reqlen) {
18115 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18116 				"0285 Allocated DMA memory size (%d) is "
18117 				"less than the requested DMA memory "
18118 				"size (%d)\n", alloclen, reqlen);
18119 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18120 		return -ENOMEM;
18121 	}
18122 	/* Set up the SGL pages in the non-embedded DMA pages */
18123 	viraddr = mbox->sge_array->addr[0];
18124 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18125 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18126 
18127 	pg_pairs = 0;
18128 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
18129 		/* Set up the sge entry */
18130 		sgl_pg_pairs->sgl_pg0_addr_lo =
18131 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
18132 		sgl_pg_pairs->sgl_pg0_addr_hi =
18133 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
18134 		sgl_pg_pairs->sgl_pg1_addr_lo =
18135 				cpu_to_le32(putPaddrLow(0));
18136 		sgl_pg_pairs->sgl_pg1_addr_hi =
18137 				cpu_to_le32(putPaddrHigh(0));
18138 
18139 		/* Keep the first xritag on the list */
18140 		if (pg_pairs == 0)
18141 			xritag_start = sglq_entry->sli4_xritag;
18142 		sgl_pg_pairs++;
18143 		pg_pairs++;
18144 	}
18145 
18146 	/* Complete initialization and perform endian conversion. */
18147 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18148 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
18149 	sgl->word0 = cpu_to_le32(sgl->word0);
18150 
18151 	if (!phba->sli4_hba.intr_enable)
18152 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18153 	else {
18154 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18155 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18156 	}
18157 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
18158 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18159 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18160 	if (!phba->sli4_hba.intr_enable)
18161 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18162 	else if (rc != MBX_TIMEOUT)
18163 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18164 	if (shdr_status || shdr_add_status || rc) {
18165 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18166 				"2513 POST_SGL_BLOCK mailbox command failed "
18167 				"status x%x add_status x%x mbx status x%x\n",
18168 				shdr_status, shdr_add_status, rc);
18169 		rc = -ENXIO;
18170 	}
18171 	return rc;
18172 }
18173 
18174 /**
18175  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
18176  * @phba: pointer to lpfc hba data structure.
18177  * @nblist: pointer to nvme buffer list.
18178  * @count: number of scsi buffers on the list.
18179  *
18180  * This routine is invoked to post a block of @count scsi sgl pages from a
18181  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
18182  * No Lock is held.
18183  *
18184  **/
18185 static int
18186 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
18187 			    int count)
18188 {
18189 	struct lpfc_io_buf *lpfc_ncmd;
18190 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18191 	struct sgl_page_pairs *sgl_pg_pairs;
18192 	void *viraddr;
18193 	LPFC_MBOXQ_t *mbox;
18194 	uint32_t reqlen, alloclen, pg_pairs;
18195 	uint32_t mbox_tmo;
18196 	uint16_t xritag_start = 0;
18197 	int rc = 0;
18198 	uint32_t shdr_status, shdr_add_status;
18199 	dma_addr_t pdma_phys_bpl1;
18200 	union lpfc_sli4_cfg_shdr *shdr;
18201 
18202 	/* Calculate the requested length of the dma memory */
18203 	reqlen = count * sizeof(struct sgl_page_pairs) +
18204 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18205 	if (reqlen > SLI4_PAGE_SIZE) {
18206 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
18207 				"6118 Block sgl registration required DMA "
18208 				"size (%d) great than a page\n", reqlen);
18209 		return -ENOMEM;
18210 	}
18211 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18212 	if (!mbox) {
18213 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18214 				"6119 Failed to allocate mbox cmd memory\n");
18215 		return -ENOMEM;
18216 	}
18217 
18218 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18219 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18220 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
18221 				    reqlen, LPFC_SLI4_MBX_NEMBED);
18222 
18223 	if (alloclen < reqlen) {
18224 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18225 				"6120 Allocated DMA memory size (%d) is "
18226 				"less than the requested DMA memory "
18227 				"size (%d)\n", alloclen, reqlen);
18228 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18229 		return -ENOMEM;
18230 	}
18231 
18232 	/* Get the first SGE entry from the non-embedded DMA memory */
18233 	viraddr = mbox->sge_array->addr[0];
18234 
18235 	/* Set up the SGL pages in the non-embedded DMA pages */
18236 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18237 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18238 
18239 	pg_pairs = 0;
18240 	list_for_each_entry(lpfc_ncmd, nblist, list) {
18241 		/* Set up the sge entry */
18242 		sgl_pg_pairs->sgl_pg0_addr_lo =
18243 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
18244 		sgl_pg_pairs->sgl_pg0_addr_hi =
18245 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
18246 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
18247 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
18248 						SGL_PAGE_SIZE;
18249 		else
18250 			pdma_phys_bpl1 = 0;
18251 		sgl_pg_pairs->sgl_pg1_addr_lo =
18252 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
18253 		sgl_pg_pairs->sgl_pg1_addr_hi =
18254 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
18255 		/* Keep the first xritag on the list */
18256 		if (pg_pairs == 0)
18257 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
18258 		sgl_pg_pairs++;
18259 		pg_pairs++;
18260 	}
18261 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18262 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
18263 	/* Perform endian conversion if necessary */
18264 	sgl->word0 = cpu_to_le32(sgl->word0);
18265 
18266 	if (!phba->sli4_hba.intr_enable) {
18267 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18268 	} else {
18269 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18270 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18271 	}
18272 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
18273 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18274 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18275 	if (!phba->sli4_hba.intr_enable)
18276 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18277 	else if (rc != MBX_TIMEOUT)
18278 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18279 	if (shdr_status || shdr_add_status || rc) {
18280 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18281 				"6125 POST_SGL_BLOCK mailbox command failed "
18282 				"status x%x add_status x%x mbx status x%x\n",
18283 				shdr_status, shdr_add_status, rc);
18284 		rc = -ENXIO;
18285 	}
18286 	return rc;
18287 }
18288 
18289 /**
18290  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
18291  * @phba: pointer to lpfc hba data structure.
18292  * @post_nblist: pointer to the nvme buffer list.
18293  * @sb_count: number of nvme buffers.
18294  *
18295  * This routine walks a list of nvme buffers that was passed in. It attempts
18296  * to construct blocks of nvme buffer sgls which contains contiguous xris and
18297  * uses the non-embedded SGL block post mailbox commands to post to the port.
18298  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
18299  * embedded SGL post mailbox command for posting. The @post_nblist passed in
18300  * must be local list, thus no lock is needed when manipulate the list.
18301  *
18302  * Returns: 0 = failure, non-zero number of successfully posted buffers.
18303  **/
18304 int
18305 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
18306 			   struct list_head *post_nblist, int sb_count)
18307 {
18308 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
18309 	int status, sgl_size;
18310 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
18311 	dma_addr_t pdma_phys_sgl1;
18312 	int last_xritag = NO_XRI;
18313 	int cur_xritag;
18314 	LIST_HEAD(prep_nblist);
18315 	LIST_HEAD(blck_nblist);
18316 	LIST_HEAD(nvme_nblist);
18317 
18318 	/* sanity check */
18319 	if (sb_count <= 0)
18320 		return -EINVAL;
18321 
18322 	sgl_size = phba->cfg_sg_dma_buf_size;
18323 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
18324 		list_del_init(&lpfc_ncmd->list);
18325 		block_cnt++;
18326 		if ((last_xritag != NO_XRI) &&
18327 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
18328 			/* a hole in xri block, form a sgl posting block */
18329 			list_splice_init(&prep_nblist, &blck_nblist);
18330 			post_cnt = block_cnt - 1;
18331 			/* prepare list for next posting block */
18332 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18333 			block_cnt = 1;
18334 		} else {
18335 			/* prepare list for next posting block */
18336 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18337 			/* enough sgls for non-embed sgl mbox command */
18338 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
18339 				list_splice_init(&prep_nblist, &blck_nblist);
18340 				post_cnt = block_cnt;
18341 				block_cnt = 0;
18342 			}
18343 		}
18344 		num_posting++;
18345 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18346 
18347 		/* end of repost sgl list condition for NVME buffers */
18348 		if (num_posting == sb_count) {
18349 			if (post_cnt == 0) {
18350 				/* last sgl posting block */
18351 				list_splice_init(&prep_nblist, &blck_nblist);
18352 				post_cnt = block_cnt;
18353 			} else if (block_cnt == 1) {
18354 				/* last single sgl with non-contiguous xri */
18355 				if (sgl_size > SGL_PAGE_SIZE)
18356 					pdma_phys_sgl1 =
18357 						lpfc_ncmd->dma_phys_sgl +
18358 						SGL_PAGE_SIZE;
18359 				else
18360 					pdma_phys_sgl1 = 0;
18361 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18362 				status = lpfc_sli4_post_sgl(
18363 						phba, lpfc_ncmd->dma_phys_sgl,
18364 						pdma_phys_sgl1, cur_xritag);
18365 				if (status) {
18366 					/* Post error.  Buffer unavailable. */
18367 					lpfc_ncmd->flags |=
18368 						LPFC_SBUF_NOT_POSTED;
18369 				} else {
18370 					/* Post success. Bffer available. */
18371 					lpfc_ncmd->flags &=
18372 						~LPFC_SBUF_NOT_POSTED;
18373 					lpfc_ncmd->status = IOSTAT_SUCCESS;
18374 					num_posted++;
18375 				}
18376 				/* success, put on NVME buffer sgl list */
18377 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18378 			}
18379 		}
18380 
18381 		/* continue until a nembed page worth of sgls */
18382 		if (post_cnt == 0)
18383 			continue;
18384 
18385 		/* post block of NVME buffer list sgls */
18386 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
18387 						     post_cnt);
18388 
18389 		/* don't reset xirtag due to hole in xri block */
18390 		if (block_cnt == 0)
18391 			last_xritag = NO_XRI;
18392 
18393 		/* reset NVME buffer post count for next round of posting */
18394 		post_cnt = 0;
18395 
18396 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
18397 		while (!list_empty(&blck_nblist)) {
18398 			list_remove_head(&blck_nblist, lpfc_ncmd,
18399 					 struct lpfc_io_buf, list);
18400 			if (status) {
18401 				/* Post error.  Mark buffer unavailable. */
18402 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
18403 			} else {
18404 				/* Post success, Mark buffer available. */
18405 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
18406 				lpfc_ncmd->status = IOSTAT_SUCCESS;
18407 				num_posted++;
18408 			}
18409 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18410 		}
18411 	}
18412 	/* Push NVME buffers with sgl posted to the available list */
18413 	lpfc_io_buf_replenish(phba, &nvme_nblist);
18414 
18415 	return num_posted;
18416 }
18417 
18418 /**
18419  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
18420  * @phba: pointer to lpfc_hba struct that the frame was received on
18421  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18422  *
18423  * This function checks the fields in the @fc_hdr to see if the FC frame is a
18424  * valid type of frame that the LPFC driver will handle. This function will
18425  * return a zero if the frame is a valid frame or a non zero value when the
18426  * frame does not pass the check.
18427  **/
18428 static int
18429 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
18430 {
18431 	/*  make rctl_names static to save stack space */
18432 	struct fc_vft_header *fc_vft_hdr;
18433 	uint32_t *header = (uint32_t *) fc_hdr;
18434 
18435 #define FC_RCTL_MDS_DIAGS	0xF4
18436 
18437 	switch (fc_hdr->fh_r_ctl) {
18438 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
18439 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
18440 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
18441 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
18442 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
18443 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
18444 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
18445 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
18446 	case FC_RCTL_ELS_REQ:	/* extended link services request */
18447 	case FC_RCTL_ELS_REP:	/* extended link services reply */
18448 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
18449 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
18450 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
18451 	case FC_RCTL_BA_RMC: 	/* remove connection */
18452 	case FC_RCTL_BA_ACC:	/* basic accept */
18453 	case FC_RCTL_BA_RJT:	/* basic reject */
18454 	case FC_RCTL_BA_PRMT:
18455 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
18456 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
18457 	case FC_RCTL_P_RJT:	/* port reject */
18458 	case FC_RCTL_F_RJT:	/* fabric reject */
18459 	case FC_RCTL_P_BSY:	/* port busy */
18460 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
18461 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
18462 	case FC_RCTL_LCR:	/* link credit reset */
18463 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
18464 	case FC_RCTL_END:	/* end */
18465 		break;
18466 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
18467 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18468 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
18469 		return lpfc_fc_frame_check(phba, fc_hdr);
18470 	case FC_RCTL_BA_NOP:	/* basic link service NOP */
18471 	default:
18472 		goto drop;
18473 	}
18474 
18475 	switch (fc_hdr->fh_type) {
18476 	case FC_TYPE_BLS:
18477 	case FC_TYPE_ELS:
18478 	case FC_TYPE_FCP:
18479 	case FC_TYPE_CT:
18480 	case FC_TYPE_NVME:
18481 		break;
18482 	case FC_TYPE_IP:
18483 	case FC_TYPE_ILS:
18484 	default:
18485 		goto drop;
18486 	}
18487 
18488 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
18489 			"2538 Received frame rctl:x%x, type:x%x, "
18490 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
18491 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
18492 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
18493 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
18494 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
18495 			be32_to_cpu(header[6]));
18496 	return 0;
18497 drop:
18498 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
18499 			"2539 Dropped frame rctl:x%x type:x%x\n",
18500 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18501 	return 1;
18502 }
18503 
18504 /**
18505  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
18506  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18507  *
18508  * This function processes the FC header to retrieve the VFI from the VF
18509  * header, if one exists. This function will return the VFI if one exists
18510  * or 0 if no VSAN Header exists.
18511  **/
18512 static uint32_t
18513 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
18514 {
18515 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18516 
18517 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
18518 		return 0;
18519 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
18520 }
18521 
18522 /**
18523  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
18524  * @phba: Pointer to the HBA structure to search for the vport on
18525  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18526  * @fcfi: The FC Fabric ID that the frame came from
18527  * @did: Destination ID to match against
18528  *
18529  * This function searches the @phba for a vport that matches the content of the
18530  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
18531  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
18532  * returns the matching vport pointer or NULL if unable to match frame to a
18533  * vport.
18534  **/
18535 static struct lpfc_vport *
18536 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
18537 		       uint16_t fcfi, uint32_t did)
18538 {
18539 	struct lpfc_vport **vports;
18540 	struct lpfc_vport *vport = NULL;
18541 	int i;
18542 
18543 	if (did == Fabric_DID)
18544 		return phba->pport;
18545 	if ((phba->pport->fc_flag & FC_PT2PT) &&
18546 		!(phba->link_state == LPFC_HBA_READY))
18547 		return phba->pport;
18548 
18549 	vports = lpfc_create_vport_work_array(phba);
18550 	if (vports != NULL) {
18551 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
18552 			if (phba->fcf.fcfi == fcfi &&
18553 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
18554 			    vports[i]->fc_myDID == did) {
18555 				vport = vports[i];
18556 				break;
18557 			}
18558 		}
18559 	}
18560 	lpfc_destroy_vport_work_array(phba, vports);
18561 	return vport;
18562 }
18563 
18564 /**
18565  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
18566  * @vport: The vport to work on.
18567  *
18568  * This function updates the receive sequence time stamp for this vport. The
18569  * receive sequence time stamp indicates the time that the last frame of the
18570  * the sequence that has been idle for the longest amount of time was received.
18571  * the driver uses this time stamp to indicate if any received sequences have
18572  * timed out.
18573  **/
18574 static void
18575 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
18576 {
18577 	struct lpfc_dmabuf *h_buf;
18578 	struct hbq_dmabuf *dmabuf = NULL;
18579 
18580 	/* get the oldest sequence on the rcv list */
18581 	h_buf = list_get_first(&vport->rcv_buffer_list,
18582 			       struct lpfc_dmabuf, list);
18583 	if (!h_buf)
18584 		return;
18585 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18586 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
18587 }
18588 
18589 /**
18590  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
18591  * @vport: The vport that the received sequences were sent to.
18592  *
18593  * This function cleans up all outstanding received sequences. This is called
18594  * by the driver when a link event or user action invalidates all the received
18595  * sequences.
18596  **/
18597 void
18598 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
18599 {
18600 	struct lpfc_dmabuf *h_buf, *hnext;
18601 	struct lpfc_dmabuf *d_buf, *dnext;
18602 	struct hbq_dmabuf *dmabuf = NULL;
18603 
18604 	/* start with the oldest sequence on the rcv list */
18605 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18606 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18607 		list_del_init(&dmabuf->hbuf.list);
18608 		list_for_each_entry_safe(d_buf, dnext,
18609 					 &dmabuf->dbuf.list, list) {
18610 			list_del_init(&d_buf->list);
18611 			lpfc_in_buf_free(vport->phba, d_buf);
18612 		}
18613 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18614 	}
18615 }
18616 
18617 /**
18618  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
18619  * @vport: The vport that the received sequences were sent to.
18620  *
18621  * This function determines whether any received sequences have timed out by
18622  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
18623  * indicates that there is at least one timed out sequence this routine will
18624  * go through the received sequences one at a time from most inactive to most
18625  * active to determine which ones need to be cleaned up. Once it has determined
18626  * that a sequence needs to be cleaned up it will simply free up the resources
18627  * without sending an abort.
18628  **/
18629 void
18630 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
18631 {
18632 	struct lpfc_dmabuf *h_buf, *hnext;
18633 	struct lpfc_dmabuf *d_buf, *dnext;
18634 	struct hbq_dmabuf *dmabuf = NULL;
18635 	unsigned long timeout;
18636 	int abort_count = 0;
18637 
18638 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18639 		   vport->rcv_buffer_time_stamp);
18640 	if (list_empty(&vport->rcv_buffer_list) ||
18641 	    time_before(jiffies, timeout))
18642 		return;
18643 	/* start with the oldest sequence on the rcv list */
18644 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18645 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18646 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18647 			   dmabuf->time_stamp);
18648 		if (time_before(jiffies, timeout))
18649 			break;
18650 		abort_count++;
18651 		list_del_init(&dmabuf->hbuf.list);
18652 		list_for_each_entry_safe(d_buf, dnext,
18653 					 &dmabuf->dbuf.list, list) {
18654 			list_del_init(&d_buf->list);
18655 			lpfc_in_buf_free(vport->phba, d_buf);
18656 		}
18657 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18658 	}
18659 	if (abort_count)
18660 		lpfc_update_rcv_time_stamp(vport);
18661 }
18662 
18663 /**
18664  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
18665  * @vport: pointer to a vitural port
18666  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
18667  *
18668  * This function searches through the existing incomplete sequences that have
18669  * been sent to this @vport. If the frame matches one of the incomplete
18670  * sequences then the dbuf in the @dmabuf is added to the list of frames that
18671  * make up that sequence. If no sequence is found that matches this frame then
18672  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
18673  * This function returns a pointer to the first dmabuf in the sequence list that
18674  * the frame was linked to.
18675  **/
18676 static struct hbq_dmabuf *
18677 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18678 {
18679 	struct fc_frame_header *new_hdr;
18680 	struct fc_frame_header *temp_hdr;
18681 	struct lpfc_dmabuf *d_buf;
18682 	struct lpfc_dmabuf *h_buf;
18683 	struct hbq_dmabuf *seq_dmabuf = NULL;
18684 	struct hbq_dmabuf *temp_dmabuf = NULL;
18685 	uint8_t	found = 0;
18686 
18687 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18688 	dmabuf->time_stamp = jiffies;
18689 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18690 
18691 	/* Use the hdr_buf to find the sequence that this frame belongs to */
18692 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18693 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18694 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18695 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18696 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18697 			continue;
18698 		/* found a pending sequence that matches this frame */
18699 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18700 		break;
18701 	}
18702 	if (!seq_dmabuf) {
18703 		/*
18704 		 * This indicates first frame received for this sequence.
18705 		 * Queue the buffer on the vport's rcv_buffer_list.
18706 		 */
18707 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18708 		lpfc_update_rcv_time_stamp(vport);
18709 		return dmabuf;
18710 	}
18711 	temp_hdr = seq_dmabuf->hbuf.virt;
18712 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
18713 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18714 		list_del_init(&seq_dmabuf->hbuf.list);
18715 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18716 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18717 		lpfc_update_rcv_time_stamp(vport);
18718 		return dmabuf;
18719 	}
18720 	/* move this sequence to the tail to indicate a young sequence */
18721 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
18722 	seq_dmabuf->time_stamp = jiffies;
18723 	lpfc_update_rcv_time_stamp(vport);
18724 	if (list_empty(&seq_dmabuf->dbuf.list)) {
18725 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18726 		return seq_dmabuf;
18727 	}
18728 	/* find the correct place in the sequence to insert this frame */
18729 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
18730 	while (!found) {
18731 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18732 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
18733 		/*
18734 		 * If the frame's sequence count is greater than the frame on
18735 		 * the list then insert the frame right after this frame
18736 		 */
18737 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
18738 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18739 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
18740 			found = 1;
18741 			break;
18742 		}
18743 
18744 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
18745 			break;
18746 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
18747 	}
18748 
18749 	if (found)
18750 		return seq_dmabuf;
18751 	return NULL;
18752 }
18753 
18754 /**
18755  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
18756  * @vport: pointer to a vitural port
18757  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18758  *
18759  * This function tries to abort from the partially assembed sequence, described
18760  * by the information from basic abbort @dmabuf. It checks to see whether such
18761  * partially assembled sequence held by the driver. If so, it shall free up all
18762  * the frames from the partially assembled sequence.
18763  *
18764  * Return
18765  * true  -- if there is matching partially assembled sequence present and all
18766  *          the frames freed with the sequence;
18767  * false -- if there is no matching partially assembled sequence present so
18768  *          nothing got aborted in the lower layer driver
18769  **/
18770 static bool
18771 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
18772 			    struct hbq_dmabuf *dmabuf)
18773 {
18774 	struct fc_frame_header *new_hdr;
18775 	struct fc_frame_header *temp_hdr;
18776 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
18777 	struct hbq_dmabuf *seq_dmabuf = NULL;
18778 
18779 	/* Use the hdr_buf to find the sequence that matches this frame */
18780 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18781 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
18782 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18783 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18784 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18785 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18786 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18787 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18788 			continue;
18789 		/* found a pending sequence that matches this frame */
18790 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18791 		break;
18792 	}
18793 
18794 	/* Free up all the frames from the partially assembled sequence */
18795 	if (seq_dmabuf) {
18796 		list_for_each_entry_safe(d_buf, n_buf,
18797 					 &seq_dmabuf->dbuf.list, list) {
18798 			list_del_init(&d_buf->list);
18799 			lpfc_in_buf_free(vport->phba, d_buf);
18800 		}
18801 		return true;
18802 	}
18803 	return false;
18804 }
18805 
18806 /**
18807  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18808  * @vport: pointer to a vitural port
18809  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18810  *
18811  * This function tries to abort from the assembed sequence from upper level
18812  * protocol, described by the information from basic abbort @dmabuf. It
18813  * checks to see whether such pending context exists at upper level protocol.
18814  * If so, it shall clean up the pending context.
18815  *
18816  * Return
18817  * true  -- if there is matching pending context of the sequence cleaned
18818  *          at ulp;
18819  * false -- if there is no matching pending context of the sequence present
18820  *          at ulp.
18821  **/
18822 static bool
18823 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18824 {
18825 	struct lpfc_hba *phba = vport->phba;
18826 	int handled;
18827 
18828 	/* Accepting abort at ulp with SLI4 only */
18829 	if (phba->sli_rev < LPFC_SLI_REV4)
18830 		return false;
18831 
18832 	/* Register all caring upper level protocols to attend abort */
18833 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18834 	if (handled)
18835 		return true;
18836 
18837 	return false;
18838 }
18839 
18840 /**
18841  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18842  * @phba: Pointer to HBA context object.
18843  * @cmd_iocbq: pointer to the command iocbq structure.
18844  * @rsp_iocbq: pointer to the response iocbq structure.
18845  *
18846  * This function handles the sequence abort response iocb command complete
18847  * event. It properly releases the memory allocated to the sequence abort
18848  * accept iocb.
18849  **/
18850 static void
18851 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18852 			     struct lpfc_iocbq *cmd_iocbq,
18853 			     struct lpfc_iocbq *rsp_iocbq)
18854 {
18855 	if (cmd_iocbq) {
18856 		lpfc_nlp_put(cmd_iocbq->ndlp);
18857 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
18858 	}
18859 
18860 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
18861 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18862 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18863 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
18864 			get_job_ulpstatus(phba, rsp_iocbq),
18865 			get_job_word4(phba, rsp_iocbq));
18866 }
18867 
18868 /**
18869  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
18870  * @phba: Pointer to HBA context object.
18871  * @xri: xri id in transaction.
18872  *
18873  * This function validates the xri maps to the known range of XRIs allocated an
18874  * used by the driver.
18875  **/
18876 uint16_t
18877 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
18878 		      uint16_t xri)
18879 {
18880 	uint16_t i;
18881 
18882 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
18883 		if (xri == phba->sli4_hba.xri_ids[i])
18884 			return i;
18885 	}
18886 	return NO_XRI;
18887 }
18888 
18889 /**
18890  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
18891  * @vport: pointer to a virtual port.
18892  * @fc_hdr: pointer to a FC frame header.
18893  * @aborted: was the partially assembled receive sequence successfully aborted
18894  *
18895  * This function sends a basic response to a previous unsol sequence abort
18896  * event after aborting the sequence handling.
18897  **/
18898 void
18899 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
18900 			struct fc_frame_header *fc_hdr, bool aborted)
18901 {
18902 	struct lpfc_hba *phba = vport->phba;
18903 	struct lpfc_iocbq *ctiocb = NULL;
18904 	struct lpfc_nodelist *ndlp;
18905 	uint16_t oxid, rxid, xri, lxri;
18906 	uint32_t sid, fctl;
18907 	union lpfc_wqe128 *icmd;
18908 	int rc;
18909 
18910 	if (!lpfc_is_link_up(phba))
18911 		return;
18912 
18913 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18914 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
18915 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
18916 
18917 	ndlp = lpfc_findnode_did(vport, sid);
18918 	if (!ndlp) {
18919 		ndlp = lpfc_nlp_init(vport, sid);
18920 		if (!ndlp) {
18921 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
18922 					 "1268 Failed to allocate ndlp for "
18923 					 "oxid:x%x SID:x%x\n", oxid, sid);
18924 			return;
18925 		}
18926 		/* Put ndlp onto pport node list */
18927 		lpfc_enqueue_node(vport, ndlp);
18928 	}
18929 
18930 	/* Allocate buffer for rsp iocb */
18931 	ctiocb = lpfc_sli_get_iocbq(phba);
18932 	if (!ctiocb)
18933 		return;
18934 
18935 	icmd = &ctiocb->wqe;
18936 
18937 	/* Extract the F_CTL field from FC_HDR */
18938 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
18939 
18940 	ctiocb->ndlp = lpfc_nlp_get(ndlp);
18941 	if (!ctiocb->ndlp) {
18942 		lpfc_sli_release_iocbq(phba, ctiocb);
18943 		return;
18944 	}
18945 
18946 	ctiocb->vport = phba->pport;
18947 	ctiocb->cmd_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
18948 	ctiocb->sli4_lxritag = NO_XRI;
18949 	ctiocb->sli4_xritag = NO_XRI;
18950 	ctiocb->abort_rctl = FC_RCTL_BA_ACC;
18951 
18952 	if (fctl & FC_FC_EX_CTX)
18953 		/* Exchange responder sent the abort so we
18954 		 * own the oxid.
18955 		 */
18956 		xri = oxid;
18957 	else
18958 		xri = rxid;
18959 	lxri = lpfc_sli4_xri_inrange(phba, xri);
18960 	if (lxri != NO_XRI)
18961 		lpfc_set_rrq_active(phba, ndlp, lxri,
18962 			(xri == oxid) ? rxid : oxid, 0);
18963 	/* For BA_ABTS from exchange responder, if the logical xri with
18964 	 * the oxid maps to the FCP XRI range, the port no longer has
18965 	 * that exchange context, send a BLS_RJT. Override the IOCB for
18966 	 * a BA_RJT.
18967 	 */
18968 	if ((fctl & FC_FC_EX_CTX) &&
18969 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
18970 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
18971 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
18972 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
18973 		       FC_BA_RJT_INV_XID);
18974 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
18975 		       FC_BA_RJT_UNABLE);
18976 	}
18977 
18978 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
18979 	 * the driver no longer has that exchange, send a BLS_RJT. Override
18980 	 * the IOCB for a BA_RJT.
18981 	 */
18982 	if (aborted == false) {
18983 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
18984 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
18985 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
18986 		       FC_BA_RJT_INV_XID);
18987 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
18988 		       FC_BA_RJT_UNABLE);
18989 	}
18990 
18991 	if (fctl & FC_FC_EX_CTX) {
18992 		/* ABTS sent by responder to CT exchange, construction
18993 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
18994 		 * field and RX_ID from ABTS for RX_ID field.
18995 		 */
18996 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_RSP;
18997 		bf_set(xmit_bls_rsp64_rxid, &icmd->xmit_bls_rsp, rxid);
18998 	} else {
18999 		/* ABTS sent by initiator to CT exchange, construction
19000 		 * of BA_ACC will need to allocate a new XRI as for the
19001 		 * XRI_TAG field.
19002 		 */
19003 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_INT;
19004 	}
19005 
19006 	/* OX_ID is invariable to who sent ABTS to CT exchange */
19007 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, oxid);
19008 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, rxid);
19009 
19010 	/* Use CT=VPI */
19011 	bf_set(wqe_els_did, &icmd->xmit_bls_rsp.wqe_dest,
19012 	       ndlp->nlp_DID);
19013 	bf_set(xmit_bls_rsp64_temprpi, &icmd->xmit_bls_rsp,
19014 	       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
19015 	bf_set(wqe_cmnd, &icmd->generic.wqe_com, CMD_XMIT_BLS_RSP64_CX);
19016 
19017 	/* Xmit CT abts response on exchange <xid> */
19018 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
19019 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
19020 			 ctiocb->abort_rctl, oxid, phba->link_state);
19021 
19022 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
19023 	if (rc == IOCB_ERROR) {
19024 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19025 				 "2925 Failed to issue CT ABTS RSP x%x on "
19026 				 "xri x%x, Data x%x\n",
19027 				 ctiocb->abort_rctl, oxid,
19028 				 phba->link_state);
19029 		lpfc_nlp_put(ndlp);
19030 		ctiocb->ndlp = NULL;
19031 		lpfc_sli_release_iocbq(phba, ctiocb);
19032 	}
19033 }
19034 
19035 /**
19036  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
19037  * @vport: Pointer to the vport on which this sequence was received
19038  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19039  *
19040  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
19041  * receive sequence is only partially assembed by the driver, it shall abort
19042  * the partially assembled frames for the sequence. Otherwise, if the
19043  * unsolicited receive sequence has been completely assembled and passed to
19044  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
19045  * unsolicited sequence has been aborted. After that, it will issue a basic
19046  * accept to accept the abort.
19047  **/
19048 static void
19049 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
19050 			     struct hbq_dmabuf *dmabuf)
19051 {
19052 	struct lpfc_hba *phba = vport->phba;
19053 	struct fc_frame_header fc_hdr;
19054 	uint32_t fctl;
19055 	bool aborted;
19056 
19057 	/* Make a copy of fc_hdr before the dmabuf being released */
19058 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
19059 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
19060 
19061 	if (fctl & FC_FC_EX_CTX) {
19062 		/* ABTS by responder to exchange, no cleanup needed */
19063 		aborted = true;
19064 	} else {
19065 		/* ABTS by initiator to exchange, need to do cleanup */
19066 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
19067 		if (aborted == false)
19068 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
19069 	}
19070 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19071 
19072 	if (phba->nvmet_support) {
19073 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
19074 		return;
19075 	}
19076 
19077 	/* Respond with BA_ACC or BA_RJT accordingly */
19078 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
19079 }
19080 
19081 /**
19082  * lpfc_seq_complete - Indicates if a sequence is complete
19083  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19084  *
19085  * This function checks the sequence, starting with the frame described by
19086  * @dmabuf, to see if all the frames associated with this sequence are present.
19087  * the frames associated with this sequence are linked to the @dmabuf using the
19088  * dbuf list. This function looks for two major things. 1) That the first frame
19089  * has a sequence count of zero. 2) There is a frame with last frame of sequence
19090  * set. 3) That there are no holes in the sequence count. The function will
19091  * return 1 when the sequence is complete, otherwise it will return 0.
19092  **/
19093 static int
19094 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
19095 {
19096 	struct fc_frame_header *hdr;
19097 	struct lpfc_dmabuf *d_buf;
19098 	struct hbq_dmabuf *seq_dmabuf;
19099 	uint32_t fctl;
19100 	int seq_count = 0;
19101 
19102 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19103 	/* make sure first fame of sequence has a sequence count of zero */
19104 	if (hdr->fh_seq_cnt != seq_count)
19105 		return 0;
19106 	fctl = (hdr->fh_f_ctl[0] << 16 |
19107 		hdr->fh_f_ctl[1] << 8 |
19108 		hdr->fh_f_ctl[2]);
19109 	/* If last frame of sequence we can return success. */
19110 	if (fctl & FC_FC_END_SEQ)
19111 		return 1;
19112 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
19113 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19114 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19115 		/* If there is a hole in the sequence count then fail. */
19116 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
19117 			return 0;
19118 		fctl = (hdr->fh_f_ctl[0] << 16 |
19119 			hdr->fh_f_ctl[1] << 8 |
19120 			hdr->fh_f_ctl[2]);
19121 		/* If last frame of sequence we can return success. */
19122 		if (fctl & FC_FC_END_SEQ)
19123 			return 1;
19124 	}
19125 	return 0;
19126 }
19127 
19128 /**
19129  * lpfc_prep_seq - Prep sequence for ULP processing
19130  * @vport: Pointer to the vport on which this sequence was received
19131  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
19132  *
19133  * This function takes a sequence, described by a list of frames, and creates
19134  * a list of iocbq structures to describe the sequence. This iocbq list will be
19135  * used to issue to the generic unsolicited sequence handler. This routine
19136  * returns a pointer to the first iocbq in the list. If the function is unable
19137  * to allocate an iocbq then it throw out the received frames that were not
19138  * able to be described and return a pointer to the first iocbq. If unable to
19139  * allocate any iocbqs (including the first) this function will return NULL.
19140  **/
19141 static struct lpfc_iocbq *
19142 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
19143 {
19144 	struct hbq_dmabuf *hbq_buf;
19145 	struct lpfc_dmabuf *d_buf, *n_buf;
19146 	struct lpfc_iocbq *first_iocbq, *iocbq;
19147 	struct fc_frame_header *fc_hdr;
19148 	uint32_t sid;
19149 	uint32_t len, tot_len;
19150 
19151 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19152 	/* remove from receive buffer list */
19153 	list_del_init(&seq_dmabuf->hbuf.list);
19154 	lpfc_update_rcv_time_stamp(vport);
19155 	/* get the Remote Port's SID */
19156 	sid = sli4_sid_from_fc_hdr(fc_hdr);
19157 	tot_len = 0;
19158 	/* Get an iocbq struct to fill in. */
19159 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
19160 	if (first_iocbq) {
19161 		/* Initialize the first IOCB. */
19162 		first_iocbq->wcqe_cmpl.total_data_placed = 0;
19163 		bf_set(lpfc_wcqe_c_status, &first_iocbq->wcqe_cmpl,
19164 		       IOSTAT_SUCCESS);
19165 		first_iocbq->vport = vport;
19166 
19167 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
19168 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
19169 			bf_set(els_rsp64_sid, &first_iocbq->wqe.xmit_els_rsp,
19170 			       sli4_did_from_fc_hdr(fc_hdr));
19171 		}
19172 
19173 		bf_set(wqe_ctxt_tag, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19174 		       NO_XRI);
19175 		bf_set(wqe_rcvoxid, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19176 		       be16_to_cpu(fc_hdr->fh_ox_id));
19177 
19178 		/* put the first buffer into the first iocb */
19179 		tot_len = bf_get(lpfc_rcqe_length,
19180 				 &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
19181 
19182 		first_iocbq->cmd_dmabuf = &seq_dmabuf->dbuf;
19183 		first_iocbq->bpl_dmabuf = NULL;
19184 		/* Keep track of the BDE count */
19185 		first_iocbq->wcqe_cmpl.word3 = 1;
19186 
19187 		if (tot_len > LPFC_DATA_BUF_SIZE)
19188 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize =
19189 				LPFC_DATA_BUF_SIZE;
19190 		else
19191 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize = tot_len;
19192 
19193 		first_iocbq->wcqe_cmpl.total_data_placed = tot_len;
19194 		bf_set(wqe_els_did, &first_iocbq->wqe.xmit_els_rsp.wqe_dest,
19195 		       sid);
19196 	}
19197 	iocbq = first_iocbq;
19198 	/*
19199 	 * Each IOCBq can have two Buffers assigned, so go through the list
19200 	 * of buffers for this sequence and save two buffers in each IOCBq
19201 	 */
19202 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
19203 		if (!iocbq) {
19204 			lpfc_in_buf_free(vport->phba, d_buf);
19205 			continue;
19206 		}
19207 		if (!iocbq->bpl_dmabuf) {
19208 			iocbq->bpl_dmabuf = d_buf;
19209 			iocbq->wcqe_cmpl.word3++;
19210 			/* We need to get the size out of the right CQE */
19211 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19212 			len = bf_get(lpfc_rcqe_length,
19213 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19214 			iocbq->unsol_rcv_len = len;
19215 			iocbq->wcqe_cmpl.total_data_placed += len;
19216 			tot_len += len;
19217 		} else {
19218 			iocbq = lpfc_sli_get_iocbq(vport->phba);
19219 			if (!iocbq) {
19220 				if (first_iocbq) {
19221 					bf_set(lpfc_wcqe_c_status,
19222 					       &first_iocbq->wcqe_cmpl,
19223 					       IOSTAT_SUCCESS);
19224 					first_iocbq->wcqe_cmpl.parameter =
19225 						IOERR_NO_RESOURCES;
19226 				}
19227 				lpfc_in_buf_free(vport->phba, d_buf);
19228 				continue;
19229 			}
19230 			/* We need to get the size out of the right CQE */
19231 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19232 			len = bf_get(lpfc_rcqe_length,
19233 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19234 			iocbq->cmd_dmabuf = d_buf;
19235 			iocbq->bpl_dmabuf = NULL;
19236 			iocbq->wcqe_cmpl.word3 = 1;
19237 
19238 			if (len > LPFC_DATA_BUF_SIZE)
19239 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19240 					LPFC_DATA_BUF_SIZE;
19241 			else
19242 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19243 					len;
19244 
19245 			tot_len += len;
19246 			iocbq->wcqe_cmpl.total_data_placed = tot_len;
19247 			bf_set(wqe_els_did, &iocbq->wqe.xmit_els_rsp.wqe_dest,
19248 			       sid);
19249 			list_add_tail(&iocbq->list, &first_iocbq->list);
19250 		}
19251 	}
19252 	/* Free the sequence's header buffer */
19253 	if (!first_iocbq)
19254 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
19255 
19256 	return first_iocbq;
19257 }
19258 
19259 static void
19260 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
19261 			  struct hbq_dmabuf *seq_dmabuf)
19262 {
19263 	struct fc_frame_header *fc_hdr;
19264 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
19265 	struct lpfc_hba *phba = vport->phba;
19266 
19267 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19268 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
19269 	if (!iocbq) {
19270 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19271 				"2707 Ring %d handler: Failed to allocate "
19272 				"iocb Rctl x%x Type x%x received\n",
19273 				LPFC_ELS_RING,
19274 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19275 		return;
19276 	}
19277 	if (!lpfc_complete_unsol_iocb(phba,
19278 				      phba->sli4_hba.els_wq->pring,
19279 				      iocbq, fc_hdr->fh_r_ctl,
19280 				      fc_hdr->fh_type)) {
19281 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19282 				"2540 Ring %d handler: unexpected Rctl "
19283 				"x%x Type x%x received\n",
19284 				LPFC_ELS_RING,
19285 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19286 		lpfc_in_buf_free(phba, &seq_dmabuf->dbuf);
19287 	}
19288 
19289 	/* Free iocb created in lpfc_prep_seq */
19290 	list_for_each_entry_safe(curr_iocb, next_iocb,
19291 				 &iocbq->list, list) {
19292 		list_del_init(&curr_iocb->list);
19293 		lpfc_sli_release_iocbq(phba, curr_iocb);
19294 	}
19295 	lpfc_sli_release_iocbq(phba, iocbq);
19296 }
19297 
19298 static void
19299 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
19300 			    struct lpfc_iocbq *rspiocb)
19301 {
19302 	struct lpfc_dmabuf *pcmd = cmdiocb->cmd_dmabuf;
19303 
19304 	if (pcmd && pcmd->virt)
19305 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19306 	kfree(pcmd);
19307 	lpfc_sli_release_iocbq(phba, cmdiocb);
19308 	lpfc_drain_txq(phba);
19309 }
19310 
19311 static void
19312 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
19313 			      struct hbq_dmabuf *dmabuf)
19314 {
19315 	struct fc_frame_header *fc_hdr;
19316 	struct lpfc_hba *phba = vport->phba;
19317 	struct lpfc_iocbq *iocbq = NULL;
19318 	union  lpfc_wqe128 *pwqe;
19319 	struct lpfc_dmabuf *pcmd = NULL;
19320 	uint32_t frame_len;
19321 	int rc;
19322 	unsigned long iflags;
19323 
19324 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19325 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
19326 
19327 	/* Send the received frame back */
19328 	iocbq = lpfc_sli_get_iocbq(phba);
19329 	if (!iocbq) {
19330 		/* Queue cq event and wakeup worker thread to process it */
19331 		spin_lock_irqsave(&phba->hbalock, iflags);
19332 		list_add_tail(&dmabuf->cq_event.list,
19333 			      &phba->sli4_hba.sp_queue_event);
19334 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
19335 		spin_unlock_irqrestore(&phba->hbalock, iflags);
19336 		lpfc_worker_wake_up(phba);
19337 		return;
19338 	}
19339 
19340 	/* Allocate buffer for command payload */
19341 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
19342 	if (pcmd)
19343 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
19344 					    &pcmd->phys);
19345 	if (!pcmd || !pcmd->virt)
19346 		goto exit;
19347 
19348 	INIT_LIST_HEAD(&pcmd->list);
19349 
19350 	/* copyin the payload */
19351 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
19352 
19353 	iocbq->cmd_dmabuf = pcmd;
19354 	iocbq->vport = vport;
19355 	iocbq->cmd_flag &= ~LPFC_FIP_ELS_ID_MASK;
19356 	iocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
19357 	iocbq->num_bdes = 0;
19358 
19359 	pwqe = &iocbq->wqe;
19360 	/* fill in BDE's for command */
19361 	pwqe->gen_req.bde.addrHigh = putPaddrHigh(pcmd->phys);
19362 	pwqe->gen_req.bde.addrLow = putPaddrLow(pcmd->phys);
19363 	pwqe->gen_req.bde.tus.f.bdeSize = frame_len;
19364 	pwqe->gen_req.bde.tus.f.bdeFlags = BUFF_TYPE_BDE_64;
19365 
19366 	pwqe->send_frame.frame_len = frame_len;
19367 	pwqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((__be32 *)fc_hdr));
19368 	pwqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((__be32 *)fc_hdr + 1));
19369 	pwqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((__be32 *)fc_hdr + 2));
19370 	pwqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((__be32 *)fc_hdr + 3));
19371 	pwqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((__be32 *)fc_hdr + 4));
19372 	pwqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((__be32 *)fc_hdr + 5));
19373 
19374 	pwqe->generic.wqe_com.word7 = 0;
19375 	pwqe->generic.wqe_com.word10 = 0;
19376 
19377 	bf_set(wqe_cmnd, &pwqe->generic.wqe_com, CMD_SEND_FRAME);
19378 	bf_set(wqe_sof, &pwqe->generic.wqe_com, 0x2E); /* SOF byte */
19379 	bf_set(wqe_eof, &pwqe->generic.wqe_com, 0x41); /* EOF byte */
19380 	bf_set(wqe_lenloc, &pwqe->generic.wqe_com, 1);
19381 	bf_set(wqe_xbl, &pwqe->generic.wqe_com, 1);
19382 	bf_set(wqe_dbde, &pwqe->generic.wqe_com, 1);
19383 	bf_set(wqe_xc, &pwqe->generic.wqe_com, 1);
19384 	bf_set(wqe_cmd_type, &pwqe->generic.wqe_com, 0xA);
19385 	bf_set(wqe_cqid, &pwqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
19386 	bf_set(wqe_xri_tag, &pwqe->generic.wqe_com, iocbq->sli4_xritag);
19387 	bf_set(wqe_reqtag, &pwqe->generic.wqe_com, iocbq->iotag);
19388 	bf_set(wqe_class, &pwqe->generic.wqe_com, CLASS3);
19389 	pwqe->generic.wqe_com.abort_tag = iocbq->iotag;
19390 
19391 	iocbq->cmd_cmpl = lpfc_sli4_mds_loopback_cmpl;
19392 
19393 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
19394 	if (rc == IOCB_ERROR)
19395 		goto exit;
19396 
19397 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19398 	return;
19399 
19400 exit:
19401 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
19402 			"2023 Unable to process MDS loopback frame\n");
19403 	if (pcmd && pcmd->virt)
19404 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19405 	kfree(pcmd);
19406 	if (iocbq)
19407 		lpfc_sli_release_iocbq(phba, iocbq);
19408 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19409 }
19410 
19411 /**
19412  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
19413  * @phba: Pointer to HBA context object.
19414  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
19415  *
19416  * This function is called with no lock held. This function processes all
19417  * the received buffers and gives it to upper layers when a received buffer
19418  * indicates that it is the final frame in the sequence. The interrupt
19419  * service routine processes received buffers at interrupt contexts.
19420  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
19421  * appropriate receive function when the final frame in a sequence is received.
19422  **/
19423 void
19424 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
19425 				 struct hbq_dmabuf *dmabuf)
19426 {
19427 	struct hbq_dmabuf *seq_dmabuf;
19428 	struct fc_frame_header *fc_hdr;
19429 	struct lpfc_vport *vport;
19430 	uint32_t fcfi;
19431 	uint32_t did;
19432 
19433 	/* Process each received buffer */
19434 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19435 
19436 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
19437 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
19438 		vport = phba->pport;
19439 		/* Handle MDS Loopback frames */
19440 		if  (!(phba->pport->load_flag & FC_UNLOADING))
19441 			lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19442 		else
19443 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19444 		return;
19445 	}
19446 
19447 	/* check to see if this a valid type of frame */
19448 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
19449 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19450 		return;
19451 	}
19452 
19453 	if ((bf_get(lpfc_cqe_code,
19454 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
19455 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
19456 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19457 	else
19458 		fcfi = bf_get(lpfc_rcqe_fcf_id,
19459 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19460 
19461 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
19462 		vport = phba->pport;
19463 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
19464 				"2023 MDS Loopback %d bytes\n",
19465 				bf_get(lpfc_rcqe_length,
19466 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
19467 		/* Handle MDS Loopback frames */
19468 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19469 		return;
19470 	}
19471 
19472 	/* d_id this frame is directed to */
19473 	did = sli4_did_from_fc_hdr(fc_hdr);
19474 
19475 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
19476 	if (!vport) {
19477 		/* throw out the frame */
19478 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19479 		return;
19480 	}
19481 
19482 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
19483 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
19484 		(did != Fabric_DID)) {
19485 		/*
19486 		 * Throw out the frame if we are not pt2pt.
19487 		 * The pt2pt protocol allows for discovery frames
19488 		 * to be received without a registered VPI.
19489 		 */
19490 		if (!(vport->fc_flag & FC_PT2PT) ||
19491 			(phba->link_state == LPFC_HBA_READY)) {
19492 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19493 			return;
19494 		}
19495 	}
19496 
19497 	/* Handle the basic abort sequence (BA_ABTS) event */
19498 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
19499 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
19500 		return;
19501 	}
19502 
19503 	/* Link this frame */
19504 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
19505 	if (!seq_dmabuf) {
19506 		/* unable to add frame to vport - throw it out */
19507 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19508 		return;
19509 	}
19510 	/* If not last frame in sequence continue processing frames. */
19511 	if (!lpfc_seq_complete(seq_dmabuf))
19512 		return;
19513 
19514 	/* Send the complete sequence to the upper layer protocol */
19515 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
19516 }
19517 
19518 /**
19519  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
19520  * @phba: pointer to lpfc hba data structure.
19521  *
19522  * This routine is invoked to post rpi header templates to the
19523  * HBA consistent with the SLI-4 interface spec.  This routine
19524  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19525  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19526  *
19527  * This routine does not require any locks.  It's usage is expected
19528  * to be driver load or reset recovery when the driver is
19529  * sequential.
19530  *
19531  * Return codes
19532  * 	0 - successful
19533  *      -EIO - The mailbox failed to complete successfully.
19534  * 	When this error occurs, the driver is not guaranteed
19535  *	to have any rpi regions posted to the device and
19536  *	must either attempt to repost the regions or take a
19537  *	fatal error.
19538  **/
19539 int
19540 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
19541 {
19542 	struct lpfc_rpi_hdr *rpi_page;
19543 	uint32_t rc = 0;
19544 	uint16_t lrpi = 0;
19545 
19546 	/* SLI4 ports that support extents do not require RPI headers. */
19547 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19548 		goto exit;
19549 	if (phba->sli4_hba.extents_in_use)
19550 		return -EIO;
19551 
19552 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
19553 		/*
19554 		 * Assign the rpi headers a physical rpi only if the driver
19555 		 * has not initialized those resources.  A port reset only
19556 		 * needs the headers posted.
19557 		 */
19558 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
19559 		    LPFC_RPI_RSRC_RDY)
19560 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19561 
19562 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
19563 		if (rc != MBX_SUCCESS) {
19564 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19565 					"2008 Error %d posting all rpi "
19566 					"headers\n", rc);
19567 			rc = -EIO;
19568 			break;
19569 		}
19570 	}
19571 
19572  exit:
19573 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
19574 	       LPFC_RPI_RSRC_RDY);
19575 	return rc;
19576 }
19577 
19578 /**
19579  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
19580  * @phba: pointer to lpfc hba data structure.
19581  * @rpi_page:  pointer to the rpi memory region.
19582  *
19583  * This routine is invoked to post a single rpi header to the
19584  * HBA consistent with the SLI-4 interface spec.  This memory region
19585  * maps up to 64 rpi context regions.
19586  *
19587  * Return codes
19588  * 	0 - successful
19589  * 	-ENOMEM - No available memory
19590  *      -EIO - The mailbox failed to complete successfully.
19591  **/
19592 int
19593 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
19594 {
19595 	LPFC_MBOXQ_t *mboxq;
19596 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
19597 	uint32_t rc = 0;
19598 	uint32_t shdr_status, shdr_add_status;
19599 	union lpfc_sli4_cfg_shdr *shdr;
19600 
19601 	/* SLI4 ports that support extents do not require RPI headers. */
19602 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19603 		return rc;
19604 	if (phba->sli4_hba.extents_in_use)
19605 		return -EIO;
19606 
19607 	/* The port is notified of the header region via a mailbox command. */
19608 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19609 	if (!mboxq) {
19610 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19611 				"2001 Unable to allocate memory for issuing "
19612 				"SLI_CONFIG_SPECIAL mailbox command\n");
19613 		return -ENOMEM;
19614 	}
19615 
19616 	/* Post all rpi memory regions to the port. */
19617 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
19618 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19619 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
19620 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
19621 			 sizeof(struct lpfc_sli4_cfg_mhdr),
19622 			 LPFC_SLI4_MBX_EMBED);
19623 
19624 
19625 	/* Post the physical rpi to the port for this rpi header. */
19626 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
19627 	       rpi_page->start_rpi);
19628 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
19629 	       hdr_tmpl, rpi_page->page_count);
19630 
19631 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
19632 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
19633 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19634 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
19635 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19636 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19637 	mempool_free(mboxq, phba->mbox_mem_pool);
19638 	if (shdr_status || shdr_add_status || rc) {
19639 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19640 				"2514 POST_RPI_HDR mailbox failed with "
19641 				"status x%x add_status x%x, mbx status x%x\n",
19642 				shdr_status, shdr_add_status, rc);
19643 		rc = -ENXIO;
19644 	} else {
19645 		/*
19646 		 * The next_rpi stores the next logical module-64 rpi value used
19647 		 * to post physical rpis in subsequent rpi postings.
19648 		 */
19649 		spin_lock_irq(&phba->hbalock);
19650 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
19651 		spin_unlock_irq(&phba->hbalock);
19652 	}
19653 	return rc;
19654 }
19655 
19656 /**
19657  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
19658  * @phba: pointer to lpfc hba data structure.
19659  *
19660  * This routine is invoked to post rpi header templates to the
19661  * HBA consistent with the SLI-4 interface spec.  This routine
19662  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19663  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19664  *
19665  * Returns
19666  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
19667  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
19668  **/
19669 int
19670 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
19671 {
19672 	unsigned long rpi;
19673 	uint16_t max_rpi, rpi_limit;
19674 	uint16_t rpi_remaining, lrpi = 0;
19675 	struct lpfc_rpi_hdr *rpi_hdr;
19676 	unsigned long iflag;
19677 
19678 	/*
19679 	 * Fetch the next logical rpi.  Because this index is logical,
19680 	 * the  driver starts at 0 each time.
19681 	 */
19682 	spin_lock_irqsave(&phba->hbalock, iflag);
19683 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
19684 	rpi_limit = phba->sli4_hba.next_rpi;
19685 
19686 	rpi = find_first_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit);
19687 	if (rpi >= rpi_limit)
19688 		rpi = LPFC_RPI_ALLOC_ERROR;
19689 	else {
19690 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
19691 		phba->sli4_hba.max_cfg_param.rpi_used++;
19692 		phba->sli4_hba.rpi_count++;
19693 	}
19694 	lpfc_printf_log(phba, KERN_INFO,
19695 			LOG_NODE | LOG_DISCOVERY,
19696 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
19697 			(int) rpi, max_rpi, rpi_limit);
19698 
19699 	/*
19700 	 * Don't try to allocate more rpi header regions if the device limit
19701 	 * has been exhausted.
19702 	 */
19703 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
19704 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
19705 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19706 		return rpi;
19707 	}
19708 
19709 	/*
19710 	 * RPI header postings are not required for SLI4 ports capable of
19711 	 * extents.
19712 	 */
19713 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
19714 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19715 		return rpi;
19716 	}
19717 
19718 	/*
19719 	 * If the driver is running low on rpi resources, allocate another
19720 	 * page now.  Note that the next_rpi value is used because
19721 	 * it represents how many are actually in use whereas max_rpi notes
19722 	 * how many are supported max by the device.
19723 	 */
19724 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
19725 	spin_unlock_irqrestore(&phba->hbalock, iflag);
19726 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
19727 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
19728 		if (!rpi_hdr) {
19729 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19730 					"2002 Error Could not grow rpi "
19731 					"count\n");
19732 		} else {
19733 			lrpi = rpi_hdr->start_rpi;
19734 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19735 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
19736 		}
19737 	}
19738 
19739 	return rpi;
19740 }
19741 
19742 /**
19743  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
19744  * @phba: pointer to lpfc hba data structure.
19745  * @rpi: rpi to free
19746  *
19747  * This routine is invoked to release an rpi to the pool of
19748  * available rpis maintained by the driver.
19749  **/
19750 static void
19751 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19752 {
19753 	/*
19754 	 * if the rpi value indicates a prior unreg has already
19755 	 * been done, skip the unreg.
19756 	 */
19757 	if (rpi == LPFC_RPI_ALLOC_ERROR)
19758 		return;
19759 
19760 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
19761 		phba->sli4_hba.rpi_count--;
19762 		phba->sli4_hba.max_cfg_param.rpi_used--;
19763 	} else {
19764 		lpfc_printf_log(phba, KERN_INFO,
19765 				LOG_NODE | LOG_DISCOVERY,
19766 				"2016 rpi %x not inuse\n",
19767 				rpi);
19768 	}
19769 }
19770 
19771 /**
19772  * lpfc_sli4_free_rpi - Release an rpi for reuse.
19773  * @phba: pointer to lpfc hba data structure.
19774  * @rpi: rpi to free
19775  *
19776  * This routine is invoked to release an rpi to the pool of
19777  * available rpis maintained by the driver.
19778  **/
19779 void
19780 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19781 {
19782 	spin_lock_irq(&phba->hbalock);
19783 	__lpfc_sli4_free_rpi(phba, rpi);
19784 	spin_unlock_irq(&phba->hbalock);
19785 }
19786 
19787 /**
19788  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19789  * @phba: pointer to lpfc hba data structure.
19790  *
19791  * This routine is invoked to remove the memory region that
19792  * provided rpi via a bitmask.
19793  **/
19794 void
19795 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19796 {
19797 	kfree(phba->sli4_hba.rpi_bmask);
19798 	kfree(phba->sli4_hba.rpi_ids);
19799 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19800 }
19801 
19802 /**
19803  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
19804  * @ndlp: pointer to lpfc nodelist data structure.
19805  * @cmpl: completion call-back.
19806  * @arg: data to load as MBox 'caller buffer information'
19807  *
19808  * This routine is invoked to remove the memory region that
19809  * provided rpi via a bitmask.
19810  **/
19811 int
19812 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19813 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
19814 {
19815 	LPFC_MBOXQ_t *mboxq;
19816 	struct lpfc_hba *phba = ndlp->phba;
19817 	int rc;
19818 
19819 	/* The port is notified of the header region via a mailbox command. */
19820 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19821 	if (!mboxq)
19822 		return -ENOMEM;
19823 
19824 	/* If cmpl assigned, then this nlp_get pairs with
19825 	 * lpfc_mbx_cmpl_resume_rpi.
19826 	 *
19827 	 * Else cmpl is NULL, then this nlp_get pairs with
19828 	 * lpfc_sli_def_mbox_cmpl.
19829 	 */
19830 	if (!lpfc_nlp_get(ndlp)) {
19831 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19832 				"2122 %s: Failed to get nlp ref\n",
19833 				__func__);
19834 		mempool_free(mboxq, phba->mbox_mem_pool);
19835 		return -EIO;
19836 	}
19837 
19838 	/* Post all rpi memory regions to the port. */
19839 	lpfc_resume_rpi(mboxq, ndlp);
19840 	if (cmpl) {
19841 		mboxq->mbox_cmpl = cmpl;
19842 		mboxq->ctx_buf = arg;
19843 	} else
19844 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19845 	mboxq->ctx_ndlp = ndlp;
19846 	mboxq->vport = ndlp->vport;
19847 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19848 	if (rc == MBX_NOT_FINISHED) {
19849 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19850 				"2010 Resume RPI Mailbox failed "
19851 				"status %d, mbxStatus x%x\n", rc,
19852 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19853 		lpfc_nlp_put(ndlp);
19854 		mempool_free(mboxq, phba->mbox_mem_pool);
19855 		return -EIO;
19856 	}
19857 	return 0;
19858 }
19859 
19860 /**
19861  * lpfc_sli4_init_vpi - Initialize a vpi with the port
19862  * @vport: Pointer to the vport for which the vpi is being initialized
19863  *
19864  * This routine is invoked to activate a vpi with the port.
19865  *
19866  * Returns:
19867  *    0 success
19868  *    -Evalue otherwise
19869  **/
19870 int
19871 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
19872 {
19873 	LPFC_MBOXQ_t *mboxq;
19874 	int rc = 0;
19875 	int retval = MBX_SUCCESS;
19876 	uint32_t mbox_tmo;
19877 	struct lpfc_hba *phba = vport->phba;
19878 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19879 	if (!mboxq)
19880 		return -ENOMEM;
19881 	lpfc_init_vpi(phba, mboxq, vport->vpi);
19882 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
19883 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
19884 	if (rc != MBX_SUCCESS) {
19885 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19886 				"2022 INIT VPI Mailbox failed "
19887 				"status %d, mbxStatus x%x\n", rc,
19888 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19889 		retval = -EIO;
19890 	}
19891 	if (rc != MBX_TIMEOUT)
19892 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
19893 
19894 	return retval;
19895 }
19896 
19897 /**
19898  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
19899  * @phba: pointer to lpfc hba data structure.
19900  * @mboxq: Pointer to mailbox object.
19901  *
19902  * This routine is invoked to manually add a single FCF record. The caller
19903  * must pass a completely initialized FCF_Record.  This routine takes
19904  * care of the nonembedded mailbox operations.
19905  **/
19906 static void
19907 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
19908 {
19909 	void *virt_addr;
19910 	union lpfc_sli4_cfg_shdr *shdr;
19911 	uint32_t shdr_status, shdr_add_status;
19912 
19913 	virt_addr = mboxq->sge_array->addr[0];
19914 	/* The IOCTL status is embedded in the mailbox subheader. */
19915 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
19916 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19917 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19918 
19919 	if ((shdr_status || shdr_add_status) &&
19920 		(shdr_status != STATUS_FCF_IN_USE))
19921 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19922 			"2558 ADD_FCF_RECORD mailbox failed with "
19923 			"status x%x add_status x%x\n",
19924 			shdr_status, shdr_add_status);
19925 
19926 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
19927 }
19928 
19929 /**
19930  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
19931  * @phba: pointer to lpfc hba data structure.
19932  * @fcf_record:  pointer to the initialized fcf record to add.
19933  *
19934  * This routine is invoked to manually add a single FCF record. The caller
19935  * must pass a completely initialized FCF_Record.  This routine takes
19936  * care of the nonembedded mailbox operations.
19937  **/
19938 int
19939 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
19940 {
19941 	int rc = 0;
19942 	LPFC_MBOXQ_t *mboxq;
19943 	uint8_t *bytep;
19944 	void *virt_addr;
19945 	struct lpfc_mbx_sge sge;
19946 	uint32_t alloc_len, req_len;
19947 	uint32_t fcfindex;
19948 
19949 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19950 	if (!mboxq) {
19951 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19952 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
19953 		return -ENOMEM;
19954 	}
19955 
19956 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
19957 		  sizeof(uint32_t);
19958 
19959 	/* Allocate DMA memory and set up the non-embedded mailbox command */
19960 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19961 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
19962 				     req_len, LPFC_SLI4_MBX_NEMBED);
19963 	if (alloc_len < req_len) {
19964 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19965 			"2523 Allocated DMA memory size (x%x) is "
19966 			"less than the requested DMA memory "
19967 			"size (x%x)\n", alloc_len, req_len);
19968 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19969 		return -ENOMEM;
19970 	}
19971 
19972 	/*
19973 	 * Get the first SGE entry from the non-embedded DMA memory.  This
19974 	 * routine only uses a single SGE.
19975 	 */
19976 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
19977 	virt_addr = mboxq->sge_array->addr[0];
19978 	/*
19979 	 * Configure the FCF record for FCFI 0.  This is the driver's
19980 	 * hardcoded default and gets used in nonFIP mode.
19981 	 */
19982 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
19983 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
19984 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
19985 
19986 	/*
19987 	 * Copy the fcf_index and the FCF Record Data. The data starts after
19988 	 * the FCoE header plus word10. The data copy needs to be endian
19989 	 * correct.
19990 	 */
19991 	bytep += sizeof(uint32_t);
19992 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
19993 	mboxq->vport = phba->pport;
19994 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
19995 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19996 	if (rc == MBX_NOT_FINISHED) {
19997 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19998 			"2515 ADD_FCF_RECORD mailbox failed with "
19999 			"status 0x%x\n", rc);
20000 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20001 		rc = -EIO;
20002 	} else
20003 		rc = 0;
20004 
20005 	return rc;
20006 }
20007 
20008 /**
20009  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
20010  * @phba: pointer to lpfc hba data structure.
20011  * @fcf_record:  pointer to the fcf record to write the default data.
20012  * @fcf_index: FCF table entry index.
20013  *
20014  * This routine is invoked to build the driver's default FCF record.  The
20015  * values used are hardcoded.  This routine handles memory initialization.
20016  *
20017  **/
20018 void
20019 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
20020 				struct fcf_record *fcf_record,
20021 				uint16_t fcf_index)
20022 {
20023 	memset(fcf_record, 0, sizeof(struct fcf_record));
20024 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
20025 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
20026 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
20027 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
20028 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
20029 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
20030 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
20031 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
20032 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
20033 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
20034 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
20035 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
20036 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
20037 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
20038 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
20039 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
20040 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
20041 	/* Set the VLAN bit map */
20042 	if (phba->valid_vlan) {
20043 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
20044 			= 1 << (phba->vlan_id % 8);
20045 	}
20046 }
20047 
20048 /**
20049  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
20050  * @phba: pointer to lpfc hba data structure.
20051  * @fcf_index: FCF table entry offset.
20052  *
20053  * This routine is invoked to scan the entire FCF table by reading FCF
20054  * record and processing it one at a time starting from the @fcf_index
20055  * for initial FCF discovery or fast FCF failover rediscovery.
20056  *
20057  * Return 0 if the mailbox command is submitted successfully, none 0
20058  * otherwise.
20059  **/
20060 int
20061 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20062 {
20063 	int rc = 0, error;
20064 	LPFC_MBOXQ_t *mboxq;
20065 
20066 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
20067 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
20068 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20069 	if (!mboxq) {
20070 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20071 				"2000 Failed to allocate mbox for "
20072 				"READ_FCF cmd\n");
20073 		error = -ENOMEM;
20074 		goto fail_fcf_scan;
20075 	}
20076 	/* Construct the read FCF record mailbox command */
20077 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20078 	if (rc) {
20079 		error = -EINVAL;
20080 		goto fail_fcf_scan;
20081 	}
20082 	/* Issue the mailbox command asynchronously */
20083 	mboxq->vport = phba->pport;
20084 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
20085 
20086 	spin_lock_irq(&phba->hbalock);
20087 	phba->hba_flag |= FCF_TS_INPROG;
20088 	spin_unlock_irq(&phba->hbalock);
20089 
20090 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20091 	if (rc == MBX_NOT_FINISHED)
20092 		error = -EIO;
20093 	else {
20094 		/* Reset eligible FCF count for new scan */
20095 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
20096 			phba->fcf.eligible_fcf_cnt = 0;
20097 		error = 0;
20098 	}
20099 fail_fcf_scan:
20100 	if (error) {
20101 		if (mboxq)
20102 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
20103 		/* FCF scan failed, clear FCF_TS_INPROG flag */
20104 		spin_lock_irq(&phba->hbalock);
20105 		phba->hba_flag &= ~FCF_TS_INPROG;
20106 		spin_unlock_irq(&phba->hbalock);
20107 	}
20108 	return error;
20109 }
20110 
20111 /**
20112  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
20113  * @phba: pointer to lpfc hba data structure.
20114  * @fcf_index: FCF table entry offset.
20115  *
20116  * This routine is invoked to read an FCF record indicated by @fcf_index
20117  * and to use it for FLOGI roundrobin FCF failover.
20118  *
20119  * Return 0 if the mailbox command is submitted successfully, none 0
20120  * otherwise.
20121  **/
20122 int
20123 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20124 {
20125 	int rc = 0, error;
20126 	LPFC_MBOXQ_t *mboxq;
20127 
20128 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20129 	if (!mboxq) {
20130 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20131 				"2763 Failed to allocate mbox for "
20132 				"READ_FCF cmd\n");
20133 		error = -ENOMEM;
20134 		goto fail_fcf_read;
20135 	}
20136 	/* Construct the read FCF record mailbox command */
20137 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20138 	if (rc) {
20139 		error = -EINVAL;
20140 		goto fail_fcf_read;
20141 	}
20142 	/* Issue the mailbox command asynchronously */
20143 	mboxq->vport = phba->pport;
20144 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
20145 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20146 	if (rc == MBX_NOT_FINISHED)
20147 		error = -EIO;
20148 	else
20149 		error = 0;
20150 
20151 fail_fcf_read:
20152 	if (error && mboxq)
20153 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20154 	return error;
20155 }
20156 
20157 /**
20158  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
20159  * @phba: pointer to lpfc hba data structure.
20160  * @fcf_index: FCF table entry offset.
20161  *
20162  * This routine is invoked to read an FCF record indicated by @fcf_index to
20163  * determine whether it's eligible for FLOGI roundrobin failover list.
20164  *
20165  * Return 0 if the mailbox command is submitted successfully, none 0
20166  * otherwise.
20167  **/
20168 int
20169 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20170 {
20171 	int rc = 0, error;
20172 	LPFC_MBOXQ_t *mboxq;
20173 
20174 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20175 	if (!mboxq) {
20176 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20177 				"2758 Failed to allocate mbox for "
20178 				"READ_FCF cmd\n");
20179 				error = -ENOMEM;
20180 				goto fail_fcf_read;
20181 	}
20182 	/* Construct the read FCF record mailbox command */
20183 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20184 	if (rc) {
20185 		error = -EINVAL;
20186 		goto fail_fcf_read;
20187 	}
20188 	/* Issue the mailbox command asynchronously */
20189 	mboxq->vport = phba->pport;
20190 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
20191 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20192 	if (rc == MBX_NOT_FINISHED)
20193 		error = -EIO;
20194 	else
20195 		error = 0;
20196 
20197 fail_fcf_read:
20198 	if (error && mboxq)
20199 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20200 	return error;
20201 }
20202 
20203 /**
20204  * lpfc_check_next_fcf_pri_level
20205  * @phba: pointer to the lpfc_hba struct for this port.
20206  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
20207  * routine when the rr_bmask is empty. The FCF indecies are put into the
20208  * rr_bmask based on their priority level. Starting from the highest priority
20209  * to the lowest. The most likely FCF candidate will be in the highest
20210  * priority group. When this routine is called it searches the fcf_pri list for
20211  * next lowest priority group and repopulates the rr_bmask with only those
20212  * fcf_indexes.
20213  * returns:
20214  * 1=success 0=failure
20215  **/
20216 static int
20217 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
20218 {
20219 	uint16_t next_fcf_pri;
20220 	uint16_t last_index;
20221 	struct lpfc_fcf_pri *fcf_pri;
20222 	int rc;
20223 	int ret = 0;
20224 
20225 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20226 			LPFC_SLI4_FCF_TBL_INDX_MAX);
20227 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20228 			"3060 Last IDX %d\n", last_index);
20229 
20230 	/* Verify the priority list has 2 or more entries */
20231 	spin_lock_irq(&phba->hbalock);
20232 	if (list_empty(&phba->fcf.fcf_pri_list) ||
20233 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
20234 		spin_unlock_irq(&phba->hbalock);
20235 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20236 			"3061 Last IDX %d\n", last_index);
20237 		return 0; /* Empty rr list */
20238 	}
20239 	spin_unlock_irq(&phba->hbalock);
20240 
20241 	next_fcf_pri = 0;
20242 	/*
20243 	 * Clear the rr_bmask and set all of the bits that are at this
20244 	 * priority.
20245 	 */
20246 	memset(phba->fcf.fcf_rr_bmask, 0,
20247 			sizeof(*phba->fcf.fcf_rr_bmask));
20248 	spin_lock_irq(&phba->hbalock);
20249 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20250 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
20251 			continue;
20252 		/*
20253 		 * the 1st priority that has not FLOGI failed
20254 		 * will be the highest.
20255 		 */
20256 		if (!next_fcf_pri)
20257 			next_fcf_pri = fcf_pri->fcf_rec.priority;
20258 		spin_unlock_irq(&phba->hbalock);
20259 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20260 			rc = lpfc_sli4_fcf_rr_index_set(phba,
20261 						fcf_pri->fcf_rec.fcf_index);
20262 			if (rc)
20263 				return 0;
20264 		}
20265 		spin_lock_irq(&phba->hbalock);
20266 	}
20267 	/*
20268 	 * if next_fcf_pri was not set above and the list is not empty then
20269 	 * we have failed flogis on all of them. So reset flogi failed
20270 	 * and start at the beginning.
20271 	 */
20272 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
20273 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20274 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
20275 			/*
20276 			 * the 1st priority that has not FLOGI failed
20277 			 * will be the highest.
20278 			 */
20279 			if (!next_fcf_pri)
20280 				next_fcf_pri = fcf_pri->fcf_rec.priority;
20281 			spin_unlock_irq(&phba->hbalock);
20282 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20283 				rc = lpfc_sli4_fcf_rr_index_set(phba,
20284 						fcf_pri->fcf_rec.fcf_index);
20285 				if (rc)
20286 					return 0;
20287 			}
20288 			spin_lock_irq(&phba->hbalock);
20289 		}
20290 	} else
20291 		ret = 1;
20292 	spin_unlock_irq(&phba->hbalock);
20293 
20294 	return ret;
20295 }
20296 /**
20297  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
20298  * @phba: pointer to lpfc hba data structure.
20299  *
20300  * This routine is to get the next eligible FCF record index in a round
20301  * robin fashion. If the next eligible FCF record index equals to the
20302  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
20303  * shall be returned, otherwise, the next eligible FCF record's index
20304  * shall be returned.
20305  **/
20306 uint16_t
20307 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
20308 {
20309 	uint16_t next_fcf_index;
20310 
20311 initial_priority:
20312 	/* Search start from next bit of currently registered FCF index */
20313 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
20314 
20315 next_priority:
20316 	/* Determine the next fcf index to check */
20317 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
20318 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
20319 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
20320 				       next_fcf_index);
20321 
20322 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
20323 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20324 		/*
20325 		 * If we have wrapped then we need to clear the bits that
20326 		 * have been tested so that we can detect when we should
20327 		 * change the priority level.
20328 		 */
20329 		next_fcf_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20330 					       LPFC_SLI4_FCF_TBL_INDX_MAX);
20331 	}
20332 
20333 
20334 	/* Check roundrobin failover list empty condition */
20335 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
20336 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
20337 		/*
20338 		 * If next fcf index is not found check if there are lower
20339 		 * Priority level fcf's in the fcf_priority list.
20340 		 * Set up the rr_bmask with all of the avaiable fcf bits
20341 		 * at that level and continue the selection process.
20342 		 */
20343 		if (lpfc_check_next_fcf_pri_level(phba))
20344 			goto initial_priority;
20345 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
20346 				"2844 No roundrobin failover FCF available\n");
20347 
20348 		return LPFC_FCOE_FCF_NEXT_NONE;
20349 	}
20350 
20351 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
20352 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
20353 		LPFC_FCF_FLOGI_FAILED) {
20354 		if (list_is_singular(&phba->fcf.fcf_pri_list))
20355 			return LPFC_FCOE_FCF_NEXT_NONE;
20356 
20357 		goto next_priority;
20358 	}
20359 
20360 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20361 			"2845 Get next roundrobin failover FCF (x%x)\n",
20362 			next_fcf_index);
20363 
20364 	return next_fcf_index;
20365 }
20366 
20367 /**
20368  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
20369  * @phba: pointer to lpfc hba data structure.
20370  * @fcf_index: index into the FCF table to 'set'
20371  *
20372  * This routine sets the FCF record index in to the eligible bmask for
20373  * roundrobin failover search. It checks to make sure that the index
20374  * does not go beyond the range of the driver allocated bmask dimension
20375  * before setting the bit.
20376  *
20377  * Returns 0 if the index bit successfully set, otherwise, it returns
20378  * -EINVAL.
20379  **/
20380 int
20381 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
20382 {
20383 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20384 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20385 				"2610 FCF (x%x) reached driver's book "
20386 				"keeping dimension:x%x\n",
20387 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20388 		return -EINVAL;
20389 	}
20390 	/* Set the eligible FCF record index bmask */
20391 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20392 
20393 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20394 			"2790 Set FCF (x%x) to roundrobin FCF failover "
20395 			"bmask\n", fcf_index);
20396 
20397 	return 0;
20398 }
20399 
20400 /**
20401  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
20402  * @phba: pointer to lpfc hba data structure.
20403  * @fcf_index: index into the FCF table to 'clear'
20404  *
20405  * This routine clears the FCF record index from the eligible bmask for
20406  * roundrobin failover search. It checks to make sure that the index
20407  * does not go beyond the range of the driver allocated bmask dimension
20408  * before clearing the bit.
20409  **/
20410 void
20411 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
20412 {
20413 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
20414 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20415 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20416 				"2762 FCF (x%x) reached driver's book "
20417 				"keeping dimension:x%x\n",
20418 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20419 		return;
20420 	}
20421 	/* Clear the eligible FCF record index bmask */
20422 	spin_lock_irq(&phba->hbalock);
20423 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
20424 				 list) {
20425 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
20426 			list_del_init(&fcf_pri->list);
20427 			break;
20428 		}
20429 	}
20430 	spin_unlock_irq(&phba->hbalock);
20431 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20432 
20433 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20434 			"2791 Clear FCF (x%x) from roundrobin failover "
20435 			"bmask\n", fcf_index);
20436 }
20437 
20438 /**
20439  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
20440  * @phba: pointer to lpfc hba data structure.
20441  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
20442  *
20443  * This routine is the completion routine for the rediscover FCF table mailbox
20444  * command. If the mailbox command returned failure, it will try to stop the
20445  * FCF rediscover wait timer.
20446  **/
20447 static void
20448 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
20449 {
20450 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20451 	uint32_t shdr_status, shdr_add_status;
20452 
20453 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20454 
20455 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20456 			     &redisc_fcf->header.cfg_shdr.response);
20457 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20458 			     &redisc_fcf->header.cfg_shdr.response);
20459 	if (shdr_status || shdr_add_status) {
20460 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20461 				"2746 Requesting for FCF rediscovery failed "
20462 				"status x%x add_status x%x\n",
20463 				shdr_status, shdr_add_status);
20464 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
20465 			spin_lock_irq(&phba->hbalock);
20466 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
20467 			spin_unlock_irq(&phba->hbalock);
20468 			/*
20469 			 * CVL event triggered FCF rediscover request failed,
20470 			 * last resort to re-try current registered FCF entry.
20471 			 */
20472 			lpfc_retry_pport_discovery(phba);
20473 		} else {
20474 			spin_lock_irq(&phba->hbalock);
20475 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
20476 			spin_unlock_irq(&phba->hbalock);
20477 			/*
20478 			 * DEAD FCF event triggered FCF rediscover request
20479 			 * failed, last resort to fail over as a link down
20480 			 * to FCF registration.
20481 			 */
20482 			lpfc_sli4_fcf_dead_failthrough(phba);
20483 		}
20484 	} else {
20485 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20486 				"2775 Start FCF rediscover quiescent timer\n");
20487 		/*
20488 		 * Start FCF rediscovery wait timer for pending FCF
20489 		 * before rescan FCF record table.
20490 		 */
20491 		lpfc_fcf_redisc_wait_start_timer(phba);
20492 	}
20493 
20494 	mempool_free(mbox, phba->mbox_mem_pool);
20495 }
20496 
20497 /**
20498  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
20499  * @phba: pointer to lpfc hba data structure.
20500  *
20501  * This routine is invoked to request for rediscovery of the entire FCF table
20502  * by the port.
20503  **/
20504 int
20505 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
20506 {
20507 	LPFC_MBOXQ_t *mbox;
20508 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20509 	int rc, length;
20510 
20511 	/* Cancel retry delay timers to all vports before FCF rediscover */
20512 	lpfc_cancel_all_vport_retry_delay_timer(phba);
20513 
20514 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20515 	if (!mbox) {
20516 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20517 				"2745 Failed to allocate mbox for "
20518 				"requesting FCF rediscover.\n");
20519 		return -ENOMEM;
20520 	}
20521 
20522 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
20523 		  sizeof(struct lpfc_sli4_cfg_mhdr));
20524 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
20525 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
20526 			 length, LPFC_SLI4_MBX_EMBED);
20527 
20528 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20529 	/* Set count to 0 for invalidating the entire FCF database */
20530 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
20531 
20532 	/* Issue the mailbox command asynchronously */
20533 	mbox->vport = phba->pport;
20534 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
20535 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
20536 
20537 	if (rc == MBX_NOT_FINISHED) {
20538 		mempool_free(mbox, phba->mbox_mem_pool);
20539 		return -EIO;
20540 	}
20541 	return 0;
20542 }
20543 
20544 /**
20545  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
20546  * @phba: pointer to lpfc hba data structure.
20547  *
20548  * This function is the failover routine as a last resort to the FCF DEAD
20549  * event when driver failed to perform fast FCF failover.
20550  **/
20551 void
20552 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
20553 {
20554 	uint32_t link_state;
20555 
20556 	/*
20557 	 * Last resort as FCF DEAD event failover will treat this as
20558 	 * a link down, but save the link state because we don't want
20559 	 * it to be changed to Link Down unless it is already down.
20560 	 */
20561 	link_state = phba->link_state;
20562 	lpfc_linkdown(phba);
20563 	phba->link_state = link_state;
20564 
20565 	/* Unregister FCF if no devices connected to it */
20566 	lpfc_unregister_unused_fcf(phba);
20567 }
20568 
20569 /**
20570  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
20571  * @phba: pointer to lpfc hba data structure.
20572  * @rgn23_data: pointer to configure region 23 data.
20573  *
20574  * This function gets SLI3 port configure region 23 data through memory dump
20575  * mailbox command. When it successfully retrieves data, the size of the data
20576  * will be returned, otherwise, 0 will be returned.
20577  **/
20578 static uint32_t
20579 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20580 {
20581 	LPFC_MBOXQ_t *pmb = NULL;
20582 	MAILBOX_t *mb;
20583 	uint32_t offset = 0;
20584 	int rc;
20585 
20586 	if (!rgn23_data)
20587 		return 0;
20588 
20589 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20590 	if (!pmb) {
20591 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20592 				"2600 failed to allocate mailbox memory\n");
20593 		return 0;
20594 	}
20595 	mb = &pmb->u.mb;
20596 
20597 	do {
20598 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
20599 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
20600 
20601 		if (rc != MBX_SUCCESS) {
20602 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20603 					"2601 failed to read config "
20604 					"region 23, rc 0x%x Status 0x%x\n",
20605 					rc, mb->mbxStatus);
20606 			mb->un.varDmp.word_cnt = 0;
20607 		}
20608 		/*
20609 		 * dump mem may return a zero when finished or we got a
20610 		 * mailbox error, either way we are done.
20611 		 */
20612 		if (mb->un.varDmp.word_cnt == 0)
20613 			break;
20614 
20615 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
20616 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
20617 
20618 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
20619 				       rgn23_data + offset,
20620 				       mb->un.varDmp.word_cnt);
20621 		offset += mb->un.varDmp.word_cnt;
20622 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
20623 
20624 	mempool_free(pmb, phba->mbox_mem_pool);
20625 	return offset;
20626 }
20627 
20628 /**
20629  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
20630  * @phba: pointer to lpfc hba data structure.
20631  * @rgn23_data: pointer to configure region 23 data.
20632  *
20633  * This function gets SLI4 port configure region 23 data through memory dump
20634  * mailbox command. When it successfully retrieves data, the size of the data
20635  * will be returned, otherwise, 0 will be returned.
20636  **/
20637 static uint32_t
20638 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20639 {
20640 	LPFC_MBOXQ_t *mboxq = NULL;
20641 	struct lpfc_dmabuf *mp = NULL;
20642 	struct lpfc_mqe *mqe;
20643 	uint32_t data_length = 0;
20644 	int rc;
20645 
20646 	if (!rgn23_data)
20647 		return 0;
20648 
20649 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20650 	if (!mboxq) {
20651 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20652 				"3105 failed to allocate mailbox memory\n");
20653 		return 0;
20654 	}
20655 
20656 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
20657 		goto out;
20658 	mqe = &mboxq->u.mqe;
20659 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
20660 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
20661 	if (rc)
20662 		goto out;
20663 	data_length = mqe->un.mb_words[5];
20664 	if (data_length == 0)
20665 		goto out;
20666 	if (data_length > DMP_RGN23_SIZE) {
20667 		data_length = 0;
20668 		goto out;
20669 	}
20670 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
20671 out:
20672 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
20673 	return data_length;
20674 }
20675 
20676 /**
20677  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
20678  * @phba: pointer to lpfc hba data structure.
20679  *
20680  * This function read region 23 and parse TLV for port status to
20681  * decide if the user disaled the port. If the TLV indicates the
20682  * port is disabled, the hba_flag is set accordingly.
20683  **/
20684 void
20685 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
20686 {
20687 	uint8_t *rgn23_data = NULL;
20688 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
20689 	uint32_t offset = 0;
20690 
20691 	/* Get adapter Region 23 data */
20692 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
20693 	if (!rgn23_data)
20694 		goto out;
20695 
20696 	if (phba->sli_rev < LPFC_SLI_REV4)
20697 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
20698 	else {
20699 		if_type = bf_get(lpfc_sli_intf_if_type,
20700 				 &phba->sli4_hba.sli_intf);
20701 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
20702 			goto out;
20703 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
20704 	}
20705 
20706 	if (!data_size)
20707 		goto out;
20708 
20709 	/* Check the region signature first */
20710 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
20711 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20712 			"2619 Config region 23 has bad signature\n");
20713 			goto out;
20714 	}
20715 	offset += 4;
20716 
20717 	/* Check the data structure version */
20718 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
20719 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20720 			"2620 Config region 23 has bad version\n");
20721 		goto out;
20722 	}
20723 	offset += 4;
20724 
20725 	/* Parse TLV entries in the region */
20726 	while (offset < data_size) {
20727 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
20728 			break;
20729 		/*
20730 		 * If the TLV is not driver specific TLV or driver id is
20731 		 * not linux driver id, skip the record.
20732 		 */
20733 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
20734 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
20735 		    (rgn23_data[offset + 3] != 0)) {
20736 			offset += rgn23_data[offset + 1] * 4 + 4;
20737 			continue;
20738 		}
20739 
20740 		/* Driver found a driver specific TLV in the config region */
20741 		sub_tlv_len = rgn23_data[offset + 1] * 4;
20742 		offset += 4;
20743 		tlv_offset = 0;
20744 
20745 		/*
20746 		 * Search for configured port state sub-TLV.
20747 		 */
20748 		while ((offset < data_size) &&
20749 			(tlv_offset < sub_tlv_len)) {
20750 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
20751 				offset += 4;
20752 				tlv_offset += 4;
20753 				break;
20754 			}
20755 			if (rgn23_data[offset] != PORT_STE_TYPE) {
20756 				offset += rgn23_data[offset + 1] * 4 + 4;
20757 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
20758 				continue;
20759 			}
20760 
20761 			/* This HBA contains PORT_STE configured */
20762 			if (!rgn23_data[offset + 2])
20763 				phba->hba_flag |= LINK_DISABLED;
20764 
20765 			goto out;
20766 		}
20767 	}
20768 
20769 out:
20770 	kfree(rgn23_data);
20771 	return;
20772 }
20773 
20774 /**
20775  * lpfc_log_fw_write_cmpl - logs firmware write completion status
20776  * @phba: pointer to lpfc hba data structure
20777  * @shdr_status: wr_object rsp's status field
20778  * @shdr_add_status: wr_object rsp's add_status field
20779  * @shdr_add_status_2: wr_object rsp's add_status_2 field
20780  * @shdr_change_status: wr_object rsp's change_status field
20781  * @shdr_csf: wr_object rsp's csf bit
20782  *
20783  * This routine is intended to be called after a firmware write completes.
20784  * It will log next action items to be performed by the user to instantiate
20785  * the newly downloaded firmware or reason for incompatibility.
20786  **/
20787 static void
20788 lpfc_log_fw_write_cmpl(struct lpfc_hba *phba, u32 shdr_status,
20789 		       u32 shdr_add_status, u32 shdr_add_status_2,
20790 		       u32 shdr_change_status, u32 shdr_csf)
20791 {
20792 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20793 			"4198 %s: flash_id x%02x, asic_rev x%02x, "
20794 			"status x%02x, add_status x%02x, add_status_2 x%02x, "
20795 			"change_status x%02x, csf %01x\n", __func__,
20796 			phba->sli4_hba.flash_id, phba->sli4_hba.asic_rev,
20797 			shdr_status, shdr_add_status, shdr_add_status_2,
20798 			shdr_change_status, shdr_csf);
20799 
20800 	if (shdr_add_status == LPFC_ADD_STATUS_INCOMPAT_OBJ) {
20801 		switch (shdr_add_status_2) {
20802 		case LPFC_ADD_STATUS_2_INCOMPAT_FLASH:
20803 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20804 				     "4199 Firmware write failed: "
20805 				     "image incompatible with flash x%02x\n",
20806 				     phba->sli4_hba.flash_id);
20807 			break;
20808 		case LPFC_ADD_STATUS_2_INCORRECT_ASIC:
20809 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20810 				     "4200 Firmware write failed: "
20811 				     "image incompatible with ASIC "
20812 				     "architecture x%02x\n",
20813 				     phba->sli4_hba.asic_rev);
20814 			break;
20815 		default:
20816 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20817 				     "4210 Firmware write failed: "
20818 				     "add_status_2 x%02x\n",
20819 				     shdr_add_status_2);
20820 			break;
20821 		}
20822 	} else if (!shdr_status && !shdr_add_status) {
20823 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20824 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20825 			if (shdr_csf)
20826 				shdr_change_status =
20827 						   LPFC_CHANGE_STATUS_PCI_RESET;
20828 		}
20829 
20830 		switch (shdr_change_status) {
20831 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20832 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20833 				     "3198 Firmware write complete: System "
20834 				     "reboot required to instantiate\n");
20835 			break;
20836 		case (LPFC_CHANGE_STATUS_FW_RESET):
20837 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20838 				     "3199 Firmware write complete: "
20839 				     "Firmware reset required to "
20840 				     "instantiate\n");
20841 			break;
20842 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20843 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20844 				     "3200 Firmware write complete: Port "
20845 				     "Migration or PCI Reset required to "
20846 				     "instantiate\n");
20847 			break;
20848 		case (LPFC_CHANGE_STATUS_PCI_RESET):
20849 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20850 				     "3201 Firmware write complete: PCI "
20851 				     "Reset required to instantiate\n");
20852 			break;
20853 		default:
20854 			break;
20855 		}
20856 	}
20857 }
20858 
20859 /**
20860  * lpfc_wr_object - write an object to the firmware
20861  * @phba: HBA structure that indicates port to create a queue on.
20862  * @dmabuf_list: list of dmabufs to write to the port.
20863  * @size: the total byte value of the objects to write to the port.
20864  * @offset: the current offset to be used to start the transfer.
20865  *
20866  * This routine will create a wr_object mailbox command to send to the port.
20867  * the mailbox command will be constructed using the dma buffers described in
20868  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
20869  * BDEs that the imbedded mailbox can support. The @offset variable will be
20870  * used to indicate the starting offset of the transfer and will also return
20871  * the offset after the write object mailbox has completed. @size is used to
20872  * determine the end of the object and whether the eof bit should be set.
20873  *
20874  * Return 0 is successful and offset will contain the new offset to use
20875  * for the next write.
20876  * Return negative value for error cases.
20877  **/
20878 int
20879 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
20880 	       uint32_t size, uint32_t *offset)
20881 {
20882 	struct lpfc_mbx_wr_object *wr_object;
20883 	LPFC_MBOXQ_t *mbox;
20884 	int rc = 0, i = 0;
20885 	int mbox_status = 0;
20886 	uint32_t shdr_status, shdr_add_status, shdr_add_status_2;
20887 	uint32_t shdr_change_status = 0, shdr_csf = 0;
20888 	uint32_t mbox_tmo;
20889 	struct lpfc_dmabuf *dmabuf;
20890 	uint32_t written = 0;
20891 	bool check_change_status = false;
20892 
20893 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20894 	if (!mbox)
20895 		return -ENOMEM;
20896 
20897 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
20898 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
20899 			sizeof(struct lpfc_mbx_wr_object) -
20900 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
20901 
20902 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
20903 	wr_object->u.request.write_offset = *offset;
20904 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
20905 	wr_object->u.request.object_name[0] =
20906 		cpu_to_le32(wr_object->u.request.object_name[0]);
20907 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
20908 	list_for_each_entry(dmabuf, dmabuf_list, list) {
20909 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
20910 			break;
20911 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
20912 		wr_object->u.request.bde[i].addrHigh =
20913 			putPaddrHigh(dmabuf->phys);
20914 		if (written + SLI4_PAGE_SIZE >= size) {
20915 			wr_object->u.request.bde[i].tus.f.bdeSize =
20916 				(size - written);
20917 			written += (size - written);
20918 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
20919 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
20920 			check_change_status = true;
20921 		} else {
20922 			wr_object->u.request.bde[i].tus.f.bdeSize =
20923 				SLI4_PAGE_SIZE;
20924 			written += SLI4_PAGE_SIZE;
20925 		}
20926 		i++;
20927 	}
20928 	wr_object->u.request.bde_count = i;
20929 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
20930 	if (!phba->sli4_hba.intr_enable)
20931 		mbox_status = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
20932 	else {
20933 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
20934 		mbox_status = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
20935 	}
20936 
20937 	/* The mbox status needs to be maintained to detect MBOX_TIMEOUT. */
20938 	rc = mbox_status;
20939 
20940 	/* The IOCTL status is embedded in the mailbox subheader. */
20941 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20942 			     &wr_object->header.cfg_shdr.response);
20943 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20944 				 &wr_object->header.cfg_shdr.response);
20945 	shdr_add_status_2 = bf_get(lpfc_mbox_hdr_add_status_2,
20946 				   &wr_object->header.cfg_shdr.response);
20947 	if (check_change_status) {
20948 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
20949 					    &wr_object->u.response);
20950 		shdr_csf = bf_get(lpfc_wr_object_csf,
20951 				  &wr_object->u.response);
20952 	}
20953 
20954 	if (shdr_status || shdr_add_status || shdr_add_status_2 || rc) {
20955 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20956 				"3025 Write Object mailbox failed with "
20957 				"status x%x add_status x%x, add_status_2 x%x, "
20958 				"mbx status x%x\n",
20959 				shdr_status, shdr_add_status, shdr_add_status_2,
20960 				rc);
20961 		rc = -ENXIO;
20962 		*offset = shdr_add_status;
20963 	} else {
20964 		*offset += wr_object->u.response.actual_write_length;
20965 	}
20966 
20967 	if (rc || check_change_status)
20968 		lpfc_log_fw_write_cmpl(phba, shdr_status, shdr_add_status,
20969 				       shdr_add_status_2, shdr_change_status,
20970 				       shdr_csf);
20971 
20972 	if (!phba->sli4_hba.intr_enable)
20973 		mempool_free(mbox, phba->mbox_mem_pool);
20974 	else if (mbox_status != MBX_TIMEOUT)
20975 		mempool_free(mbox, phba->mbox_mem_pool);
20976 
20977 	return rc;
20978 }
20979 
20980 /**
20981  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
20982  * @vport: pointer to vport data structure.
20983  *
20984  * This function iterate through the mailboxq and clean up all REG_LOGIN
20985  * and REG_VPI mailbox commands associated with the vport. This function
20986  * is called when driver want to restart discovery of the vport due to
20987  * a Clear Virtual Link event.
20988  **/
20989 void
20990 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
20991 {
20992 	struct lpfc_hba *phba = vport->phba;
20993 	LPFC_MBOXQ_t *mb, *nextmb;
20994 	struct lpfc_nodelist *ndlp;
20995 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
20996 	LIST_HEAD(mbox_cmd_list);
20997 	uint8_t restart_loop;
20998 
20999 	/* Clean up internally queued mailbox commands with the vport */
21000 	spin_lock_irq(&phba->hbalock);
21001 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
21002 		if (mb->vport != vport)
21003 			continue;
21004 
21005 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21006 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
21007 			continue;
21008 
21009 		list_move_tail(&mb->list, &mbox_cmd_list);
21010 	}
21011 	/* Clean up active mailbox command with the vport */
21012 	mb = phba->sli.mbox_active;
21013 	if (mb && (mb->vport == vport)) {
21014 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
21015 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
21016 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21017 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21018 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
21019 
21020 			/* This reference is local to this routine.  The
21021 			 * reference is removed at routine exit.
21022 			 */
21023 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
21024 
21025 			/* Unregister the RPI when mailbox complete */
21026 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21027 		}
21028 	}
21029 	/* Cleanup any mailbox completions which are not yet processed */
21030 	do {
21031 		restart_loop = 0;
21032 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
21033 			/*
21034 			 * If this mailox is already processed or it is
21035 			 * for another vport ignore it.
21036 			 */
21037 			if ((mb->vport != vport) ||
21038 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
21039 				continue;
21040 
21041 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21042 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
21043 				continue;
21044 
21045 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21046 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21047 				ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
21048 				/* Unregister the RPI when mailbox complete */
21049 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21050 				restart_loop = 1;
21051 				spin_unlock_irq(&phba->hbalock);
21052 				spin_lock(&ndlp->lock);
21053 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21054 				spin_unlock(&ndlp->lock);
21055 				spin_lock_irq(&phba->hbalock);
21056 				break;
21057 			}
21058 		}
21059 	} while (restart_loop);
21060 
21061 	spin_unlock_irq(&phba->hbalock);
21062 
21063 	/* Release the cleaned-up mailbox commands */
21064 	while (!list_empty(&mbox_cmd_list)) {
21065 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
21066 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21067 			ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
21068 			mb->ctx_ndlp = NULL;
21069 			if (ndlp) {
21070 				spin_lock(&ndlp->lock);
21071 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21072 				spin_unlock(&ndlp->lock);
21073 				lpfc_nlp_put(ndlp);
21074 			}
21075 		}
21076 		lpfc_mbox_rsrc_cleanup(phba, mb, MBOX_THD_UNLOCKED);
21077 	}
21078 
21079 	/* Release the ndlp with the cleaned-up active mailbox command */
21080 	if (act_mbx_ndlp) {
21081 		spin_lock(&act_mbx_ndlp->lock);
21082 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21083 		spin_unlock(&act_mbx_ndlp->lock);
21084 		lpfc_nlp_put(act_mbx_ndlp);
21085 	}
21086 }
21087 
21088 /**
21089  * lpfc_drain_txq - Drain the txq
21090  * @phba: Pointer to HBA context object.
21091  *
21092  * This function attempt to submit IOCBs on the txq
21093  * to the adapter.  For SLI4 adapters, the txq contains
21094  * ELS IOCBs that have been deferred because the there
21095  * are no SGLs.  This congestion can occur with large
21096  * vport counts during node discovery.
21097  **/
21098 
21099 uint32_t
21100 lpfc_drain_txq(struct lpfc_hba *phba)
21101 {
21102 	LIST_HEAD(completions);
21103 	struct lpfc_sli_ring *pring;
21104 	struct lpfc_iocbq *piocbq = NULL;
21105 	unsigned long iflags = 0;
21106 	char *fail_msg = NULL;
21107 	uint32_t txq_cnt = 0;
21108 	struct lpfc_queue *wq;
21109 	int ret = 0;
21110 
21111 	if (phba->link_flag & LS_MDS_LOOPBACK) {
21112 		/* MDS WQE are posted only to first WQ*/
21113 		wq = phba->sli4_hba.hdwq[0].io_wq;
21114 		if (unlikely(!wq))
21115 			return 0;
21116 		pring = wq->pring;
21117 	} else {
21118 		wq = phba->sli4_hba.els_wq;
21119 		if (unlikely(!wq))
21120 			return 0;
21121 		pring = lpfc_phba_elsring(phba);
21122 	}
21123 
21124 	if (unlikely(!pring) || list_empty(&pring->txq))
21125 		return 0;
21126 
21127 	spin_lock_irqsave(&pring->ring_lock, iflags);
21128 	list_for_each_entry(piocbq, &pring->txq, list) {
21129 		txq_cnt++;
21130 	}
21131 
21132 	if (txq_cnt > pring->txq_max)
21133 		pring->txq_max = txq_cnt;
21134 
21135 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
21136 
21137 	while (!list_empty(&pring->txq)) {
21138 		spin_lock_irqsave(&pring->ring_lock, iflags);
21139 
21140 		piocbq = lpfc_sli_ringtx_get(phba, pring);
21141 		if (!piocbq) {
21142 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21143 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21144 				"2823 txq empty and txq_cnt is %d\n ",
21145 				txq_cnt);
21146 			break;
21147 		}
21148 		txq_cnt--;
21149 
21150 		ret = __lpfc_sli_issue_iocb(phba, pring->ringno, piocbq, 0);
21151 
21152 		if (ret && ret != IOCB_BUSY) {
21153 			fail_msg = " - Cannot send IO ";
21154 			piocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21155 		}
21156 		if (fail_msg) {
21157 			piocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
21158 			/* Failed means we can't issue and need to cancel */
21159 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21160 					"2822 IOCB failed %s iotag 0x%x "
21161 					"xri 0x%x %d flg x%x\n",
21162 					fail_msg, piocbq->iotag,
21163 					piocbq->sli4_xritag, ret,
21164 					piocbq->cmd_flag);
21165 			list_add_tail(&piocbq->list, &completions);
21166 			fail_msg = NULL;
21167 		}
21168 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21169 		if (txq_cnt == 0 || ret == IOCB_BUSY)
21170 			break;
21171 	}
21172 	/* Cancel all the IOCBs that cannot be issued */
21173 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
21174 			      IOERR_SLI_ABORTED);
21175 
21176 	return txq_cnt;
21177 }
21178 
21179 /**
21180  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
21181  * @phba: Pointer to HBA context object.
21182  * @pwqeq: Pointer to command WQE.
21183  * @sglq: Pointer to the scatter gather queue object.
21184  *
21185  * This routine converts the bpl or bde that is in the WQE
21186  * to a sgl list for the sli4 hardware. The physical address
21187  * of the bpl/bde is converted back to a virtual address.
21188  * If the WQE contains a BPL then the list of BDE's is
21189  * converted to sli4_sge's. If the WQE contains a single
21190  * BDE then it is converted to a single sli_sge.
21191  * The WQE is still in cpu endianness so the contents of
21192  * the bpl can be used without byte swapping.
21193  *
21194  * Returns valid XRI = Success, NO_XRI = Failure.
21195  */
21196 static uint16_t
21197 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
21198 		 struct lpfc_sglq *sglq)
21199 {
21200 	uint16_t xritag = NO_XRI;
21201 	struct ulp_bde64 *bpl = NULL;
21202 	struct ulp_bde64 bde;
21203 	struct sli4_sge *sgl  = NULL;
21204 	struct lpfc_dmabuf *dmabuf;
21205 	union lpfc_wqe128 *wqe;
21206 	int numBdes = 0;
21207 	int i = 0;
21208 	uint32_t offset = 0; /* accumulated offset in the sg request list */
21209 	int inbound = 0; /* number of sg reply entries inbound from firmware */
21210 	uint32_t cmd;
21211 
21212 	if (!pwqeq || !sglq)
21213 		return xritag;
21214 
21215 	sgl  = (struct sli4_sge *)sglq->sgl;
21216 	wqe = &pwqeq->wqe;
21217 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
21218 
21219 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
21220 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
21221 		return sglq->sli4_xritag;
21222 	numBdes = pwqeq->num_bdes;
21223 	if (numBdes) {
21224 		/* The addrHigh and addrLow fields within the WQE
21225 		 * have not been byteswapped yet so there is no
21226 		 * need to swap them back.
21227 		 */
21228 		if (pwqeq->bpl_dmabuf)
21229 			dmabuf = pwqeq->bpl_dmabuf;
21230 		else
21231 			return xritag;
21232 
21233 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
21234 		if (!bpl)
21235 			return xritag;
21236 
21237 		for (i = 0; i < numBdes; i++) {
21238 			/* Should already be byte swapped. */
21239 			sgl->addr_hi = bpl->addrHigh;
21240 			sgl->addr_lo = bpl->addrLow;
21241 
21242 			sgl->word2 = le32_to_cpu(sgl->word2);
21243 			if ((i+1) == numBdes)
21244 				bf_set(lpfc_sli4_sge_last, sgl, 1);
21245 			else
21246 				bf_set(lpfc_sli4_sge_last, sgl, 0);
21247 			/* swap the size field back to the cpu so we
21248 			 * can assign it to the sgl.
21249 			 */
21250 			bde.tus.w = le32_to_cpu(bpl->tus.w);
21251 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
21252 			/* The offsets in the sgl need to be accumulated
21253 			 * separately for the request and reply lists.
21254 			 * The request is always first, the reply follows.
21255 			 */
21256 			switch (cmd) {
21257 			case CMD_GEN_REQUEST64_WQE:
21258 				/* add up the reply sg entries */
21259 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
21260 					inbound++;
21261 				/* first inbound? reset the offset */
21262 				if (inbound == 1)
21263 					offset = 0;
21264 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21265 				bf_set(lpfc_sli4_sge_type, sgl,
21266 					LPFC_SGE_TYPE_DATA);
21267 				offset += bde.tus.f.bdeSize;
21268 				break;
21269 			case CMD_FCP_TRSP64_WQE:
21270 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
21271 				bf_set(lpfc_sli4_sge_type, sgl,
21272 					LPFC_SGE_TYPE_DATA);
21273 				break;
21274 			case CMD_FCP_TSEND64_WQE:
21275 			case CMD_FCP_TRECEIVE64_WQE:
21276 				bf_set(lpfc_sli4_sge_type, sgl,
21277 					bpl->tus.f.bdeFlags);
21278 				if (i < 3)
21279 					offset = 0;
21280 				else
21281 					offset += bde.tus.f.bdeSize;
21282 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21283 				break;
21284 			}
21285 			sgl->word2 = cpu_to_le32(sgl->word2);
21286 			bpl++;
21287 			sgl++;
21288 		}
21289 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
21290 		/* The addrHigh and addrLow fields of the BDE have not
21291 		 * been byteswapped yet so they need to be swapped
21292 		 * before putting them in the sgl.
21293 		 */
21294 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
21295 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
21296 		sgl->word2 = le32_to_cpu(sgl->word2);
21297 		bf_set(lpfc_sli4_sge_last, sgl, 1);
21298 		sgl->word2 = cpu_to_le32(sgl->word2);
21299 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
21300 	}
21301 	return sglq->sli4_xritag;
21302 }
21303 
21304 /**
21305  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
21306  * @phba: Pointer to HBA context object.
21307  * @qp: Pointer to HDW queue.
21308  * @pwqe: Pointer to command WQE.
21309  **/
21310 int
21311 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21312 		    struct lpfc_iocbq *pwqe)
21313 {
21314 	union lpfc_wqe128 *wqe = &pwqe->wqe;
21315 	struct lpfc_async_xchg_ctx *ctxp;
21316 	struct lpfc_queue *wq;
21317 	struct lpfc_sglq *sglq;
21318 	struct lpfc_sli_ring *pring;
21319 	unsigned long iflags;
21320 	uint32_t ret = 0;
21321 
21322 	/* NVME_LS and NVME_LS ABTS requests. */
21323 	if (pwqe->cmd_flag & LPFC_IO_NVME_LS) {
21324 		pring =  phba->sli4_hba.nvmels_wq->pring;
21325 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21326 					  qp, wq_access);
21327 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
21328 		if (!sglq) {
21329 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21330 			return WQE_BUSY;
21331 		}
21332 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
21333 		pwqe->sli4_xritag = sglq->sli4_xritag;
21334 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
21335 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21336 			return WQE_ERROR;
21337 		}
21338 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21339 		       pwqe->sli4_xritag);
21340 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
21341 		if (ret) {
21342 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21343 			return ret;
21344 		}
21345 
21346 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21347 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21348 
21349 		lpfc_sli4_poll_eq(qp->hba_eq);
21350 		return 0;
21351 	}
21352 
21353 	/* NVME_FCREQ and NVME_ABTS requests */
21354 	if (pwqe->cmd_flag & (LPFC_IO_NVME | LPFC_IO_FCP | LPFC_IO_CMF)) {
21355 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21356 		wq = qp->io_wq;
21357 		pring = wq->pring;
21358 
21359 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21360 
21361 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21362 					  qp, wq_access);
21363 		ret = lpfc_sli4_wq_put(wq, wqe);
21364 		if (ret) {
21365 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21366 			return ret;
21367 		}
21368 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21369 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21370 
21371 		lpfc_sli4_poll_eq(qp->hba_eq);
21372 		return 0;
21373 	}
21374 
21375 	/* NVMET requests */
21376 	if (pwqe->cmd_flag & LPFC_IO_NVMET) {
21377 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21378 		wq = qp->io_wq;
21379 		pring = wq->pring;
21380 
21381 		ctxp = pwqe->context_un.axchg;
21382 		sglq = ctxp->ctxbuf->sglq;
21383 		if (pwqe->sli4_xritag ==  NO_XRI) {
21384 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
21385 			pwqe->sli4_xritag = sglq->sli4_xritag;
21386 		}
21387 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21388 		       pwqe->sli4_xritag);
21389 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21390 
21391 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21392 					  qp, wq_access);
21393 		ret = lpfc_sli4_wq_put(wq, wqe);
21394 		if (ret) {
21395 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21396 			return ret;
21397 		}
21398 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21399 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21400 
21401 		lpfc_sli4_poll_eq(qp->hba_eq);
21402 		return 0;
21403 	}
21404 	return WQE_ERROR;
21405 }
21406 
21407 /**
21408  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
21409  * @phba: Pointer to HBA context object.
21410  * @cmdiocb: Pointer to driver command iocb object.
21411  * @cmpl: completion function.
21412  *
21413  * Fill the appropriate fields for the abort WQE and call
21414  * internal routine lpfc_sli4_issue_wqe to send the WQE
21415  * This function is called with hbalock held and no ring_lock held.
21416  *
21417  * RETURNS 0 - SUCCESS
21418  **/
21419 
21420 int
21421 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
21422 			    void *cmpl)
21423 {
21424 	struct lpfc_vport *vport = cmdiocb->vport;
21425 	struct lpfc_iocbq *abtsiocb = NULL;
21426 	union lpfc_wqe128 *abtswqe;
21427 	struct lpfc_io_buf *lpfc_cmd;
21428 	int retval = IOCB_ERROR;
21429 	u16 xritag = cmdiocb->sli4_xritag;
21430 
21431 	/*
21432 	 * The scsi command can not be in txq and it is in flight because the
21433 	 * pCmd is still pointing at the SCSI command we have to abort. There
21434 	 * is no need to search the txcmplq. Just send an abort to the FW.
21435 	 */
21436 
21437 	abtsiocb = __lpfc_sli_get_iocbq(phba);
21438 	if (!abtsiocb)
21439 		return WQE_NORESOURCE;
21440 
21441 	/* Indicate the IO is being aborted by the driver. */
21442 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
21443 
21444 	abtswqe = &abtsiocb->wqe;
21445 	memset(abtswqe, 0, sizeof(*abtswqe));
21446 
21447 	if (!lpfc_is_link_up(phba) || (phba->link_flag & LS_EXTERNAL_LOOPBACK))
21448 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
21449 	bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
21450 	abtswqe->abort_cmd.rsrvd5 = 0;
21451 	abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
21452 	bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
21453 	bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
21454 	bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
21455 	bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
21456 	bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
21457 	bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
21458 
21459 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
21460 	abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
21461 	abtsiocb->cmd_flag |= LPFC_USE_FCPWQIDX;
21462 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
21463 		abtsiocb->cmd_flag |= LPFC_IO_FCP;
21464 	if (cmdiocb->cmd_flag & LPFC_IO_NVME)
21465 		abtsiocb->cmd_flag |= LPFC_IO_NVME;
21466 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
21467 		abtsiocb->cmd_flag |= LPFC_IO_FOF;
21468 	abtsiocb->vport = vport;
21469 	abtsiocb->cmd_cmpl = cmpl;
21470 
21471 	lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
21472 	retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
21473 
21474 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21475 			 "0359 Abort xri x%x, original iotag x%x, "
21476 			 "abort cmd iotag x%x retval x%x\n",
21477 			 xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
21478 
21479 	if (retval) {
21480 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21481 		__lpfc_sli_release_iocbq(phba, abtsiocb);
21482 	}
21483 
21484 	return retval;
21485 }
21486 
21487 #ifdef LPFC_MXP_STAT
21488 /**
21489  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
21490  * @phba: pointer to lpfc hba data structure.
21491  * @hwqid: belong to which HWQ.
21492  *
21493  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
21494  * 15 seconds after a test case is running.
21495  *
21496  * The user should call lpfc_debugfs_multixripools_write before running a test
21497  * case to clear stat_snapshot_taken. Then the user starts a test case. During
21498  * test case is running, stat_snapshot_taken is incremented by 1 every time when
21499  * this routine is called from heartbeat timer. When stat_snapshot_taken is
21500  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
21501  **/
21502 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
21503 {
21504 	struct lpfc_sli4_hdw_queue *qp;
21505 	struct lpfc_multixri_pool *multixri_pool;
21506 	struct lpfc_pvt_pool *pvt_pool;
21507 	struct lpfc_pbl_pool *pbl_pool;
21508 	u32 txcmplq_cnt;
21509 
21510 	qp = &phba->sli4_hba.hdwq[hwqid];
21511 	multixri_pool = qp->p_multixri_pool;
21512 	if (!multixri_pool)
21513 		return;
21514 
21515 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
21516 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21517 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21518 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21519 
21520 		multixri_pool->stat_pbl_count = pbl_pool->count;
21521 		multixri_pool->stat_pvt_count = pvt_pool->count;
21522 		multixri_pool->stat_busy_count = txcmplq_cnt;
21523 	}
21524 
21525 	multixri_pool->stat_snapshot_taken++;
21526 }
21527 #endif
21528 
21529 /**
21530  * lpfc_adjust_pvt_pool_count - Adjust private pool count
21531  * @phba: pointer to lpfc hba data structure.
21532  * @hwqid: belong to which HWQ.
21533  *
21534  * This routine moves some XRIs from private to public pool when private pool
21535  * is not busy.
21536  **/
21537 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
21538 {
21539 	struct lpfc_multixri_pool *multixri_pool;
21540 	u32 io_req_count;
21541 	u32 prev_io_req_count;
21542 
21543 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21544 	if (!multixri_pool)
21545 		return;
21546 	io_req_count = multixri_pool->io_req_count;
21547 	prev_io_req_count = multixri_pool->prev_io_req_count;
21548 
21549 	if (prev_io_req_count != io_req_count) {
21550 		/* Private pool is busy */
21551 		multixri_pool->prev_io_req_count = io_req_count;
21552 	} else {
21553 		/* Private pool is not busy.
21554 		 * Move XRIs from private to public pool.
21555 		 */
21556 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
21557 	}
21558 }
21559 
21560 /**
21561  * lpfc_adjust_high_watermark - Adjust high watermark
21562  * @phba: pointer to lpfc hba data structure.
21563  * @hwqid: belong to which HWQ.
21564  *
21565  * This routine sets high watermark as number of outstanding XRIs,
21566  * but make sure the new value is between xri_limit/2 and xri_limit.
21567  **/
21568 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
21569 {
21570 	u32 new_watermark;
21571 	u32 watermark_max;
21572 	u32 watermark_min;
21573 	u32 xri_limit;
21574 	u32 txcmplq_cnt;
21575 	u32 abts_io_bufs;
21576 	struct lpfc_multixri_pool *multixri_pool;
21577 	struct lpfc_sli4_hdw_queue *qp;
21578 
21579 	qp = &phba->sli4_hba.hdwq[hwqid];
21580 	multixri_pool = qp->p_multixri_pool;
21581 	if (!multixri_pool)
21582 		return;
21583 	xri_limit = multixri_pool->xri_limit;
21584 
21585 	watermark_max = xri_limit;
21586 	watermark_min = xri_limit / 2;
21587 
21588 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21589 	abts_io_bufs = qp->abts_scsi_io_bufs;
21590 	abts_io_bufs += qp->abts_nvme_io_bufs;
21591 
21592 	new_watermark = txcmplq_cnt + abts_io_bufs;
21593 	new_watermark = min(watermark_max, new_watermark);
21594 	new_watermark = max(watermark_min, new_watermark);
21595 	multixri_pool->pvt_pool.high_watermark = new_watermark;
21596 
21597 #ifdef LPFC_MXP_STAT
21598 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
21599 					  new_watermark);
21600 #endif
21601 }
21602 
21603 /**
21604  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
21605  * @phba: pointer to lpfc hba data structure.
21606  * @hwqid: belong to which HWQ.
21607  *
21608  * This routine is called from hearbeat timer when pvt_pool is idle.
21609  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
21610  * The first step moves (all - low_watermark) amount of XRIs.
21611  * The second step moves the rest of XRIs.
21612  **/
21613 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
21614 {
21615 	struct lpfc_pbl_pool *pbl_pool;
21616 	struct lpfc_pvt_pool *pvt_pool;
21617 	struct lpfc_sli4_hdw_queue *qp;
21618 	struct lpfc_io_buf *lpfc_ncmd;
21619 	struct lpfc_io_buf *lpfc_ncmd_next;
21620 	unsigned long iflag;
21621 	struct list_head tmp_list;
21622 	u32 tmp_count;
21623 
21624 	qp = &phba->sli4_hba.hdwq[hwqid];
21625 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
21626 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
21627 	tmp_count = 0;
21628 
21629 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
21630 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
21631 
21632 	if (pvt_pool->count > pvt_pool->low_watermark) {
21633 		/* Step 1: move (all - low_watermark) from pvt_pool
21634 		 * to pbl_pool
21635 		 */
21636 
21637 		/* Move low watermark of bufs from pvt_pool to tmp_list */
21638 		INIT_LIST_HEAD(&tmp_list);
21639 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21640 					 &pvt_pool->list, list) {
21641 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
21642 			tmp_count++;
21643 			if (tmp_count >= pvt_pool->low_watermark)
21644 				break;
21645 		}
21646 
21647 		/* Move all bufs from pvt_pool to pbl_pool */
21648 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21649 
21650 		/* Move all bufs from tmp_list to pvt_pool */
21651 		list_splice(&tmp_list, &pvt_pool->list);
21652 
21653 		pbl_pool->count += (pvt_pool->count - tmp_count);
21654 		pvt_pool->count = tmp_count;
21655 	} else {
21656 		/* Step 2: move the rest from pvt_pool to pbl_pool */
21657 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21658 		pbl_pool->count += pvt_pool->count;
21659 		pvt_pool->count = 0;
21660 	}
21661 
21662 	spin_unlock(&pvt_pool->lock);
21663 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21664 }
21665 
21666 /**
21667  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21668  * @phba: pointer to lpfc hba data structure
21669  * @qp: pointer to HDW queue
21670  * @pbl_pool: specified public free XRI pool
21671  * @pvt_pool: specified private free XRI pool
21672  * @count: number of XRIs to move
21673  *
21674  * This routine tries to move some free common bufs from the specified pbl_pool
21675  * to the specified pvt_pool. It might move less than count XRIs if there's not
21676  * enough in public pool.
21677  *
21678  * Return:
21679  *   true - if XRIs are successfully moved from the specified pbl_pool to the
21680  *          specified pvt_pool
21681  *   false - if the specified pbl_pool is empty or locked by someone else
21682  **/
21683 static bool
21684 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21685 			  struct lpfc_pbl_pool *pbl_pool,
21686 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
21687 {
21688 	struct lpfc_io_buf *lpfc_ncmd;
21689 	struct lpfc_io_buf *lpfc_ncmd_next;
21690 	unsigned long iflag;
21691 	int ret;
21692 
21693 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
21694 	if (ret) {
21695 		if (pbl_pool->count) {
21696 			/* Move a batch of XRIs from public to private pool */
21697 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
21698 			list_for_each_entry_safe(lpfc_ncmd,
21699 						 lpfc_ncmd_next,
21700 						 &pbl_pool->list,
21701 						 list) {
21702 				list_move_tail(&lpfc_ncmd->list,
21703 					       &pvt_pool->list);
21704 				pvt_pool->count++;
21705 				pbl_pool->count--;
21706 				count--;
21707 				if (count == 0)
21708 					break;
21709 			}
21710 
21711 			spin_unlock(&pvt_pool->lock);
21712 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21713 			return true;
21714 		}
21715 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21716 	}
21717 
21718 	return false;
21719 }
21720 
21721 /**
21722  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21723  * @phba: pointer to lpfc hba data structure.
21724  * @hwqid: belong to which HWQ.
21725  * @count: number of XRIs to move
21726  *
21727  * This routine tries to find some free common bufs in one of public pools with
21728  * Round Robin method. The search always starts from local hwqid, then the next
21729  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
21730  * a batch of free common bufs are moved to private pool on hwqid.
21731  * It might move less than count XRIs if there's not enough in public pool.
21732  **/
21733 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
21734 {
21735 	struct lpfc_multixri_pool *multixri_pool;
21736 	struct lpfc_multixri_pool *next_multixri_pool;
21737 	struct lpfc_pvt_pool *pvt_pool;
21738 	struct lpfc_pbl_pool *pbl_pool;
21739 	struct lpfc_sli4_hdw_queue *qp;
21740 	u32 next_hwqid;
21741 	u32 hwq_count;
21742 	int ret;
21743 
21744 	qp = &phba->sli4_hba.hdwq[hwqid];
21745 	multixri_pool = qp->p_multixri_pool;
21746 	pvt_pool = &multixri_pool->pvt_pool;
21747 	pbl_pool = &multixri_pool->pbl_pool;
21748 
21749 	/* Check if local pbl_pool is available */
21750 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
21751 	if (ret) {
21752 #ifdef LPFC_MXP_STAT
21753 		multixri_pool->local_pbl_hit_count++;
21754 #endif
21755 		return;
21756 	}
21757 
21758 	hwq_count = phba->cfg_hdw_queue;
21759 
21760 	/* Get the next hwqid which was found last time */
21761 	next_hwqid = multixri_pool->rrb_next_hwqid;
21762 
21763 	do {
21764 		/* Go to next hwq */
21765 		next_hwqid = (next_hwqid + 1) % hwq_count;
21766 
21767 		next_multixri_pool =
21768 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
21769 		pbl_pool = &next_multixri_pool->pbl_pool;
21770 
21771 		/* Check if the public free xri pool is available */
21772 		ret = _lpfc_move_xri_pbl_to_pvt(
21773 			phba, qp, pbl_pool, pvt_pool, count);
21774 
21775 		/* Exit while-loop if success or all hwqid are checked */
21776 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
21777 
21778 	/* Starting point for the next time */
21779 	multixri_pool->rrb_next_hwqid = next_hwqid;
21780 
21781 	if (!ret) {
21782 		/* stats: all public pools are empty*/
21783 		multixri_pool->pbl_empty_count++;
21784 	}
21785 
21786 #ifdef LPFC_MXP_STAT
21787 	if (ret) {
21788 		if (next_hwqid == hwqid)
21789 			multixri_pool->local_pbl_hit_count++;
21790 		else
21791 			multixri_pool->other_pbl_hit_count++;
21792 	}
21793 #endif
21794 }
21795 
21796 /**
21797  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
21798  * @phba: pointer to lpfc hba data structure.
21799  * @hwqid: belong to which HWQ.
21800  *
21801  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
21802  * low watermark.
21803  **/
21804 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
21805 {
21806 	struct lpfc_multixri_pool *multixri_pool;
21807 	struct lpfc_pvt_pool *pvt_pool;
21808 
21809 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21810 	pvt_pool = &multixri_pool->pvt_pool;
21811 
21812 	if (pvt_pool->count < pvt_pool->low_watermark)
21813 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21814 }
21815 
21816 /**
21817  * lpfc_release_io_buf - Return one IO buf back to free pool
21818  * @phba: pointer to lpfc hba data structure.
21819  * @lpfc_ncmd: IO buf to be returned.
21820  * @qp: belong to which HWQ.
21821  *
21822  * This routine returns one IO buf back to free pool. If this is an urgent IO,
21823  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
21824  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
21825  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
21826  * lpfc_io_buf_list_put.
21827  **/
21828 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
21829 			 struct lpfc_sli4_hdw_queue *qp)
21830 {
21831 	unsigned long iflag;
21832 	struct lpfc_pbl_pool *pbl_pool;
21833 	struct lpfc_pvt_pool *pvt_pool;
21834 	struct lpfc_epd_pool *epd_pool;
21835 	u32 txcmplq_cnt;
21836 	u32 xri_owned;
21837 	u32 xri_limit;
21838 	u32 abts_io_bufs;
21839 
21840 	/* MUST zero fields if buffer is reused by another protocol */
21841 	lpfc_ncmd->nvmeCmd = NULL;
21842 	lpfc_ncmd->cur_iocbq.cmd_cmpl = NULL;
21843 
21844 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
21845 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
21846 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
21847 
21848 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
21849 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
21850 
21851 	if (phba->cfg_xri_rebalancing) {
21852 		if (lpfc_ncmd->expedite) {
21853 			/* Return to expedite pool */
21854 			epd_pool = &phba->epd_pool;
21855 			spin_lock_irqsave(&epd_pool->lock, iflag);
21856 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21857 			epd_pool->count++;
21858 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
21859 			return;
21860 		}
21861 
21862 		/* Avoid invalid access if an IO sneaks in and is being rejected
21863 		 * just _after_ xri pools are destroyed in lpfc_offline.
21864 		 * Nothing much can be done at this point.
21865 		 */
21866 		if (!qp->p_multixri_pool)
21867 			return;
21868 
21869 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21870 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21871 
21872 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21873 		abts_io_bufs = qp->abts_scsi_io_bufs;
21874 		abts_io_bufs += qp->abts_nvme_io_bufs;
21875 
21876 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21877 		xri_limit = qp->p_multixri_pool->xri_limit;
21878 
21879 #ifdef LPFC_MXP_STAT
21880 		if (xri_owned <= xri_limit)
21881 			qp->p_multixri_pool->below_limit_count++;
21882 		else
21883 			qp->p_multixri_pool->above_limit_count++;
21884 #endif
21885 
21886 		/* XRI goes to either public or private free xri pool
21887 		 *     based on watermark and xri_limit
21888 		 */
21889 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
21890 		    (xri_owned < xri_limit &&
21891 		     pvt_pool->count < pvt_pool->high_watermark)) {
21892 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
21893 						  qp, free_pvt_pool);
21894 			list_add_tail(&lpfc_ncmd->list,
21895 				      &pvt_pool->list);
21896 			pvt_pool->count++;
21897 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21898 		} else {
21899 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
21900 						  qp, free_pub_pool);
21901 			list_add_tail(&lpfc_ncmd->list,
21902 				      &pbl_pool->list);
21903 			pbl_pool->count++;
21904 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21905 		}
21906 	} else {
21907 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
21908 					  qp, free_xri);
21909 		list_add_tail(&lpfc_ncmd->list,
21910 			      &qp->lpfc_io_buf_list_put);
21911 		qp->put_io_bufs++;
21912 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
21913 				       iflag);
21914 	}
21915 }
21916 
21917 /**
21918  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
21919  * @phba: pointer to lpfc hba data structure.
21920  * @qp: pointer to HDW queue
21921  * @pvt_pool: pointer to private pool data structure.
21922  * @ndlp: pointer to lpfc nodelist data structure.
21923  *
21924  * This routine tries to get one free IO buf from private pool.
21925  *
21926  * Return:
21927  *   pointer to one free IO buf - if private pool is not empty
21928  *   NULL - if private pool is empty
21929  **/
21930 static struct lpfc_io_buf *
21931 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
21932 				  struct lpfc_sli4_hdw_queue *qp,
21933 				  struct lpfc_pvt_pool *pvt_pool,
21934 				  struct lpfc_nodelist *ndlp)
21935 {
21936 	struct lpfc_io_buf *lpfc_ncmd;
21937 	struct lpfc_io_buf *lpfc_ncmd_next;
21938 	unsigned long iflag;
21939 
21940 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
21941 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21942 				 &pvt_pool->list, list) {
21943 		if (lpfc_test_rrq_active(
21944 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
21945 			continue;
21946 		list_del(&lpfc_ncmd->list);
21947 		pvt_pool->count--;
21948 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21949 		return lpfc_ncmd;
21950 	}
21951 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21952 
21953 	return NULL;
21954 }
21955 
21956 /**
21957  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
21958  * @phba: pointer to lpfc hba data structure.
21959  *
21960  * This routine tries to get one free IO buf from expedite pool.
21961  *
21962  * Return:
21963  *   pointer to one free IO buf - if expedite pool is not empty
21964  *   NULL - if expedite pool is empty
21965  **/
21966 static struct lpfc_io_buf *
21967 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
21968 {
21969 	struct lpfc_io_buf *lpfc_ncmd = NULL, *iter;
21970 	struct lpfc_io_buf *lpfc_ncmd_next;
21971 	unsigned long iflag;
21972 	struct lpfc_epd_pool *epd_pool;
21973 
21974 	epd_pool = &phba->epd_pool;
21975 
21976 	spin_lock_irqsave(&epd_pool->lock, iflag);
21977 	if (epd_pool->count > 0) {
21978 		list_for_each_entry_safe(iter, lpfc_ncmd_next,
21979 					 &epd_pool->list, list) {
21980 			list_del(&iter->list);
21981 			epd_pool->count--;
21982 			lpfc_ncmd = iter;
21983 			break;
21984 		}
21985 	}
21986 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
21987 
21988 	return lpfc_ncmd;
21989 }
21990 
21991 /**
21992  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
21993  * @phba: pointer to lpfc hba data structure.
21994  * @ndlp: pointer to lpfc nodelist data structure.
21995  * @hwqid: belong to which HWQ
21996  * @expedite: 1 means this request is urgent.
21997  *
21998  * This routine will do the following actions and then return a pointer to
21999  * one free IO buf.
22000  *
22001  * 1. If private free xri count is empty, move some XRIs from public to
22002  *    private pool.
22003  * 2. Get one XRI from private free xri pool.
22004  * 3. If we fail to get one from pvt_pool and this is an expedite request,
22005  *    get one free xri from expedite pool.
22006  *
22007  * Note: ndlp is only used on SCSI side for RRQ testing.
22008  *       The caller should pass NULL for ndlp on NVME side.
22009  *
22010  * Return:
22011  *   pointer to one free IO buf - if private pool is not empty
22012  *   NULL - if private pool is empty
22013  **/
22014 static struct lpfc_io_buf *
22015 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
22016 				    struct lpfc_nodelist *ndlp,
22017 				    int hwqid, int expedite)
22018 {
22019 	struct lpfc_sli4_hdw_queue *qp;
22020 	struct lpfc_multixri_pool *multixri_pool;
22021 	struct lpfc_pvt_pool *pvt_pool;
22022 	struct lpfc_io_buf *lpfc_ncmd;
22023 
22024 	qp = &phba->sli4_hba.hdwq[hwqid];
22025 	lpfc_ncmd = NULL;
22026 	if (!qp) {
22027 		lpfc_printf_log(phba, KERN_INFO,
22028 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22029 				"5556 NULL qp for hwqid  x%x\n", hwqid);
22030 		return lpfc_ncmd;
22031 	}
22032 	multixri_pool = qp->p_multixri_pool;
22033 	if (!multixri_pool) {
22034 		lpfc_printf_log(phba, KERN_INFO,
22035 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22036 				"5557 NULL multixri for hwqid  x%x\n", hwqid);
22037 		return lpfc_ncmd;
22038 	}
22039 	pvt_pool = &multixri_pool->pvt_pool;
22040 	if (!pvt_pool) {
22041 		lpfc_printf_log(phba, KERN_INFO,
22042 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22043 				"5558 NULL pvt_pool for hwqid  x%x\n", hwqid);
22044 		return lpfc_ncmd;
22045 	}
22046 	multixri_pool->io_req_count++;
22047 
22048 	/* If pvt_pool is empty, move some XRIs from public to private pool */
22049 	if (pvt_pool->count == 0)
22050 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
22051 
22052 	/* Get one XRI from private free xri pool */
22053 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
22054 
22055 	if (lpfc_ncmd) {
22056 		lpfc_ncmd->hdwq = qp;
22057 		lpfc_ncmd->hdwq_no = hwqid;
22058 	} else if (expedite) {
22059 		/* If we fail to get one from pvt_pool and this is an expedite
22060 		 * request, get one free xri from expedite pool.
22061 		 */
22062 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
22063 	}
22064 
22065 	return lpfc_ncmd;
22066 }
22067 
22068 static inline struct lpfc_io_buf *
22069 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
22070 {
22071 	struct lpfc_sli4_hdw_queue *qp;
22072 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
22073 
22074 	qp = &phba->sli4_hba.hdwq[idx];
22075 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
22076 				 &qp->lpfc_io_buf_list_get, list) {
22077 		if (lpfc_test_rrq_active(phba, ndlp,
22078 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
22079 			continue;
22080 
22081 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
22082 			continue;
22083 
22084 		list_del_init(&lpfc_cmd->list);
22085 		qp->get_io_bufs--;
22086 		lpfc_cmd->hdwq = qp;
22087 		lpfc_cmd->hdwq_no = idx;
22088 		return lpfc_cmd;
22089 	}
22090 	return NULL;
22091 }
22092 
22093 /**
22094  * lpfc_get_io_buf - Get one IO buffer from free pool
22095  * @phba: The HBA for which this call is being executed.
22096  * @ndlp: pointer to lpfc nodelist data structure.
22097  * @hwqid: belong to which HWQ
22098  * @expedite: 1 means this request is urgent.
22099  *
22100  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
22101  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
22102  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
22103  *
22104  * Note: ndlp is only used on SCSI side for RRQ testing.
22105  *       The caller should pass NULL for ndlp on NVME side.
22106  *
22107  * Return codes:
22108  *   NULL - Error
22109  *   Pointer to lpfc_io_buf - Success
22110  **/
22111 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
22112 				    struct lpfc_nodelist *ndlp,
22113 				    u32 hwqid, int expedite)
22114 {
22115 	struct lpfc_sli4_hdw_queue *qp;
22116 	unsigned long iflag;
22117 	struct lpfc_io_buf *lpfc_cmd;
22118 
22119 	qp = &phba->sli4_hba.hdwq[hwqid];
22120 	lpfc_cmd = NULL;
22121 	if (!qp) {
22122 		lpfc_printf_log(phba, KERN_WARNING,
22123 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22124 				"5555 NULL qp for hwqid  x%x\n", hwqid);
22125 		return lpfc_cmd;
22126 	}
22127 
22128 	if (phba->cfg_xri_rebalancing)
22129 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
22130 			phba, ndlp, hwqid, expedite);
22131 	else {
22132 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
22133 					  qp, alloc_xri_get);
22134 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
22135 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22136 		if (!lpfc_cmd) {
22137 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
22138 					  qp, alloc_xri_put);
22139 			list_splice(&qp->lpfc_io_buf_list_put,
22140 				    &qp->lpfc_io_buf_list_get);
22141 			qp->get_io_bufs += qp->put_io_bufs;
22142 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
22143 			qp->put_io_bufs = 0;
22144 			spin_unlock(&qp->io_buf_list_put_lock);
22145 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
22146 			    expedite)
22147 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22148 		}
22149 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
22150 	}
22151 
22152 	return lpfc_cmd;
22153 }
22154 
22155 /**
22156  * lpfc_read_object - Retrieve object data from HBA
22157  * @phba: The HBA for which this call is being executed.
22158  * @rdobject: Pathname of object data we want to read.
22159  * @datap: Pointer to where data will be copied to.
22160  * @datasz: size of data area
22161  *
22162  * This routine is limited to object sizes of LPFC_BPL_SIZE (1024) or less.
22163  * The data will be truncated if datasz is not large enough.
22164  * Version 1 is not supported with Embedded mbox cmd, so we must use version 0.
22165  * Returns the actual bytes read from the object.
22166  */
22167 int
22168 lpfc_read_object(struct lpfc_hba *phba, char *rdobject, uint32_t *datap,
22169 		 uint32_t datasz)
22170 {
22171 	struct lpfc_mbx_read_object *read_object;
22172 	LPFC_MBOXQ_t *mbox;
22173 	int rc, length, eof, j, byte_cnt = 0;
22174 	uint32_t shdr_status, shdr_add_status;
22175 	union lpfc_sli4_cfg_shdr *shdr;
22176 	struct lpfc_dmabuf *pcmd;
22177 	u32 rd_object_name[LPFC_MBX_OBJECT_NAME_LEN_DW] = {0};
22178 
22179 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
22180 	if (!mbox)
22181 		return -ENOMEM;
22182 	length = (sizeof(struct lpfc_mbx_read_object) -
22183 		  sizeof(struct lpfc_sli4_cfg_mhdr));
22184 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
22185 			 LPFC_MBOX_OPCODE_READ_OBJECT,
22186 			 length, LPFC_SLI4_MBX_EMBED);
22187 	read_object = &mbox->u.mqe.un.read_object;
22188 	shdr = (union lpfc_sli4_cfg_shdr *)&read_object->header.cfg_shdr;
22189 
22190 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_0);
22191 	bf_set(lpfc_mbx_rd_object_rlen, &read_object->u.request, datasz);
22192 	read_object->u.request.rd_object_offset = 0;
22193 	read_object->u.request.rd_object_cnt = 1;
22194 
22195 	memset((void *)read_object->u.request.rd_object_name, 0,
22196 	       LPFC_OBJ_NAME_SZ);
22197 	scnprintf((char *)rd_object_name, sizeof(rd_object_name), rdobject);
22198 	for (j = 0; j < strlen(rdobject); j++)
22199 		read_object->u.request.rd_object_name[j] =
22200 			cpu_to_le32(rd_object_name[j]);
22201 
22202 	pcmd = kmalloc(sizeof(*pcmd), GFP_KERNEL);
22203 	if (pcmd)
22204 		pcmd->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &pcmd->phys);
22205 	if (!pcmd || !pcmd->virt) {
22206 		kfree(pcmd);
22207 		mempool_free(mbox, phba->mbox_mem_pool);
22208 		return -ENOMEM;
22209 	}
22210 	memset((void *)pcmd->virt, 0, LPFC_BPL_SIZE);
22211 	read_object->u.request.rd_object_hbuf[0].pa_lo =
22212 		putPaddrLow(pcmd->phys);
22213 	read_object->u.request.rd_object_hbuf[0].pa_hi =
22214 		putPaddrHigh(pcmd->phys);
22215 	read_object->u.request.rd_object_hbuf[0].length = LPFC_BPL_SIZE;
22216 
22217 	mbox->vport = phba->pport;
22218 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
22219 	mbox->ctx_ndlp = NULL;
22220 
22221 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
22222 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
22223 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
22224 
22225 	if (shdr_status == STATUS_FAILED &&
22226 	    shdr_add_status == ADD_STATUS_INVALID_OBJECT_NAME) {
22227 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22228 				"4674 No port cfg file in FW.\n");
22229 		byte_cnt = -ENOENT;
22230 	} else if (shdr_status || shdr_add_status || rc) {
22231 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22232 				"2625 READ_OBJECT mailbox failed with "
22233 				"status x%x add_status x%x, mbx status x%x\n",
22234 				shdr_status, shdr_add_status, rc);
22235 		byte_cnt = -ENXIO;
22236 	} else {
22237 		/* Success */
22238 		length = read_object->u.response.rd_object_actual_rlen;
22239 		eof = bf_get(lpfc_mbx_rd_object_eof, &read_object->u.response);
22240 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_CGN_MGMT,
22241 				"2626 READ_OBJECT Success len %d:%d, EOF %d\n",
22242 				length, datasz, eof);
22243 
22244 		/* Detect the port config file exists but is empty */
22245 		if (!length && eof) {
22246 			byte_cnt = 0;
22247 			goto exit;
22248 		}
22249 
22250 		byte_cnt = length;
22251 		lpfc_sli_pcimem_bcopy(pcmd->virt, datap, byte_cnt);
22252 	}
22253 
22254  exit:
22255 	/* This is an embedded SLI4 mailbox with an external buffer allocated.
22256 	 * Free the pcmd and then cleanup with the correct routine.
22257 	 */
22258 	lpfc_mbuf_free(phba, pcmd->virt, pcmd->phys);
22259 	kfree(pcmd);
22260 	lpfc_sli4_mbox_cmd_free(phba, mbox);
22261 	return byte_cnt;
22262 }
22263 
22264 /**
22265  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
22266  * @phba: The HBA for which this call is being executed.
22267  * @lpfc_buf: IO buf structure to append the SGL chunk
22268  *
22269  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
22270  * and will allocate an SGL chunk if the pool is empty.
22271  *
22272  * Return codes:
22273  *   NULL - Error
22274  *   Pointer to sli4_hybrid_sgl - Success
22275  **/
22276 struct sli4_hybrid_sgl *
22277 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22278 {
22279 	struct sli4_hybrid_sgl *list_entry = NULL;
22280 	struct sli4_hybrid_sgl *tmp = NULL;
22281 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
22282 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22283 	struct list_head *buf_list = &hdwq->sgl_list;
22284 	unsigned long iflags;
22285 
22286 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22287 
22288 	if (likely(!list_empty(buf_list))) {
22289 		/* break off 1 chunk from the sgl_list */
22290 		list_for_each_entry_safe(list_entry, tmp,
22291 					 buf_list, list_node) {
22292 			list_move_tail(&list_entry->list_node,
22293 				       &lpfc_buf->dma_sgl_xtra_list);
22294 			break;
22295 		}
22296 	} else {
22297 		/* allocate more */
22298 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22299 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22300 				   cpu_to_node(hdwq->io_wq->chann));
22301 		if (!tmp) {
22302 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22303 					"8353 error kmalloc memory for HDWQ "
22304 					"%d %s\n",
22305 					lpfc_buf->hdwq_no, __func__);
22306 			return NULL;
22307 		}
22308 
22309 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
22310 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
22311 		if (!tmp->dma_sgl) {
22312 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22313 					"8354 error pool_alloc memory for HDWQ "
22314 					"%d %s\n",
22315 					lpfc_buf->hdwq_no, __func__);
22316 			kfree(tmp);
22317 			return NULL;
22318 		}
22319 
22320 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22321 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
22322 	}
22323 
22324 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
22325 					struct sli4_hybrid_sgl,
22326 					list_node);
22327 
22328 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22329 
22330 	return allocated_sgl;
22331 }
22332 
22333 /**
22334  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
22335  * @phba: The HBA for which this call is being executed.
22336  * @lpfc_buf: IO buf structure with the SGL chunk
22337  *
22338  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
22339  *
22340  * Return codes:
22341  *   0 - Success
22342  *   -EINVAL - Error
22343  **/
22344 int
22345 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22346 {
22347 	int rc = 0;
22348 	struct sli4_hybrid_sgl *list_entry = NULL;
22349 	struct sli4_hybrid_sgl *tmp = NULL;
22350 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22351 	struct list_head *buf_list = &hdwq->sgl_list;
22352 	unsigned long iflags;
22353 
22354 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22355 
22356 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
22357 		list_for_each_entry_safe(list_entry, tmp,
22358 					 &lpfc_buf->dma_sgl_xtra_list,
22359 					 list_node) {
22360 			list_move_tail(&list_entry->list_node,
22361 				       buf_list);
22362 		}
22363 	} else {
22364 		rc = -EINVAL;
22365 	}
22366 
22367 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22368 	return rc;
22369 }
22370 
22371 /**
22372  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
22373  * @phba: phba object
22374  * @hdwq: hdwq to cleanup sgl buff resources on
22375  *
22376  * This routine frees all SGL chunks of hdwq SGL chunk pool.
22377  *
22378  * Return codes:
22379  *   None
22380  **/
22381 void
22382 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
22383 		       struct lpfc_sli4_hdw_queue *hdwq)
22384 {
22385 	struct list_head *buf_list = &hdwq->sgl_list;
22386 	struct sli4_hybrid_sgl *list_entry = NULL;
22387 	struct sli4_hybrid_sgl *tmp = NULL;
22388 	unsigned long iflags;
22389 
22390 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22391 
22392 	/* Free sgl pool */
22393 	list_for_each_entry_safe(list_entry, tmp,
22394 				 buf_list, list_node) {
22395 		list_del(&list_entry->list_node);
22396 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
22397 			      list_entry->dma_sgl,
22398 			      list_entry->dma_phys_sgl);
22399 		kfree(list_entry);
22400 	}
22401 
22402 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22403 }
22404 
22405 /**
22406  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
22407  * @phba: The HBA for which this call is being executed.
22408  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
22409  *
22410  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
22411  * and will allocate an CMD/RSP buffer if the pool is empty.
22412  *
22413  * Return codes:
22414  *   NULL - Error
22415  *   Pointer to fcp_cmd_rsp_buf - Success
22416  **/
22417 struct fcp_cmd_rsp_buf *
22418 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22419 			      struct lpfc_io_buf *lpfc_buf)
22420 {
22421 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22422 	struct fcp_cmd_rsp_buf *tmp = NULL;
22423 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
22424 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22425 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22426 	unsigned long iflags;
22427 
22428 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22429 
22430 	if (likely(!list_empty(buf_list))) {
22431 		/* break off 1 chunk from the list */
22432 		list_for_each_entry_safe(list_entry, tmp,
22433 					 buf_list,
22434 					 list_node) {
22435 			list_move_tail(&list_entry->list_node,
22436 				       &lpfc_buf->dma_cmd_rsp_list);
22437 			break;
22438 		}
22439 	} else {
22440 		/* allocate more */
22441 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22442 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22443 				   cpu_to_node(hdwq->io_wq->chann));
22444 		if (!tmp) {
22445 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22446 					"8355 error kmalloc memory for HDWQ "
22447 					"%d %s\n",
22448 					lpfc_buf->hdwq_no, __func__);
22449 			return NULL;
22450 		}
22451 
22452 		tmp->fcp_cmnd = dma_pool_zalloc(phba->lpfc_cmd_rsp_buf_pool,
22453 						GFP_ATOMIC,
22454 						&tmp->fcp_cmd_rsp_dma_handle);
22455 
22456 		if (!tmp->fcp_cmnd) {
22457 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22458 					"8356 error pool_alloc memory for HDWQ "
22459 					"%d %s\n",
22460 					lpfc_buf->hdwq_no, __func__);
22461 			kfree(tmp);
22462 			return NULL;
22463 		}
22464 
22465 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
22466 				sizeof(struct fcp_cmnd));
22467 
22468 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22469 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
22470 	}
22471 
22472 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
22473 					struct fcp_cmd_rsp_buf,
22474 					list_node);
22475 
22476 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22477 
22478 	return allocated_buf;
22479 }
22480 
22481 /**
22482  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
22483  * @phba: The HBA for which this call is being executed.
22484  * @lpfc_buf: IO buf structure with the CMD/RSP buf
22485  *
22486  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
22487  *
22488  * Return codes:
22489  *   0 - Success
22490  *   -EINVAL - Error
22491  **/
22492 int
22493 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22494 			      struct lpfc_io_buf *lpfc_buf)
22495 {
22496 	int rc = 0;
22497 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22498 	struct fcp_cmd_rsp_buf *tmp = NULL;
22499 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22500 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22501 	unsigned long iflags;
22502 
22503 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22504 
22505 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
22506 		list_for_each_entry_safe(list_entry, tmp,
22507 					 &lpfc_buf->dma_cmd_rsp_list,
22508 					 list_node) {
22509 			list_move_tail(&list_entry->list_node,
22510 				       buf_list);
22511 		}
22512 	} else {
22513 		rc = -EINVAL;
22514 	}
22515 
22516 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22517 	return rc;
22518 }
22519 
22520 /**
22521  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
22522  * @phba: phba object
22523  * @hdwq: hdwq to cleanup cmd rsp buff resources on
22524  *
22525  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
22526  *
22527  * Return codes:
22528  *   None
22529  **/
22530 void
22531 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22532 			       struct lpfc_sli4_hdw_queue *hdwq)
22533 {
22534 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22535 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22536 	struct fcp_cmd_rsp_buf *tmp = NULL;
22537 	unsigned long iflags;
22538 
22539 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22540 
22541 	/* Free cmd_rsp buf pool */
22542 	list_for_each_entry_safe(list_entry, tmp,
22543 				 buf_list,
22544 				 list_node) {
22545 		list_del(&list_entry->list_node);
22546 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
22547 			      list_entry->fcp_cmnd,
22548 			      list_entry->fcp_cmd_rsp_dma_handle);
22549 		kfree(list_entry);
22550 	}
22551 
22552 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22553 }
22554 
22555 /**
22556  * lpfc_sli_prep_wqe - Prepare WQE for the command to be posted
22557  * @phba: phba object
22558  * @job: job entry of the command to be posted.
22559  *
22560  * Fill the common fields of the wqe for each of the command.
22561  *
22562  * Return codes:
22563  *	None
22564  **/
22565 void
22566 lpfc_sli_prep_wqe(struct lpfc_hba *phba, struct lpfc_iocbq *job)
22567 {
22568 	u8 cmnd;
22569 	u32 *pcmd;
22570 	u32 if_type = 0;
22571 	u32 fip, abort_tag;
22572 	struct lpfc_nodelist *ndlp = NULL;
22573 	union lpfc_wqe128 *wqe = &job->wqe;
22574 	u8 command_type = ELS_COMMAND_NON_FIP;
22575 
22576 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
22577 	/* The fcp commands will set command type */
22578 	if (job->cmd_flag &  LPFC_IO_FCP)
22579 		command_type = FCP_COMMAND;
22580 	else if (fip && (job->cmd_flag & LPFC_FIP_ELS_ID_MASK))
22581 		command_type = ELS_COMMAND_FIP;
22582 	else
22583 		command_type = ELS_COMMAND_NON_FIP;
22584 
22585 	abort_tag = job->iotag;
22586 	cmnd = bf_get(wqe_cmnd, &wqe->els_req.wqe_com);
22587 
22588 	switch (cmnd) {
22589 	case CMD_ELS_REQUEST64_WQE:
22590 		ndlp = job->ndlp;
22591 
22592 		if_type = bf_get(lpfc_sli_intf_if_type,
22593 				 &phba->sli4_hba.sli_intf);
22594 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22595 			pcmd = (u32 *)job->cmd_dmabuf->virt;
22596 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
22597 				     *pcmd == ELS_CMD_SCR ||
22598 				     *pcmd == ELS_CMD_RDF ||
22599 				     *pcmd == ELS_CMD_EDC ||
22600 				     *pcmd == ELS_CMD_RSCN_XMT ||
22601 				     *pcmd == ELS_CMD_FDISC ||
22602 				     *pcmd == ELS_CMD_LOGO ||
22603 				     *pcmd == ELS_CMD_QFPA ||
22604 				     *pcmd == ELS_CMD_UVEM ||
22605 				     *pcmd == ELS_CMD_PLOGI)) {
22606 				bf_set(els_req64_sp, &wqe->els_req, 1);
22607 				bf_set(els_req64_sid, &wqe->els_req,
22608 				       job->vport->fc_myDID);
22609 
22610 				if ((*pcmd == ELS_CMD_FLOGI) &&
22611 				    !(phba->fc_topology ==
22612 				      LPFC_TOPOLOGY_LOOP))
22613 					bf_set(els_req64_sid, &wqe->els_req, 0);
22614 
22615 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
22616 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22617 				       phba->vpi_ids[job->vport->vpi]);
22618 			} else if (pcmd) {
22619 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
22620 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22621 				       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22622 			}
22623 		}
22624 
22625 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
22626 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22627 
22628 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
22629 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
22630 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
22631 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22632 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
22633 		break;
22634 	case CMD_XMIT_ELS_RSP64_WQE:
22635 		ndlp = job->ndlp;
22636 
22637 		/* word4 */
22638 		wqe->xmit_els_rsp.word4 = 0;
22639 
22640 		if_type = bf_get(lpfc_sli_intf_if_type,
22641 				 &phba->sli4_hba.sli_intf);
22642 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22643 			if (job->vport->fc_flag & FC_PT2PT) {
22644 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22645 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22646 				       job->vport->fc_myDID);
22647 				if (job->vport->fc_myDID == Fabric_DID) {
22648 					bf_set(wqe_els_did,
22649 					       &wqe->xmit_els_rsp.wqe_dest, 0);
22650 				}
22651 			}
22652 		}
22653 
22654 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
22655 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
22656 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
22657 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
22658 		       LPFC_WQE_LENLOC_WORD3);
22659 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
22660 
22661 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
22662 			bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22663 			bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22664 			       job->vport->fc_myDID);
22665 			bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
22666 		}
22667 
22668 		if (phba->sli_rev == LPFC_SLI_REV4) {
22669 			bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
22670 			       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22671 
22672 			if (bf_get(wqe_ct, &wqe->xmit_els_rsp.wqe_com))
22673 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
22674 				       phba->vpi_ids[job->vport->vpi]);
22675 		}
22676 		command_type = OTHER_COMMAND;
22677 		break;
22678 	case CMD_GEN_REQUEST64_WQE:
22679 		/* Word 10 */
22680 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
22681 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
22682 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
22683 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22684 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
22685 		command_type = OTHER_COMMAND;
22686 		break;
22687 	case CMD_XMIT_SEQUENCE64_WQE:
22688 		if (phba->link_flag & LS_LOOPBACK_MODE)
22689 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
22690 
22691 		wqe->xmit_sequence.rsvd3 = 0;
22692 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
22693 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
22694 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
22695 		       LPFC_WQE_IOD_WRITE);
22696 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
22697 		       LPFC_WQE_LENLOC_WORD12);
22698 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
22699 		command_type = OTHER_COMMAND;
22700 		break;
22701 	case CMD_XMIT_BLS_RSP64_WQE:
22702 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
22703 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
22704 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
22705 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
22706 		       phba->vpi_ids[phba->pport->vpi]);
22707 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
22708 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
22709 		       LPFC_WQE_LENLOC_NONE);
22710 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
22711 		command_type = OTHER_COMMAND;
22712 		break;
22713 	case CMD_FCP_ICMND64_WQE:	/* task mgmt commands */
22714 	case CMD_ABORT_XRI_WQE:		/* abort iotag */
22715 	case CMD_SEND_FRAME:		/* mds loopback */
22716 		/* cases already formatted for sli4 wqe - no chgs necessary */
22717 		return;
22718 	default:
22719 		dump_stack();
22720 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
22721 				"6207 Invalid command 0x%x\n",
22722 				cmnd);
22723 		break;
22724 	}
22725 
22726 	wqe->generic.wqe_com.abort_tag = abort_tag;
22727 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, job->iotag);
22728 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
22729 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
22730 }
22731