xref: /linux/drivers/scsi/lpfc/lpfc_sli.c (revision 0be3ff0c)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2022 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.     *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/pci.h>
26 #include <linux/interrupt.h>
27 #include <linux/delay.h>
28 #include <linux/slab.h>
29 #include <linux/lockdep.h>
30 
31 #include <scsi/scsi.h>
32 #include <scsi/scsi_cmnd.h>
33 #include <scsi/scsi_device.h>
34 #include <scsi/scsi_host.h>
35 #include <scsi/scsi_transport_fc.h>
36 #include <scsi/fc/fc_fs.h>
37 #include <linux/aer.h>
38 #include <linux/crash_dump.h>
39 #ifdef CONFIG_X86
40 #include <asm/set_memory.h>
41 #endif
42 
43 #include "lpfc_hw4.h"
44 #include "lpfc_hw.h"
45 #include "lpfc_sli.h"
46 #include "lpfc_sli4.h"
47 #include "lpfc_nl.h"
48 #include "lpfc_disc.h"
49 #include "lpfc.h"
50 #include "lpfc_scsi.h"
51 #include "lpfc_nvme.h"
52 #include "lpfc_crtn.h"
53 #include "lpfc_logmsg.h"
54 #include "lpfc_compat.h"
55 #include "lpfc_debugfs.h"
56 #include "lpfc_vport.h"
57 #include "lpfc_version.h"
58 
59 /* There are only four IOCB completion types. */
60 typedef enum _lpfc_iocb_type {
61 	LPFC_UNKNOWN_IOCB,
62 	LPFC_UNSOL_IOCB,
63 	LPFC_SOL_IOCB,
64 	LPFC_ABORT_IOCB
65 } lpfc_iocb_type;
66 
67 
68 /* Provide function prototypes local to this module. */
69 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
70 				  uint32_t);
71 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
72 			      uint8_t *, uint32_t *);
73 static struct lpfc_iocbq *
74 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
75 				  struct lpfc_iocbq *rspiocbq);
76 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
77 				      struct hbq_dmabuf *);
78 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
79 					  struct hbq_dmabuf *dmabuf);
80 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
81 				   struct lpfc_queue *cq, struct lpfc_cqe *cqe);
82 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
83 				       int);
84 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
85 				     struct lpfc_queue *eq,
86 				     struct lpfc_eqe *eqe);
87 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
88 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
89 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
90 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
91 				    struct lpfc_queue *cq,
92 				    struct lpfc_cqe *cqe);
93 static uint16_t lpfc_wqe_bpl2sgl(struct lpfc_hba *phba,
94 				 struct lpfc_iocbq *pwqeq,
95 				 struct lpfc_sglq *sglq);
96 
97 union lpfc_wqe128 lpfc_iread_cmd_template;
98 union lpfc_wqe128 lpfc_iwrite_cmd_template;
99 union lpfc_wqe128 lpfc_icmnd_cmd_template;
100 
101 /* Setup WQE templates for IOs */
102 void lpfc_wqe_cmd_template(void)
103 {
104 	union lpfc_wqe128 *wqe;
105 
106 	/* IREAD template */
107 	wqe = &lpfc_iread_cmd_template;
108 	memset(wqe, 0, sizeof(union lpfc_wqe128));
109 
110 	/* Word 0, 1, 2 - BDE is variable */
111 
112 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
113 
114 	/* Word 4 - total_xfer_len is variable */
115 
116 	/* Word 5 - is zero */
117 
118 	/* Word 6 - ctxt_tag, xri_tag is variable */
119 
120 	/* Word 7 */
121 	bf_set(wqe_cmnd, &wqe->fcp_iread.wqe_com, CMD_FCP_IREAD64_WQE);
122 	bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, PARM_READ_CHECK);
123 	bf_set(wqe_class, &wqe->fcp_iread.wqe_com, CLASS3);
124 	bf_set(wqe_ct, &wqe->fcp_iread.wqe_com, SLI4_CT_RPI);
125 
126 	/* Word 8 - abort_tag is variable */
127 
128 	/* Word 9  - reqtag is variable */
129 
130 	/* Word 10 - dbde, wqes is variable */
131 	bf_set(wqe_qosd, &wqe->fcp_iread.wqe_com, 0);
132 	bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
133 	bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com, LPFC_WQE_LENLOC_WORD4);
134 	bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
135 	bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
136 
137 	/* Word 11 - pbde is variable */
138 	bf_set(wqe_cmd_type, &wqe->fcp_iread.wqe_com, COMMAND_DATA_IN);
139 	bf_set(wqe_cqid, &wqe->fcp_iread.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
140 	bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
141 
142 	/* Word 12 - is zero */
143 
144 	/* Word 13, 14, 15 - PBDE is variable */
145 
146 	/* IWRITE template */
147 	wqe = &lpfc_iwrite_cmd_template;
148 	memset(wqe, 0, sizeof(union lpfc_wqe128));
149 
150 	/* Word 0, 1, 2 - BDE is variable */
151 
152 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
153 
154 	/* Word 4 - total_xfer_len is variable */
155 
156 	/* Word 5 - initial_xfer_len is variable */
157 
158 	/* Word 6 - ctxt_tag, xri_tag is variable */
159 
160 	/* Word 7 */
161 	bf_set(wqe_cmnd, &wqe->fcp_iwrite.wqe_com, CMD_FCP_IWRITE64_WQE);
162 	bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, PARM_READ_CHECK);
163 	bf_set(wqe_class, &wqe->fcp_iwrite.wqe_com, CLASS3);
164 	bf_set(wqe_ct, &wqe->fcp_iwrite.wqe_com, SLI4_CT_RPI);
165 
166 	/* Word 8 - abort_tag is variable */
167 
168 	/* Word 9  - reqtag is variable */
169 
170 	/* Word 10 - dbde, wqes is variable */
171 	bf_set(wqe_qosd, &wqe->fcp_iwrite.wqe_com, 0);
172 	bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
173 	bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_LENLOC_WORD4);
174 	bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
175 	bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
176 
177 	/* Word 11 - pbde is variable */
178 	bf_set(wqe_cmd_type, &wqe->fcp_iwrite.wqe_com, COMMAND_DATA_OUT);
179 	bf_set(wqe_cqid, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
180 	bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
181 
182 	/* Word 12 - is zero */
183 
184 	/* Word 13, 14, 15 - PBDE is variable */
185 
186 	/* ICMND template */
187 	wqe = &lpfc_icmnd_cmd_template;
188 	memset(wqe, 0, sizeof(union lpfc_wqe128));
189 
190 	/* Word 0, 1, 2 - BDE is variable */
191 
192 	/* Word 3 - payload_offset_len is variable */
193 
194 	/* Word 4, 5 - is zero */
195 
196 	/* Word 6 - ctxt_tag, xri_tag is variable */
197 
198 	/* Word 7 */
199 	bf_set(wqe_cmnd, &wqe->fcp_icmd.wqe_com, CMD_FCP_ICMND64_WQE);
200 	bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
201 	bf_set(wqe_class, &wqe->fcp_icmd.wqe_com, CLASS3);
202 	bf_set(wqe_ct, &wqe->fcp_icmd.wqe_com, SLI4_CT_RPI);
203 
204 	/* Word 8 - abort_tag is variable */
205 
206 	/* Word 9  - reqtag is variable */
207 
208 	/* Word 10 - dbde, wqes is variable */
209 	bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
210 	bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_NONE);
211 	bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com, LPFC_WQE_LENLOC_NONE);
212 	bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
213 	bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
214 
215 	/* Word 11 */
216 	bf_set(wqe_cmd_type, &wqe->fcp_icmd.wqe_com, COMMAND_DATA_IN);
217 	bf_set(wqe_cqid, &wqe->fcp_icmd.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
218 	bf_set(wqe_pbde, &wqe->fcp_icmd.wqe_com, 0);
219 
220 	/* Word 12, 13, 14, 15 - is zero */
221 }
222 
223 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
224 /**
225  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
226  * @srcp: Source memory pointer.
227  * @destp: Destination memory pointer.
228  * @cnt: Number of words required to be copied.
229  *       Must be a multiple of sizeof(uint64_t)
230  *
231  * This function is used for copying data between driver memory
232  * and the SLI WQ. This function also changes the endianness
233  * of each word if native endianness is different from SLI
234  * endianness. This function can be called with or without
235  * lock.
236  **/
237 static void
238 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
239 {
240 	uint64_t *src = srcp;
241 	uint64_t *dest = destp;
242 	int i;
243 
244 	for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
245 		*dest++ = *src++;
246 }
247 #else
248 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
249 #endif
250 
251 /**
252  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
253  * @q: The Work Queue to operate on.
254  * @wqe: The work Queue Entry to put on the Work queue.
255  *
256  * This routine will copy the contents of @wqe to the next available entry on
257  * the @q. This function will then ring the Work Queue Doorbell to signal the
258  * HBA to start processing the Work Queue Entry. This function returns 0 if
259  * successful. If no entries are available on @q then this function will return
260  * -ENOMEM.
261  * The caller is expected to hold the hbalock when calling this routine.
262  **/
263 static int
264 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
265 {
266 	union lpfc_wqe *temp_wqe;
267 	struct lpfc_register doorbell;
268 	uint32_t host_index;
269 	uint32_t idx;
270 	uint32_t i = 0;
271 	uint8_t *tmp;
272 	u32 if_type;
273 
274 	/* sanity check on queue memory */
275 	if (unlikely(!q))
276 		return -ENOMEM;
277 
278 	temp_wqe = lpfc_sli4_qe(q, q->host_index);
279 
280 	/* If the host has not yet processed the next entry then we are done */
281 	idx = ((q->host_index + 1) % q->entry_count);
282 	if (idx == q->hba_index) {
283 		q->WQ_overflow++;
284 		return -EBUSY;
285 	}
286 	q->WQ_posted++;
287 	/* set consumption flag every once in a while */
288 	if (!((q->host_index + 1) % q->notify_interval))
289 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
290 	else
291 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
292 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
293 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
294 	lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
295 	if (q->dpp_enable && q->phba->cfg_enable_dpp) {
296 		/* write to DPP aperture taking advatage of Combined Writes */
297 		tmp = (uint8_t *)temp_wqe;
298 #ifdef __raw_writeq
299 		for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
300 			__raw_writeq(*((uint64_t *)(tmp + i)),
301 					q->dpp_regaddr + i);
302 #else
303 		for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
304 			__raw_writel(*((uint32_t *)(tmp + i)),
305 					q->dpp_regaddr + i);
306 #endif
307 	}
308 	/* ensure WQE bcopy and DPP flushed before doorbell write */
309 	wmb();
310 
311 	/* Update the host index before invoking device */
312 	host_index = q->host_index;
313 
314 	q->host_index = idx;
315 
316 	/* Ring Doorbell */
317 	doorbell.word0 = 0;
318 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
319 		if (q->dpp_enable && q->phba->cfg_enable_dpp) {
320 			bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
321 			bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
322 			bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
323 			    q->dpp_id);
324 			bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
325 			    q->queue_id);
326 		} else {
327 			bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
328 			bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
329 
330 			/* Leave bits <23:16> clear for if_type 6 dpp */
331 			if_type = bf_get(lpfc_sli_intf_if_type,
332 					 &q->phba->sli4_hba.sli_intf);
333 			if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
334 				bf_set(lpfc_wq_db_list_fm_index, &doorbell,
335 				       host_index);
336 		}
337 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
338 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
339 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
340 	} else {
341 		return -EINVAL;
342 	}
343 	writel(doorbell.word0, q->db_regaddr);
344 
345 	return 0;
346 }
347 
348 /**
349  * lpfc_sli4_wq_release - Updates internal hba index for WQ
350  * @q: The Work Queue to operate on.
351  * @index: The index to advance the hba index to.
352  *
353  * This routine will update the HBA index of a queue to reflect consumption of
354  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
355  * an entry the host calls this function to update the queue's internal
356  * pointers.
357  **/
358 static void
359 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
360 {
361 	/* sanity check on queue memory */
362 	if (unlikely(!q))
363 		return;
364 
365 	q->hba_index = index;
366 }
367 
368 /**
369  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
370  * @q: The Mailbox Queue to operate on.
371  * @mqe: The Mailbox Queue Entry to put on the Work queue.
372  *
373  * This routine will copy the contents of @mqe to the next available entry on
374  * the @q. This function will then ring the Work Queue Doorbell to signal the
375  * HBA to start processing the Work Queue Entry. This function returns 0 if
376  * successful. If no entries are available on @q then this function will return
377  * -ENOMEM.
378  * The caller is expected to hold the hbalock when calling this routine.
379  **/
380 static uint32_t
381 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
382 {
383 	struct lpfc_mqe *temp_mqe;
384 	struct lpfc_register doorbell;
385 
386 	/* sanity check on queue memory */
387 	if (unlikely(!q))
388 		return -ENOMEM;
389 	temp_mqe = lpfc_sli4_qe(q, q->host_index);
390 
391 	/* If the host has not yet processed the next entry then we are done */
392 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
393 		return -ENOMEM;
394 	lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
395 	/* Save off the mailbox pointer for completion */
396 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
397 
398 	/* Update the host index before invoking device */
399 	q->host_index = ((q->host_index + 1) % q->entry_count);
400 
401 	/* Ring Doorbell */
402 	doorbell.word0 = 0;
403 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
404 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
405 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
406 	return 0;
407 }
408 
409 /**
410  * lpfc_sli4_mq_release - Updates internal hba index for MQ
411  * @q: The Mailbox Queue to operate on.
412  *
413  * This routine will update the HBA index of a queue to reflect consumption of
414  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
415  * an entry the host calls this function to update the queue's internal
416  * pointers. This routine returns the number of entries that were consumed by
417  * the HBA.
418  **/
419 static uint32_t
420 lpfc_sli4_mq_release(struct lpfc_queue *q)
421 {
422 	/* sanity check on queue memory */
423 	if (unlikely(!q))
424 		return 0;
425 
426 	/* Clear the mailbox pointer for completion */
427 	q->phba->mbox = NULL;
428 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
429 	return 1;
430 }
431 
432 /**
433  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
434  * @q: The Event Queue to get the first valid EQE from
435  *
436  * This routine will get the first valid Event Queue Entry from @q, update
437  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
438  * the Queue (no more work to do), or the Queue is full of EQEs that have been
439  * processed, but not popped back to the HBA then this routine will return NULL.
440  **/
441 static struct lpfc_eqe *
442 lpfc_sli4_eq_get(struct lpfc_queue *q)
443 {
444 	struct lpfc_eqe *eqe;
445 
446 	/* sanity check on queue memory */
447 	if (unlikely(!q))
448 		return NULL;
449 	eqe = lpfc_sli4_qe(q, q->host_index);
450 
451 	/* If the next EQE is not valid then we are done */
452 	if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
453 		return NULL;
454 
455 	/*
456 	 * insert barrier for instruction interlock : data from the hardware
457 	 * must have the valid bit checked before it can be copied and acted
458 	 * upon. Speculative instructions were allowing a bcopy at the start
459 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
460 	 * after our return, to copy data before the valid bit check above
461 	 * was done. As such, some of the copied data was stale. The barrier
462 	 * ensures the check is before any data is copied.
463 	 */
464 	mb();
465 	return eqe;
466 }
467 
468 /**
469  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
470  * @q: The Event Queue to disable interrupts
471  *
472  **/
473 void
474 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
475 {
476 	struct lpfc_register doorbell;
477 
478 	doorbell.word0 = 0;
479 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
480 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
481 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
482 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
483 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
484 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
485 }
486 
487 /**
488  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
489  * @q: The Event Queue to disable interrupts
490  *
491  **/
492 void
493 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
494 {
495 	struct lpfc_register doorbell;
496 
497 	doorbell.word0 = 0;
498 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
499 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
500 }
501 
502 /**
503  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
504  * @phba: adapter with EQ
505  * @q: The Event Queue that the host has completed processing for.
506  * @count: Number of elements that have been consumed
507  * @arm: Indicates whether the host wants to arms this CQ.
508  *
509  * This routine will notify the HBA, by ringing the doorbell, that count
510  * number of EQEs have been processed. The @arm parameter indicates whether
511  * the queue should be rearmed when ringing the doorbell.
512  **/
513 void
514 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
515 		     uint32_t count, bool arm)
516 {
517 	struct lpfc_register doorbell;
518 
519 	/* sanity check on queue memory */
520 	if (unlikely(!q || (count == 0 && !arm)))
521 		return;
522 
523 	/* ring doorbell for number popped */
524 	doorbell.word0 = 0;
525 	if (arm) {
526 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
527 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
528 	}
529 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
530 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
531 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
532 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
533 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
534 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
535 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
536 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
537 		readl(q->phba->sli4_hba.EQDBregaddr);
538 }
539 
540 /**
541  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
542  * @phba: adapter with EQ
543  * @q: The Event Queue that the host has completed processing for.
544  * @count: Number of elements that have been consumed
545  * @arm: Indicates whether the host wants to arms this CQ.
546  *
547  * This routine will notify the HBA, by ringing the doorbell, that count
548  * number of EQEs have been processed. The @arm parameter indicates whether
549  * the queue should be rearmed when ringing the doorbell.
550  **/
551 void
552 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
553 			  uint32_t count, bool arm)
554 {
555 	struct lpfc_register doorbell;
556 
557 	/* sanity check on queue memory */
558 	if (unlikely(!q || (count == 0 && !arm)))
559 		return;
560 
561 	/* ring doorbell for number popped */
562 	doorbell.word0 = 0;
563 	if (arm)
564 		bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
565 	bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
566 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
567 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
568 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
569 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
570 		readl(q->phba->sli4_hba.EQDBregaddr);
571 }
572 
573 static void
574 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
575 			struct lpfc_eqe *eqe)
576 {
577 	if (!phba->sli4_hba.pc_sli4_params.eqav)
578 		bf_set_le32(lpfc_eqe_valid, eqe, 0);
579 
580 	eq->host_index = ((eq->host_index + 1) % eq->entry_count);
581 
582 	/* if the index wrapped around, toggle the valid bit */
583 	if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
584 		eq->qe_valid = (eq->qe_valid) ? 0 : 1;
585 }
586 
587 static void
588 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
589 {
590 	struct lpfc_eqe *eqe = NULL;
591 	u32 eq_count = 0, cq_count = 0;
592 	struct lpfc_cqe *cqe = NULL;
593 	struct lpfc_queue *cq = NULL, *childq = NULL;
594 	int cqid = 0;
595 
596 	/* walk all the EQ entries and drop on the floor */
597 	eqe = lpfc_sli4_eq_get(eq);
598 	while (eqe) {
599 		/* Get the reference to the corresponding CQ */
600 		cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
601 		cq = NULL;
602 
603 		list_for_each_entry(childq, &eq->child_list, list) {
604 			if (childq->queue_id == cqid) {
605 				cq = childq;
606 				break;
607 			}
608 		}
609 		/* If CQ is valid, iterate through it and drop all the CQEs */
610 		if (cq) {
611 			cqe = lpfc_sli4_cq_get(cq);
612 			while (cqe) {
613 				__lpfc_sli4_consume_cqe(phba, cq, cqe);
614 				cq_count++;
615 				cqe = lpfc_sli4_cq_get(cq);
616 			}
617 			/* Clear and re-arm the CQ */
618 			phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
619 			    LPFC_QUEUE_REARM);
620 			cq_count = 0;
621 		}
622 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
623 		eq_count++;
624 		eqe = lpfc_sli4_eq_get(eq);
625 	}
626 
627 	/* Clear and re-arm the EQ */
628 	phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
629 }
630 
631 static int
632 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
633 		     uint8_t rearm)
634 {
635 	struct lpfc_eqe *eqe;
636 	int count = 0, consumed = 0;
637 
638 	if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
639 		goto rearm_and_exit;
640 
641 	eqe = lpfc_sli4_eq_get(eq);
642 	while (eqe) {
643 		lpfc_sli4_hba_handle_eqe(phba, eq, eqe);
644 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
645 
646 		consumed++;
647 		if (!(++count % eq->max_proc_limit))
648 			break;
649 
650 		if (!(count % eq->notify_interval)) {
651 			phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
652 							LPFC_QUEUE_NOARM);
653 			consumed = 0;
654 		}
655 
656 		eqe = lpfc_sli4_eq_get(eq);
657 	}
658 	eq->EQ_processed += count;
659 
660 	/* Track the max number of EQEs processed in 1 intr */
661 	if (count > eq->EQ_max_eqe)
662 		eq->EQ_max_eqe = count;
663 
664 	xchg(&eq->queue_claimed, 0);
665 
666 rearm_and_exit:
667 	/* Always clear the EQ. */
668 	phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
669 
670 	return count;
671 }
672 
673 /**
674  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
675  * @q: The Completion Queue to get the first valid CQE from
676  *
677  * This routine will get the first valid Completion Queue Entry from @q, update
678  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
679  * the Queue (no more work to do), or the Queue is full of CQEs that have been
680  * processed, but not popped back to the HBA then this routine will return NULL.
681  **/
682 static struct lpfc_cqe *
683 lpfc_sli4_cq_get(struct lpfc_queue *q)
684 {
685 	struct lpfc_cqe *cqe;
686 
687 	/* sanity check on queue memory */
688 	if (unlikely(!q))
689 		return NULL;
690 	cqe = lpfc_sli4_qe(q, q->host_index);
691 
692 	/* If the next CQE is not valid then we are done */
693 	if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
694 		return NULL;
695 
696 	/*
697 	 * insert barrier for instruction interlock : data from the hardware
698 	 * must have the valid bit checked before it can be copied and acted
699 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
700 	 * instructions allowing action on content before valid bit checked,
701 	 * add barrier here as well. May not be needed as "content" is a
702 	 * single 32-bit entity here (vs multi word structure for cq's).
703 	 */
704 	mb();
705 	return cqe;
706 }
707 
708 static void
709 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
710 			struct lpfc_cqe *cqe)
711 {
712 	if (!phba->sli4_hba.pc_sli4_params.cqav)
713 		bf_set_le32(lpfc_cqe_valid, cqe, 0);
714 
715 	cq->host_index = ((cq->host_index + 1) % cq->entry_count);
716 
717 	/* if the index wrapped around, toggle the valid bit */
718 	if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
719 		cq->qe_valid = (cq->qe_valid) ? 0 : 1;
720 }
721 
722 /**
723  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
724  * @phba: the adapter with the CQ
725  * @q: The Completion Queue that the host has completed processing for.
726  * @count: the number of elements that were consumed
727  * @arm: Indicates whether the host wants to arms this CQ.
728  *
729  * This routine will notify the HBA, by ringing the doorbell, that the
730  * CQEs have been processed. The @arm parameter specifies whether the
731  * queue should be rearmed when ringing the doorbell.
732  **/
733 void
734 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
735 		     uint32_t count, bool arm)
736 {
737 	struct lpfc_register doorbell;
738 
739 	/* sanity check on queue memory */
740 	if (unlikely(!q || (count == 0 && !arm)))
741 		return;
742 
743 	/* ring doorbell for number popped */
744 	doorbell.word0 = 0;
745 	if (arm)
746 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
747 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
748 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
749 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
750 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
751 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
752 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
753 }
754 
755 /**
756  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
757  * @phba: the adapter with the CQ
758  * @q: The Completion Queue that the host has completed processing for.
759  * @count: the number of elements that were consumed
760  * @arm: Indicates whether the host wants to arms this CQ.
761  *
762  * This routine will notify the HBA, by ringing the doorbell, that the
763  * CQEs have been processed. The @arm parameter specifies whether the
764  * queue should be rearmed when ringing the doorbell.
765  **/
766 void
767 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
768 			 uint32_t count, bool arm)
769 {
770 	struct lpfc_register doorbell;
771 
772 	/* sanity check on queue memory */
773 	if (unlikely(!q || (count == 0 && !arm)))
774 		return;
775 
776 	/* ring doorbell for number popped */
777 	doorbell.word0 = 0;
778 	if (arm)
779 		bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
780 	bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
781 	bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
782 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
783 }
784 
785 /*
786  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
787  *
788  * This routine will copy the contents of @wqe to the next available entry on
789  * the @q. This function will then ring the Receive Queue Doorbell to signal the
790  * HBA to start processing the Receive Queue Entry. This function returns the
791  * index that the rqe was copied to if successful. If no entries are available
792  * on @q then this function will return -ENOMEM.
793  * The caller is expected to hold the hbalock when calling this routine.
794  **/
795 int
796 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
797 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
798 {
799 	struct lpfc_rqe *temp_hrqe;
800 	struct lpfc_rqe *temp_drqe;
801 	struct lpfc_register doorbell;
802 	int hq_put_index;
803 	int dq_put_index;
804 
805 	/* sanity check on queue memory */
806 	if (unlikely(!hq) || unlikely(!dq))
807 		return -ENOMEM;
808 	hq_put_index = hq->host_index;
809 	dq_put_index = dq->host_index;
810 	temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
811 	temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
812 
813 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
814 		return -EINVAL;
815 	if (hq_put_index != dq_put_index)
816 		return -EINVAL;
817 	/* If the host has not yet processed the next entry then we are done */
818 	if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
819 		return -EBUSY;
820 	lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
821 	lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
822 
823 	/* Update the host index to point to the next slot */
824 	hq->host_index = ((hq_put_index + 1) % hq->entry_count);
825 	dq->host_index = ((dq_put_index + 1) % dq->entry_count);
826 	hq->RQ_buf_posted++;
827 
828 	/* Ring The Header Receive Queue Doorbell */
829 	if (!(hq->host_index % hq->notify_interval)) {
830 		doorbell.word0 = 0;
831 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
832 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
833 			       hq->notify_interval);
834 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
835 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
836 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
837 			       hq->notify_interval);
838 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
839 			       hq->host_index);
840 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
841 		} else {
842 			return -EINVAL;
843 		}
844 		writel(doorbell.word0, hq->db_regaddr);
845 	}
846 	return hq_put_index;
847 }
848 
849 /*
850  * lpfc_sli4_rq_release - Updates internal hba index for RQ
851  *
852  * This routine will update the HBA index of a queue to reflect consumption of
853  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
854  * consumed an entry the host calls this function to update the queue's
855  * internal pointers. This routine returns the number of entries that were
856  * consumed by the HBA.
857  **/
858 static uint32_t
859 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
860 {
861 	/* sanity check on queue memory */
862 	if (unlikely(!hq) || unlikely(!dq))
863 		return 0;
864 
865 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
866 		return 0;
867 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
868 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
869 	return 1;
870 }
871 
872 /**
873  * lpfc_cmd_iocb - Get next command iocb entry in the ring
874  * @phba: Pointer to HBA context object.
875  * @pring: Pointer to driver SLI ring object.
876  *
877  * This function returns pointer to next command iocb entry
878  * in the command ring. The caller must hold hbalock to prevent
879  * other threads consume the next command iocb.
880  * SLI-2/SLI-3 provide different sized iocbs.
881  **/
882 static inline IOCB_t *
883 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
884 {
885 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
886 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
887 }
888 
889 /**
890  * lpfc_resp_iocb - Get next response iocb entry in the ring
891  * @phba: Pointer to HBA context object.
892  * @pring: Pointer to driver SLI ring object.
893  *
894  * This function returns pointer to next response iocb entry
895  * in the response ring. The caller must hold hbalock to make sure
896  * that no other thread consume the next response iocb.
897  * SLI-2/SLI-3 provide different sized iocbs.
898  **/
899 static inline IOCB_t *
900 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
901 {
902 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
903 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
904 }
905 
906 /**
907  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
908  * @phba: Pointer to HBA context object.
909  *
910  * This function is called with hbalock held. This function
911  * allocates a new driver iocb object from the iocb pool. If the
912  * allocation is successful, it returns pointer to the newly
913  * allocated iocb object else it returns NULL.
914  **/
915 struct lpfc_iocbq *
916 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
917 {
918 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
919 	struct lpfc_iocbq * iocbq = NULL;
920 
921 	lockdep_assert_held(&phba->hbalock);
922 
923 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
924 	if (iocbq)
925 		phba->iocb_cnt++;
926 	if (phba->iocb_cnt > phba->iocb_max)
927 		phba->iocb_max = phba->iocb_cnt;
928 	return iocbq;
929 }
930 
931 /**
932  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
933  * @phba: Pointer to HBA context object.
934  * @xritag: XRI value.
935  *
936  * This function clears the sglq pointer from the array of active
937  * sglq's. The xritag that is passed in is used to index into the
938  * array. Before the xritag can be used it needs to be adjusted
939  * by subtracting the xribase.
940  *
941  * Returns sglq ponter = success, NULL = Failure.
942  **/
943 struct lpfc_sglq *
944 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
945 {
946 	struct lpfc_sglq *sglq;
947 
948 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
949 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
950 	return sglq;
951 }
952 
953 /**
954  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
955  * @phba: Pointer to HBA context object.
956  * @xritag: XRI value.
957  *
958  * This function returns the sglq pointer from the array of active
959  * sglq's. The xritag that is passed in is used to index into the
960  * array. Before the xritag can be used it needs to be adjusted
961  * by subtracting the xribase.
962  *
963  * Returns sglq ponter = success, NULL = Failure.
964  **/
965 struct lpfc_sglq *
966 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
967 {
968 	struct lpfc_sglq *sglq;
969 
970 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
971 	return sglq;
972 }
973 
974 /**
975  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
976  * @phba: Pointer to HBA context object.
977  * @xritag: xri used in this exchange.
978  * @rrq: The RRQ to be cleared.
979  *
980  **/
981 void
982 lpfc_clr_rrq_active(struct lpfc_hba *phba,
983 		    uint16_t xritag,
984 		    struct lpfc_node_rrq *rrq)
985 {
986 	struct lpfc_nodelist *ndlp = NULL;
987 
988 	/* Lookup did to verify if did is still active on this vport */
989 	if (rrq->vport)
990 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
991 
992 	if (!ndlp)
993 		goto out;
994 
995 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
996 		rrq->send_rrq = 0;
997 		rrq->xritag = 0;
998 		rrq->rrq_stop_time = 0;
999 	}
1000 out:
1001 	mempool_free(rrq, phba->rrq_pool);
1002 }
1003 
1004 /**
1005  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
1006  * @phba: Pointer to HBA context object.
1007  *
1008  * This function is called with hbalock held. This function
1009  * Checks if stop_time (ratov from setting rrq active) has
1010  * been reached, if it has and the send_rrq flag is set then
1011  * it will call lpfc_send_rrq. If the send_rrq flag is not set
1012  * then it will just call the routine to clear the rrq and
1013  * free the rrq resource.
1014  * The timer is set to the next rrq that is going to expire before
1015  * leaving the routine.
1016  *
1017  **/
1018 void
1019 lpfc_handle_rrq_active(struct lpfc_hba *phba)
1020 {
1021 	struct lpfc_node_rrq *rrq;
1022 	struct lpfc_node_rrq *nextrrq;
1023 	unsigned long next_time;
1024 	unsigned long iflags;
1025 	LIST_HEAD(send_rrq);
1026 
1027 	spin_lock_irqsave(&phba->hbalock, iflags);
1028 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1029 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1030 	list_for_each_entry_safe(rrq, nextrrq,
1031 				 &phba->active_rrq_list, list) {
1032 		if (time_after(jiffies, rrq->rrq_stop_time))
1033 			list_move(&rrq->list, &send_rrq);
1034 		else if (time_before(rrq->rrq_stop_time, next_time))
1035 			next_time = rrq->rrq_stop_time;
1036 	}
1037 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1038 	if ((!list_empty(&phba->active_rrq_list)) &&
1039 	    (!(phba->pport->load_flag & FC_UNLOADING)))
1040 		mod_timer(&phba->rrq_tmr, next_time);
1041 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
1042 		list_del(&rrq->list);
1043 		if (!rrq->send_rrq) {
1044 			/* this call will free the rrq */
1045 			lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1046 		} else if (lpfc_send_rrq(phba, rrq)) {
1047 			/* if we send the rrq then the completion handler
1048 			*  will clear the bit in the xribitmap.
1049 			*/
1050 			lpfc_clr_rrq_active(phba, rrq->xritag,
1051 					    rrq);
1052 		}
1053 	}
1054 }
1055 
1056 /**
1057  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
1058  * @vport: Pointer to vport context object.
1059  * @xri: The xri used in the exchange.
1060  * @did: The targets DID for this exchange.
1061  *
1062  * returns NULL = rrq not found in the phba->active_rrq_list.
1063  *         rrq = rrq for this xri and target.
1064  **/
1065 struct lpfc_node_rrq *
1066 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
1067 {
1068 	struct lpfc_hba *phba = vport->phba;
1069 	struct lpfc_node_rrq *rrq;
1070 	struct lpfc_node_rrq *nextrrq;
1071 	unsigned long iflags;
1072 
1073 	if (phba->sli_rev != LPFC_SLI_REV4)
1074 		return NULL;
1075 	spin_lock_irqsave(&phba->hbalock, iflags);
1076 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1077 		if (rrq->vport == vport && rrq->xritag == xri &&
1078 				rrq->nlp_DID == did){
1079 			list_del(&rrq->list);
1080 			spin_unlock_irqrestore(&phba->hbalock, iflags);
1081 			return rrq;
1082 		}
1083 	}
1084 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1085 	return NULL;
1086 }
1087 
1088 /**
1089  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
1090  * @vport: Pointer to vport context object.
1091  * @ndlp: Pointer to the lpfc_node_list structure.
1092  * If ndlp is NULL Remove all active RRQs for this vport from the
1093  * phba->active_rrq_list and clear the rrq.
1094  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
1095  **/
1096 void
1097 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
1098 
1099 {
1100 	struct lpfc_hba *phba = vport->phba;
1101 	struct lpfc_node_rrq *rrq;
1102 	struct lpfc_node_rrq *nextrrq;
1103 	unsigned long iflags;
1104 	LIST_HEAD(rrq_list);
1105 
1106 	if (phba->sli_rev != LPFC_SLI_REV4)
1107 		return;
1108 	if (!ndlp) {
1109 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
1110 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
1111 	}
1112 	spin_lock_irqsave(&phba->hbalock, iflags);
1113 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1114 		if (rrq->vport != vport)
1115 			continue;
1116 
1117 		if (!ndlp || ndlp == lpfc_findnode_did(vport, rrq->nlp_DID))
1118 			list_move(&rrq->list, &rrq_list);
1119 
1120 	}
1121 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1122 
1123 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1124 		list_del(&rrq->list);
1125 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1126 	}
1127 }
1128 
1129 /**
1130  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1131  * @phba: Pointer to HBA context object.
1132  * @ndlp: Targets nodelist pointer for this exchange.
1133  * @xritag: the xri in the bitmap to test.
1134  *
1135  * This function returns:
1136  * 0 = rrq not active for this xri
1137  * 1 = rrq is valid for this xri.
1138  **/
1139 int
1140 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1141 			uint16_t  xritag)
1142 {
1143 	if (!ndlp)
1144 		return 0;
1145 	if (!ndlp->active_rrqs_xri_bitmap)
1146 		return 0;
1147 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1148 		return 1;
1149 	else
1150 		return 0;
1151 }
1152 
1153 /**
1154  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1155  * @phba: Pointer to HBA context object.
1156  * @ndlp: nodelist pointer for this target.
1157  * @xritag: xri used in this exchange.
1158  * @rxid: Remote Exchange ID.
1159  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1160  *
1161  * This function takes the hbalock.
1162  * The active bit is always set in the active rrq xri_bitmap even
1163  * if there is no slot avaiable for the other rrq information.
1164  *
1165  * returns 0 rrq actived for this xri
1166  *         < 0 No memory or invalid ndlp.
1167  **/
1168 int
1169 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1170 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1171 {
1172 	unsigned long iflags;
1173 	struct lpfc_node_rrq *rrq;
1174 	int empty;
1175 
1176 	if (!ndlp)
1177 		return -EINVAL;
1178 
1179 	if (!phba->cfg_enable_rrq)
1180 		return -EINVAL;
1181 
1182 	spin_lock_irqsave(&phba->hbalock, iflags);
1183 	if (phba->pport->load_flag & FC_UNLOADING) {
1184 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1185 		goto out;
1186 	}
1187 
1188 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
1189 		goto out;
1190 
1191 	if (!ndlp->active_rrqs_xri_bitmap)
1192 		goto out;
1193 
1194 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1195 		goto out;
1196 
1197 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1198 	rrq = mempool_alloc(phba->rrq_pool, GFP_ATOMIC);
1199 	if (!rrq) {
1200 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1201 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1202 				" DID:0x%x Send:%d\n",
1203 				xritag, rxid, ndlp->nlp_DID, send_rrq);
1204 		return -EINVAL;
1205 	}
1206 	if (phba->cfg_enable_rrq == 1)
1207 		rrq->send_rrq = send_rrq;
1208 	else
1209 		rrq->send_rrq = 0;
1210 	rrq->xritag = xritag;
1211 	rrq->rrq_stop_time = jiffies +
1212 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1213 	rrq->nlp_DID = ndlp->nlp_DID;
1214 	rrq->vport = ndlp->vport;
1215 	rrq->rxid = rxid;
1216 	spin_lock_irqsave(&phba->hbalock, iflags);
1217 	empty = list_empty(&phba->active_rrq_list);
1218 	list_add_tail(&rrq->list, &phba->active_rrq_list);
1219 	phba->hba_flag |= HBA_RRQ_ACTIVE;
1220 	if (empty)
1221 		lpfc_worker_wake_up(phba);
1222 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1223 	return 0;
1224 out:
1225 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1226 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1227 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
1228 			" DID:0x%x Send:%d\n",
1229 			xritag, rxid, ndlp->nlp_DID, send_rrq);
1230 	return -EINVAL;
1231 }
1232 
1233 /**
1234  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1235  * @phba: Pointer to HBA context object.
1236  * @piocbq: Pointer to the iocbq.
1237  *
1238  * The driver calls this function with either the nvme ls ring lock
1239  * or the fc els ring lock held depending on the iocb usage.  This function
1240  * gets a new driver sglq object from the sglq list. If the list is not empty
1241  * then it is successful, it returns pointer to the newly allocated sglq
1242  * object else it returns NULL.
1243  **/
1244 static struct lpfc_sglq *
1245 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1246 {
1247 	struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1248 	struct lpfc_sglq *sglq = NULL;
1249 	struct lpfc_sglq *start_sglq = NULL;
1250 	struct lpfc_io_buf *lpfc_cmd;
1251 	struct lpfc_nodelist *ndlp;
1252 	int found = 0;
1253 	u8 cmnd;
1254 
1255 	cmnd = get_job_cmnd(phba, piocbq);
1256 
1257 	if (piocbq->cmd_flag &  LPFC_IO_FCP) {
1258 		lpfc_cmd = (struct lpfc_io_buf *) piocbq->context1;
1259 		ndlp = lpfc_cmd->rdata->pnode;
1260 	} else  if ((cmnd == CMD_GEN_REQUEST64_CR) &&
1261 			!(piocbq->cmd_flag & LPFC_IO_LIBDFC)) {
1262 		ndlp = piocbq->context_un.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->context_un.ndlp;
1268 	} else {
1269 		ndlp = piocbq->context1;
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 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1377 	unsigned long iflag = 0;
1378 	struct lpfc_sli_ring *pring;
1379 
1380 	if (iocbq->sli4_xritag == NO_XRI)
1381 		sglq = NULL;
1382 	else
1383 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1384 
1385 
1386 	if (sglq)  {
1387 		if (iocbq->cmd_flag & LPFC_IO_NVMET) {
1388 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1389 					  iflag);
1390 			sglq->state = SGL_FREED;
1391 			sglq->ndlp = NULL;
1392 			list_add_tail(&sglq->list,
1393 				      &phba->sli4_hba.lpfc_nvmet_sgl_list);
1394 			spin_unlock_irqrestore(
1395 				&phba->sli4_hba.sgl_list_lock, iflag);
1396 			goto out;
1397 		}
1398 
1399 		if ((iocbq->cmd_flag & LPFC_EXCHANGE_BUSY) &&
1400 		    (!(unlikely(pci_channel_offline(phba->pcidev)))) &&
1401 		    sglq->state != SGL_XRI_ABORTED) {
1402 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1403 					  iflag);
1404 
1405 			/* Check if we can get a reference on ndlp */
1406 			if (sglq->ndlp && !lpfc_nlp_get(sglq->ndlp))
1407 				sglq->ndlp = NULL;
1408 
1409 			list_add(&sglq->list,
1410 				 &phba->sli4_hba.lpfc_abts_els_sgl_list);
1411 			spin_unlock_irqrestore(
1412 				&phba->sli4_hba.sgl_list_lock, iflag);
1413 		} else {
1414 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1415 					  iflag);
1416 			sglq->state = SGL_FREED;
1417 			sglq->ndlp = NULL;
1418 			list_add_tail(&sglq->list,
1419 				      &phba->sli4_hba.lpfc_els_sgl_list);
1420 			spin_unlock_irqrestore(
1421 				&phba->sli4_hba.sgl_list_lock, iflag);
1422 			pring = lpfc_phba_elsring(phba);
1423 			/* Check if TXQ queue needs to be serviced */
1424 			if (pring && (!list_empty(&pring->txq)))
1425 				lpfc_worker_wake_up(phba);
1426 		}
1427 	}
1428 
1429 out:
1430 	/*
1431 	 * Clean all volatile data fields, preserve iotag and node struct.
1432 	 */
1433 	memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1434 	iocbq->sli4_lxritag = NO_XRI;
1435 	iocbq->sli4_xritag = NO_XRI;
1436 	iocbq->cmd_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET | LPFC_IO_CMF |
1437 			      LPFC_IO_NVME_LS);
1438 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1439 }
1440 
1441 
1442 /**
1443  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1444  * @phba: Pointer to HBA context object.
1445  * @iocbq: Pointer to driver iocb object.
1446  *
1447  * This function is called to release the driver iocb object to the
1448  * iocb pool. The iotag in the iocb object does not change for each
1449  * use of the iocb object. This function clears all other fields of
1450  * the iocb object when it is freed. The hbalock is asserted held in
1451  * the code path calling this routine.
1452  **/
1453 static void
1454 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1455 {
1456 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1457 
1458 	/*
1459 	 * Clean all volatile data fields, preserve iotag and node struct.
1460 	 */
1461 	memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1462 	iocbq->sli4_xritag = NO_XRI;
1463 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1464 }
1465 
1466 /**
1467  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1468  * @phba: Pointer to HBA context object.
1469  * @iocbq: Pointer to driver iocb object.
1470  *
1471  * This function is called with hbalock held to release driver
1472  * iocb object to the iocb pool. The iotag in the iocb object
1473  * does not change for each use of the iocb object. This function
1474  * clears all other fields of the iocb object when it is freed.
1475  **/
1476 static void
1477 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1478 {
1479 	lockdep_assert_held(&phba->hbalock);
1480 
1481 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1482 	phba->iocb_cnt--;
1483 }
1484 
1485 /**
1486  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1487  * @phba: Pointer to HBA context object.
1488  * @iocbq: Pointer to driver iocb object.
1489  *
1490  * This function is called with no lock held to release the iocb to
1491  * iocb pool.
1492  **/
1493 void
1494 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1495 {
1496 	unsigned long iflags;
1497 
1498 	/*
1499 	 * Clean all volatile data fields, preserve iotag and node struct.
1500 	 */
1501 	spin_lock_irqsave(&phba->hbalock, iflags);
1502 	__lpfc_sli_release_iocbq(phba, iocbq);
1503 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1504 }
1505 
1506 /**
1507  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1508  * @phba: Pointer to HBA context object.
1509  * @iocblist: List of IOCBs.
1510  * @ulpstatus: ULP status in IOCB command field.
1511  * @ulpWord4: ULP word-4 in IOCB command field.
1512  *
1513  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1514  * on the list by invoking the complete callback function associated with the
1515  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1516  * fields.
1517  **/
1518 void
1519 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1520 		      uint32_t ulpstatus, uint32_t ulpWord4)
1521 {
1522 	struct lpfc_iocbq *piocb;
1523 
1524 	while (!list_empty(iocblist)) {
1525 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1526 		if (piocb->cmd_cmpl) {
1527 			if (piocb->cmd_flag & LPFC_IO_NVME) {
1528 				lpfc_nvme_cancel_iocb(phba, piocb,
1529 						      ulpstatus, ulpWord4);
1530 			} else {
1531 				if (phba->sli_rev == LPFC_SLI_REV4) {
1532 					bf_set(lpfc_wcqe_c_status,
1533 					       &piocb->wcqe_cmpl, ulpstatus);
1534 					piocb->wcqe_cmpl.parameter = ulpWord4;
1535 				} else {
1536 					piocb->iocb.ulpStatus = ulpstatus;
1537 					piocb->iocb.un.ulpWord[4] = ulpWord4;
1538 				}
1539 				(piocb->cmd_cmpl) (phba, piocb, piocb);
1540 			}
1541 		} else {
1542 			lpfc_sli_release_iocbq(phba, piocb);
1543 		}
1544 	}
1545 	return;
1546 }
1547 
1548 /**
1549  * lpfc_sli_iocb_cmd_type - Get the iocb type
1550  * @iocb_cmnd: iocb command code.
1551  *
1552  * This function is called by ring event handler function to get the iocb type.
1553  * This function translates the iocb command to an iocb command type used to
1554  * decide the final disposition of each completed IOCB.
1555  * The function returns
1556  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1557  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1558  * LPFC_ABORT_IOCB   if it is an abort iocb
1559  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1560  *
1561  * The caller is not required to hold any lock.
1562  **/
1563 static lpfc_iocb_type
1564 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1565 {
1566 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1567 
1568 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1569 		return 0;
1570 
1571 	switch (iocb_cmnd) {
1572 	case CMD_XMIT_SEQUENCE_CR:
1573 	case CMD_XMIT_SEQUENCE_CX:
1574 	case CMD_XMIT_BCAST_CN:
1575 	case CMD_XMIT_BCAST_CX:
1576 	case CMD_ELS_REQUEST_CR:
1577 	case CMD_ELS_REQUEST_CX:
1578 	case CMD_CREATE_XRI_CR:
1579 	case CMD_CREATE_XRI_CX:
1580 	case CMD_GET_RPI_CN:
1581 	case CMD_XMIT_ELS_RSP_CX:
1582 	case CMD_GET_RPI_CR:
1583 	case CMD_FCP_IWRITE_CR:
1584 	case CMD_FCP_IWRITE_CX:
1585 	case CMD_FCP_IREAD_CR:
1586 	case CMD_FCP_IREAD_CX:
1587 	case CMD_FCP_ICMND_CR:
1588 	case CMD_FCP_ICMND_CX:
1589 	case CMD_FCP_TSEND_CX:
1590 	case CMD_FCP_TRSP_CX:
1591 	case CMD_FCP_TRECEIVE_CX:
1592 	case CMD_FCP_AUTO_TRSP_CX:
1593 	case CMD_ADAPTER_MSG:
1594 	case CMD_ADAPTER_DUMP:
1595 	case CMD_XMIT_SEQUENCE64_CR:
1596 	case CMD_XMIT_SEQUENCE64_CX:
1597 	case CMD_XMIT_BCAST64_CN:
1598 	case CMD_XMIT_BCAST64_CX:
1599 	case CMD_ELS_REQUEST64_CR:
1600 	case CMD_ELS_REQUEST64_CX:
1601 	case CMD_FCP_IWRITE64_CR:
1602 	case CMD_FCP_IWRITE64_CX:
1603 	case CMD_FCP_IREAD64_CR:
1604 	case CMD_FCP_IREAD64_CX:
1605 	case CMD_FCP_ICMND64_CR:
1606 	case CMD_FCP_ICMND64_CX:
1607 	case CMD_FCP_TSEND64_CX:
1608 	case CMD_FCP_TRSP64_CX:
1609 	case CMD_FCP_TRECEIVE64_CX:
1610 	case CMD_GEN_REQUEST64_CR:
1611 	case CMD_GEN_REQUEST64_CX:
1612 	case CMD_XMIT_ELS_RSP64_CX:
1613 	case DSSCMD_IWRITE64_CR:
1614 	case DSSCMD_IWRITE64_CX:
1615 	case DSSCMD_IREAD64_CR:
1616 	case DSSCMD_IREAD64_CX:
1617 	case CMD_SEND_FRAME:
1618 		type = LPFC_SOL_IOCB;
1619 		break;
1620 	case CMD_ABORT_XRI_CN:
1621 	case CMD_ABORT_XRI_CX:
1622 	case CMD_CLOSE_XRI_CN:
1623 	case CMD_CLOSE_XRI_CX:
1624 	case CMD_XRI_ABORTED_CX:
1625 	case CMD_ABORT_MXRI64_CN:
1626 	case CMD_XMIT_BLS_RSP64_CX:
1627 		type = LPFC_ABORT_IOCB;
1628 		break;
1629 	case CMD_RCV_SEQUENCE_CX:
1630 	case CMD_RCV_ELS_REQ_CX:
1631 	case CMD_RCV_SEQUENCE64_CX:
1632 	case CMD_RCV_ELS_REQ64_CX:
1633 	case CMD_ASYNC_STATUS:
1634 	case CMD_IOCB_RCV_SEQ64_CX:
1635 	case CMD_IOCB_RCV_ELS64_CX:
1636 	case CMD_IOCB_RCV_CONT64_CX:
1637 	case CMD_IOCB_RET_XRI64_CX:
1638 		type = LPFC_UNSOL_IOCB;
1639 		break;
1640 	case CMD_IOCB_XMIT_MSEQ64_CR:
1641 	case CMD_IOCB_XMIT_MSEQ64_CX:
1642 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1643 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1644 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1645 	case CMD_IOCB_ABORT_EXTENDED_CN:
1646 	case CMD_IOCB_RET_HBQE64_CN:
1647 	case CMD_IOCB_FCP_IBIDIR64_CR:
1648 	case CMD_IOCB_FCP_IBIDIR64_CX:
1649 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1650 	case CMD_IOCB_LOGENTRY_CN:
1651 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1652 		printk("%s - Unhandled SLI-3 Command x%x\n",
1653 				__func__, iocb_cmnd);
1654 		type = LPFC_UNKNOWN_IOCB;
1655 		break;
1656 	default:
1657 		type = LPFC_UNKNOWN_IOCB;
1658 		break;
1659 	}
1660 
1661 	return type;
1662 }
1663 
1664 /**
1665  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1666  * @phba: Pointer to HBA context object.
1667  *
1668  * This function is called from SLI initialization code
1669  * to configure every ring of the HBA's SLI interface. The
1670  * caller is not required to hold any lock. This function issues
1671  * a config_ring mailbox command for each ring.
1672  * This function returns zero if successful else returns a negative
1673  * error code.
1674  **/
1675 static int
1676 lpfc_sli_ring_map(struct lpfc_hba *phba)
1677 {
1678 	struct lpfc_sli *psli = &phba->sli;
1679 	LPFC_MBOXQ_t *pmb;
1680 	MAILBOX_t *pmbox;
1681 	int i, rc, ret = 0;
1682 
1683 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1684 	if (!pmb)
1685 		return -ENOMEM;
1686 	pmbox = &pmb->u.mb;
1687 	phba->link_state = LPFC_INIT_MBX_CMDS;
1688 	for (i = 0; i < psli->num_rings; i++) {
1689 		lpfc_config_ring(phba, i, pmb);
1690 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1691 		if (rc != MBX_SUCCESS) {
1692 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1693 					"0446 Adapter failed to init (%d), "
1694 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1695 					"ring %d\n",
1696 					rc, pmbox->mbxCommand,
1697 					pmbox->mbxStatus, i);
1698 			phba->link_state = LPFC_HBA_ERROR;
1699 			ret = -ENXIO;
1700 			break;
1701 		}
1702 	}
1703 	mempool_free(pmb, phba->mbox_mem_pool);
1704 	return ret;
1705 }
1706 
1707 /**
1708  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1709  * @phba: Pointer to HBA context object.
1710  * @pring: Pointer to driver SLI ring object.
1711  * @piocb: Pointer to the driver iocb object.
1712  *
1713  * The driver calls this function with the hbalock held for SLI3 ports or
1714  * the ring lock held for SLI4 ports. The function adds the
1715  * new iocb to txcmplq of the given ring. This function always returns
1716  * 0. If this function is called for ELS ring, this function checks if
1717  * there is a vport associated with the ELS command. This function also
1718  * starts els_tmofunc timer if this is an ELS command.
1719  **/
1720 static int
1721 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1722 			struct lpfc_iocbq *piocb)
1723 {
1724 	u32 ulp_command = 0;
1725 
1726 	BUG_ON(!piocb);
1727 	ulp_command = get_job_cmnd(phba, piocb);
1728 
1729 	list_add_tail(&piocb->list, &pring->txcmplq);
1730 	piocb->cmd_flag |= LPFC_IO_ON_TXCMPLQ;
1731 	pring->txcmplq_cnt++;
1732 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1733 	   (ulp_command != CMD_ABORT_XRI_WQE) &&
1734 	   (ulp_command != CMD_ABORT_XRI_CN) &&
1735 	   (ulp_command != CMD_CLOSE_XRI_CN)) {
1736 		BUG_ON(!piocb->vport);
1737 		if (!(piocb->vport->load_flag & FC_UNLOADING))
1738 			mod_timer(&piocb->vport->els_tmofunc,
1739 				  jiffies +
1740 				  msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1741 	}
1742 
1743 	return 0;
1744 }
1745 
1746 /**
1747  * lpfc_sli_ringtx_get - Get first element of the txq
1748  * @phba: Pointer to HBA context object.
1749  * @pring: Pointer to driver SLI ring object.
1750  *
1751  * This function is called with hbalock held to get next
1752  * iocb in txq of the given ring. If there is any iocb in
1753  * the txq, the function returns first iocb in the list after
1754  * removing the iocb from the list, else it returns NULL.
1755  **/
1756 struct lpfc_iocbq *
1757 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1758 {
1759 	struct lpfc_iocbq *cmd_iocb;
1760 
1761 	lockdep_assert_held(&phba->hbalock);
1762 
1763 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1764 	return cmd_iocb;
1765 }
1766 
1767 /**
1768  * lpfc_cmf_sync_cmpl - Process a CMF_SYNC_WQE cmpl
1769  * @phba: Pointer to HBA context object.
1770  * @cmdiocb: Pointer to driver command iocb object.
1771  * @rspiocb: Pointer to driver response iocb object.
1772  *
1773  * This routine will inform the driver of any BW adjustments we need
1774  * to make. These changes will be picked up during the next CMF
1775  * timer interrupt. In addition, any BW changes will be logged
1776  * with LOG_CGN_MGMT.
1777  **/
1778 static void
1779 lpfc_cmf_sync_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
1780 		   struct lpfc_iocbq *rspiocb)
1781 {
1782 	union lpfc_wqe128 *wqe;
1783 	uint32_t status, info;
1784 	struct lpfc_wcqe_complete *wcqe = &rspiocb->wcqe_cmpl;
1785 	uint64_t bw, bwdif, slop;
1786 	uint64_t pcent, bwpcent;
1787 	int asig, afpin, sigcnt, fpincnt;
1788 	int wsigmax, wfpinmax, cg, tdp;
1789 	char *s;
1790 
1791 	/* First check for error */
1792 	status = bf_get(lpfc_wcqe_c_status, wcqe);
1793 	if (status) {
1794 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1795 				"6211 CMF_SYNC_WQE Error "
1796 				"req_tag x%x status x%x hwstatus x%x "
1797 				"tdatap x%x parm x%x\n",
1798 				bf_get(lpfc_wcqe_c_request_tag, wcqe),
1799 				bf_get(lpfc_wcqe_c_status, wcqe),
1800 				bf_get(lpfc_wcqe_c_hw_status, wcqe),
1801 				wcqe->total_data_placed,
1802 				wcqe->parameter);
1803 		goto out;
1804 	}
1805 
1806 	/* Gather congestion information on a successful cmpl */
1807 	info = wcqe->parameter;
1808 	phba->cmf_active_info = info;
1809 
1810 	/* See if firmware info count is valid or has changed */
1811 	if (info > LPFC_MAX_CMF_INFO || phba->cmf_info_per_interval == info)
1812 		info = 0;
1813 	else
1814 		phba->cmf_info_per_interval = info;
1815 
1816 	tdp = bf_get(lpfc_wcqe_c_cmf_bw, wcqe);
1817 	cg = bf_get(lpfc_wcqe_c_cmf_cg, wcqe);
1818 
1819 	/* Get BW requirement from firmware */
1820 	bw = (uint64_t)tdp * LPFC_CMF_BLK_SIZE;
1821 	if (!bw) {
1822 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1823 				"6212 CMF_SYNC_WQE x%x: NULL bw\n",
1824 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
1825 		goto out;
1826 	}
1827 
1828 	/* Gather information needed for logging if a BW change is required */
1829 	wqe = &cmdiocb->wqe;
1830 	asig = bf_get(cmf_sync_asig, &wqe->cmf_sync);
1831 	afpin = bf_get(cmf_sync_afpin, &wqe->cmf_sync);
1832 	fpincnt = bf_get(cmf_sync_wfpincnt, &wqe->cmf_sync);
1833 	sigcnt = bf_get(cmf_sync_wsigcnt, &wqe->cmf_sync);
1834 	if (phba->cmf_max_bytes_per_interval != bw ||
1835 	    (asig || afpin || sigcnt || fpincnt)) {
1836 		/* Are we increasing or decreasing BW */
1837 		if (phba->cmf_max_bytes_per_interval <  bw) {
1838 			bwdif = bw - phba->cmf_max_bytes_per_interval;
1839 			s = "Increase";
1840 		} else {
1841 			bwdif = phba->cmf_max_bytes_per_interval - bw;
1842 			s = "Decrease";
1843 		}
1844 
1845 		/* What is the change percentage */
1846 		slop = div_u64(phba->cmf_link_byte_count, 200); /*For rounding*/
1847 		pcent = div64_u64(bwdif * 100 + slop,
1848 				  phba->cmf_link_byte_count);
1849 		bwpcent = div64_u64(bw * 100 + slop,
1850 				    phba->cmf_link_byte_count);
1851 		if (asig) {
1852 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1853 					"6237 BW Threshold %lld%% (%lld): "
1854 					"%lld%% %s: Signal Alarm: cg:%d "
1855 					"Info:%u\n",
1856 					bwpcent, bw, pcent, s, cg,
1857 					phba->cmf_active_info);
1858 		} else if (afpin) {
1859 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1860 					"6238 BW Threshold %lld%% (%lld): "
1861 					"%lld%% %s: FPIN Alarm: cg:%d "
1862 					"Info:%u\n",
1863 					bwpcent, bw, pcent, s, cg,
1864 					phba->cmf_active_info);
1865 		} else if (sigcnt) {
1866 			wsigmax = bf_get(cmf_sync_wsigmax, &wqe->cmf_sync);
1867 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1868 					"6239 BW Threshold %lld%% (%lld): "
1869 					"%lld%% %s: Signal Warning: "
1870 					"Cnt %d Max %d: cg:%d Info:%u\n",
1871 					bwpcent, bw, pcent, s, sigcnt,
1872 					wsigmax, cg, phba->cmf_active_info);
1873 		} else if (fpincnt) {
1874 			wfpinmax = bf_get(cmf_sync_wfpinmax, &wqe->cmf_sync);
1875 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1876 					"6240 BW Threshold %lld%% (%lld): "
1877 					"%lld%% %s: FPIN Warning: "
1878 					"Cnt %d Max %d: cg:%d Info:%u\n",
1879 					bwpcent, bw, pcent, s, fpincnt,
1880 					wfpinmax, cg, phba->cmf_active_info);
1881 		} else {
1882 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1883 					"6241 BW Threshold %lld%% (%lld): "
1884 					"CMF %lld%% %s: cg:%d Info:%u\n",
1885 					bwpcent, bw, pcent, s, cg,
1886 					phba->cmf_active_info);
1887 		}
1888 	} else if (info) {
1889 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1890 				"6246 Info Threshold %u\n", info);
1891 	}
1892 
1893 	/* Save BW change to be picked up during next timer interrupt */
1894 	phba->cmf_last_sync_bw = bw;
1895 out:
1896 	lpfc_sli_release_iocbq(phba, cmdiocb);
1897 }
1898 
1899 /**
1900  * lpfc_issue_cmf_sync_wqe - Issue a CMF_SYNC_WQE
1901  * @phba: Pointer to HBA context object.
1902  * @ms:   ms to set in WQE interval, 0 means use init op
1903  * @total: Total rcv bytes for this interval
1904  *
1905  * This routine is called every CMF timer interrupt. Its purpose is
1906  * to issue a CMF_SYNC_WQE to the firmware to inform it of any events
1907  * that may indicate we have congestion (FPINs or Signals). Upon
1908  * completion, the firmware will indicate any BW restrictions the
1909  * driver may need to take.
1910  **/
1911 int
1912 lpfc_issue_cmf_sync_wqe(struct lpfc_hba *phba, u32 ms, u64 total)
1913 {
1914 	union lpfc_wqe128 *wqe;
1915 	struct lpfc_iocbq *sync_buf;
1916 	unsigned long iflags;
1917 	u32 ret_val;
1918 	u32 atot, wtot, max;
1919 
1920 	/* First address any alarm / warning activity */
1921 	atot = atomic_xchg(&phba->cgn_sync_alarm_cnt, 0);
1922 	wtot = atomic_xchg(&phba->cgn_sync_warn_cnt, 0);
1923 
1924 	/* ONLY Managed mode will send the CMF_SYNC_WQE to the HBA */
1925 	if (phba->cmf_active_mode != LPFC_CFG_MANAGED ||
1926 	    phba->link_state == LPFC_LINK_DOWN)
1927 		return 0;
1928 
1929 	spin_lock_irqsave(&phba->hbalock, iflags);
1930 	sync_buf = __lpfc_sli_get_iocbq(phba);
1931 	if (!sync_buf) {
1932 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
1933 				"6213 No available WQEs for CMF_SYNC_WQE\n");
1934 		ret_val = ENOMEM;
1935 		goto out_unlock;
1936 	}
1937 
1938 	wqe = &sync_buf->wqe;
1939 
1940 	/* WQEs are reused.  Clear stale data and set key fields to zero */
1941 	memset(wqe, 0, sizeof(*wqe));
1942 
1943 	/* If this is the very first CMF_SYNC_WQE, issue an init operation */
1944 	if (!ms) {
1945 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1946 				"6441 CMF Init %d - CMF_SYNC_WQE\n",
1947 				phba->fc_eventTag);
1948 		bf_set(cmf_sync_op, &wqe->cmf_sync, 1); /* 1=init */
1949 		bf_set(cmf_sync_interval, &wqe->cmf_sync, LPFC_CMF_INTERVAL);
1950 		goto initpath;
1951 	}
1952 
1953 	bf_set(cmf_sync_op, &wqe->cmf_sync, 0); /* 0=recalc */
1954 	bf_set(cmf_sync_interval, &wqe->cmf_sync, ms);
1955 
1956 	/* Check for alarms / warnings */
1957 	if (atot) {
1958 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1959 			/* We hit an Signal alarm condition */
1960 			bf_set(cmf_sync_asig, &wqe->cmf_sync, 1);
1961 		} else {
1962 			/* We hit a FPIN alarm condition */
1963 			bf_set(cmf_sync_afpin, &wqe->cmf_sync, 1);
1964 		}
1965 	} else if (wtot) {
1966 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
1967 		    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1968 			/* We hit an Signal warning condition */
1969 			max = LPFC_SEC_TO_MSEC / lpfc_fabric_cgn_frequency *
1970 				lpfc_acqe_cgn_frequency;
1971 			bf_set(cmf_sync_wsigmax, &wqe->cmf_sync, max);
1972 			bf_set(cmf_sync_wsigcnt, &wqe->cmf_sync, wtot);
1973 		} else {
1974 			/* We hit a FPIN warning condition */
1975 			bf_set(cmf_sync_wfpinmax, &wqe->cmf_sync, 1);
1976 			bf_set(cmf_sync_wfpincnt, &wqe->cmf_sync, 1);
1977 		}
1978 	}
1979 
1980 	/* Update total read blocks during previous timer interval */
1981 	wqe->cmf_sync.read_bytes = (u32)(total / LPFC_CMF_BLK_SIZE);
1982 
1983 initpath:
1984 	bf_set(cmf_sync_ver, &wqe->cmf_sync, LPFC_CMF_SYNC_VER);
1985 	wqe->cmf_sync.event_tag = phba->fc_eventTag;
1986 	bf_set(cmf_sync_cmnd, &wqe->cmf_sync, CMD_CMF_SYNC_WQE);
1987 
1988 	/* Setup reqtag to match the wqe completion. */
1989 	bf_set(cmf_sync_reqtag, &wqe->cmf_sync, sync_buf->iotag);
1990 
1991 	bf_set(cmf_sync_qosd, &wqe->cmf_sync, 1);
1992 
1993 	bf_set(cmf_sync_cmd_type, &wqe->cmf_sync, CMF_SYNC_COMMAND);
1994 	bf_set(cmf_sync_wqec, &wqe->cmf_sync, 1);
1995 	bf_set(cmf_sync_cqid, &wqe->cmf_sync, LPFC_WQE_CQ_ID_DEFAULT);
1996 
1997 	sync_buf->vport = phba->pport;
1998 	sync_buf->cmd_cmpl = lpfc_cmf_sync_cmpl;
1999 	sync_buf->context1 = NULL;
2000 	sync_buf->context2 = NULL;
2001 	sync_buf->context3 = NULL;
2002 	sync_buf->sli4_xritag = NO_XRI;
2003 
2004 	sync_buf->cmd_flag |= LPFC_IO_CMF;
2005 	ret_val = lpfc_sli4_issue_wqe(phba, &phba->sli4_hba.hdwq[0], sync_buf);
2006 	if (ret_val)
2007 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
2008 				"6214 Cannot issue CMF_SYNC_WQE: x%x\n",
2009 				ret_val);
2010 out_unlock:
2011 	spin_unlock_irqrestore(&phba->hbalock, iflags);
2012 	return ret_val;
2013 }
2014 
2015 /**
2016  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
2017  * @phba: Pointer to HBA context object.
2018  * @pring: Pointer to driver SLI ring object.
2019  *
2020  * This function is called with hbalock held and the caller must post the
2021  * iocb without releasing the lock. If the caller releases the lock,
2022  * iocb slot returned by the function is not guaranteed to be available.
2023  * The function returns pointer to the next available iocb slot if there
2024  * is available slot in the ring, else it returns NULL.
2025  * If the get index of the ring is ahead of the put index, the function
2026  * will post an error attention event to the worker thread to take the
2027  * HBA to offline state.
2028  **/
2029 static IOCB_t *
2030 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2031 {
2032 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2033 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
2034 
2035 	lockdep_assert_held(&phba->hbalock);
2036 
2037 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
2038 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
2039 		pring->sli.sli3.next_cmdidx = 0;
2040 
2041 	if (unlikely(pring->sli.sli3.local_getidx ==
2042 		pring->sli.sli3.next_cmdidx)) {
2043 
2044 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
2045 
2046 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
2047 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2048 					"0315 Ring %d issue: portCmdGet %d "
2049 					"is bigger than cmd ring %d\n",
2050 					pring->ringno,
2051 					pring->sli.sli3.local_getidx,
2052 					max_cmd_idx);
2053 
2054 			phba->link_state = LPFC_HBA_ERROR;
2055 			/*
2056 			 * All error attention handlers are posted to
2057 			 * worker thread
2058 			 */
2059 			phba->work_ha |= HA_ERATT;
2060 			phba->work_hs = HS_FFER3;
2061 
2062 			lpfc_worker_wake_up(phba);
2063 
2064 			return NULL;
2065 		}
2066 
2067 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
2068 			return NULL;
2069 	}
2070 
2071 	return lpfc_cmd_iocb(phba, pring);
2072 }
2073 
2074 /**
2075  * lpfc_sli_next_iotag - Get an iotag for the iocb
2076  * @phba: Pointer to HBA context object.
2077  * @iocbq: Pointer to driver iocb object.
2078  *
2079  * This function gets an iotag for the iocb. If there is no unused iotag and
2080  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
2081  * array and assigns a new iotag.
2082  * The function returns the allocated iotag if successful, else returns zero.
2083  * Zero is not a valid iotag.
2084  * The caller is not required to hold any lock.
2085  **/
2086 uint16_t
2087 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
2088 {
2089 	struct lpfc_iocbq **new_arr;
2090 	struct lpfc_iocbq **old_arr;
2091 	size_t new_len;
2092 	struct lpfc_sli *psli = &phba->sli;
2093 	uint16_t iotag;
2094 
2095 	spin_lock_irq(&phba->hbalock);
2096 	iotag = psli->last_iotag;
2097 	if(++iotag < psli->iocbq_lookup_len) {
2098 		psli->last_iotag = iotag;
2099 		psli->iocbq_lookup[iotag] = iocbq;
2100 		spin_unlock_irq(&phba->hbalock);
2101 		iocbq->iotag = iotag;
2102 		return iotag;
2103 	} else if (psli->iocbq_lookup_len < (0xffff
2104 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
2105 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
2106 		spin_unlock_irq(&phba->hbalock);
2107 		new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
2108 				  GFP_KERNEL);
2109 		if (new_arr) {
2110 			spin_lock_irq(&phba->hbalock);
2111 			old_arr = psli->iocbq_lookup;
2112 			if (new_len <= psli->iocbq_lookup_len) {
2113 				/* highly unprobable case */
2114 				kfree(new_arr);
2115 				iotag = psli->last_iotag;
2116 				if(++iotag < psli->iocbq_lookup_len) {
2117 					psli->last_iotag = iotag;
2118 					psli->iocbq_lookup[iotag] = iocbq;
2119 					spin_unlock_irq(&phba->hbalock);
2120 					iocbq->iotag = iotag;
2121 					return iotag;
2122 				}
2123 				spin_unlock_irq(&phba->hbalock);
2124 				return 0;
2125 			}
2126 			if (psli->iocbq_lookup)
2127 				memcpy(new_arr, old_arr,
2128 				       ((psli->last_iotag  + 1) *
2129 					sizeof (struct lpfc_iocbq *)));
2130 			psli->iocbq_lookup = new_arr;
2131 			psli->iocbq_lookup_len = new_len;
2132 			psli->last_iotag = iotag;
2133 			psli->iocbq_lookup[iotag] = iocbq;
2134 			spin_unlock_irq(&phba->hbalock);
2135 			iocbq->iotag = iotag;
2136 			kfree(old_arr);
2137 			return iotag;
2138 		}
2139 	} else
2140 		spin_unlock_irq(&phba->hbalock);
2141 
2142 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2143 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
2144 			psli->last_iotag);
2145 
2146 	return 0;
2147 }
2148 
2149 /**
2150  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
2151  * @phba: Pointer to HBA context object.
2152  * @pring: Pointer to driver SLI ring object.
2153  * @iocb: Pointer to iocb slot in the ring.
2154  * @nextiocb: Pointer to driver iocb object which need to be
2155  *            posted to firmware.
2156  *
2157  * This function is called to post a new iocb to the firmware. This
2158  * function copies the new iocb to ring iocb slot and updates the
2159  * ring pointers. It adds the new iocb to txcmplq if there is
2160  * a completion call back for this iocb else the function will free the
2161  * iocb object.  The hbalock is asserted held in the code path calling
2162  * this routine.
2163  **/
2164 static void
2165 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2166 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
2167 {
2168 	/*
2169 	 * Set up an iotag
2170 	 */
2171 	nextiocb->iocb.ulpIoTag = (nextiocb->cmd_cmpl) ? nextiocb->iotag : 0;
2172 
2173 
2174 	if (pring->ringno == LPFC_ELS_RING) {
2175 		lpfc_debugfs_slow_ring_trc(phba,
2176 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
2177 			*(((uint32_t *) &nextiocb->iocb) + 4),
2178 			*(((uint32_t *) &nextiocb->iocb) + 6),
2179 			*(((uint32_t *) &nextiocb->iocb) + 7));
2180 	}
2181 
2182 	/*
2183 	 * Issue iocb command to adapter
2184 	 */
2185 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
2186 	wmb();
2187 	pring->stats.iocb_cmd++;
2188 
2189 	/*
2190 	 * If there is no completion routine to call, we can release the
2191 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
2192 	 * that have no rsp ring completion, cmd_cmpl MUST be NULL.
2193 	 */
2194 	if (nextiocb->cmd_cmpl)
2195 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
2196 	else
2197 		__lpfc_sli_release_iocbq(phba, nextiocb);
2198 
2199 	/*
2200 	 * Let the HBA know what IOCB slot will be the next one the
2201 	 * driver will put a command into.
2202 	 */
2203 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
2204 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
2205 }
2206 
2207 /**
2208  * lpfc_sli_update_full_ring - Update the chip attention register
2209  * @phba: Pointer to HBA context object.
2210  * @pring: Pointer to driver SLI ring object.
2211  *
2212  * The caller is not required to hold any lock for calling this function.
2213  * This function updates the chip attention bits for the ring to inform firmware
2214  * that there are pending work to be done for this ring and requests an
2215  * interrupt when there is space available in the ring. This function is
2216  * called when the driver is unable to post more iocbs to the ring due
2217  * to unavailability of space in the ring.
2218  **/
2219 static void
2220 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2221 {
2222 	int ringno = pring->ringno;
2223 
2224 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
2225 
2226 	wmb();
2227 
2228 	/*
2229 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
2230 	 * The HBA will tell us when an IOCB entry is available.
2231 	 */
2232 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
2233 	readl(phba->CAregaddr); /* flush */
2234 
2235 	pring->stats.iocb_cmd_full++;
2236 }
2237 
2238 /**
2239  * lpfc_sli_update_ring - Update chip attention register
2240  * @phba: Pointer to HBA context object.
2241  * @pring: Pointer to driver SLI ring object.
2242  *
2243  * This function updates the chip attention register bit for the
2244  * given ring to inform HBA that there is more work to be done
2245  * in this ring. The caller is not required to hold any lock.
2246  **/
2247 static void
2248 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2249 {
2250 	int ringno = pring->ringno;
2251 
2252 	/*
2253 	 * Tell the HBA that there is work to do in this ring.
2254 	 */
2255 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
2256 		wmb();
2257 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
2258 		readl(phba->CAregaddr); /* flush */
2259 	}
2260 }
2261 
2262 /**
2263  * lpfc_sli_resume_iocb - Process iocbs in the txq
2264  * @phba: Pointer to HBA context object.
2265  * @pring: Pointer to driver SLI ring object.
2266  *
2267  * This function is called with hbalock held to post pending iocbs
2268  * in the txq to the firmware. This function is called when driver
2269  * detects space available in the ring.
2270  **/
2271 static void
2272 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2273 {
2274 	IOCB_t *iocb;
2275 	struct lpfc_iocbq *nextiocb;
2276 
2277 	lockdep_assert_held(&phba->hbalock);
2278 
2279 	/*
2280 	 * Check to see if:
2281 	 *  (a) there is anything on the txq to send
2282 	 *  (b) link is up
2283 	 *  (c) link attention events can be processed (fcp ring only)
2284 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
2285 	 */
2286 
2287 	if (lpfc_is_link_up(phba) &&
2288 	    (!list_empty(&pring->txq)) &&
2289 	    (pring->ringno != LPFC_FCP_RING ||
2290 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
2291 
2292 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
2293 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
2294 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
2295 
2296 		if (iocb)
2297 			lpfc_sli_update_ring(phba, pring);
2298 		else
2299 			lpfc_sli_update_full_ring(phba, pring);
2300 	}
2301 
2302 	return;
2303 }
2304 
2305 /**
2306  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
2307  * @phba: Pointer to HBA context object.
2308  * @hbqno: HBQ number.
2309  *
2310  * This function is called with hbalock held to get the next
2311  * available slot for the given HBQ. If there is free slot
2312  * available for the HBQ it will return pointer to the next available
2313  * HBQ entry else it will return NULL.
2314  **/
2315 static struct lpfc_hbq_entry *
2316 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
2317 {
2318 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
2319 
2320 	lockdep_assert_held(&phba->hbalock);
2321 
2322 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
2323 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
2324 		hbqp->next_hbqPutIdx = 0;
2325 
2326 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
2327 		uint32_t raw_index = phba->hbq_get[hbqno];
2328 		uint32_t getidx = le32_to_cpu(raw_index);
2329 
2330 		hbqp->local_hbqGetIdx = getidx;
2331 
2332 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
2333 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2334 					"1802 HBQ %d: local_hbqGetIdx "
2335 					"%u is > than hbqp->entry_count %u\n",
2336 					hbqno, hbqp->local_hbqGetIdx,
2337 					hbqp->entry_count);
2338 
2339 			phba->link_state = LPFC_HBA_ERROR;
2340 			return NULL;
2341 		}
2342 
2343 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
2344 			return NULL;
2345 	}
2346 
2347 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
2348 			hbqp->hbqPutIdx;
2349 }
2350 
2351 /**
2352  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
2353  * @phba: Pointer to HBA context object.
2354  *
2355  * This function is called with no lock held to free all the
2356  * hbq buffers while uninitializing the SLI interface. It also
2357  * frees the HBQ buffers returned by the firmware but not yet
2358  * processed by the upper layers.
2359  **/
2360 void
2361 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
2362 {
2363 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
2364 	struct hbq_dmabuf *hbq_buf;
2365 	unsigned long flags;
2366 	int i, hbq_count;
2367 
2368 	hbq_count = lpfc_sli_hbq_count();
2369 	/* Return all memory used by all HBQs */
2370 	spin_lock_irqsave(&phba->hbalock, flags);
2371 	for (i = 0; i < hbq_count; ++i) {
2372 		list_for_each_entry_safe(dmabuf, next_dmabuf,
2373 				&phba->hbqs[i].hbq_buffer_list, list) {
2374 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2375 			list_del(&hbq_buf->dbuf.list);
2376 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2377 		}
2378 		phba->hbqs[i].buffer_count = 0;
2379 	}
2380 
2381 	/* Mark the HBQs not in use */
2382 	phba->hbq_in_use = 0;
2383 	spin_unlock_irqrestore(&phba->hbalock, flags);
2384 }
2385 
2386 /**
2387  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2388  * @phba: Pointer to HBA context object.
2389  * @hbqno: HBQ number.
2390  * @hbq_buf: Pointer to HBQ buffer.
2391  *
2392  * This function is called with the hbalock held to post a
2393  * hbq buffer to the firmware. If the function finds an empty
2394  * slot in the HBQ, it will post the buffer. The function will return
2395  * pointer to the hbq entry if it successfully post the buffer
2396  * else it will return NULL.
2397  **/
2398 static int
2399 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2400 			 struct hbq_dmabuf *hbq_buf)
2401 {
2402 	lockdep_assert_held(&phba->hbalock);
2403 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2404 }
2405 
2406 /**
2407  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2408  * @phba: Pointer to HBA context object.
2409  * @hbqno: HBQ number.
2410  * @hbq_buf: Pointer to HBQ buffer.
2411  *
2412  * This function is called with the hbalock held to post a hbq buffer to the
2413  * firmware. If the function finds an empty slot in the HBQ, it will post the
2414  * buffer and place it on the hbq_buffer_list. The function will return zero if
2415  * it successfully post the buffer else it will return an error.
2416  **/
2417 static int
2418 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2419 			    struct hbq_dmabuf *hbq_buf)
2420 {
2421 	struct lpfc_hbq_entry *hbqe;
2422 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
2423 
2424 	lockdep_assert_held(&phba->hbalock);
2425 	/* Get next HBQ entry slot to use */
2426 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2427 	if (hbqe) {
2428 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
2429 
2430 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2431 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2432 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2433 		hbqe->bde.tus.f.bdeFlags = 0;
2434 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2435 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2436 				/* Sync SLIM */
2437 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2438 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2439 				/* flush */
2440 		readl(phba->hbq_put + hbqno);
2441 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2442 		return 0;
2443 	} else
2444 		return -ENOMEM;
2445 }
2446 
2447 /**
2448  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2449  * @phba: Pointer to HBA context object.
2450  * @hbqno: HBQ number.
2451  * @hbq_buf: Pointer to HBQ buffer.
2452  *
2453  * This function is called with the hbalock held to post an RQE to the SLI4
2454  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2455  * the hbq_buffer_list and return zero, otherwise it will return an error.
2456  **/
2457 static int
2458 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2459 			    struct hbq_dmabuf *hbq_buf)
2460 {
2461 	int rc;
2462 	struct lpfc_rqe hrqe;
2463 	struct lpfc_rqe drqe;
2464 	struct lpfc_queue *hrq;
2465 	struct lpfc_queue *drq;
2466 
2467 	if (hbqno != LPFC_ELS_HBQ)
2468 		return 1;
2469 	hrq = phba->sli4_hba.hdr_rq;
2470 	drq = phba->sli4_hba.dat_rq;
2471 
2472 	lockdep_assert_held(&phba->hbalock);
2473 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2474 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2475 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2476 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2477 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2478 	if (rc < 0)
2479 		return rc;
2480 	hbq_buf->tag = (rc | (hbqno << 16));
2481 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2482 	return 0;
2483 }
2484 
2485 /* HBQ for ELS and CT traffic. */
2486 static struct lpfc_hbq_init lpfc_els_hbq = {
2487 	.rn = 1,
2488 	.entry_count = 256,
2489 	.mask_count = 0,
2490 	.profile = 0,
2491 	.ring_mask = (1 << LPFC_ELS_RING),
2492 	.buffer_count = 0,
2493 	.init_count = 40,
2494 	.add_count = 40,
2495 };
2496 
2497 /* Array of HBQs */
2498 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2499 	&lpfc_els_hbq,
2500 };
2501 
2502 /**
2503  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2504  * @phba: Pointer to HBA context object.
2505  * @hbqno: HBQ number.
2506  * @count: Number of HBQ buffers to be posted.
2507  *
2508  * This function is called with no lock held to post more hbq buffers to the
2509  * given HBQ. The function returns the number of HBQ buffers successfully
2510  * posted.
2511  **/
2512 static int
2513 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2514 {
2515 	uint32_t i, posted = 0;
2516 	unsigned long flags;
2517 	struct hbq_dmabuf *hbq_buffer;
2518 	LIST_HEAD(hbq_buf_list);
2519 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2520 		return 0;
2521 
2522 	if ((phba->hbqs[hbqno].buffer_count + count) >
2523 	    lpfc_hbq_defs[hbqno]->entry_count)
2524 		count = lpfc_hbq_defs[hbqno]->entry_count -
2525 					phba->hbqs[hbqno].buffer_count;
2526 	if (!count)
2527 		return 0;
2528 	/* Allocate HBQ entries */
2529 	for (i = 0; i < count; i++) {
2530 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2531 		if (!hbq_buffer)
2532 			break;
2533 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2534 	}
2535 	/* Check whether HBQ is still in use */
2536 	spin_lock_irqsave(&phba->hbalock, flags);
2537 	if (!phba->hbq_in_use)
2538 		goto err;
2539 	while (!list_empty(&hbq_buf_list)) {
2540 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2541 				 dbuf.list);
2542 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2543 				      (hbqno << 16));
2544 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2545 			phba->hbqs[hbqno].buffer_count++;
2546 			posted++;
2547 		} else
2548 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2549 	}
2550 	spin_unlock_irqrestore(&phba->hbalock, flags);
2551 	return posted;
2552 err:
2553 	spin_unlock_irqrestore(&phba->hbalock, flags);
2554 	while (!list_empty(&hbq_buf_list)) {
2555 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2556 				 dbuf.list);
2557 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2558 	}
2559 	return 0;
2560 }
2561 
2562 /**
2563  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2564  * @phba: Pointer to HBA context object.
2565  * @qno: HBQ number.
2566  *
2567  * This function posts more buffers to the HBQ. This function
2568  * is called with no lock held. The function returns the number of HBQ entries
2569  * successfully allocated.
2570  **/
2571 int
2572 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2573 {
2574 	if (phba->sli_rev == LPFC_SLI_REV4)
2575 		return 0;
2576 	else
2577 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2578 					 lpfc_hbq_defs[qno]->add_count);
2579 }
2580 
2581 /**
2582  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2583  * @phba: Pointer to HBA context object.
2584  * @qno:  HBQ queue number.
2585  *
2586  * This function is called from SLI initialization code path with
2587  * no lock held to post initial HBQ buffers to firmware. The
2588  * function returns the number of HBQ entries successfully allocated.
2589  **/
2590 static int
2591 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2592 {
2593 	if (phba->sli_rev == LPFC_SLI_REV4)
2594 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2595 					lpfc_hbq_defs[qno]->entry_count);
2596 	else
2597 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2598 					 lpfc_hbq_defs[qno]->init_count);
2599 }
2600 
2601 /*
2602  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2603  *
2604  * This function removes the first hbq buffer on an hbq list and returns a
2605  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2606  **/
2607 static struct hbq_dmabuf *
2608 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2609 {
2610 	struct lpfc_dmabuf *d_buf;
2611 
2612 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2613 	if (!d_buf)
2614 		return NULL;
2615 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2616 }
2617 
2618 /**
2619  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2620  * @phba: Pointer to HBA context object.
2621  * @hrq: HBQ number.
2622  *
2623  * This function removes the first RQ buffer on an RQ buffer list and returns a
2624  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2625  **/
2626 static struct rqb_dmabuf *
2627 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2628 {
2629 	struct lpfc_dmabuf *h_buf;
2630 	struct lpfc_rqb *rqbp;
2631 
2632 	rqbp = hrq->rqbp;
2633 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2634 			 struct lpfc_dmabuf, list);
2635 	if (!h_buf)
2636 		return NULL;
2637 	rqbp->buffer_count--;
2638 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2639 }
2640 
2641 /**
2642  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2643  * @phba: Pointer to HBA context object.
2644  * @tag: Tag of the hbq buffer.
2645  *
2646  * This function searches for the hbq buffer associated with the given tag in
2647  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2648  * otherwise it returns NULL.
2649  **/
2650 static struct hbq_dmabuf *
2651 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2652 {
2653 	struct lpfc_dmabuf *d_buf;
2654 	struct hbq_dmabuf *hbq_buf;
2655 	uint32_t hbqno;
2656 
2657 	hbqno = tag >> 16;
2658 	if (hbqno >= LPFC_MAX_HBQS)
2659 		return NULL;
2660 
2661 	spin_lock_irq(&phba->hbalock);
2662 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2663 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2664 		if (hbq_buf->tag == tag) {
2665 			spin_unlock_irq(&phba->hbalock);
2666 			return hbq_buf;
2667 		}
2668 	}
2669 	spin_unlock_irq(&phba->hbalock);
2670 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2671 			"1803 Bad hbq tag. Data: x%x x%x\n",
2672 			tag, phba->hbqs[tag >> 16].buffer_count);
2673 	return NULL;
2674 }
2675 
2676 /**
2677  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2678  * @phba: Pointer to HBA context object.
2679  * @hbq_buffer: Pointer to HBQ buffer.
2680  *
2681  * This function is called with hbalock. This function gives back
2682  * the hbq buffer to firmware. If the HBQ does not have space to
2683  * post the buffer, it will free the buffer.
2684  **/
2685 void
2686 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2687 {
2688 	uint32_t hbqno;
2689 
2690 	if (hbq_buffer) {
2691 		hbqno = hbq_buffer->tag >> 16;
2692 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2693 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2694 	}
2695 }
2696 
2697 /**
2698  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2699  * @mbxCommand: mailbox command code.
2700  *
2701  * This function is called by the mailbox event handler function to verify
2702  * that the completed mailbox command is a legitimate mailbox command. If the
2703  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2704  * and the mailbox event handler will take the HBA offline.
2705  **/
2706 static int
2707 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2708 {
2709 	uint8_t ret;
2710 
2711 	switch (mbxCommand) {
2712 	case MBX_LOAD_SM:
2713 	case MBX_READ_NV:
2714 	case MBX_WRITE_NV:
2715 	case MBX_WRITE_VPARMS:
2716 	case MBX_RUN_BIU_DIAG:
2717 	case MBX_INIT_LINK:
2718 	case MBX_DOWN_LINK:
2719 	case MBX_CONFIG_LINK:
2720 	case MBX_CONFIG_RING:
2721 	case MBX_RESET_RING:
2722 	case MBX_READ_CONFIG:
2723 	case MBX_READ_RCONFIG:
2724 	case MBX_READ_SPARM:
2725 	case MBX_READ_STATUS:
2726 	case MBX_READ_RPI:
2727 	case MBX_READ_XRI:
2728 	case MBX_READ_REV:
2729 	case MBX_READ_LNK_STAT:
2730 	case MBX_REG_LOGIN:
2731 	case MBX_UNREG_LOGIN:
2732 	case MBX_CLEAR_LA:
2733 	case MBX_DUMP_MEMORY:
2734 	case MBX_DUMP_CONTEXT:
2735 	case MBX_RUN_DIAGS:
2736 	case MBX_RESTART:
2737 	case MBX_UPDATE_CFG:
2738 	case MBX_DOWN_LOAD:
2739 	case MBX_DEL_LD_ENTRY:
2740 	case MBX_RUN_PROGRAM:
2741 	case MBX_SET_MASK:
2742 	case MBX_SET_VARIABLE:
2743 	case MBX_UNREG_D_ID:
2744 	case MBX_KILL_BOARD:
2745 	case MBX_CONFIG_FARP:
2746 	case MBX_BEACON:
2747 	case MBX_LOAD_AREA:
2748 	case MBX_RUN_BIU_DIAG64:
2749 	case MBX_CONFIG_PORT:
2750 	case MBX_READ_SPARM64:
2751 	case MBX_READ_RPI64:
2752 	case MBX_REG_LOGIN64:
2753 	case MBX_READ_TOPOLOGY:
2754 	case MBX_WRITE_WWN:
2755 	case MBX_SET_DEBUG:
2756 	case MBX_LOAD_EXP_ROM:
2757 	case MBX_ASYNCEVT_ENABLE:
2758 	case MBX_REG_VPI:
2759 	case MBX_UNREG_VPI:
2760 	case MBX_HEARTBEAT:
2761 	case MBX_PORT_CAPABILITIES:
2762 	case MBX_PORT_IOV_CONTROL:
2763 	case MBX_SLI4_CONFIG:
2764 	case MBX_SLI4_REQ_FTRS:
2765 	case MBX_REG_FCFI:
2766 	case MBX_UNREG_FCFI:
2767 	case MBX_REG_VFI:
2768 	case MBX_UNREG_VFI:
2769 	case MBX_INIT_VPI:
2770 	case MBX_INIT_VFI:
2771 	case MBX_RESUME_RPI:
2772 	case MBX_READ_EVENT_LOG_STATUS:
2773 	case MBX_READ_EVENT_LOG:
2774 	case MBX_SECURITY_MGMT:
2775 	case MBX_AUTH_PORT:
2776 	case MBX_ACCESS_VDATA:
2777 		ret = mbxCommand;
2778 		break;
2779 	default:
2780 		ret = MBX_SHUTDOWN;
2781 		break;
2782 	}
2783 	return ret;
2784 }
2785 
2786 /**
2787  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2788  * @phba: Pointer to HBA context object.
2789  * @pmboxq: Pointer to mailbox command.
2790  *
2791  * This is completion handler function for mailbox commands issued from
2792  * lpfc_sli_issue_mbox_wait function. This function is called by the
2793  * mailbox event handler function with no lock held. This function
2794  * will wake up thread waiting on the wait queue pointed by context1
2795  * of the mailbox.
2796  **/
2797 void
2798 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2799 {
2800 	unsigned long drvr_flag;
2801 	struct completion *pmbox_done;
2802 
2803 	/*
2804 	 * If pmbox_done is empty, the driver thread gave up waiting and
2805 	 * continued running.
2806 	 */
2807 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2808 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2809 	pmbox_done = (struct completion *)pmboxq->context3;
2810 	if (pmbox_done)
2811 		complete(pmbox_done);
2812 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2813 	return;
2814 }
2815 
2816 static void
2817 __lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2818 {
2819 	unsigned long iflags;
2820 
2821 	if (ndlp->nlp_flag & NLP_RELEASE_RPI) {
2822 		lpfc_sli4_free_rpi(vport->phba, ndlp->nlp_rpi);
2823 		spin_lock_irqsave(&ndlp->lock, iflags);
2824 		ndlp->nlp_flag &= ~NLP_RELEASE_RPI;
2825 		ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
2826 		spin_unlock_irqrestore(&ndlp->lock, iflags);
2827 	}
2828 	ndlp->nlp_flag &= ~NLP_UNREG_INP;
2829 }
2830 
2831 void
2832 lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2833 {
2834 	__lpfc_sli_rpi_release(vport, ndlp);
2835 }
2836 
2837 /**
2838  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2839  * @phba: Pointer to HBA context object.
2840  * @pmb: Pointer to mailbox object.
2841  *
2842  * This function is the default mailbox completion handler. It
2843  * frees the memory resources associated with the completed mailbox
2844  * command. If the completed command is a REG_LOGIN mailbox command,
2845  * this function will issue a UREG_LOGIN to re-claim the RPI.
2846  **/
2847 void
2848 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2849 {
2850 	struct lpfc_vport  *vport = pmb->vport;
2851 	struct lpfc_dmabuf *mp;
2852 	struct lpfc_nodelist *ndlp;
2853 	struct Scsi_Host *shost;
2854 	uint16_t rpi, vpi;
2855 	int rc;
2856 
2857 	mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
2858 
2859 	if (mp) {
2860 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
2861 		kfree(mp);
2862 	}
2863 
2864 	/*
2865 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2866 	 * is in re-discovery driver need to cleanup the RPI.
2867 	 */
2868 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2869 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2870 	    !pmb->u.mb.mbxStatus) {
2871 		rpi = pmb->u.mb.un.varWords[0];
2872 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2873 		if (phba->sli_rev == LPFC_SLI_REV4)
2874 			vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2875 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2876 		pmb->vport = vport;
2877 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2878 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2879 		if (rc != MBX_NOT_FINISHED)
2880 			return;
2881 	}
2882 
2883 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2884 		!(phba->pport->load_flag & FC_UNLOADING) &&
2885 		!pmb->u.mb.mbxStatus) {
2886 		shost = lpfc_shost_from_vport(vport);
2887 		spin_lock_irq(shost->host_lock);
2888 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2889 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2890 		spin_unlock_irq(shost->host_lock);
2891 	}
2892 
2893 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2894 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2895 		lpfc_nlp_put(ndlp);
2896 		pmb->ctx_buf = NULL;
2897 		pmb->ctx_ndlp = NULL;
2898 	}
2899 
2900 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2901 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2902 
2903 		/* Check to see if there are any deferred events to process */
2904 		if (ndlp) {
2905 			lpfc_printf_vlog(
2906 				vport,
2907 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2908 				"1438 UNREG cmpl deferred mbox x%x "
2909 				"on NPort x%x Data: x%x x%x x%px x%x x%x\n",
2910 				ndlp->nlp_rpi, ndlp->nlp_DID,
2911 				ndlp->nlp_flag, ndlp->nlp_defer_did,
2912 				ndlp, vport->load_flag, kref_read(&ndlp->kref));
2913 
2914 			if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2915 			    (ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING)) {
2916 				ndlp->nlp_flag &= ~NLP_UNREG_INP;
2917 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2918 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2919 			} else {
2920 				__lpfc_sli_rpi_release(vport, ndlp);
2921 			}
2922 
2923 			/* The unreg_login mailbox is complete and had a
2924 			 * reference that has to be released.  The PLOGI
2925 			 * got its own ref.
2926 			 */
2927 			lpfc_nlp_put(ndlp);
2928 			pmb->ctx_ndlp = NULL;
2929 		}
2930 	}
2931 
2932 	/* This nlp_put pairs with lpfc_sli4_resume_rpi */
2933 	if (pmb->u.mb.mbxCommand == MBX_RESUME_RPI) {
2934 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2935 		lpfc_nlp_put(ndlp);
2936 	}
2937 
2938 	/* Check security permission status on INIT_LINK mailbox command */
2939 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2940 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2941 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2942 				"2860 SLI authentication is required "
2943 				"for INIT_LINK but has not done yet\n");
2944 
2945 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2946 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2947 	else
2948 		mempool_free(pmb, phba->mbox_mem_pool);
2949 }
2950  /**
2951  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2952  * @phba: Pointer to HBA context object.
2953  * @pmb: Pointer to mailbox object.
2954  *
2955  * This function is the unreg rpi mailbox completion handler. It
2956  * frees the memory resources associated with the completed mailbox
2957  * command. An additional reference is put on the ndlp to prevent
2958  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2959  * the unreg mailbox command completes, this routine puts the
2960  * reference back.
2961  *
2962  **/
2963 void
2964 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2965 {
2966 	struct lpfc_vport  *vport = pmb->vport;
2967 	struct lpfc_nodelist *ndlp;
2968 
2969 	ndlp = pmb->ctx_ndlp;
2970 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2971 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2972 		    (bf_get(lpfc_sli_intf_if_type,
2973 		     &phba->sli4_hba.sli_intf) >=
2974 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2975 			if (ndlp) {
2976 				lpfc_printf_vlog(
2977 					 vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2978 					 "0010 UNREG_LOGIN vpi:%x "
2979 					 "rpi:%x DID:%x defer x%x flg x%x "
2980 					 "x%px\n",
2981 					 vport->vpi, ndlp->nlp_rpi,
2982 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
2983 					 ndlp->nlp_flag,
2984 					 ndlp);
2985 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2986 
2987 				/* Check to see if there are any deferred
2988 				 * events to process
2989 				 */
2990 				if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2991 				    (ndlp->nlp_defer_did !=
2992 				    NLP_EVT_NOTHING_PENDING)) {
2993 					lpfc_printf_vlog(
2994 						vport, KERN_INFO, LOG_DISCOVERY,
2995 						"4111 UNREG cmpl deferred "
2996 						"clr x%x on "
2997 						"NPort x%x Data: x%x x%px\n",
2998 						ndlp->nlp_rpi, ndlp->nlp_DID,
2999 						ndlp->nlp_defer_did, ndlp);
3000 					ndlp->nlp_flag &= ~NLP_UNREG_INP;
3001 					ndlp->nlp_defer_did =
3002 						NLP_EVT_NOTHING_PENDING;
3003 					lpfc_issue_els_plogi(
3004 						vport, ndlp->nlp_DID, 0);
3005 				} else {
3006 					__lpfc_sli_rpi_release(vport, ndlp);
3007 				}
3008 				lpfc_nlp_put(ndlp);
3009 			}
3010 		}
3011 	}
3012 
3013 	mempool_free(pmb, phba->mbox_mem_pool);
3014 }
3015 
3016 /**
3017  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
3018  * @phba: Pointer to HBA context object.
3019  *
3020  * This function is called with no lock held. This function processes all
3021  * the completed mailbox commands and gives it to upper layers. The interrupt
3022  * service routine processes mailbox completion interrupt and adds completed
3023  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
3024  * Worker thread call lpfc_sli_handle_mb_event, which will return the
3025  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
3026  * function returns the mailbox commands to the upper layer by calling the
3027  * completion handler function of each mailbox.
3028  **/
3029 int
3030 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
3031 {
3032 	MAILBOX_t *pmbox;
3033 	LPFC_MBOXQ_t *pmb;
3034 	int rc;
3035 	LIST_HEAD(cmplq);
3036 
3037 	phba->sli.slistat.mbox_event++;
3038 
3039 	/* Get all completed mailboxe buffers into the cmplq */
3040 	spin_lock_irq(&phba->hbalock);
3041 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
3042 	spin_unlock_irq(&phba->hbalock);
3043 
3044 	/* Get a Mailbox buffer to setup mailbox commands for callback */
3045 	do {
3046 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
3047 		if (pmb == NULL)
3048 			break;
3049 
3050 		pmbox = &pmb->u.mb;
3051 
3052 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
3053 			if (pmb->vport) {
3054 				lpfc_debugfs_disc_trc(pmb->vport,
3055 					LPFC_DISC_TRC_MBOX_VPORT,
3056 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
3057 					(uint32_t)pmbox->mbxCommand,
3058 					pmbox->un.varWords[0],
3059 					pmbox->un.varWords[1]);
3060 			}
3061 			else {
3062 				lpfc_debugfs_disc_trc(phba->pport,
3063 					LPFC_DISC_TRC_MBOX,
3064 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
3065 					(uint32_t)pmbox->mbxCommand,
3066 					pmbox->un.varWords[0],
3067 					pmbox->un.varWords[1]);
3068 			}
3069 		}
3070 
3071 		/*
3072 		 * It is a fatal error if unknown mbox command completion.
3073 		 */
3074 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
3075 		    MBX_SHUTDOWN) {
3076 			/* Unknown mailbox command compl */
3077 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3078 					"(%d):0323 Unknown Mailbox command "
3079 					"x%x (x%x/x%x) Cmpl\n",
3080 					pmb->vport ? pmb->vport->vpi :
3081 					LPFC_VPORT_UNKNOWN,
3082 					pmbox->mbxCommand,
3083 					lpfc_sli_config_mbox_subsys_get(phba,
3084 									pmb),
3085 					lpfc_sli_config_mbox_opcode_get(phba,
3086 									pmb));
3087 			phba->link_state = LPFC_HBA_ERROR;
3088 			phba->work_hs = HS_FFER3;
3089 			lpfc_handle_eratt(phba);
3090 			continue;
3091 		}
3092 
3093 		if (pmbox->mbxStatus) {
3094 			phba->sli.slistat.mbox_stat_err++;
3095 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
3096 				/* Mbox cmd cmpl error - RETRYing */
3097 				lpfc_printf_log(phba, KERN_INFO,
3098 					LOG_MBOX | LOG_SLI,
3099 					"(%d):0305 Mbox cmd cmpl "
3100 					"error - RETRYing Data: x%x "
3101 					"(x%x/x%x) x%x x%x x%x\n",
3102 					pmb->vport ? pmb->vport->vpi :
3103 					LPFC_VPORT_UNKNOWN,
3104 					pmbox->mbxCommand,
3105 					lpfc_sli_config_mbox_subsys_get(phba,
3106 									pmb),
3107 					lpfc_sli_config_mbox_opcode_get(phba,
3108 									pmb),
3109 					pmbox->mbxStatus,
3110 					pmbox->un.varWords[0],
3111 					pmb->vport ? pmb->vport->port_state :
3112 					LPFC_VPORT_UNKNOWN);
3113 				pmbox->mbxStatus = 0;
3114 				pmbox->mbxOwner = OWN_HOST;
3115 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3116 				if (rc != MBX_NOT_FINISHED)
3117 					continue;
3118 			}
3119 		}
3120 
3121 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
3122 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
3123 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
3124 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
3125 				"x%x x%x x%x\n",
3126 				pmb->vport ? pmb->vport->vpi : 0,
3127 				pmbox->mbxCommand,
3128 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
3129 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
3130 				pmb->mbox_cmpl,
3131 				*((uint32_t *) pmbox),
3132 				pmbox->un.varWords[0],
3133 				pmbox->un.varWords[1],
3134 				pmbox->un.varWords[2],
3135 				pmbox->un.varWords[3],
3136 				pmbox->un.varWords[4],
3137 				pmbox->un.varWords[5],
3138 				pmbox->un.varWords[6],
3139 				pmbox->un.varWords[7],
3140 				pmbox->un.varWords[8],
3141 				pmbox->un.varWords[9],
3142 				pmbox->un.varWords[10]);
3143 
3144 		if (pmb->mbox_cmpl)
3145 			pmb->mbox_cmpl(phba,pmb);
3146 	} while (1);
3147 	return 0;
3148 }
3149 
3150 /**
3151  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
3152  * @phba: Pointer to HBA context object.
3153  * @pring: Pointer to driver SLI ring object.
3154  * @tag: buffer tag.
3155  *
3156  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
3157  * is set in the tag the buffer is posted for a particular exchange,
3158  * the function will return the buffer without replacing the buffer.
3159  * If the buffer is for unsolicited ELS or CT traffic, this function
3160  * returns the buffer and also posts another buffer to the firmware.
3161  **/
3162 static struct lpfc_dmabuf *
3163 lpfc_sli_get_buff(struct lpfc_hba *phba,
3164 		  struct lpfc_sli_ring *pring,
3165 		  uint32_t tag)
3166 {
3167 	struct hbq_dmabuf *hbq_entry;
3168 
3169 	if (tag & QUE_BUFTAG_BIT)
3170 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
3171 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
3172 	if (!hbq_entry)
3173 		return NULL;
3174 	return &hbq_entry->dbuf;
3175 }
3176 
3177 /**
3178  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
3179  *                              containing a NVME LS request.
3180  * @phba: pointer to lpfc hba data structure.
3181  * @piocb: pointer to the iocbq struct representing the sequence starting
3182  *        frame.
3183  *
3184  * This routine initially validates the NVME LS, validates there is a login
3185  * with the port that sent the LS, and then calls the appropriate nvme host
3186  * or target LS request handler.
3187  **/
3188 static void
3189 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
3190 {
3191 	struct lpfc_nodelist *ndlp;
3192 	struct lpfc_dmabuf *d_buf;
3193 	struct hbq_dmabuf *nvmebuf;
3194 	struct fc_frame_header *fc_hdr;
3195 	struct lpfc_async_xchg_ctx *axchg = NULL;
3196 	char *failwhy = NULL;
3197 	uint32_t oxid, sid, did, fctl, size;
3198 	int ret = 1;
3199 
3200 	d_buf = piocb->context2;
3201 
3202 	nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
3203 	fc_hdr = nvmebuf->hbuf.virt;
3204 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
3205 	sid = sli4_sid_from_fc_hdr(fc_hdr);
3206 	did = sli4_did_from_fc_hdr(fc_hdr);
3207 	fctl = (fc_hdr->fh_f_ctl[0] << 16 |
3208 		fc_hdr->fh_f_ctl[1] << 8 |
3209 		fc_hdr->fh_f_ctl[2]);
3210 	size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
3211 
3212 	lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
3213 			 oxid, size, sid);
3214 
3215 	if (phba->pport->load_flag & FC_UNLOADING) {
3216 		failwhy = "Driver Unloading";
3217 	} else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
3218 		failwhy = "NVME FC4 Disabled";
3219 	} else if (!phba->nvmet_support && !phba->pport->localport) {
3220 		failwhy = "No Localport";
3221 	} else if (phba->nvmet_support && !phba->targetport) {
3222 		failwhy = "No Targetport";
3223 	} else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
3224 		failwhy = "Bad NVME LS R_CTL";
3225 	} else if (unlikely((fctl & 0x00FF0000) !=
3226 			(FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
3227 		failwhy = "Bad NVME LS F_CTL";
3228 	} else {
3229 		axchg = kzalloc(sizeof(*axchg), GFP_ATOMIC);
3230 		if (!axchg)
3231 			failwhy = "No CTX memory";
3232 	}
3233 
3234 	if (unlikely(failwhy)) {
3235 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3236 				"6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
3237 				sid, oxid, failwhy);
3238 		goto out_fail;
3239 	}
3240 
3241 	/* validate the source of the LS is logged in */
3242 	ndlp = lpfc_findnode_did(phba->pport, sid);
3243 	if (!ndlp ||
3244 	    ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
3245 	     (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
3246 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
3247 				"6216 NVME Unsol rcv: No ndlp: "
3248 				"NPort_ID x%x oxid x%x\n",
3249 				sid, oxid);
3250 		goto out_fail;
3251 	}
3252 
3253 	axchg->phba = phba;
3254 	axchg->ndlp = ndlp;
3255 	axchg->size = size;
3256 	axchg->oxid = oxid;
3257 	axchg->sid = sid;
3258 	axchg->wqeq = NULL;
3259 	axchg->state = LPFC_NVME_STE_LS_RCV;
3260 	axchg->entry_cnt = 1;
3261 	axchg->rqb_buffer = (void *)nvmebuf;
3262 	axchg->hdwq = &phba->sli4_hba.hdwq[0];
3263 	axchg->payload = nvmebuf->dbuf.virt;
3264 	INIT_LIST_HEAD(&axchg->list);
3265 
3266 	if (phba->nvmet_support) {
3267 		ret = lpfc_nvmet_handle_lsreq(phba, axchg);
3268 		spin_lock_irq(&ndlp->lock);
3269 		if (!ret && !(ndlp->fc4_xpt_flags & NLP_XPT_HAS_HH)) {
3270 			ndlp->fc4_xpt_flags |= NLP_XPT_HAS_HH;
3271 			spin_unlock_irq(&ndlp->lock);
3272 
3273 			/* This reference is a single occurrence to hold the
3274 			 * node valid until the nvmet transport calls
3275 			 * host_release.
3276 			 */
3277 			if (!lpfc_nlp_get(ndlp))
3278 				goto out_fail;
3279 
3280 			lpfc_printf_log(phba, KERN_ERR, LOG_NODE,
3281 					"6206 NVMET unsol ls_req ndlp x%px "
3282 					"DID x%x xflags x%x refcnt %d\n",
3283 					ndlp, ndlp->nlp_DID,
3284 					ndlp->fc4_xpt_flags,
3285 					kref_read(&ndlp->kref));
3286 		} else {
3287 			spin_unlock_irq(&ndlp->lock);
3288 		}
3289 	} else {
3290 		ret = lpfc_nvme_handle_lsreq(phba, axchg);
3291 	}
3292 
3293 	/* if zero, LS was successfully handled. If non-zero, LS not handled */
3294 	if (!ret)
3295 		return;
3296 
3297 out_fail:
3298 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3299 			"6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
3300 			"NVMe%s handler failed %d\n",
3301 			did, sid, oxid,
3302 			(phba->nvmet_support) ? "T" : "I", ret);
3303 
3304 	/* recycle receive buffer */
3305 	lpfc_in_buf_free(phba, &nvmebuf->dbuf);
3306 
3307 	/* If start of new exchange, abort it */
3308 	if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
3309 		ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
3310 
3311 	if (ret)
3312 		kfree(axchg);
3313 }
3314 
3315 /**
3316  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
3317  * @phba: Pointer to HBA context object.
3318  * @pring: Pointer to driver SLI ring object.
3319  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
3320  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
3321  * @fch_type: the type for the first frame of the sequence.
3322  *
3323  * This function is called with no lock held. This function uses the r_ctl and
3324  * type of the received sequence to find the correct callback function to call
3325  * to process the sequence.
3326  **/
3327 static int
3328 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3329 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
3330 			 uint32_t fch_type)
3331 {
3332 	int i;
3333 
3334 	switch (fch_type) {
3335 	case FC_TYPE_NVME:
3336 		lpfc_nvme_unsol_ls_handler(phba, saveq);
3337 		return 1;
3338 	default:
3339 		break;
3340 	}
3341 
3342 	/* unSolicited Responses */
3343 	if (pring->prt[0].profile) {
3344 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
3345 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
3346 									saveq);
3347 		return 1;
3348 	}
3349 	/* We must search, based on rctl / type
3350 	   for the right routine */
3351 	for (i = 0; i < pring->num_mask; i++) {
3352 		if ((pring->prt[i].rctl == fch_r_ctl) &&
3353 		    (pring->prt[i].type == fch_type)) {
3354 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
3355 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
3356 						(phba, pring, saveq);
3357 			return 1;
3358 		}
3359 	}
3360 	return 0;
3361 }
3362 
3363 static void
3364 lpfc_sli_prep_unsol_wqe(struct lpfc_hba *phba,
3365 			struct lpfc_iocbq *saveq)
3366 {
3367 	IOCB_t *irsp;
3368 	union lpfc_wqe128 *wqe;
3369 	u16 i = 0;
3370 
3371 	irsp = &saveq->iocb;
3372 	wqe = &saveq->wqe;
3373 
3374 	/* Fill wcqe with the IOCB status fields */
3375 	bf_set(lpfc_wcqe_c_status, &saveq->wcqe_cmpl, irsp->ulpStatus);
3376 	saveq->wcqe_cmpl.word3 = irsp->ulpBdeCount;
3377 	saveq->wcqe_cmpl.parameter = irsp->un.ulpWord[4];
3378 	saveq->wcqe_cmpl.total_data_placed = irsp->unsli3.rcvsli3.acc_len;
3379 
3380 	/* Source ID */
3381 	bf_set(els_rsp64_sid, &wqe->xmit_els_rsp, irsp->un.rcvels.parmRo);
3382 
3383 	/* rx-id of the response frame */
3384 	bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com, irsp->ulpContext);
3385 
3386 	/* ox-id of the frame */
3387 	bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
3388 	       irsp->unsli3.rcvsli3.ox_id);
3389 
3390 	/* DID */
3391 	bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
3392 	       irsp->un.rcvels.remoteID);
3393 
3394 	/* unsol data len */
3395 	for (i = 0; i < irsp->ulpBdeCount; i++) {
3396 		struct lpfc_hbq_entry *hbqe = NULL;
3397 
3398 		if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3399 			if (i == 0) {
3400 				hbqe = (struct lpfc_hbq_entry *)
3401 					&irsp->un.ulpWord[0];
3402 				saveq->wqe.gen_req.bde.tus.f.bdeSize =
3403 					hbqe->bde.tus.f.bdeSize;
3404 			} else if (i == 1) {
3405 				hbqe = (struct lpfc_hbq_entry *)
3406 					&irsp->unsli3.sli3Words[4];
3407 				saveq->unsol_rcv_len = hbqe->bde.tus.f.bdeSize;
3408 			}
3409 		}
3410 	}
3411 }
3412 
3413 /**
3414  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
3415  * @phba: Pointer to HBA context object.
3416  * @pring: Pointer to driver SLI ring object.
3417  * @saveq: Pointer to the unsolicited iocb.
3418  *
3419  * This function is called with no lock held by the ring event handler
3420  * when there is an unsolicited iocb posted to the response ring by the
3421  * firmware. This function gets the buffer associated with the iocbs
3422  * and calls the event handler for the ring. This function handles both
3423  * qring buffers and hbq buffers.
3424  * When the function returns 1 the caller can free the iocb object otherwise
3425  * upper layer functions will free the iocb objects.
3426  **/
3427 static int
3428 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3429 			    struct lpfc_iocbq *saveq)
3430 {
3431 	IOCB_t           * irsp;
3432 	WORD5            * w5p;
3433 	dma_addr_t	 paddr;
3434 	uint32_t           Rctl, Type;
3435 	struct lpfc_iocbq *iocbq;
3436 	struct lpfc_dmabuf *dmzbuf;
3437 
3438 	irsp = &saveq->iocb;
3439 	saveq->vport = phba->pport;
3440 
3441 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
3442 		if (pring->lpfc_sli_rcv_async_status)
3443 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
3444 		else
3445 			lpfc_printf_log(phba,
3446 					KERN_WARNING,
3447 					LOG_SLI,
3448 					"0316 Ring %d handler: unexpected "
3449 					"ASYNC_STATUS iocb received evt_code "
3450 					"0x%x\n",
3451 					pring->ringno,
3452 					irsp->un.asyncstat.evt_code);
3453 		return 1;
3454 	}
3455 
3456 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3457 	    (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3458 		if (irsp->ulpBdeCount > 0) {
3459 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3460 						   irsp->un.ulpWord[3]);
3461 			lpfc_in_buf_free(phba, dmzbuf);
3462 		}
3463 
3464 		if (irsp->ulpBdeCount > 1) {
3465 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3466 						   irsp->unsli3.sli3Words[3]);
3467 			lpfc_in_buf_free(phba, dmzbuf);
3468 		}
3469 
3470 		if (irsp->ulpBdeCount > 2) {
3471 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3472 						   irsp->unsli3.sli3Words[7]);
3473 			lpfc_in_buf_free(phba, dmzbuf);
3474 		}
3475 
3476 		return 1;
3477 	}
3478 
3479 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3480 		if (irsp->ulpBdeCount != 0) {
3481 			saveq->context2 = lpfc_sli_get_buff(phba, pring,
3482 						irsp->un.ulpWord[3]);
3483 			if (!saveq->context2)
3484 				lpfc_printf_log(phba,
3485 					KERN_ERR,
3486 					LOG_SLI,
3487 					"0341 Ring %d Cannot find buffer for "
3488 					"an unsolicited iocb. tag 0x%x\n",
3489 					pring->ringno,
3490 					irsp->un.ulpWord[3]);
3491 		}
3492 		if (irsp->ulpBdeCount == 2) {
3493 			saveq->context3 = lpfc_sli_get_buff(phba, pring,
3494 						irsp->unsli3.sli3Words[7]);
3495 			if (!saveq->context3)
3496 				lpfc_printf_log(phba,
3497 					KERN_ERR,
3498 					LOG_SLI,
3499 					"0342 Ring %d Cannot find buffer for an"
3500 					" unsolicited iocb. tag 0x%x\n",
3501 					pring->ringno,
3502 					irsp->unsli3.sli3Words[7]);
3503 		}
3504 		list_for_each_entry(iocbq, &saveq->list, list) {
3505 			irsp = &iocbq->iocb;
3506 			if (irsp->ulpBdeCount != 0) {
3507 				iocbq->context2 = lpfc_sli_get_buff(phba,
3508 							pring,
3509 							irsp->un.ulpWord[3]);
3510 				if (!iocbq->context2)
3511 					lpfc_printf_log(phba,
3512 						KERN_ERR,
3513 						LOG_SLI,
3514 						"0343 Ring %d Cannot find "
3515 						"buffer for an unsolicited iocb"
3516 						". tag 0x%x\n", pring->ringno,
3517 						irsp->un.ulpWord[3]);
3518 			}
3519 			if (irsp->ulpBdeCount == 2) {
3520 				iocbq->context3 = lpfc_sli_get_buff(phba,
3521 						pring,
3522 						irsp->unsli3.sli3Words[7]);
3523 				if (!iocbq->context3)
3524 					lpfc_printf_log(phba,
3525 						KERN_ERR,
3526 						LOG_SLI,
3527 						"0344 Ring %d Cannot find "
3528 						"buffer for an unsolicited "
3529 						"iocb. tag 0x%x\n",
3530 						pring->ringno,
3531 						irsp->unsli3.sli3Words[7]);
3532 			}
3533 		}
3534 	} else {
3535 		paddr = getPaddr(irsp->un.cont64[0].addrHigh,
3536 				 irsp->un.cont64[0].addrLow);
3537 		saveq->context2 = lpfc_sli_ringpostbuf_get(phba, pring,
3538 							     paddr);
3539 		if (irsp->ulpBdeCount == 2) {
3540 			paddr = getPaddr(irsp->un.cont64[1].addrHigh,
3541 					 irsp->un.cont64[1].addrLow);
3542 			saveq->context3 = lpfc_sli_ringpostbuf_get(phba,
3543 								   pring,
3544 								   paddr);
3545 		}
3546 	}
3547 
3548 	if (irsp->ulpBdeCount != 0 &&
3549 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3550 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3551 		int found = 0;
3552 
3553 		/* search continue save q for same XRI */
3554 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3555 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3556 				saveq->iocb.unsli3.rcvsli3.ox_id) {
3557 				list_add_tail(&saveq->list, &iocbq->list);
3558 				found = 1;
3559 				break;
3560 			}
3561 		}
3562 		if (!found)
3563 			list_add_tail(&saveq->clist,
3564 				      &pring->iocb_continue_saveq);
3565 
3566 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3567 			list_del_init(&iocbq->clist);
3568 			saveq = iocbq;
3569 			irsp = &saveq->iocb;
3570 		} else {
3571 			return 0;
3572 		}
3573 	}
3574 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3575 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3576 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3577 		Rctl = FC_RCTL_ELS_REQ;
3578 		Type = FC_TYPE_ELS;
3579 	} else {
3580 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3581 		Rctl = w5p->hcsw.Rctl;
3582 		Type = w5p->hcsw.Type;
3583 
3584 		/* Firmware Workaround */
3585 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3586 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3587 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3588 			Rctl = FC_RCTL_ELS_REQ;
3589 			Type = FC_TYPE_ELS;
3590 			w5p->hcsw.Rctl = Rctl;
3591 			w5p->hcsw.Type = Type;
3592 		}
3593 	}
3594 
3595 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) &&
3596 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX ||
3597 	    irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3598 		if (irsp->unsli3.rcvsli3.vpi == 0xffff)
3599 			saveq->vport = phba->pport;
3600 		else
3601 			saveq->vport = lpfc_find_vport_by_vpid(phba,
3602 					       irsp->unsli3.rcvsli3.vpi);
3603 	}
3604 
3605 	/* Prepare WQE with Unsol frame */
3606 	lpfc_sli_prep_unsol_wqe(phba, saveq);
3607 
3608 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3609 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3610 				"0313 Ring %d handler: unexpected Rctl x%x "
3611 				"Type x%x received\n",
3612 				pring->ringno, Rctl, Type);
3613 
3614 	return 1;
3615 }
3616 
3617 /**
3618  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3619  * @phba: Pointer to HBA context object.
3620  * @pring: Pointer to driver SLI ring object.
3621  * @prspiocb: Pointer to response iocb object.
3622  *
3623  * This function looks up the iocb_lookup table to get the command iocb
3624  * corresponding to the given response iocb using the iotag of the
3625  * response iocb. The driver calls this function with the hbalock held
3626  * for SLI3 ports or the ring lock held for SLI4 ports.
3627  * This function returns the command iocb object if it finds the command
3628  * iocb else returns NULL.
3629  **/
3630 static struct lpfc_iocbq *
3631 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3632 		      struct lpfc_sli_ring *pring,
3633 		      struct lpfc_iocbq *prspiocb)
3634 {
3635 	struct lpfc_iocbq *cmd_iocb = NULL;
3636 	u16 iotag;
3637 
3638 	if (phba->sli_rev == LPFC_SLI_REV4)
3639 		iotag = get_wqe_reqtag(prspiocb);
3640 	else
3641 		iotag = prspiocb->iocb.ulpIoTag;
3642 
3643 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3644 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3645 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3646 			/* remove from txcmpl queue list */
3647 			list_del_init(&cmd_iocb->list);
3648 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3649 			pring->txcmplq_cnt--;
3650 			return cmd_iocb;
3651 		}
3652 	}
3653 
3654 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3655 			"0317 iotag x%x is out of "
3656 			"range: max iotag x%x\n",
3657 			iotag, phba->sli.last_iotag);
3658 	return NULL;
3659 }
3660 
3661 /**
3662  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3663  * @phba: Pointer to HBA context object.
3664  * @pring: Pointer to driver SLI ring object.
3665  * @iotag: IOCB tag.
3666  *
3667  * This function looks up the iocb_lookup table to get the command iocb
3668  * corresponding to the given iotag. The driver calls this function with
3669  * the ring lock held because this function is an SLI4 port only helper.
3670  * This function returns the command iocb object if it finds the command
3671  * iocb else returns NULL.
3672  **/
3673 static struct lpfc_iocbq *
3674 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3675 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3676 {
3677 	struct lpfc_iocbq *cmd_iocb = NULL;
3678 
3679 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3680 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3681 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3682 			/* remove from txcmpl queue list */
3683 			list_del_init(&cmd_iocb->list);
3684 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3685 			pring->txcmplq_cnt--;
3686 			return cmd_iocb;
3687 		}
3688 	}
3689 
3690 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3691 			"0372 iotag x%x lookup error: max iotag (x%x) "
3692 			"cmd_flag x%x\n",
3693 			iotag, phba->sli.last_iotag,
3694 			cmd_iocb ? cmd_iocb->cmd_flag : 0xffff);
3695 	return NULL;
3696 }
3697 
3698 /**
3699  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3700  * @phba: Pointer to HBA context object.
3701  * @pring: Pointer to driver SLI ring object.
3702  * @saveq: Pointer to the response iocb to be processed.
3703  *
3704  * This function is called by the ring event handler for non-fcp
3705  * rings when there is a new response iocb in the response ring.
3706  * The caller is not required to hold any locks. This function
3707  * gets the command iocb associated with the response iocb and
3708  * calls the completion handler for the command iocb. If there
3709  * is no completion handler, the function will free the resources
3710  * associated with command iocb. If the response iocb is for
3711  * an already aborted command iocb, the status of the completion
3712  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3713  * This function always returns 1.
3714  **/
3715 static int
3716 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3717 			  struct lpfc_iocbq *saveq)
3718 {
3719 	struct lpfc_iocbq *cmdiocbp;
3720 	int rc = 1;
3721 	unsigned long iflag;
3722 	u32 ulp_command, ulp_status, ulp_word4, ulp_context, iotag;
3723 
3724 	if (phba->sli_rev == LPFC_SLI_REV4)
3725 		spin_lock_irqsave(&pring->ring_lock, iflag);
3726 	else
3727 		spin_lock_irqsave(&phba->hbalock, iflag);
3728 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3729 	if (phba->sli_rev == LPFC_SLI_REV4)
3730 		spin_unlock_irqrestore(&pring->ring_lock, iflag);
3731 	else
3732 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3733 
3734 	ulp_command = get_job_cmnd(phba, saveq);
3735 	ulp_status = get_job_ulpstatus(phba, saveq);
3736 	ulp_word4 = get_job_word4(phba, saveq);
3737 	ulp_context = get_job_ulpcontext(phba, saveq);
3738 	if (phba->sli_rev == LPFC_SLI_REV4)
3739 		iotag = get_wqe_reqtag(saveq);
3740 	else
3741 		iotag = saveq->iocb.ulpIoTag;
3742 
3743 	if (cmdiocbp) {
3744 		ulp_command = get_job_cmnd(phba, cmdiocbp);
3745 		if (cmdiocbp->cmd_cmpl) {
3746 			/*
3747 			 * If an ELS command failed send an event to mgmt
3748 			 * application.
3749 			 */
3750 			if (ulp_status &&
3751 			     (pring->ringno == LPFC_ELS_RING) &&
3752 			     (ulp_command == CMD_ELS_REQUEST64_CR))
3753 				lpfc_send_els_failure_event(phba,
3754 					cmdiocbp, saveq);
3755 
3756 			/*
3757 			 * Post all ELS completions to the worker thread.
3758 			 * All other are passed to the completion callback.
3759 			 */
3760 			if (pring->ringno == LPFC_ELS_RING) {
3761 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3762 				    (cmdiocbp->cmd_flag &
3763 							LPFC_DRIVER_ABORTED)) {
3764 					spin_lock_irqsave(&phba->hbalock,
3765 							  iflag);
3766 					cmdiocbp->cmd_flag &=
3767 						~LPFC_DRIVER_ABORTED;
3768 					spin_unlock_irqrestore(&phba->hbalock,
3769 							       iflag);
3770 					saveq->iocb.ulpStatus =
3771 						IOSTAT_LOCAL_REJECT;
3772 					saveq->iocb.un.ulpWord[4] =
3773 						IOERR_SLI_ABORTED;
3774 
3775 					/* Firmware could still be in progress
3776 					 * of DMAing payload, so don't free data
3777 					 * buffer till after a hbeat.
3778 					 */
3779 					spin_lock_irqsave(&phba->hbalock,
3780 							  iflag);
3781 					saveq->cmd_flag |= LPFC_DELAY_MEM_FREE;
3782 					spin_unlock_irqrestore(&phba->hbalock,
3783 							       iflag);
3784 				}
3785 				if (phba->sli_rev == LPFC_SLI_REV4) {
3786 					if (saveq->cmd_flag &
3787 					    LPFC_EXCHANGE_BUSY) {
3788 						/* Set cmdiocb flag for the
3789 						 * exchange busy so sgl (xri)
3790 						 * will not be released until
3791 						 * the abort xri is received
3792 						 * from hba.
3793 						 */
3794 						spin_lock_irqsave(
3795 							&phba->hbalock, iflag);
3796 						cmdiocbp->cmd_flag |=
3797 							LPFC_EXCHANGE_BUSY;
3798 						spin_unlock_irqrestore(
3799 							&phba->hbalock, iflag);
3800 					}
3801 					if (cmdiocbp->cmd_flag &
3802 					    LPFC_DRIVER_ABORTED) {
3803 						/*
3804 						 * Clear LPFC_DRIVER_ABORTED
3805 						 * bit in case it was driver
3806 						 * initiated abort.
3807 						 */
3808 						spin_lock_irqsave(
3809 							&phba->hbalock, iflag);
3810 						cmdiocbp->cmd_flag &=
3811 							~LPFC_DRIVER_ABORTED;
3812 						spin_unlock_irqrestore(
3813 							&phba->hbalock, iflag);
3814 						set_job_ulpstatus(cmdiocbp,
3815 								  IOSTAT_LOCAL_REJECT);
3816 						set_job_ulpword4(cmdiocbp,
3817 								 IOERR_ABORT_REQUESTED);
3818 						/*
3819 						 * For SLI4, irsiocb contains
3820 						 * NO_XRI in sli_xritag, it
3821 						 * shall not affect releasing
3822 						 * sgl (xri) process.
3823 						 */
3824 						set_job_ulpstatus(saveq,
3825 								  IOSTAT_LOCAL_REJECT);
3826 						set_job_ulpword4(saveq,
3827 								 IOERR_SLI_ABORTED);
3828 						spin_lock_irqsave(
3829 							&phba->hbalock, iflag);
3830 						saveq->cmd_flag |=
3831 							LPFC_DELAY_MEM_FREE;
3832 						spin_unlock_irqrestore(
3833 							&phba->hbalock, iflag);
3834 					}
3835 				}
3836 			}
3837 			(cmdiocbp->cmd_cmpl) (phba, cmdiocbp, saveq);
3838 		} else
3839 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3840 	} else {
3841 		/*
3842 		 * Unknown initiating command based on the response iotag.
3843 		 * This could be the case on the ELS ring because of
3844 		 * lpfc_els_abort().
3845 		 */
3846 		if (pring->ringno != LPFC_ELS_RING) {
3847 			/*
3848 			 * Ring <ringno> handler: unexpected completion IoTag
3849 			 * <IoTag>
3850 			 */
3851 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3852 					 "0322 Ring %d handler: "
3853 					 "unexpected completion IoTag x%x "
3854 					 "Data: x%x x%x x%x x%x\n",
3855 					 pring->ringno, iotag, ulp_status,
3856 					 ulp_word4, ulp_command, ulp_context);
3857 		}
3858 	}
3859 
3860 	return rc;
3861 }
3862 
3863 /**
3864  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3865  * @phba: Pointer to HBA context object.
3866  * @pring: Pointer to driver SLI ring object.
3867  *
3868  * This function is called from the iocb ring event handlers when
3869  * put pointer is ahead of the get pointer for a ring. This function signal
3870  * an error attention condition to the worker thread and the worker
3871  * thread will transition the HBA to offline state.
3872  **/
3873 static void
3874 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3875 {
3876 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3877 	/*
3878 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3879 	 * rsp ring <portRspMax>
3880 	 */
3881 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3882 			"0312 Ring %d handler: portRspPut %d "
3883 			"is bigger than rsp ring %d\n",
3884 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3885 			pring->sli.sli3.numRiocb);
3886 
3887 	phba->link_state = LPFC_HBA_ERROR;
3888 
3889 	/*
3890 	 * All error attention handlers are posted to
3891 	 * worker thread
3892 	 */
3893 	phba->work_ha |= HA_ERATT;
3894 	phba->work_hs = HS_FFER3;
3895 
3896 	lpfc_worker_wake_up(phba);
3897 
3898 	return;
3899 }
3900 
3901 /**
3902  * lpfc_poll_eratt - Error attention polling timer timeout handler
3903  * @t: Context to fetch pointer to address of HBA context object from.
3904  *
3905  * This function is invoked by the Error Attention polling timer when the
3906  * timer times out. It will check the SLI Error Attention register for
3907  * possible attention events. If so, it will post an Error Attention event
3908  * and wake up worker thread to process it. Otherwise, it will set up the
3909  * Error Attention polling timer for the next poll.
3910  **/
3911 void lpfc_poll_eratt(struct timer_list *t)
3912 {
3913 	struct lpfc_hba *phba;
3914 	uint32_t eratt = 0;
3915 	uint64_t sli_intr, cnt;
3916 
3917 	phba = from_timer(phba, t, eratt_poll);
3918 
3919 	/* Here we will also keep track of interrupts per sec of the hba */
3920 	sli_intr = phba->sli.slistat.sli_intr;
3921 
3922 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3923 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3924 			sli_intr);
3925 	else
3926 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3927 
3928 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3929 	do_div(cnt, phba->eratt_poll_interval);
3930 	phba->sli.slistat.sli_ips = cnt;
3931 
3932 	phba->sli.slistat.sli_prev_intr = sli_intr;
3933 
3934 	/* Check chip HA register for error event */
3935 	eratt = lpfc_sli_check_eratt(phba);
3936 
3937 	if (eratt)
3938 		/* Tell the worker thread there is work to do */
3939 		lpfc_worker_wake_up(phba);
3940 	else
3941 		/* Restart the timer for next eratt poll */
3942 		mod_timer(&phba->eratt_poll,
3943 			  jiffies +
3944 			  msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3945 	return;
3946 }
3947 
3948 
3949 /**
3950  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3951  * @phba: Pointer to HBA context object.
3952  * @pring: Pointer to driver SLI ring object.
3953  * @mask: Host attention register mask for this ring.
3954  *
3955  * This function is called from the interrupt context when there is a ring
3956  * event for the fcp ring. The caller does not hold any lock.
3957  * The function processes each response iocb in the response ring until it
3958  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3959  * LE bit set. The function will call the completion handler of the command iocb
3960  * if the response iocb indicates a completion for a command iocb or it is
3961  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3962  * function if this is an unsolicited iocb.
3963  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3964  * to check it explicitly.
3965  */
3966 int
3967 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3968 				struct lpfc_sli_ring *pring, uint32_t mask)
3969 {
3970 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3971 	IOCB_t *irsp = NULL;
3972 	IOCB_t *entry = NULL;
3973 	struct lpfc_iocbq *cmdiocbq = NULL;
3974 	struct lpfc_iocbq rspiocbq;
3975 	uint32_t status;
3976 	uint32_t portRspPut, portRspMax;
3977 	int rc = 1;
3978 	lpfc_iocb_type type;
3979 	unsigned long iflag;
3980 	uint32_t rsp_cmpl = 0;
3981 
3982 	spin_lock_irqsave(&phba->hbalock, iflag);
3983 	pring->stats.iocb_event++;
3984 
3985 	/*
3986 	 * The next available response entry should never exceed the maximum
3987 	 * entries.  If it does, treat it as an adapter hardware error.
3988 	 */
3989 	portRspMax = pring->sli.sli3.numRiocb;
3990 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3991 	if (unlikely(portRspPut >= portRspMax)) {
3992 		lpfc_sli_rsp_pointers_error(phba, pring);
3993 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3994 		return 1;
3995 	}
3996 	if (phba->fcp_ring_in_use) {
3997 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3998 		return 1;
3999 	} else
4000 		phba->fcp_ring_in_use = 1;
4001 
4002 	rmb();
4003 	while (pring->sli.sli3.rspidx != portRspPut) {
4004 		/*
4005 		 * Fetch an entry off the ring and copy it into a local data
4006 		 * structure.  The copy involves a byte-swap since the
4007 		 * network byte order and pci byte orders are different.
4008 		 */
4009 		entry = lpfc_resp_iocb(phba, pring);
4010 		phba->last_completion_time = jiffies;
4011 
4012 		if (++pring->sli.sli3.rspidx >= portRspMax)
4013 			pring->sli.sli3.rspidx = 0;
4014 
4015 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
4016 				      (uint32_t *) &rspiocbq.iocb,
4017 				      phba->iocb_rsp_size);
4018 		INIT_LIST_HEAD(&(rspiocbq.list));
4019 		irsp = &rspiocbq.iocb;
4020 
4021 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
4022 		pring->stats.iocb_rsp++;
4023 		rsp_cmpl++;
4024 
4025 		if (unlikely(irsp->ulpStatus)) {
4026 			/*
4027 			 * If resource errors reported from HBA, reduce
4028 			 * queuedepths of the SCSI device.
4029 			 */
4030 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
4031 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
4032 			     IOERR_NO_RESOURCES)) {
4033 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4034 				phba->lpfc_rampdown_queue_depth(phba);
4035 				spin_lock_irqsave(&phba->hbalock, iflag);
4036 			}
4037 
4038 			/* Rsp ring <ringno> error: IOCB */
4039 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4040 					"0336 Rsp Ring %d error: IOCB Data: "
4041 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
4042 					pring->ringno,
4043 					irsp->un.ulpWord[0],
4044 					irsp->un.ulpWord[1],
4045 					irsp->un.ulpWord[2],
4046 					irsp->un.ulpWord[3],
4047 					irsp->un.ulpWord[4],
4048 					irsp->un.ulpWord[5],
4049 					*(uint32_t *)&irsp->un1,
4050 					*((uint32_t *)&irsp->un1 + 1));
4051 		}
4052 
4053 		switch (type) {
4054 		case LPFC_ABORT_IOCB:
4055 		case LPFC_SOL_IOCB:
4056 			/*
4057 			 * Idle exchange closed via ABTS from port.  No iocb
4058 			 * resources need to be recovered.
4059 			 */
4060 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
4061 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4062 						"0333 IOCB cmd 0x%x"
4063 						" processed. Skipping"
4064 						" completion\n",
4065 						irsp->ulpCommand);
4066 				break;
4067 			}
4068 
4069 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
4070 							 &rspiocbq);
4071 			if (unlikely(!cmdiocbq))
4072 				break;
4073 			if (cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED)
4074 				cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
4075 			if (cmdiocbq->cmd_cmpl) {
4076 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4077 				(cmdiocbq->cmd_cmpl)(phba, cmdiocbq,
4078 						      &rspiocbq);
4079 				spin_lock_irqsave(&phba->hbalock, iflag);
4080 			}
4081 			break;
4082 		case LPFC_UNSOL_IOCB:
4083 			spin_unlock_irqrestore(&phba->hbalock, iflag);
4084 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
4085 			spin_lock_irqsave(&phba->hbalock, iflag);
4086 			break;
4087 		default:
4088 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
4089 				char adaptermsg[LPFC_MAX_ADPTMSG];
4090 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4091 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
4092 				       MAX_MSG_DATA);
4093 				dev_warn(&((phba->pcidev)->dev),
4094 					 "lpfc%d: %s\n",
4095 					 phba->brd_no, adaptermsg);
4096 			} else {
4097 				/* Unknown IOCB command */
4098 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4099 						"0334 Unknown IOCB command "
4100 						"Data: x%x, x%x x%x x%x x%x\n",
4101 						type, irsp->ulpCommand,
4102 						irsp->ulpStatus,
4103 						irsp->ulpIoTag,
4104 						irsp->ulpContext);
4105 			}
4106 			break;
4107 		}
4108 
4109 		/*
4110 		 * The response IOCB has been processed.  Update the ring
4111 		 * pointer in SLIM.  If the port response put pointer has not
4112 		 * been updated, sync the pgp->rspPutInx and fetch the new port
4113 		 * response put pointer.
4114 		 */
4115 		writel(pring->sli.sli3.rspidx,
4116 			&phba->host_gp[pring->ringno].rspGetInx);
4117 
4118 		if (pring->sli.sli3.rspidx == portRspPut)
4119 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4120 	}
4121 
4122 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
4123 		pring->stats.iocb_rsp_full++;
4124 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4125 		writel(status, phba->CAregaddr);
4126 		readl(phba->CAregaddr);
4127 	}
4128 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4129 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4130 		pring->stats.iocb_cmd_empty++;
4131 
4132 		/* Force update of the local copy of cmdGetInx */
4133 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4134 		lpfc_sli_resume_iocb(phba, pring);
4135 
4136 		if ((pring->lpfc_sli_cmd_available))
4137 			(pring->lpfc_sli_cmd_available) (phba, pring);
4138 
4139 	}
4140 
4141 	phba->fcp_ring_in_use = 0;
4142 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4143 	return rc;
4144 }
4145 
4146 /**
4147  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
4148  * @phba: Pointer to HBA context object.
4149  * @pring: Pointer to driver SLI ring object.
4150  * @rspiocbp: Pointer to driver response IOCB object.
4151  *
4152  * This function is called from the worker thread when there is a slow-path
4153  * response IOCB to process. This function chains all the response iocbs until
4154  * seeing the iocb with the LE bit set. The function will call
4155  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
4156  * completion of a command iocb. The function will call the
4157  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
4158  * The function frees the resources or calls the completion handler if this
4159  * iocb is an abort completion. The function returns NULL when the response
4160  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
4161  * this function shall chain the iocb on to the iocb_continueq and return the
4162  * response iocb passed in.
4163  **/
4164 static struct lpfc_iocbq *
4165 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
4166 			struct lpfc_iocbq *rspiocbp)
4167 {
4168 	struct lpfc_iocbq *saveq;
4169 	struct lpfc_iocbq *cmdiocb;
4170 	struct lpfc_iocbq *next_iocb;
4171 	IOCB_t *irsp;
4172 	uint32_t free_saveq;
4173 	u8 cmd_type;
4174 	lpfc_iocb_type type;
4175 	unsigned long iflag;
4176 	u32 ulp_status = get_job_ulpstatus(phba, rspiocbp);
4177 	u32 ulp_word4 = get_job_word4(phba, rspiocbp);
4178 	u32 ulp_command = get_job_cmnd(phba, rspiocbp);
4179 	int rc;
4180 
4181 	spin_lock_irqsave(&phba->hbalock, iflag);
4182 	/* First add the response iocb to the countinueq list */
4183 	list_add_tail(&rspiocbp->list, &pring->iocb_continueq);
4184 	pring->iocb_continueq_cnt++;
4185 
4186 	/*
4187 	 * By default, the driver expects to free all resources
4188 	 * associated with this iocb completion.
4189 	 */
4190 	free_saveq = 1;
4191 	saveq = list_get_first(&pring->iocb_continueq,
4192 			       struct lpfc_iocbq, list);
4193 	list_del_init(&pring->iocb_continueq);
4194 	pring->iocb_continueq_cnt = 0;
4195 
4196 	pring->stats.iocb_rsp++;
4197 
4198 	/*
4199 	 * If resource errors reported from HBA, reduce
4200 	 * queuedepths of the SCSI device.
4201 	 */
4202 	if (ulp_status == IOSTAT_LOCAL_REJECT &&
4203 	    ((ulp_word4 & IOERR_PARAM_MASK) ==
4204 	     IOERR_NO_RESOURCES)) {
4205 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4206 		phba->lpfc_rampdown_queue_depth(phba);
4207 		spin_lock_irqsave(&phba->hbalock, iflag);
4208 	}
4209 
4210 	if (ulp_status) {
4211 		/* Rsp ring <ringno> error: IOCB */
4212 		if (phba->sli_rev < LPFC_SLI_REV4) {
4213 			irsp = &rspiocbp->iocb;
4214 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4215 					"0328 Rsp Ring %d error: ulp_status x%x "
4216 					"IOCB Data: "
4217 					"x%08x x%08x x%08x x%08x "
4218 					"x%08x x%08x x%08x x%08x "
4219 					"x%08x x%08x x%08x x%08x "
4220 					"x%08x x%08x x%08x x%08x\n",
4221 					pring->ringno, ulp_status,
4222 					get_job_ulpword(rspiocbp, 0),
4223 					get_job_ulpword(rspiocbp, 1),
4224 					get_job_ulpword(rspiocbp, 2),
4225 					get_job_ulpword(rspiocbp, 3),
4226 					get_job_ulpword(rspiocbp, 4),
4227 					get_job_ulpword(rspiocbp, 5),
4228 					*(((uint32_t *)irsp) + 6),
4229 					*(((uint32_t *)irsp) + 7),
4230 					*(((uint32_t *)irsp) + 8),
4231 					*(((uint32_t *)irsp) + 9),
4232 					*(((uint32_t *)irsp) + 10),
4233 					*(((uint32_t *)irsp) + 11),
4234 					*(((uint32_t *)irsp) + 12),
4235 					*(((uint32_t *)irsp) + 13),
4236 					*(((uint32_t *)irsp) + 14),
4237 					*(((uint32_t *)irsp) + 15));
4238 		} else {
4239 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4240 					"0321 Rsp Ring %d error: "
4241 					"IOCB Data: "
4242 					"x%x x%x x%x x%x\n",
4243 					pring->ringno,
4244 					rspiocbp->wcqe_cmpl.word0,
4245 					rspiocbp->wcqe_cmpl.total_data_placed,
4246 					rspiocbp->wcqe_cmpl.parameter,
4247 					rspiocbp->wcqe_cmpl.word3);
4248 		}
4249 	}
4250 
4251 
4252 	/*
4253 	 * Fetch the iocb command type and call the correct completion
4254 	 * routine. Solicited and Unsolicited IOCBs on the ELS ring
4255 	 * get freed back to the lpfc_iocb_list by the discovery
4256 	 * kernel thread.
4257 	 */
4258 	cmd_type = ulp_command & CMD_IOCB_MASK;
4259 	type = lpfc_sli_iocb_cmd_type(cmd_type);
4260 	switch (type) {
4261 	case LPFC_SOL_IOCB:
4262 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4263 		rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
4264 		spin_lock_irqsave(&phba->hbalock, iflag);
4265 		break;
4266 	case LPFC_UNSOL_IOCB:
4267 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4268 		rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
4269 		spin_lock_irqsave(&phba->hbalock, iflag);
4270 		if (!rc)
4271 			free_saveq = 0;
4272 		break;
4273 	case LPFC_ABORT_IOCB:
4274 		cmdiocb = NULL;
4275 		if (ulp_command != CMD_XRI_ABORTED_CX)
4276 			cmdiocb = lpfc_sli_iocbq_lookup(phba, pring,
4277 							saveq);
4278 		if (cmdiocb) {
4279 			/* Call the specified completion routine */
4280 			if (cmdiocb->cmd_cmpl) {
4281 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4282 				cmdiocb->cmd_cmpl(phba, cmdiocb, saveq);
4283 				spin_lock_irqsave(&phba->hbalock, iflag);
4284 			} else {
4285 				__lpfc_sli_release_iocbq(phba, cmdiocb);
4286 			}
4287 		}
4288 		break;
4289 	case LPFC_UNKNOWN_IOCB:
4290 		if (ulp_command == CMD_ADAPTER_MSG) {
4291 			char adaptermsg[LPFC_MAX_ADPTMSG];
4292 
4293 			memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4294 			memcpy(&adaptermsg[0], (uint8_t *)&rspiocbp->wqe,
4295 			       MAX_MSG_DATA);
4296 			dev_warn(&((phba->pcidev)->dev),
4297 				 "lpfc%d: %s\n",
4298 				 phba->brd_no, adaptermsg);
4299 		} else {
4300 			/* Unknown command */
4301 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4302 					"0335 Unknown IOCB "
4303 					"command Data: x%x "
4304 					"x%x x%x x%x\n",
4305 					ulp_command,
4306 					ulp_status,
4307 					get_wqe_reqtag(rspiocbp),
4308 					get_job_ulpcontext(phba, rspiocbp));
4309 		}
4310 		break;
4311 	}
4312 
4313 	if (free_saveq) {
4314 		list_for_each_entry_safe(rspiocbp, next_iocb,
4315 					 &saveq->list, list) {
4316 			list_del_init(&rspiocbp->list);
4317 			__lpfc_sli_release_iocbq(phba, rspiocbp);
4318 		}
4319 		__lpfc_sli_release_iocbq(phba, saveq);
4320 	}
4321 	rspiocbp = NULL;
4322 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4323 	return rspiocbp;
4324 }
4325 
4326 /**
4327  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
4328  * @phba: Pointer to HBA context object.
4329  * @pring: Pointer to driver SLI ring object.
4330  * @mask: Host attention register mask for this ring.
4331  *
4332  * This routine wraps the actual slow_ring event process routine from the
4333  * API jump table function pointer from the lpfc_hba struct.
4334  **/
4335 void
4336 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
4337 				struct lpfc_sli_ring *pring, uint32_t mask)
4338 {
4339 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
4340 }
4341 
4342 /**
4343  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
4344  * @phba: Pointer to HBA context object.
4345  * @pring: Pointer to driver SLI ring object.
4346  * @mask: Host attention register mask for this ring.
4347  *
4348  * This function is called from the worker thread when there is a ring event
4349  * for non-fcp rings. The caller does not hold any lock. The function will
4350  * remove each response iocb in the response ring and calls the handle
4351  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4352  **/
4353 static void
4354 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
4355 				   struct lpfc_sli_ring *pring, uint32_t mask)
4356 {
4357 	struct lpfc_pgp *pgp;
4358 	IOCB_t *entry;
4359 	IOCB_t *irsp = NULL;
4360 	struct lpfc_iocbq *rspiocbp = NULL;
4361 	uint32_t portRspPut, portRspMax;
4362 	unsigned long iflag;
4363 	uint32_t status;
4364 
4365 	pgp = &phba->port_gp[pring->ringno];
4366 	spin_lock_irqsave(&phba->hbalock, iflag);
4367 	pring->stats.iocb_event++;
4368 
4369 	/*
4370 	 * The next available response entry should never exceed the maximum
4371 	 * entries.  If it does, treat it as an adapter hardware error.
4372 	 */
4373 	portRspMax = pring->sli.sli3.numRiocb;
4374 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4375 	if (portRspPut >= portRspMax) {
4376 		/*
4377 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
4378 		 * rsp ring <portRspMax>
4379 		 */
4380 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4381 				"0303 Ring %d handler: portRspPut %d "
4382 				"is bigger than rsp ring %d\n",
4383 				pring->ringno, portRspPut, portRspMax);
4384 
4385 		phba->link_state = LPFC_HBA_ERROR;
4386 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4387 
4388 		phba->work_hs = HS_FFER3;
4389 		lpfc_handle_eratt(phba);
4390 
4391 		return;
4392 	}
4393 
4394 	rmb();
4395 	while (pring->sli.sli3.rspidx != portRspPut) {
4396 		/*
4397 		 * Build a completion list and call the appropriate handler.
4398 		 * The process is to get the next available response iocb, get
4399 		 * a free iocb from the list, copy the response data into the
4400 		 * free iocb, insert to the continuation list, and update the
4401 		 * next response index to slim.  This process makes response
4402 		 * iocb's in the ring available to DMA as fast as possible but
4403 		 * pays a penalty for a copy operation.  Since the iocb is
4404 		 * only 32 bytes, this penalty is considered small relative to
4405 		 * the PCI reads for register values and a slim write.  When
4406 		 * the ulpLe field is set, the entire Command has been
4407 		 * received.
4408 		 */
4409 		entry = lpfc_resp_iocb(phba, pring);
4410 
4411 		phba->last_completion_time = jiffies;
4412 		rspiocbp = __lpfc_sli_get_iocbq(phba);
4413 		if (rspiocbp == NULL) {
4414 			printk(KERN_ERR "%s: out of buffers! Failing "
4415 			       "completion.\n", __func__);
4416 			break;
4417 		}
4418 
4419 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
4420 				      phba->iocb_rsp_size);
4421 		irsp = &rspiocbp->iocb;
4422 
4423 		if (++pring->sli.sli3.rspidx >= portRspMax)
4424 			pring->sli.sli3.rspidx = 0;
4425 
4426 		if (pring->ringno == LPFC_ELS_RING) {
4427 			lpfc_debugfs_slow_ring_trc(phba,
4428 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
4429 				*(((uint32_t *) irsp) + 4),
4430 				*(((uint32_t *) irsp) + 6),
4431 				*(((uint32_t *) irsp) + 7));
4432 		}
4433 
4434 		writel(pring->sli.sli3.rspidx,
4435 			&phba->host_gp[pring->ringno].rspGetInx);
4436 
4437 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4438 		/* Handle the response IOCB */
4439 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
4440 		spin_lock_irqsave(&phba->hbalock, iflag);
4441 
4442 		/*
4443 		 * If the port response put pointer has not been updated, sync
4444 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
4445 		 * response put pointer.
4446 		 */
4447 		if (pring->sli.sli3.rspidx == portRspPut) {
4448 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4449 		}
4450 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
4451 
4452 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
4453 		/* At least one response entry has been freed */
4454 		pring->stats.iocb_rsp_full++;
4455 		/* SET RxRE_RSP in Chip Att register */
4456 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4457 		writel(status, phba->CAregaddr);
4458 		readl(phba->CAregaddr); /* flush */
4459 	}
4460 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4461 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4462 		pring->stats.iocb_cmd_empty++;
4463 
4464 		/* Force update of the local copy of cmdGetInx */
4465 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4466 		lpfc_sli_resume_iocb(phba, pring);
4467 
4468 		if ((pring->lpfc_sli_cmd_available))
4469 			(pring->lpfc_sli_cmd_available) (phba, pring);
4470 
4471 	}
4472 
4473 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4474 	return;
4475 }
4476 
4477 /**
4478  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
4479  * @phba: Pointer to HBA context object.
4480  * @pring: Pointer to driver SLI ring object.
4481  * @mask: Host attention register mask for this ring.
4482  *
4483  * This function is called from the worker thread when there is a pending
4484  * ELS response iocb on the driver internal slow-path response iocb worker
4485  * queue. The caller does not hold any lock. The function will remove each
4486  * response iocb from the response worker queue and calls the handle
4487  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4488  **/
4489 static void
4490 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4491 				   struct lpfc_sli_ring *pring, uint32_t mask)
4492 {
4493 	struct lpfc_iocbq *irspiocbq;
4494 	struct hbq_dmabuf *dmabuf;
4495 	struct lpfc_cq_event *cq_event;
4496 	unsigned long iflag;
4497 	int count = 0;
4498 
4499 	spin_lock_irqsave(&phba->hbalock, iflag);
4500 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
4501 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4502 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4503 		/* Get the response iocb from the head of work queue */
4504 		spin_lock_irqsave(&phba->hbalock, iflag);
4505 		list_remove_head(&phba->sli4_hba.sp_queue_event,
4506 				 cq_event, struct lpfc_cq_event, list);
4507 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4508 
4509 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4510 		case CQE_CODE_COMPL_WQE:
4511 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4512 						 cq_event);
4513 			/* Translate ELS WCQE to response IOCBQ */
4514 			irspiocbq = lpfc_sli4_els_preprocess_rspiocbq(phba,
4515 								      irspiocbq);
4516 			if (irspiocbq)
4517 				lpfc_sli_sp_handle_rspiocb(phba, pring,
4518 							   irspiocbq);
4519 			count++;
4520 			break;
4521 		case CQE_CODE_RECEIVE:
4522 		case CQE_CODE_RECEIVE_V1:
4523 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
4524 					      cq_event);
4525 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
4526 			count++;
4527 			break;
4528 		default:
4529 			break;
4530 		}
4531 
4532 		/* Limit the number of events to 64 to avoid soft lockups */
4533 		if (count == 64)
4534 			break;
4535 	}
4536 }
4537 
4538 /**
4539  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4540  * @phba: Pointer to HBA context object.
4541  * @pring: Pointer to driver SLI ring object.
4542  *
4543  * This function aborts all iocbs in the given ring and frees all the iocb
4544  * objects in txq. This function issues an abort iocb for all the iocb commands
4545  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4546  * the return of this function. The caller is not required to hold any locks.
4547  **/
4548 void
4549 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4550 {
4551 	LIST_HEAD(tx_completions);
4552 	LIST_HEAD(txcmplq_completions);
4553 	struct lpfc_iocbq *iocb, *next_iocb;
4554 	int offline;
4555 
4556 	if (pring->ringno == LPFC_ELS_RING) {
4557 		lpfc_fabric_abort_hba(phba);
4558 	}
4559 	offline = pci_channel_offline(phba->pcidev);
4560 
4561 	/* Error everything on txq and txcmplq
4562 	 * First do the txq.
4563 	 */
4564 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4565 		spin_lock_irq(&pring->ring_lock);
4566 		list_splice_init(&pring->txq, &tx_completions);
4567 		pring->txq_cnt = 0;
4568 
4569 		if (offline) {
4570 			list_splice_init(&pring->txcmplq,
4571 					 &txcmplq_completions);
4572 		} else {
4573 			/* Next issue ABTS for everything on the txcmplq */
4574 			list_for_each_entry_safe(iocb, next_iocb,
4575 						 &pring->txcmplq, list)
4576 				lpfc_sli_issue_abort_iotag(phba, pring,
4577 							   iocb, NULL);
4578 		}
4579 		spin_unlock_irq(&pring->ring_lock);
4580 	} else {
4581 		spin_lock_irq(&phba->hbalock);
4582 		list_splice_init(&pring->txq, &tx_completions);
4583 		pring->txq_cnt = 0;
4584 
4585 		if (offline) {
4586 			list_splice_init(&pring->txcmplq, &txcmplq_completions);
4587 		} else {
4588 			/* Next issue ABTS for everything on the txcmplq */
4589 			list_for_each_entry_safe(iocb, next_iocb,
4590 						 &pring->txcmplq, list)
4591 				lpfc_sli_issue_abort_iotag(phba, pring,
4592 							   iocb, NULL);
4593 		}
4594 		spin_unlock_irq(&phba->hbalock);
4595 	}
4596 
4597 	if (offline) {
4598 		/* Cancel all the IOCBs from the completions list */
4599 		lpfc_sli_cancel_iocbs(phba, &txcmplq_completions,
4600 				      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
4601 	} else {
4602 		/* Make sure HBA is alive */
4603 		lpfc_issue_hb_tmo(phba);
4604 	}
4605 	/* Cancel all the IOCBs from the completions list */
4606 	lpfc_sli_cancel_iocbs(phba, &tx_completions, IOSTAT_LOCAL_REJECT,
4607 			      IOERR_SLI_ABORTED);
4608 }
4609 
4610 /**
4611  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4612  * @phba: Pointer to HBA context object.
4613  *
4614  * This function aborts all iocbs in FCP rings and frees all the iocb
4615  * objects in txq. This function issues an abort iocb for all the iocb commands
4616  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4617  * the return of this function. The caller is not required to hold any locks.
4618  **/
4619 void
4620 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4621 {
4622 	struct lpfc_sli *psli = &phba->sli;
4623 	struct lpfc_sli_ring  *pring;
4624 	uint32_t i;
4625 
4626 	/* Look on all the FCP Rings for the iotag */
4627 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4628 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4629 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4630 			lpfc_sli_abort_iocb_ring(phba, pring);
4631 		}
4632 	} else {
4633 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4634 		lpfc_sli_abort_iocb_ring(phba, pring);
4635 	}
4636 }
4637 
4638 /**
4639  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4640  * @phba: Pointer to HBA context object.
4641  *
4642  * This function flushes all iocbs in the IO ring and frees all the iocb
4643  * objects in txq and txcmplq. This function will not issue abort iocbs
4644  * for all the iocb commands in txcmplq, they will just be returned with
4645  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4646  * slot has been permanently disabled.
4647  **/
4648 void
4649 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4650 {
4651 	LIST_HEAD(txq);
4652 	LIST_HEAD(txcmplq);
4653 	struct lpfc_sli *psli = &phba->sli;
4654 	struct lpfc_sli_ring  *pring;
4655 	uint32_t i;
4656 	struct lpfc_iocbq *piocb, *next_iocb;
4657 
4658 	spin_lock_irq(&phba->hbalock);
4659 	/* Indicate the I/O queues are flushed */
4660 	phba->hba_flag |= HBA_IOQ_FLUSH;
4661 	spin_unlock_irq(&phba->hbalock);
4662 
4663 	/* Look on all the FCP Rings for the iotag */
4664 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4665 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4666 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4667 
4668 			spin_lock_irq(&pring->ring_lock);
4669 			/* Retrieve everything on txq */
4670 			list_splice_init(&pring->txq, &txq);
4671 			list_for_each_entry_safe(piocb, next_iocb,
4672 						 &pring->txcmplq, list)
4673 				piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4674 			/* Retrieve everything on the txcmplq */
4675 			list_splice_init(&pring->txcmplq, &txcmplq);
4676 			pring->txq_cnt = 0;
4677 			pring->txcmplq_cnt = 0;
4678 			spin_unlock_irq(&pring->ring_lock);
4679 
4680 			/* Flush the txq */
4681 			lpfc_sli_cancel_iocbs(phba, &txq,
4682 					      IOSTAT_LOCAL_REJECT,
4683 					      IOERR_SLI_DOWN);
4684 			/* Flush the txcmplq */
4685 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4686 					      IOSTAT_LOCAL_REJECT,
4687 					      IOERR_SLI_DOWN);
4688 			if (unlikely(pci_channel_offline(phba->pcidev)))
4689 				lpfc_sli4_io_xri_aborted(phba, NULL, 0);
4690 		}
4691 	} else {
4692 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4693 
4694 		spin_lock_irq(&phba->hbalock);
4695 		/* Retrieve everything on txq */
4696 		list_splice_init(&pring->txq, &txq);
4697 		list_for_each_entry_safe(piocb, next_iocb,
4698 					 &pring->txcmplq, list)
4699 			piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4700 		/* Retrieve everything on the txcmplq */
4701 		list_splice_init(&pring->txcmplq, &txcmplq);
4702 		pring->txq_cnt = 0;
4703 		pring->txcmplq_cnt = 0;
4704 		spin_unlock_irq(&phba->hbalock);
4705 
4706 		/* Flush the txq */
4707 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4708 				      IOERR_SLI_DOWN);
4709 		/* Flush the txcmpq */
4710 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4711 				      IOERR_SLI_DOWN);
4712 	}
4713 }
4714 
4715 /**
4716  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4717  * @phba: Pointer to HBA context object.
4718  * @mask: Bit mask to be checked.
4719  *
4720  * This function reads the host status register and compares
4721  * with the provided bit mask to check if HBA completed
4722  * the restart. This function will wait in a loop for the
4723  * HBA to complete restart. If the HBA does not restart within
4724  * 15 iterations, the function will reset the HBA again. The
4725  * function returns 1 when HBA fail to restart otherwise returns
4726  * zero.
4727  **/
4728 static int
4729 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4730 {
4731 	uint32_t status;
4732 	int i = 0;
4733 	int retval = 0;
4734 
4735 	/* Read the HBA Host Status Register */
4736 	if (lpfc_readl(phba->HSregaddr, &status))
4737 		return 1;
4738 
4739 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4740 
4741 	/*
4742 	 * Check status register every 100ms for 5 retries, then every
4743 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4744 	 * every 2.5 sec for 4.
4745 	 * Break our of the loop if errors occurred during init.
4746 	 */
4747 	while (((status & mask) != mask) &&
4748 	       !(status & HS_FFERM) &&
4749 	       i++ < 20) {
4750 
4751 		if (i <= 5)
4752 			msleep(10);
4753 		else if (i <= 10)
4754 			msleep(500);
4755 		else
4756 			msleep(2500);
4757 
4758 		if (i == 15) {
4759 				/* Do post */
4760 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4761 			lpfc_sli_brdrestart(phba);
4762 		}
4763 		/* Read the HBA Host Status Register */
4764 		if (lpfc_readl(phba->HSregaddr, &status)) {
4765 			retval = 1;
4766 			break;
4767 		}
4768 	}
4769 
4770 	/* Check to see if any errors occurred during init */
4771 	if ((status & HS_FFERM) || (i >= 20)) {
4772 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4773 				"2751 Adapter failed to restart, "
4774 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4775 				status,
4776 				readl(phba->MBslimaddr + 0xa8),
4777 				readl(phba->MBslimaddr + 0xac));
4778 		phba->link_state = LPFC_HBA_ERROR;
4779 		retval = 1;
4780 	}
4781 
4782 	return retval;
4783 }
4784 
4785 /**
4786  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4787  * @phba: Pointer to HBA context object.
4788  * @mask: Bit mask to be checked.
4789  *
4790  * This function checks the host status register to check if HBA is
4791  * ready. This function will wait in a loop for the HBA to be ready
4792  * If the HBA is not ready , the function will will reset the HBA PCI
4793  * function again. The function returns 1 when HBA fail to be ready
4794  * otherwise returns zero.
4795  **/
4796 static int
4797 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4798 {
4799 	uint32_t status;
4800 	int retval = 0;
4801 
4802 	/* Read the HBA Host Status Register */
4803 	status = lpfc_sli4_post_status_check(phba);
4804 
4805 	if (status) {
4806 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4807 		lpfc_sli_brdrestart(phba);
4808 		status = lpfc_sli4_post_status_check(phba);
4809 	}
4810 
4811 	/* Check to see if any errors occurred during init */
4812 	if (status) {
4813 		phba->link_state = LPFC_HBA_ERROR;
4814 		retval = 1;
4815 	} else
4816 		phba->sli4_hba.intr_enable = 0;
4817 
4818 	phba->hba_flag &= ~HBA_SETUP;
4819 	return retval;
4820 }
4821 
4822 /**
4823  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4824  * @phba: Pointer to HBA context object.
4825  * @mask: Bit mask to be checked.
4826  *
4827  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4828  * from the API jump table function pointer from the lpfc_hba struct.
4829  **/
4830 int
4831 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4832 {
4833 	return phba->lpfc_sli_brdready(phba, mask);
4834 }
4835 
4836 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4837 
4838 /**
4839  * lpfc_reset_barrier - Make HBA ready for HBA reset
4840  * @phba: Pointer to HBA context object.
4841  *
4842  * This function is called before resetting an HBA. This function is called
4843  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4844  **/
4845 void lpfc_reset_barrier(struct lpfc_hba *phba)
4846 {
4847 	uint32_t __iomem *resp_buf;
4848 	uint32_t __iomem *mbox_buf;
4849 	volatile struct MAILBOX_word0 mbox;
4850 	uint32_t hc_copy, ha_copy, resp_data;
4851 	int  i;
4852 	uint8_t hdrtype;
4853 
4854 	lockdep_assert_held(&phba->hbalock);
4855 
4856 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4857 	if (hdrtype != 0x80 ||
4858 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4859 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4860 		return;
4861 
4862 	/*
4863 	 * Tell the other part of the chip to suspend temporarily all
4864 	 * its DMA activity.
4865 	 */
4866 	resp_buf = phba->MBslimaddr;
4867 
4868 	/* Disable the error attention */
4869 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4870 		return;
4871 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4872 	readl(phba->HCregaddr); /* flush */
4873 	phba->link_flag |= LS_IGNORE_ERATT;
4874 
4875 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4876 		return;
4877 	if (ha_copy & HA_ERATT) {
4878 		/* Clear Chip error bit */
4879 		writel(HA_ERATT, phba->HAregaddr);
4880 		phba->pport->stopped = 1;
4881 	}
4882 
4883 	mbox.word0 = 0;
4884 	mbox.mbxCommand = MBX_KILL_BOARD;
4885 	mbox.mbxOwner = OWN_CHIP;
4886 
4887 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4888 	mbox_buf = phba->MBslimaddr;
4889 	writel(mbox.word0, mbox_buf);
4890 
4891 	for (i = 0; i < 50; i++) {
4892 		if (lpfc_readl((resp_buf + 1), &resp_data))
4893 			return;
4894 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4895 			mdelay(1);
4896 		else
4897 			break;
4898 	}
4899 	resp_data = 0;
4900 	if (lpfc_readl((resp_buf + 1), &resp_data))
4901 		return;
4902 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4903 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4904 		    phba->pport->stopped)
4905 			goto restore_hc;
4906 		else
4907 			goto clear_errat;
4908 	}
4909 
4910 	mbox.mbxOwner = OWN_HOST;
4911 	resp_data = 0;
4912 	for (i = 0; i < 500; i++) {
4913 		if (lpfc_readl(resp_buf, &resp_data))
4914 			return;
4915 		if (resp_data != mbox.word0)
4916 			mdelay(1);
4917 		else
4918 			break;
4919 	}
4920 
4921 clear_errat:
4922 
4923 	while (++i < 500) {
4924 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4925 			return;
4926 		if (!(ha_copy & HA_ERATT))
4927 			mdelay(1);
4928 		else
4929 			break;
4930 	}
4931 
4932 	if (readl(phba->HAregaddr) & HA_ERATT) {
4933 		writel(HA_ERATT, phba->HAregaddr);
4934 		phba->pport->stopped = 1;
4935 	}
4936 
4937 restore_hc:
4938 	phba->link_flag &= ~LS_IGNORE_ERATT;
4939 	writel(hc_copy, phba->HCregaddr);
4940 	readl(phba->HCregaddr); /* flush */
4941 }
4942 
4943 /**
4944  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4945  * @phba: Pointer to HBA context object.
4946  *
4947  * This function issues a kill_board mailbox command and waits for
4948  * the error attention interrupt. This function is called for stopping
4949  * the firmware processing. The caller is not required to hold any
4950  * locks. This function calls lpfc_hba_down_post function to free
4951  * any pending commands after the kill. The function will return 1 when it
4952  * fails to kill the board else will return 0.
4953  **/
4954 int
4955 lpfc_sli_brdkill(struct lpfc_hba *phba)
4956 {
4957 	struct lpfc_sli *psli;
4958 	LPFC_MBOXQ_t *pmb;
4959 	uint32_t status;
4960 	uint32_t ha_copy;
4961 	int retval;
4962 	int i = 0;
4963 
4964 	psli = &phba->sli;
4965 
4966 	/* Kill HBA */
4967 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4968 			"0329 Kill HBA Data: x%x x%x\n",
4969 			phba->pport->port_state, psli->sli_flag);
4970 
4971 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4972 	if (!pmb)
4973 		return 1;
4974 
4975 	/* Disable the error attention */
4976 	spin_lock_irq(&phba->hbalock);
4977 	if (lpfc_readl(phba->HCregaddr, &status)) {
4978 		spin_unlock_irq(&phba->hbalock);
4979 		mempool_free(pmb, phba->mbox_mem_pool);
4980 		return 1;
4981 	}
4982 	status &= ~HC_ERINT_ENA;
4983 	writel(status, phba->HCregaddr);
4984 	readl(phba->HCregaddr); /* flush */
4985 	phba->link_flag |= LS_IGNORE_ERATT;
4986 	spin_unlock_irq(&phba->hbalock);
4987 
4988 	lpfc_kill_board(phba, pmb);
4989 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4990 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4991 
4992 	if (retval != MBX_SUCCESS) {
4993 		if (retval != MBX_BUSY)
4994 			mempool_free(pmb, phba->mbox_mem_pool);
4995 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4996 				"2752 KILL_BOARD command failed retval %d\n",
4997 				retval);
4998 		spin_lock_irq(&phba->hbalock);
4999 		phba->link_flag &= ~LS_IGNORE_ERATT;
5000 		spin_unlock_irq(&phba->hbalock);
5001 		return 1;
5002 	}
5003 
5004 	spin_lock_irq(&phba->hbalock);
5005 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
5006 	spin_unlock_irq(&phba->hbalock);
5007 
5008 	mempool_free(pmb, phba->mbox_mem_pool);
5009 
5010 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
5011 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
5012 	 * 3 seconds we still set HBA_ERROR state because the status of the
5013 	 * board is now undefined.
5014 	 */
5015 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
5016 		return 1;
5017 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
5018 		mdelay(100);
5019 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
5020 			return 1;
5021 	}
5022 
5023 	del_timer_sync(&psli->mbox_tmo);
5024 	if (ha_copy & HA_ERATT) {
5025 		writel(HA_ERATT, phba->HAregaddr);
5026 		phba->pport->stopped = 1;
5027 	}
5028 	spin_lock_irq(&phba->hbalock);
5029 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5030 	psli->mbox_active = NULL;
5031 	phba->link_flag &= ~LS_IGNORE_ERATT;
5032 	spin_unlock_irq(&phba->hbalock);
5033 
5034 	lpfc_hba_down_post(phba);
5035 	phba->link_state = LPFC_HBA_ERROR;
5036 
5037 	return ha_copy & HA_ERATT ? 0 : 1;
5038 }
5039 
5040 /**
5041  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
5042  * @phba: Pointer to HBA context object.
5043  *
5044  * This function resets the HBA by writing HC_INITFF to the control
5045  * register. After the HBA resets, this function resets all the iocb ring
5046  * indices. This function disables PCI layer parity checking during
5047  * the reset.
5048  * This function returns 0 always.
5049  * The caller is not required to hold any locks.
5050  **/
5051 int
5052 lpfc_sli_brdreset(struct lpfc_hba *phba)
5053 {
5054 	struct lpfc_sli *psli;
5055 	struct lpfc_sli_ring *pring;
5056 	uint16_t cfg_value;
5057 	int i;
5058 
5059 	psli = &phba->sli;
5060 
5061 	/* Reset HBA */
5062 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5063 			"0325 Reset HBA Data: x%x x%x\n",
5064 			(phba->pport) ? phba->pport->port_state : 0,
5065 			psli->sli_flag);
5066 
5067 	/* perform board reset */
5068 	phba->fc_eventTag = 0;
5069 	phba->link_events = 0;
5070 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5071 	if (phba->pport) {
5072 		phba->pport->fc_myDID = 0;
5073 		phba->pport->fc_prevDID = 0;
5074 	}
5075 
5076 	/* Turn off parity checking and serr during the physical reset */
5077 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
5078 		return -EIO;
5079 
5080 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
5081 			      (cfg_value &
5082 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5083 
5084 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
5085 
5086 	/* Now toggle INITFF bit in the Host Control Register */
5087 	writel(HC_INITFF, phba->HCregaddr);
5088 	mdelay(1);
5089 	readl(phba->HCregaddr); /* flush */
5090 	writel(0, phba->HCregaddr);
5091 	readl(phba->HCregaddr); /* flush */
5092 
5093 	/* Restore PCI cmd register */
5094 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5095 
5096 	/* Initialize relevant SLI info */
5097 	for (i = 0; i < psli->num_rings; i++) {
5098 		pring = &psli->sli3_ring[i];
5099 		pring->flag = 0;
5100 		pring->sli.sli3.rspidx = 0;
5101 		pring->sli.sli3.next_cmdidx  = 0;
5102 		pring->sli.sli3.local_getidx = 0;
5103 		pring->sli.sli3.cmdidx = 0;
5104 		pring->missbufcnt = 0;
5105 	}
5106 
5107 	phba->link_state = LPFC_WARM_START;
5108 	return 0;
5109 }
5110 
5111 /**
5112  * lpfc_sli4_brdreset - Reset a sli-4 HBA
5113  * @phba: Pointer to HBA context object.
5114  *
5115  * This function resets a SLI4 HBA. This function disables PCI layer parity
5116  * checking during resets the device. The caller is not required to hold
5117  * any locks.
5118  *
5119  * This function returns 0 on success else returns negative error code.
5120  **/
5121 int
5122 lpfc_sli4_brdreset(struct lpfc_hba *phba)
5123 {
5124 	struct lpfc_sli *psli = &phba->sli;
5125 	uint16_t cfg_value;
5126 	int rc = 0;
5127 
5128 	/* Reset HBA */
5129 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5130 			"0295 Reset HBA Data: x%x x%x x%x\n",
5131 			phba->pport->port_state, psli->sli_flag,
5132 			phba->hba_flag);
5133 
5134 	/* perform board reset */
5135 	phba->fc_eventTag = 0;
5136 	phba->link_events = 0;
5137 	phba->pport->fc_myDID = 0;
5138 	phba->pport->fc_prevDID = 0;
5139 	phba->hba_flag &= ~HBA_SETUP;
5140 
5141 	spin_lock_irq(&phba->hbalock);
5142 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
5143 	phba->fcf.fcf_flag = 0;
5144 	spin_unlock_irq(&phba->hbalock);
5145 
5146 	/* Now physically reset the device */
5147 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5148 			"0389 Performing PCI function reset!\n");
5149 
5150 	/* Turn off parity checking and serr during the physical reset */
5151 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
5152 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5153 				"3205 PCI read Config failed\n");
5154 		return -EIO;
5155 	}
5156 
5157 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
5158 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5159 
5160 	/* Perform FCoE PCI function reset before freeing queue memory */
5161 	rc = lpfc_pci_function_reset(phba);
5162 
5163 	/* Restore PCI cmd register */
5164 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5165 
5166 	return rc;
5167 }
5168 
5169 /**
5170  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
5171  * @phba: Pointer to HBA context object.
5172  *
5173  * This function is called in the SLI initialization code path to
5174  * restart the HBA. The caller is not required to hold any lock.
5175  * This function writes MBX_RESTART mailbox command to the SLIM and
5176  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
5177  * function to free any pending commands. The function enables
5178  * POST only during the first initialization. The function returns zero.
5179  * The function does not guarantee completion of MBX_RESTART mailbox
5180  * command before the return of this function.
5181  **/
5182 static int
5183 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
5184 {
5185 	volatile struct MAILBOX_word0 mb;
5186 	struct lpfc_sli *psli;
5187 	void __iomem *to_slim;
5188 	uint32_t hba_aer_enabled;
5189 
5190 	spin_lock_irq(&phba->hbalock);
5191 
5192 	/* Take PCIe device Advanced Error Reporting (AER) state */
5193 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
5194 
5195 	psli = &phba->sli;
5196 
5197 	/* Restart HBA */
5198 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5199 			"0337 Restart HBA Data: x%x x%x\n",
5200 			(phba->pport) ? phba->pport->port_state : 0,
5201 			psli->sli_flag);
5202 
5203 	mb.word0 = 0;
5204 	mb.mbxCommand = MBX_RESTART;
5205 	mb.mbxHc = 1;
5206 
5207 	lpfc_reset_barrier(phba);
5208 
5209 	to_slim = phba->MBslimaddr;
5210 	writel(mb.word0, to_slim);
5211 	readl(to_slim); /* flush */
5212 
5213 	/* Only skip post after fc_ffinit is completed */
5214 	if (phba->pport && phba->pport->port_state)
5215 		mb.word0 = 1;	/* This is really setting up word1 */
5216 	else
5217 		mb.word0 = 0;	/* This is really setting up word1 */
5218 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
5219 	writel(mb.word0, to_slim);
5220 	readl(to_slim); /* flush */
5221 
5222 	lpfc_sli_brdreset(phba);
5223 	if (phba->pport)
5224 		phba->pport->stopped = 0;
5225 	phba->link_state = LPFC_INIT_START;
5226 	phba->hba_flag = 0;
5227 	spin_unlock_irq(&phba->hbalock);
5228 
5229 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5230 	psli->stats_start = ktime_get_seconds();
5231 
5232 	/* Give the INITFF and Post time to settle. */
5233 	mdelay(100);
5234 
5235 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
5236 	if (hba_aer_enabled)
5237 		pci_disable_pcie_error_reporting(phba->pcidev);
5238 
5239 	lpfc_hba_down_post(phba);
5240 
5241 	return 0;
5242 }
5243 
5244 /**
5245  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
5246  * @phba: Pointer to HBA context object.
5247  *
5248  * This function is called in the SLI initialization code path to restart
5249  * a SLI4 HBA. The caller is not required to hold any lock.
5250  * At the end of the function, it calls lpfc_hba_down_post function to
5251  * free any pending commands.
5252  **/
5253 static int
5254 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
5255 {
5256 	struct lpfc_sli *psli = &phba->sli;
5257 	uint32_t hba_aer_enabled;
5258 	int rc;
5259 
5260 	/* Restart HBA */
5261 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5262 			"0296 Restart HBA Data: x%x x%x\n",
5263 			phba->pport->port_state, psli->sli_flag);
5264 
5265 	/* Take PCIe device Advanced Error Reporting (AER) state */
5266 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
5267 
5268 	rc = lpfc_sli4_brdreset(phba);
5269 	if (rc) {
5270 		phba->link_state = LPFC_HBA_ERROR;
5271 		goto hba_down_queue;
5272 	}
5273 
5274 	spin_lock_irq(&phba->hbalock);
5275 	phba->pport->stopped = 0;
5276 	phba->link_state = LPFC_INIT_START;
5277 	phba->hba_flag = 0;
5278 	spin_unlock_irq(&phba->hbalock);
5279 
5280 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5281 	psli->stats_start = ktime_get_seconds();
5282 
5283 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
5284 	if (hba_aer_enabled)
5285 		pci_disable_pcie_error_reporting(phba->pcidev);
5286 
5287 hba_down_queue:
5288 	lpfc_hba_down_post(phba);
5289 	lpfc_sli4_queue_destroy(phba);
5290 
5291 	return rc;
5292 }
5293 
5294 /**
5295  * lpfc_sli_brdrestart - Wrapper func for restarting hba
5296  * @phba: Pointer to HBA context object.
5297  *
5298  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
5299  * API jump table function pointer from the lpfc_hba struct.
5300 **/
5301 int
5302 lpfc_sli_brdrestart(struct lpfc_hba *phba)
5303 {
5304 	return phba->lpfc_sli_brdrestart(phba);
5305 }
5306 
5307 /**
5308  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
5309  * @phba: Pointer to HBA context object.
5310  *
5311  * This function is called after a HBA restart to wait for successful
5312  * restart of the HBA. Successful restart of the HBA is indicated by
5313  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
5314  * iteration, the function will restart the HBA again. The function returns
5315  * zero if HBA successfully restarted else returns negative error code.
5316  **/
5317 int
5318 lpfc_sli_chipset_init(struct lpfc_hba *phba)
5319 {
5320 	uint32_t status, i = 0;
5321 
5322 	/* Read the HBA Host Status Register */
5323 	if (lpfc_readl(phba->HSregaddr, &status))
5324 		return -EIO;
5325 
5326 	/* Check status register to see what current state is */
5327 	i = 0;
5328 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
5329 
5330 		/* Check every 10ms for 10 retries, then every 100ms for 90
5331 		 * retries, then every 1 sec for 50 retires for a total of
5332 		 * ~60 seconds before reset the board again and check every
5333 		 * 1 sec for 50 retries. The up to 60 seconds before the
5334 		 * board ready is required by the Falcon FIPS zeroization
5335 		 * complete, and any reset the board in between shall cause
5336 		 * restart of zeroization, further delay the board ready.
5337 		 */
5338 		if (i++ >= 200) {
5339 			/* Adapter failed to init, timeout, status reg
5340 			   <status> */
5341 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5342 					"0436 Adapter failed to init, "
5343 					"timeout, status reg x%x, "
5344 					"FW Data: A8 x%x AC x%x\n", status,
5345 					readl(phba->MBslimaddr + 0xa8),
5346 					readl(phba->MBslimaddr + 0xac));
5347 			phba->link_state = LPFC_HBA_ERROR;
5348 			return -ETIMEDOUT;
5349 		}
5350 
5351 		/* Check to see if any errors occurred during init */
5352 		if (status & HS_FFERM) {
5353 			/* ERROR: During chipset initialization */
5354 			/* Adapter failed to init, chipset, status reg
5355 			   <status> */
5356 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5357 					"0437 Adapter failed to init, "
5358 					"chipset, status reg x%x, "
5359 					"FW Data: A8 x%x AC x%x\n", status,
5360 					readl(phba->MBslimaddr + 0xa8),
5361 					readl(phba->MBslimaddr + 0xac));
5362 			phba->link_state = LPFC_HBA_ERROR;
5363 			return -EIO;
5364 		}
5365 
5366 		if (i <= 10)
5367 			msleep(10);
5368 		else if (i <= 100)
5369 			msleep(100);
5370 		else
5371 			msleep(1000);
5372 
5373 		if (i == 150) {
5374 			/* Do post */
5375 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5376 			lpfc_sli_brdrestart(phba);
5377 		}
5378 		/* Read the HBA Host Status Register */
5379 		if (lpfc_readl(phba->HSregaddr, &status))
5380 			return -EIO;
5381 	}
5382 
5383 	/* Check to see if any errors occurred during init */
5384 	if (status & HS_FFERM) {
5385 		/* ERROR: During chipset initialization */
5386 		/* Adapter failed to init, chipset, status reg <status> */
5387 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5388 				"0438 Adapter failed to init, chipset, "
5389 				"status reg x%x, "
5390 				"FW Data: A8 x%x AC x%x\n", status,
5391 				readl(phba->MBslimaddr + 0xa8),
5392 				readl(phba->MBslimaddr + 0xac));
5393 		phba->link_state = LPFC_HBA_ERROR;
5394 		return -EIO;
5395 	}
5396 
5397 	phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5398 
5399 	/* Clear all interrupt enable conditions */
5400 	writel(0, phba->HCregaddr);
5401 	readl(phba->HCregaddr); /* flush */
5402 
5403 	/* setup host attn register */
5404 	writel(0xffffffff, phba->HAregaddr);
5405 	readl(phba->HAregaddr); /* flush */
5406 	return 0;
5407 }
5408 
5409 /**
5410  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5411  *
5412  * This function calculates and returns the number of HBQs required to be
5413  * configured.
5414  **/
5415 int
5416 lpfc_sli_hbq_count(void)
5417 {
5418 	return ARRAY_SIZE(lpfc_hbq_defs);
5419 }
5420 
5421 /**
5422  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5423  *
5424  * This function adds the number of hbq entries in every HBQ to get
5425  * the total number of hbq entries required for the HBA and returns
5426  * the total count.
5427  **/
5428 static int
5429 lpfc_sli_hbq_entry_count(void)
5430 {
5431 	int  hbq_count = lpfc_sli_hbq_count();
5432 	int  count = 0;
5433 	int  i;
5434 
5435 	for (i = 0; i < hbq_count; ++i)
5436 		count += lpfc_hbq_defs[i]->entry_count;
5437 	return count;
5438 }
5439 
5440 /**
5441  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5442  *
5443  * This function calculates amount of memory required for all hbq entries
5444  * to be configured and returns the total memory required.
5445  **/
5446 int
5447 lpfc_sli_hbq_size(void)
5448 {
5449 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5450 }
5451 
5452 /**
5453  * lpfc_sli_hbq_setup - configure and initialize HBQs
5454  * @phba: Pointer to HBA context object.
5455  *
5456  * This function is called during the SLI initialization to configure
5457  * all the HBQs and post buffers to the HBQ. The caller is not
5458  * required to hold any locks. This function will return zero if successful
5459  * else it will return negative error code.
5460  **/
5461 static int
5462 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5463 {
5464 	int  hbq_count = lpfc_sli_hbq_count();
5465 	LPFC_MBOXQ_t *pmb;
5466 	MAILBOX_t *pmbox;
5467 	uint32_t hbqno;
5468 	uint32_t hbq_entry_index;
5469 
5470 				/* Get a Mailbox buffer to setup mailbox
5471 				 * commands for HBA initialization
5472 				 */
5473 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5474 
5475 	if (!pmb)
5476 		return -ENOMEM;
5477 
5478 	pmbox = &pmb->u.mb;
5479 
5480 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
5481 	phba->link_state = LPFC_INIT_MBX_CMDS;
5482 	phba->hbq_in_use = 1;
5483 
5484 	hbq_entry_index = 0;
5485 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5486 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
5487 		phba->hbqs[hbqno].hbqPutIdx      = 0;
5488 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5489 		phba->hbqs[hbqno].entry_count =
5490 			lpfc_hbq_defs[hbqno]->entry_count;
5491 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5492 			hbq_entry_index, pmb);
5493 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
5494 
5495 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5496 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5497 			   mbxStatus <status>, ring <num> */
5498 
5499 			lpfc_printf_log(phba, KERN_ERR,
5500 					LOG_SLI | LOG_VPORT,
5501 					"1805 Adapter failed to init. "
5502 					"Data: x%x x%x x%x\n",
5503 					pmbox->mbxCommand,
5504 					pmbox->mbxStatus, hbqno);
5505 
5506 			phba->link_state = LPFC_HBA_ERROR;
5507 			mempool_free(pmb, phba->mbox_mem_pool);
5508 			return -ENXIO;
5509 		}
5510 	}
5511 	phba->hbq_count = hbq_count;
5512 
5513 	mempool_free(pmb, phba->mbox_mem_pool);
5514 
5515 	/* Initially populate or replenish the HBQs */
5516 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5517 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5518 	return 0;
5519 }
5520 
5521 /**
5522  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5523  * @phba: Pointer to HBA context object.
5524  *
5525  * This function is called during the SLI initialization to configure
5526  * all the HBQs and post buffers to the HBQ. The caller is not
5527  * required to hold any locks. This function will return zero if successful
5528  * else it will return negative error code.
5529  **/
5530 static int
5531 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5532 {
5533 	phba->hbq_in_use = 1;
5534 	/**
5535 	 * Specific case when the MDS diagnostics is enabled and supported.
5536 	 * The receive buffer count is truncated to manage the incoming
5537 	 * traffic.
5538 	 **/
5539 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5540 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5541 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5542 	else
5543 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5544 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5545 	phba->hbq_count = 1;
5546 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5547 	/* Initially populate or replenish the HBQs */
5548 	return 0;
5549 }
5550 
5551 /**
5552  * lpfc_sli_config_port - Issue config port mailbox command
5553  * @phba: Pointer to HBA context object.
5554  * @sli_mode: sli mode - 2/3
5555  *
5556  * This function is called by the sli initialization code path
5557  * to issue config_port mailbox command. This function restarts the
5558  * HBA firmware and issues a config_port mailbox command to configure
5559  * the SLI interface in the sli mode specified by sli_mode
5560  * variable. The caller is not required to hold any locks.
5561  * The function returns 0 if successful, else returns negative error
5562  * code.
5563  **/
5564 int
5565 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5566 {
5567 	LPFC_MBOXQ_t *pmb;
5568 	uint32_t resetcount = 0, rc = 0, done = 0;
5569 
5570 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5571 	if (!pmb) {
5572 		phba->link_state = LPFC_HBA_ERROR;
5573 		return -ENOMEM;
5574 	}
5575 
5576 	phba->sli_rev = sli_mode;
5577 	while (resetcount < 2 && !done) {
5578 		spin_lock_irq(&phba->hbalock);
5579 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5580 		spin_unlock_irq(&phba->hbalock);
5581 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5582 		lpfc_sli_brdrestart(phba);
5583 		rc = lpfc_sli_chipset_init(phba);
5584 		if (rc)
5585 			break;
5586 
5587 		spin_lock_irq(&phba->hbalock);
5588 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5589 		spin_unlock_irq(&phba->hbalock);
5590 		resetcount++;
5591 
5592 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5593 		 * value of 0 means the call was successful.  Any other
5594 		 * nonzero value is a failure, but if ERESTART is returned,
5595 		 * the driver may reset the HBA and try again.
5596 		 */
5597 		rc = lpfc_config_port_prep(phba);
5598 		if (rc == -ERESTART) {
5599 			phba->link_state = LPFC_LINK_UNKNOWN;
5600 			continue;
5601 		} else if (rc)
5602 			break;
5603 
5604 		phba->link_state = LPFC_INIT_MBX_CMDS;
5605 		lpfc_config_port(phba, pmb);
5606 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5607 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5608 					LPFC_SLI3_HBQ_ENABLED |
5609 					LPFC_SLI3_CRP_ENABLED |
5610 					LPFC_SLI3_DSS_ENABLED);
5611 		if (rc != MBX_SUCCESS) {
5612 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5613 				"0442 Adapter failed to init, mbxCmd x%x "
5614 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5615 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5616 			spin_lock_irq(&phba->hbalock);
5617 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5618 			spin_unlock_irq(&phba->hbalock);
5619 			rc = -ENXIO;
5620 		} else {
5621 			/* Allow asynchronous mailbox command to go through */
5622 			spin_lock_irq(&phba->hbalock);
5623 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5624 			spin_unlock_irq(&phba->hbalock);
5625 			done = 1;
5626 
5627 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5628 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5629 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5630 					"3110 Port did not grant ASABT\n");
5631 		}
5632 	}
5633 	if (!done) {
5634 		rc = -EINVAL;
5635 		goto do_prep_failed;
5636 	}
5637 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5638 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5639 			rc = -ENXIO;
5640 			goto do_prep_failed;
5641 		}
5642 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5643 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5644 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5645 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5646 				phba->max_vpi : phba->max_vports;
5647 
5648 		} else
5649 			phba->max_vpi = 0;
5650 		if (pmb->u.mb.un.varCfgPort.gerbm)
5651 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5652 		if (pmb->u.mb.un.varCfgPort.gcrp)
5653 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5654 
5655 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5656 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5657 
5658 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5659 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5660 				phba->cfg_enable_bg = 0;
5661 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5662 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5663 						"0443 Adapter did not grant "
5664 						"BlockGuard\n");
5665 			}
5666 		}
5667 	} else {
5668 		phba->hbq_get = NULL;
5669 		phba->port_gp = phba->mbox->us.s2.port;
5670 		phba->max_vpi = 0;
5671 	}
5672 do_prep_failed:
5673 	mempool_free(pmb, phba->mbox_mem_pool);
5674 	return rc;
5675 }
5676 
5677 
5678 /**
5679  * lpfc_sli_hba_setup - SLI initialization function
5680  * @phba: Pointer to HBA context object.
5681  *
5682  * This function is the main SLI initialization function. This function
5683  * is called by the HBA initialization code, HBA reset code and HBA
5684  * error attention handler code. Caller is not required to hold any
5685  * locks. This function issues config_port mailbox command to configure
5686  * the SLI, setup iocb rings and HBQ rings. In the end the function
5687  * calls the config_port_post function to issue init_link mailbox
5688  * command and to start the discovery. The function will return zero
5689  * if successful, else it will return negative error code.
5690  **/
5691 int
5692 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5693 {
5694 	uint32_t rc;
5695 	int  i;
5696 	int longs;
5697 
5698 	/* Enable ISR already does config_port because of config_msi mbx */
5699 	if (phba->hba_flag & HBA_NEEDS_CFG_PORT) {
5700 		rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5701 		if (rc)
5702 			return -EIO;
5703 		phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
5704 	}
5705 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5706 
5707 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
5708 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
5709 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
5710 		if (!rc) {
5711 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5712 					"2709 This device supports "
5713 					"Advanced Error Reporting (AER)\n");
5714 			spin_lock_irq(&phba->hbalock);
5715 			phba->hba_flag |= HBA_AER_ENABLED;
5716 			spin_unlock_irq(&phba->hbalock);
5717 		} else {
5718 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5719 					"2708 This device does not support "
5720 					"Advanced Error Reporting (AER): %d\n",
5721 					rc);
5722 			phba->cfg_aer_support = 0;
5723 		}
5724 	}
5725 
5726 	if (phba->sli_rev == 3) {
5727 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5728 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5729 	} else {
5730 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5731 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5732 		phba->sli3_options = 0;
5733 	}
5734 
5735 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5736 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5737 			phba->sli_rev, phba->max_vpi);
5738 	rc = lpfc_sli_ring_map(phba);
5739 
5740 	if (rc)
5741 		goto lpfc_sli_hba_setup_error;
5742 
5743 	/* Initialize VPIs. */
5744 	if (phba->sli_rev == LPFC_SLI_REV3) {
5745 		/*
5746 		 * The VPI bitmask and physical ID array are allocated
5747 		 * and initialized once only - at driver load.  A port
5748 		 * reset doesn't need to reinitialize this memory.
5749 		 */
5750 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5751 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5752 			phba->vpi_bmask = kcalloc(longs,
5753 						  sizeof(unsigned long),
5754 						  GFP_KERNEL);
5755 			if (!phba->vpi_bmask) {
5756 				rc = -ENOMEM;
5757 				goto lpfc_sli_hba_setup_error;
5758 			}
5759 
5760 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5761 						sizeof(uint16_t),
5762 						GFP_KERNEL);
5763 			if (!phba->vpi_ids) {
5764 				kfree(phba->vpi_bmask);
5765 				rc = -ENOMEM;
5766 				goto lpfc_sli_hba_setup_error;
5767 			}
5768 			for (i = 0; i < phba->max_vpi; i++)
5769 				phba->vpi_ids[i] = i;
5770 		}
5771 	}
5772 
5773 	/* Init HBQs */
5774 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5775 		rc = lpfc_sli_hbq_setup(phba);
5776 		if (rc)
5777 			goto lpfc_sli_hba_setup_error;
5778 	}
5779 	spin_lock_irq(&phba->hbalock);
5780 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5781 	spin_unlock_irq(&phba->hbalock);
5782 
5783 	rc = lpfc_config_port_post(phba);
5784 	if (rc)
5785 		goto lpfc_sli_hba_setup_error;
5786 
5787 	return rc;
5788 
5789 lpfc_sli_hba_setup_error:
5790 	phba->link_state = LPFC_HBA_ERROR;
5791 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5792 			"0445 Firmware initialization failed\n");
5793 	return rc;
5794 }
5795 
5796 /**
5797  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5798  * @phba: Pointer to HBA context object.
5799  *
5800  * This function issue a dump mailbox command to read config region
5801  * 23 and parse the records in the region and populate driver
5802  * data structure.
5803  **/
5804 static int
5805 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5806 {
5807 	LPFC_MBOXQ_t *mboxq;
5808 	struct lpfc_dmabuf *mp;
5809 	struct lpfc_mqe *mqe;
5810 	uint32_t data_length;
5811 	int rc;
5812 
5813 	/* Program the default value of vlan_id and fc_map */
5814 	phba->valid_vlan = 0;
5815 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5816 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5817 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5818 
5819 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5820 	if (!mboxq)
5821 		return -ENOMEM;
5822 
5823 	mqe = &mboxq->u.mqe;
5824 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5825 		rc = -ENOMEM;
5826 		goto out_free_mboxq;
5827 	}
5828 
5829 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5830 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5831 
5832 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5833 			"(%d):2571 Mailbox cmd x%x Status x%x "
5834 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5835 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5836 			"CQ: x%x x%x x%x x%x\n",
5837 			mboxq->vport ? mboxq->vport->vpi : 0,
5838 			bf_get(lpfc_mqe_command, mqe),
5839 			bf_get(lpfc_mqe_status, mqe),
5840 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5841 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5842 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5843 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5844 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5845 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5846 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5847 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5848 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5849 			mboxq->mcqe.word0,
5850 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5851 			mboxq->mcqe.trailer);
5852 
5853 	if (rc) {
5854 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5855 		kfree(mp);
5856 		rc = -EIO;
5857 		goto out_free_mboxq;
5858 	}
5859 	data_length = mqe->un.mb_words[5];
5860 	if (data_length > DMP_RGN23_SIZE) {
5861 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5862 		kfree(mp);
5863 		rc = -EIO;
5864 		goto out_free_mboxq;
5865 	}
5866 
5867 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5868 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
5869 	kfree(mp);
5870 	rc = 0;
5871 
5872 out_free_mboxq:
5873 	mempool_free(mboxq, phba->mbox_mem_pool);
5874 	return rc;
5875 }
5876 
5877 /**
5878  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5879  * @phba: pointer to lpfc hba data structure.
5880  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5881  * @vpd: pointer to the memory to hold resulting port vpd data.
5882  * @vpd_size: On input, the number of bytes allocated to @vpd.
5883  *	      On output, the number of data bytes in @vpd.
5884  *
5885  * This routine executes a READ_REV SLI4 mailbox command.  In
5886  * addition, this routine gets the port vpd data.
5887  *
5888  * Return codes
5889  * 	0 - successful
5890  * 	-ENOMEM - could not allocated memory.
5891  **/
5892 static int
5893 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5894 		    uint8_t *vpd, uint32_t *vpd_size)
5895 {
5896 	int rc = 0;
5897 	uint32_t dma_size;
5898 	struct lpfc_dmabuf *dmabuf;
5899 	struct lpfc_mqe *mqe;
5900 
5901 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5902 	if (!dmabuf)
5903 		return -ENOMEM;
5904 
5905 	/*
5906 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5907 	 * mailbox command.
5908 	 */
5909 	dma_size = *vpd_size;
5910 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5911 					  &dmabuf->phys, GFP_KERNEL);
5912 	if (!dmabuf->virt) {
5913 		kfree(dmabuf);
5914 		return -ENOMEM;
5915 	}
5916 
5917 	/*
5918 	 * The SLI4 implementation of READ_REV conflicts at word1,
5919 	 * bits 31:16 and SLI4 adds vpd functionality not present
5920 	 * in SLI3.  This code corrects the conflicts.
5921 	 */
5922 	lpfc_read_rev(phba, mboxq);
5923 	mqe = &mboxq->u.mqe;
5924 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5925 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5926 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5927 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5928 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5929 
5930 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5931 	if (rc) {
5932 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5933 				  dmabuf->virt, dmabuf->phys);
5934 		kfree(dmabuf);
5935 		return -EIO;
5936 	}
5937 
5938 	/*
5939 	 * The available vpd length cannot be bigger than the
5940 	 * DMA buffer passed to the port.  Catch the less than
5941 	 * case and update the caller's size.
5942 	 */
5943 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5944 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5945 
5946 	memcpy(vpd, dmabuf->virt, *vpd_size);
5947 
5948 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5949 			  dmabuf->virt, dmabuf->phys);
5950 	kfree(dmabuf);
5951 	return 0;
5952 }
5953 
5954 /**
5955  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5956  * @phba: pointer to lpfc hba data structure.
5957  *
5958  * This routine retrieves SLI4 device physical port name this PCI function
5959  * is attached to.
5960  *
5961  * Return codes
5962  *      0 - successful
5963  *      otherwise - failed to retrieve controller attributes
5964  **/
5965 static int
5966 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5967 {
5968 	LPFC_MBOXQ_t *mboxq;
5969 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5970 	struct lpfc_controller_attribute *cntl_attr;
5971 	void *virtaddr = NULL;
5972 	uint32_t alloclen, reqlen;
5973 	uint32_t shdr_status, shdr_add_status;
5974 	union lpfc_sli4_cfg_shdr *shdr;
5975 	int rc;
5976 
5977 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5978 	if (!mboxq)
5979 		return -ENOMEM;
5980 
5981 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5982 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5983 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5984 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5985 			LPFC_SLI4_MBX_NEMBED);
5986 
5987 	if (alloclen < reqlen) {
5988 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5989 				"3084 Allocated DMA memory size (%d) is "
5990 				"less than the requested DMA memory size "
5991 				"(%d)\n", alloclen, reqlen);
5992 		rc = -ENOMEM;
5993 		goto out_free_mboxq;
5994 	}
5995 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5996 	virtaddr = mboxq->sge_array->addr[0];
5997 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5998 	shdr = &mbx_cntl_attr->cfg_shdr;
5999 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6000 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6001 	if (shdr_status || shdr_add_status || rc) {
6002 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6003 				"3085 Mailbox x%x (x%x/x%x) failed, "
6004 				"rc:x%x, status:x%x, add_status:x%x\n",
6005 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6006 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6007 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6008 				rc, shdr_status, shdr_add_status);
6009 		rc = -ENXIO;
6010 		goto out_free_mboxq;
6011 	}
6012 
6013 	cntl_attr = &mbx_cntl_attr->cntl_attr;
6014 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
6015 	phba->sli4_hba.lnk_info.lnk_tp =
6016 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
6017 	phba->sli4_hba.lnk_info.lnk_no =
6018 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
6019 	phba->sli4_hba.flash_id = bf_get(lpfc_cntl_attr_flash_id, cntl_attr);
6020 	phba->sli4_hba.asic_rev = bf_get(lpfc_cntl_attr_asic_rev, cntl_attr);
6021 
6022 	memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
6023 	strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
6024 		sizeof(phba->BIOSVersion));
6025 
6026 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6027 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s, "
6028 			"flash_id: x%02x, asic_rev: x%02x\n",
6029 			phba->sli4_hba.lnk_info.lnk_tp,
6030 			phba->sli4_hba.lnk_info.lnk_no,
6031 			phba->BIOSVersion, phba->sli4_hba.flash_id,
6032 			phba->sli4_hba.asic_rev);
6033 out_free_mboxq:
6034 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6035 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6036 	else
6037 		mempool_free(mboxq, phba->mbox_mem_pool);
6038 	return rc;
6039 }
6040 
6041 /**
6042  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
6043  * @phba: pointer to lpfc hba data structure.
6044  *
6045  * This routine retrieves SLI4 device physical port name this PCI function
6046  * is attached to.
6047  *
6048  * Return codes
6049  *      0 - successful
6050  *      otherwise - failed to retrieve physical port name
6051  **/
6052 static int
6053 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
6054 {
6055 	LPFC_MBOXQ_t *mboxq;
6056 	struct lpfc_mbx_get_port_name *get_port_name;
6057 	uint32_t shdr_status, shdr_add_status;
6058 	union lpfc_sli4_cfg_shdr *shdr;
6059 	char cport_name = 0;
6060 	int rc;
6061 
6062 	/* We assume nothing at this point */
6063 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6064 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
6065 
6066 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6067 	if (!mboxq)
6068 		return -ENOMEM;
6069 	/* obtain link type and link number via READ_CONFIG */
6070 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6071 	lpfc_sli4_read_config(phba);
6072 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
6073 		goto retrieve_ppname;
6074 
6075 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
6076 	rc = lpfc_sli4_get_ctl_attr(phba);
6077 	if (rc)
6078 		goto out_free_mboxq;
6079 
6080 retrieve_ppname:
6081 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
6082 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
6083 		sizeof(struct lpfc_mbx_get_port_name) -
6084 		sizeof(struct lpfc_sli4_cfg_mhdr),
6085 		LPFC_SLI4_MBX_EMBED);
6086 	get_port_name = &mboxq->u.mqe.un.get_port_name;
6087 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
6088 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
6089 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
6090 		phba->sli4_hba.lnk_info.lnk_tp);
6091 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6092 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6093 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6094 	if (shdr_status || shdr_add_status || rc) {
6095 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6096 				"3087 Mailbox x%x (x%x/x%x) failed: "
6097 				"rc:x%x, status:x%x, add_status:x%x\n",
6098 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6099 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6100 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6101 				rc, shdr_status, shdr_add_status);
6102 		rc = -ENXIO;
6103 		goto out_free_mboxq;
6104 	}
6105 	switch (phba->sli4_hba.lnk_info.lnk_no) {
6106 	case LPFC_LINK_NUMBER_0:
6107 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
6108 				&get_port_name->u.response);
6109 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6110 		break;
6111 	case LPFC_LINK_NUMBER_1:
6112 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
6113 				&get_port_name->u.response);
6114 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6115 		break;
6116 	case LPFC_LINK_NUMBER_2:
6117 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
6118 				&get_port_name->u.response);
6119 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6120 		break;
6121 	case LPFC_LINK_NUMBER_3:
6122 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
6123 				&get_port_name->u.response);
6124 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6125 		break;
6126 	default:
6127 		break;
6128 	}
6129 
6130 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
6131 		phba->Port[0] = cport_name;
6132 		phba->Port[1] = '\0';
6133 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6134 				"3091 SLI get port name: %s\n", phba->Port);
6135 	}
6136 
6137 out_free_mboxq:
6138 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6139 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6140 	else
6141 		mempool_free(mboxq, phba->mbox_mem_pool);
6142 	return rc;
6143 }
6144 
6145 /**
6146  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
6147  * @phba: pointer to lpfc hba data structure.
6148  *
6149  * This routine is called to explicitly arm the SLI4 device's completion and
6150  * event queues
6151  **/
6152 static void
6153 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
6154 {
6155 	int qidx;
6156 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
6157 	struct lpfc_sli4_hdw_queue *qp;
6158 	struct lpfc_queue *eq;
6159 
6160 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
6161 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
6162 	if (sli4_hba->nvmels_cq)
6163 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
6164 					   LPFC_QUEUE_REARM);
6165 
6166 	if (sli4_hba->hdwq) {
6167 		/* Loop thru all Hardware Queues */
6168 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
6169 			qp = &sli4_hba->hdwq[qidx];
6170 			/* ARM the corresponding CQ */
6171 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
6172 						LPFC_QUEUE_REARM);
6173 		}
6174 
6175 		/* Loop thru all IRQ vectors */
6176 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
6177 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
6178 			/* ARM the corresponding EQ */
6179 			sli4_hba->sli4_write_eq_db(phba, eq,
6180 						   0, LPFC_QUEUE_REARM);
6181 		}
6182 	}
6183 
6184 	if (phba->nvmet_support) {
6185 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
6186 			sli4_hba->sli4_write_cq_db(phba,
6187 				sli4_hba->nvmet_cqset[qidx], 0,
6188 				LPFC_QUEUE_REARM);
6189 		}
6190 	}
6191 }
6192 
6193 /**
6194  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
6195  * @phba: Pointer to HBA context object.
6196  * @type: The resource extent type.
6197  * @extnt_count: buffer to hold port available extent count.
6198  * @extnt_size: buffer to hold element count per extent.
6199  *
6200  * This function calls the port and retrievs the number of available
6201  * extents and their size for a particular extent type.
6202  *
6203  * Returns: 0 if successful.  Nonzero otherwise.
6204  **/
6205 int
6206 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
6207 			       uint16_t *extnt_count, uint16_t *extnt_size)
6208 {
6209 	int rc = 0;
6210 	uint32_t length;
6211 	uint32_t mbox_tmo;
6212 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
6213 	LPFC_MBOXQ_t *mbox;
6214 
6215 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6216 	if (!mbox)
6217 		return -ENOMEM;
6218 
6219 	/* Find out how many extents are available for this resource type */
6220 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
6221 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6222 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6223 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
6224 			 length, LPFC_SLI4_MBX_EMBED);
6225 
6226 	/* Send an extents count of 0 - the GET doesn't use it. */
6227 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6228 					LPFC_SLI4_MBX_EMBED);
6229 	if (unlikely(rc)) {
6230 		rc = -EIO;
6231 		goto err_exit;
6232 	}
6233 
6234 	if (!phba->sli4_hba.intr_enable)
6235 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6236 	else {
6237 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6238 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6239 	}
6240 	if (unlikely(rc)) {
6241 		rc = -EIO;
6242 		goto err_exit;
6243 	}
6244 
6245 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
6246 	if (bf_get(lpfc_mbox_hdr_status,
6247 		   &rsrc_info->header.cfg_shdr.response)) {
6248 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6249 				"2930 Failed to get resource extents "
6250 				"Status 0x%x Add'l Status 0x%x\n",
6251 				bf_get(lpfc_mbox_hdr_status,
6252 				       &rsrc_info->header.cfg_shdr.response),
6253 				bf_get(lpfc_mbox_hdr_add_status,
6254 				       &rsrc_info->header.cfg_shdr.response));
6255 		rc = -EIO;
6256 		goto err_exit;
6257 	}
6258 
6259 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
6260 			      &rsrc_info->u.rsp);
6261 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
6262 			     &rsrc_info->u.rsp);
6263 
6264 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6265 			"3162 Retrieved extents type-%d from port: count:%d, "
6266 			"size:%d\n", type, *extnt_count, *extnt_size);
6267 
6268 err_exit:
6269 	mempool_free(mbox, phba->mbox_mem_pool);
6270 	return rc;
6271 }
6272 
6273 /**
6274  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
6275  * @phba: Pointer to HBA context object.
6276  * @type: The extent type to check.
6277  *
6278  * This function reads the current available extents from the port and checks
6279  * if the extent count or extent size has changed since the last access.
6280  * Callers use this routine post port reset to understand if there is a
6281  * extent reprovisioning requirement.
6282  *
6283  * Returns:
6284  *   -Error: error indicates problem.
6285  *   1: Extent count or size has changed.
6286  *   0: No changes.
6287  **/
6288 static int
6289 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
6290 {
6291 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
6292 	uint16_t size_diff, rsrc_ext_size;
6293 	int rc = 0;
6294 	struct lpfc_rsrc_blks *rsrc_entry;
6295 	struct list_head *rsrc_blk_list = NULL;
6296 
6297 	size_diff = 0;
6298 	curr_ext_cnt = 0;
6299 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6300 					    &rsrc_ext_cnt,
6301 					    &rsrc_ext_size);
6302 	if (unlikely(rc))
6303 		return -EIO;
6304 
6305 	switch (type) {
6306 	case LPFC_RSC_TYPE_FCOE_RPI:
6307 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6308 		break;
6309 	case LPFC_RSC_TYPE_FCOE_VPI:
6310 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
6311 		break;
6312 	case LPFC_RSC_TYPE_FCOE_XRI:
6313 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6314 		break;
6315 	case LPFC_RSC_TYPE_FCOE_VFI:
6316 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6317 		break;
6318 	default:
6319 		break;
6320 	}
6321 
6322 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
6323 		curr_ext_cnt++;
6324 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
6325 			size_diff++;
6326 	}
6327 
6328 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
6329 		rc = 1;
6330 
6331 	return rc;
6332 }
6333 
6334 /**
6335  * lpfc_sli4_cfg_post_extnts -
6336  * @phba: Pointer to HBA context object.
6337  * @extnt_cnt: number of available extents.
6338  * @type: the extent type (rpi, xri, vfi, vpi).
6339  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
6340  * @mbox: pointer to the caller's allocated mailbox structure.
6341  *
6342  * This function executes the extents allocation request.  It also
6343  * takes care of the amount of memory needed to allocate or get the
6344  * allocated extents. It is the caller's responsibility to evaluate
6345  * the response.
6346  *
6347  * Returns:
6348  *   -Error:  Error value describes the condition found.
6349  *   0: if successful
6350  **/
6351 static int
6352 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6353 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6354 {
6355 	int rc = 0;
6356 	uint32_t req_len;
6357 	uint32_t emb_len;
6358 	uint32_t alloc_len, mbox_tmo;
6359 
6360 	/* Calculate the total requested length of the dma memory */
6361 	req_len = extnt_cnt * sizeof(uint16_t);
6362 
6363 	/*
6364 	 * Calculate the size of an embedded mailbox.  The uint32_t
6365 	 * accounts for extents-specific word.
6366 	 */
6367 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6368 		sizeof(uint32_t);
6369 
6370 	/*
6371 	 * Presume the allocation and response will fit into an embedded
6372 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6373 	 */
6374 	*emb = LPFC_SLI4_MBX_EMBED;
6375 	if (req_len > emb_len) {
6376 		req_len = extnt_cnt * sizeof(uint16_t) +
6377 			sizeof(union lpfc_sli4_cfg_shdr) +
6378 			sizeof(uint32_t);
6379 		*emb = LPFC_SLI4_MBX_NEMBED;
6380 	}
6381 
6382 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6383 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6384 				     req_len, *emb);
6385 	if (alloc_len < req_len) {
6386 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6387 			"2982 Allocated DMA memory size (x%x) is "
6388 			"less than the requested DMA memory "
6389 			"size (x%x)\n", alloc_len, req_len);
6390 		return -ENOMEM;
6391 	}
6392 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6393 	if (unlikely(rc))
6394 		return -EIO;
6395 
6396 	if (!phba->sli4_hba.intr_enable)
6397 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6398 	else {
6399 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6400 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6401 	}
6402 
6403 	if (unlikely(rc))
6404 		rc = -EIO;
6405 	return rc;
6406 }
6407 
6408 /**
6409  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6410  * @phba: Pointer to HBA context object.
6411  * @type:  The resource extent type to allocate.
6412  *
6413  * This function allocates the number of elements for the specified
6414  * resource type.
6415  **/
6416 static int
6417 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6418 {
6419 	bool emb = false;
6420 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6421 	uint16_t rsrc_id, rsrc_start, j, k;
6422 	uint16_t *ids;
6423 	int i, rc;
6424 	unsigned long longs;
6425 	unsigned long *bmask;
6426 	struct lpfc_rsrc_blks *rsrc_blks;
6427 	LPFC_MBOXQ_t *mbox;
6428 	uint32_t length;
6429 	struct lpfc_id_range *id_array = NULL;
6430 	void *virtaddr = NULL;
6431 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6432 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6433 	struct list_head *ext_blk_list;
6434 
6435 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6436 					    &rsrc_cnt,
6437 					    &rsrc_size);
6438 	if (unlikely(rc))
6439 		return -EIO;
6440 
6441 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6442 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6443 			"3009 No available Resource Extents "
6444 			"for resource type 0x%x: Count: 0x%x, "
6445 			"Size 0x%x\n", type, rsrc_cnt,
6446 			rsrc_size);
6447 		return -ENOMEM;
6448 	}
6449 
6450 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6451 			"2903 Post resource extents type-0x%x: "
6452 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6453 
6454 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6455 	if (!mbox)
6456 		return -ENOMEM;
6457 
6458 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6459 	if (unlikely(rc)) {
6460 		rc = -EIO;
6461 		goto err_exit;
6462 	}
6463 
6464 	/*
6465 	 * Figure out where the response is located.  Then get local pointers
6466 	 * to the response data.  The port does not guarantee to respond to
6467 	 * all extents counts request so update the local variable with the
6468 	 * allocated count from the port.
6469 	 */
6470 	if (emb == LPFC_SLI4_MBX_EMBED) {
6471 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6472 		id_array = &rsrc_ext->u.rsp.id[0];
6473 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6474 	} else {
6475 		virtaddr = mbox->sge_array->addr[0];
6476 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6477 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6478 		id_array = &n_rsrc->id;
6479 	}
6480 
6481 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6482 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6483 
6484 	/*
6485 	 * Based on the resource size and count, correct the base and max
6486 	 * resource values.
6487 	 */
6488 	length = sizeof(struct lpfc_rsrc_blks);
6489 	switch (type) {
6490 	case LPFC_RSC_TYPE_FCOE_RPI:
6491 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6492 						   sizeof(unsigned long),
6493 						   GFP_KERNEL);
6494 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6495 			rc = -ENOMEM;
6496 			goto err_exit;
6497 		}
6498 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6499 						 sizeof(uint16_t),
6500 						 GFP_KERNEL);
6501 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6502 			kfree(phba->sli4_hba.rpi_bmask);
6503 			rc = -ENOMEM;
6504 			goto err_exit;
6505 		}
6506 
6507 		/*
6508 		 * The next_rpi was initialized with the maximum available
6509 		 * count but the port may allocate a smaller number.  Catch
6510 		 * that case and update the next_rpi.
6511 		 */
6512 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6513 
6514 		/* Initialize local ptrs for common extent processing later. */
6515 		bmask = phba->sli4_hba.rpi_bmask;
6516 		ids = phba->sli4_hba.rpi_ids;
6517 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6518 		break;
6519 	case LPFC_RSC_TYPE_FCOE_VPI:
6520 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6521 					  GFP_KERNEL);
6522 		if (unlikely(!phba->vpi_bmask)) {
6523 			rc = -ENOMEM;
6524 			goto err_exit;
6525 		}
6526 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6527 					 GFP_KERNEL);
6528 		if (unlikely(!phba->vpi_ids)) {
6529 			kfree(phba->vpi_bmask);
6530 			rc = -ENOMEM;
6531 			goto err_exit;
6532 		}
6533 
6534 		/* Initialize local ptrs for common extent processing later. */
6535 		bmask = phba->vpi_bmask;
6536 		ids = phba->vpi_ids;
6537 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6538 		break;
6539 	case LPFC_RSC_TYPE_FCOE_XRI:
6540 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6541 						   sizeof(unsigned long),
6542 						   GFP_KERNEL);
6543 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6544 			rc = -ENOMEM;
6545 			goto err_exit;
6546 		}
6547 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6548 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6549 						 sizeof(uint16_t),
6550 						 GFP_KERNEL);
6551 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6552 			kfree(phba->sli4_hba.xri_bmask);
6553 			rc = -ENOMEM;
6554 			goto err_exit;
6555 		}
6556 
6557 		/* Initialize local ptrs for common extent processing later. */
6558 		bmask = phba->sli4_hba.xri_bmask;
6559 		ids = phba->sli4_hba.xri_ids;
6560 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6561 		break;
6562 	case LPFC_RSC_TYPE_FCOE_VFI:
6563 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6564 						   sizeof(unsigned long),
6565 						   GFP_KERNEL);
6566 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6567 			rc = -ENOMEM;
6568 			goto err_exit;
6569 		}
6570 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6571 						 sizeof(uint16_t),
6572 						 GFP_KERNEL);
6573 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6574 			kfree(phba->sli4_hba.vfi_bmask);
6575 			rc = -ENOMEM;
6576 			goto err_exit;
6577 		}
6578 
6579 		/* Initialize local ptrs for common extent processing later. */
6580 		bmask = phba->sli4_hba.vfi_bmask;
6581 		ids = phba->sli4_hba.vfi_ids;
6582 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6583 		break;
6584 	default:
6585 		/* Unsupported Opcode.  Fail call. */
6586 		id_array = NULL;
6587 		bmask = NULL;
6588 		ids = NULL;
6589 		ext_blk_list = NULL;
6590 		goto err_exit;
6591 	}
6592 
6593 	/*
6594 	 * Complete initializing the extent configuration with the
6595 	 * allocated ids assigned to this function.  The bitmask serves
6596 	 * as an index into the array and manages the available ids.  The
6597 	 * array just stores the ids communicated to the port via the wqes.
6598 	 */
6599 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6600 		if ((i % 2) == 0)
6601 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6602 					 &id_array[k]);
6603 		else
6604 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6605 					 &id_array[k]);
6606 
6607 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6608 		if (unlikely(!rsrc_blks)) {
6609 			rc = -ENOMEM;
6610 			kfree(bmask);
6611 			kfree(ids);
6612 			goto err_exit;
6613 		}
6614 		rsrc_blks->rsrc_start = rsrc_id;
6615 		rsrc_blks->rsrc_size = rsrc_size;
6616 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6617 		rsrc_start = rsrc_id;
6618 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6619 			phba->sli4_hba.io_xri_start = rsrc_start +
6620 				lpfc_sli4_get_iocb_cnt(phba);
6621 		}
6622 
6623 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6624 			ids[j] = rsrc_id;
6625 			rsrc_id++;
6626 			j++;
6627 		}
6628 		/* Entire word processed.  Get next word.*/
6629 		if ((i % 2) == 1)
6630 			k++;
6631 	}
6632  err_exit:
6633 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6634 	return rc;
6635 }
6636 
6637 
6638 
6639 /**
6640  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6641  * @phba: Pointer to HBA context object.
6642  * @type: the extent's type.
6643  *
6644  * This function deallocates all extents of a particular resource type.
6645  * SLI4 does not allow for deallocating a particular extent range.  It
6646  * is the caller's responsibility to release all kernel memory resources.
6647  **/
6648 static int
6649 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6650 {
6651 	int rc;
6652 	uint32_t length, mbox_tmo = 0;
6653 	LPFC_MBOXQ_t *mbox;
6654 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6655 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6656 
6657 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6658 	if (!mbox)
6659 		return -ENOMEM;
6660 
6661 	/*
6662 	 * This function sends an embedded mailbox because it only sends the
6663 	 * the resource type.  All extents of this type are released by the
6664 	 * port.
6665 	 */
6666 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6667 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6668 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6669 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6670 			 length, LPFC_SLI4_MBX_EMBED);
6671 
6672 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6673 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6674 					LPFC_SLI4_MBX_EMBED);
6675 	if (unlikely(rc)) {
6676 		rc = -EIO;
6677 		goto out_free_mbox;
6678 	}
6679 	if (!phba->sli4_hba.intr_enable)
6680 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6681 	else {
6682 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6683 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6684 	}
6685 	if (unlikely(rc)) {
6686 		rc = -EIO;
6687 		goto out_free_mbox;
6688 	}
6689 
6690 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6691 	if (bf_get(lpfc_mbox_hdr_status,
6692 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6693 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6694 				"2919 Failed to release resource extents "
6695 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6696 				"Resource memory not released.\n",
6697 				type,
6698 				bf_get(lpfc_mbox_hdr_status,
6699 				    &dealloc_rsrc->header.cfg_shdr.response),
6700 				bf_get(lpfc_mbox_hdr_add_status,
6701 				    &dealloc_rsrc->header.cfg_shdr.response));
6702 		rc = -EIO;
6703 		goto out_free_mbox;
6704 	}
6705 
6706 	/* Release kernel memory resources for the specific type. */
6707 	switch (type) {
6708 	case LPFC_RSC_TYPE_FCOE_VPI:
6709 		kfree(phba->vpi_bmask);
6710 		kfree(phba->vpi_ids);
6711 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6712 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6713 				    &phba->lpfc_vpi_blk_list, list) {
6714 			list_del_init(&rsrc_blk->list);
6715 			kfree(rsrc_blk);
6716 		}
6717 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6718 		break;
6719 	case LPFC_RSC_TYPE_FCOE_XRI:
6720 		kfree(phba->sli4_hba.xri_bmask);
6721 		kfree(phba->sli4_hba.xri_ids);
6722 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6723 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6724 			list_del_init(&rsrc_blk->list);
6725 			kfree(rsrc_blk);
6726 		}
6727 		break;
6728 	case LPFC_RSC_TYPE_FCOE_VFI:
6729 		kfree(phba->sli4_hba.vfi_bmask);
6730 		kfree(phba->sli4_hba.vfi_ids);
6731 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6732 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6733 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6734 			list_del_init(&rsrc_blk->list);
6735 			kfree(rsrc_blk);
6736 		}
6737 		break;
6738 	case LPFC_RSC_TYPE_FCOE_RPI:
6739 		/* RPI bitmask and physical id array are cleaned up earlier. */
6740 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6741 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6742 			list_del_init(&rsrc_blk->list);
6743 			kfree(rsrc_blk);
6744 		}
6745 		break;
6746 	default:
6747 		break;
6748 	}
6749 
6750 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6751 
6752  out_free_mbox:
6753 	mempool_free(mbox, phba->mbox_mem_pool);
6754 	return rc;
6755 }
6756 
6757 static void
6758 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6759 		  uint32_t feature)
6760 {
6761 	uint32_t len;
6762 	u32 sig_freq = 0;
6763 
6764 	len = sizeof(struct lpfc_mbx_set_feature) -
6765 		sizeof(struct lpfc_sli4_cfg_mhdr);
6766 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6767 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6768 			 LPFC_SLI4_MBX_EMBED);
6769 
6770 	switch (feature) {
6771 	case LPFC_SET_UE_RECOVERY:
6772 		bf_set(lpfc_mbx_set_feature_UER,
6773 		       &mbox->u.mqe.un.set_feature, 1);
6774 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6775 		mbox->u.mqe.un.set_feature.param_len = 8;
6776 		break;
6777 	case LPFC_SET_MDS_DIAGS:
6778 		bf_set(lpfc_mbx_set_feature_mds,
6779 		       &mbox->u.mqe.un.set_feature, 1);
6780 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6781 		       &mbox->u.mqe.un.set_feature, 1);
6782 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6783 		mbox->u.mqe.un.set_feature.param_len = 8;
6784 		break;
6785 	case LPFC_SET_CGN_SIGNAL:
6786 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6787 			sig_freq = 0;
6788 		else
6789 			sig_freq = phba->cgn_sig_freq;
6790 
6791 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6792 			bf_set(lpfc_mbx_set_feature_CGN_alarm_freq,
6793 			       &mbox->u.mqe.un.set_feature, sig_freq);
6794 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6795 			       &mbox->u.mqe.un.set_feature, sig_freq);
6796 		}
6797 
6798 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY)
6799 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6800 			       &mbox->u.mqe.un.set_feature, sig_freq);
6801 
6802 		if (phba->cmf_active_mode == LPFC_CFG_OFF ||
6803 		    phba->cgn_reg_signal == EDC_CG_SIG_NOTSUPPORTED)
6804 			sig_freq = 0;
6805 		else
6806 			sig_freq = lpfc_acqe_cgn_frequency;
6807 
6808 		bf_set(lpfc_mbx_set_feature_CGN_acqe_freq,
6809 		       &mbox->u.mqe.un.set_feature, sig_freq);
6810 
6811 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_CGN_SIGNAL;
6812 		mbox->u.mqe.un.set_feature.param_len = 12;
6813 		break;
6814 	case LPFC_SET_DUAL_DUMP:
6815 		bf_set(lpfc_mbx_set_feature_dd,
6816 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6817 		bf_set(lpfc_mbx_set_feature_ddquery,
6818 		       &mbox->u.mqe.un.set_feature, 0);
6819 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6820 		mbox->u.mqe.un.set_feature.param_len = 4;
6821 		break;
6822 	case LPFC_SET_ENABLE_MI:
6823 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_MI;
6824 		mbox->u.mqe.un.set_feature.param_len = 4;
6825 		bf_set(lpfc_mbx_set_feature_milunq, &mbox->u.mqe.un.set_feature,
6826 		       phba->pport->cfg_lun_queue_depth);
6827 		bf_set(lpfc_mbx_set_feature_mi, &mbox->u.mqe.un.set_feature,
6828 		       phba->sli4_hba.pc_sli4_params.mi_ver);
6829 		break;
6830 	case LPFC_SET_ENABLE_CMF:
6831 		bf_set(lpfc_mbx_set_feature_dd, &mbox->u.mqe.un.set_feature, 1);
6832 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_CMF;
6833 		mbox->u.mqe.un.set_feature.param_len = 4;
6834 		bf_set(lpfc_mbx_set_feature_cmf,
6835 		       &mbox->u.mqe.un.set_feature, 1);
6836 		break;
6837 	}
6838 	return;
6839 }
6840 
6841 /**
6842  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6843  * @phba: Pointer to HBA context object.
6844  *
6845  * Disable FW logging into host memory on the adapter. To
6846  * be done before reading logs from the host memory.
6847  **/
6848 void
6849 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6850 {
6851 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6852 
6853 	spin_lock_irq(&phba->hbalock);
6854 	ras_fwlog->state = INACTIVE;
6855 	spin_unlock_irq(&phba->hbalock);
6856 
6857 	/* Disable FW logging to host memory */
6858 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6859 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6860 
6861 	/* Wait 10ms for firmware to stop using DMA buffer */
6862 	usleep_range(10 * 1000, 20 * 1000);
6863 }
6864 
6865 /**
6866  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6867  * @phba: Pointer to HBA context object.
6868  *
6869  * This function is called to free memory allocated for RAS FW logging
6870  * support in the driver.
6871  **/
6872 void
6873 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6874 {
6875 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6876 	struct lpfc_dmabuf *dmabuf, *next;
6877 
6878 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6879 		list_for_each_entry_safe(dmabuf, next,
6880 				    &ras_fwlog->fwlog_buff_list,
6881 				    list) {
6882 			list_del(&dmabuf->list);
6883 			dma_free_coherent(&phba->pcidev->dev,
6884 					  LPFC_RAS_MAX_ENTRY_SIZE,
6885 					  dmabuf->virt, dmabuf->phys);
6886 			kfree(dmabuf);
6887 		}
6888 	}
6889 
6890 	if (ras_fwlog->lwpd.virt) {
6891 		dma_free_coherent(&phba->pcidev->dev,
6892 				  sizeof(uint32_t) * 2,
6893 				  ras_fwlog->lwpd.virt,
6894 				  ras_fwlog->lwpd.phys);
6895 		ras_fwlog->lwpd.virt = NULL;
6896 	}
6897 
6898 	spin_lock_irq(&phba->hbalock);
6899 	ras_fwlog->state = INACTIVE;
6900 	spin_unlock_irq(&phba->hbalock);
6901 }
6902 
6903 /**
6904  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6905  * @phba: Pointer to HBA context object.
6906  * @fwlog_buff_count: Count of buffers to be created.
6907  *
6908  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6909  * to update FW log is posted to the adapter.
6910  * Buffer count is calculated based on module param ras_fwlog_buffsize
6911  * Size of each buffer posted to FW is 64K.
6912  **/
6913 
6914 static int
6915 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6916 			uint32_t fwlog_buff_count)
6917 {
6918 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6919 	struct lpfc_dmabuf *dmabuf;
6920 	int rc = 0, i = 0;
6921 
6922 	/* Initialize List */
6923 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6924 
6925 	/* Allocate memory for the LWPD */
6926 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6927 					    sizeof(uint32_t) * 2,
6928 					    &ras_fwlog->lwpd.phys,
6929 					    GFP_KERNEL);
6930 	if (!ras_fwlog->lwpd.virt) {
6931 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6932 				"6185 LWPD Memory Alloc Failed\n");
6933 
6934 		return -ENOMEM;
6935 	}
6936 
6937 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6938 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6939 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6940 				 GFP_KERNEL);
6941 		if (!dmabuf) {
6942 			rc = -ENOMEM;
6943 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6944 					"6186 Memory Alloc failed FW logging");
6945 			goto free_mem;
6946 		}
6947 
6948 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6949 						  LPFC_RAS_MAX_ENTRY_SIZE,
6950 						  &dmabuf->phys, GFP_KERNEL);
6951 		if (!dmabuf->virt) {
6952 			kfree(dmabuf);
6953 			rc = -ENOMEM;
6954 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6955 					"6187 DMA Alloc Failed FW logging");
6956 			goto free_mem;
6957 		}
6958 		dmabuf->buffer_tag = i;
6959 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6960 	}
6961 
6962 free_mem:
6963 	if (rc)
6964 		lpfc_sli4_ras_dma_free(phba);
6965 
6966 	return rc;
6967 }
6968 
6969 /**
6970  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6971  * @phba: pointer to lpfc hba data structure.
6972  * @pmb: pointer to the driver internal queue element for mailbox command.
6973  *
6974  * Completion handler for driver's RAS MBX command to the device.
6975  **/
6976 static void
6977 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6978 {
6979 	MAILBOX_t *mb;
6980 	union lpfc_sli4_cfg_shdr *shdr;
6981 	uint32_t shdr_status, shdr_add_status;
6982 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6983 
6984 	mb = &pmb->u.mb;
6985 
6986 	shdr = (union lpfc_sli4_cfg_shdr *)
6987 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6988 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6989 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6990 
6991 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6992 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6993 				"6188 FW LOG mailbox "
6994 				"completed with status x%x add_status x%x,"
6995 				" mbx status x%x\n",
6996 				shdr_status, shdr_add_status, mb->mbxStatus);
6997 
6998 		ras_fwlog->ras_hwsupport = false;
6999 		goto disable_ras;
7000 	}
7001 
7002 	spin_lock_irq(&phba->hbalock);
7003 	ras_fwlog->state = ACTIVE;
7004 	spin_unlock_irq(&phba->hbalock);
7005 	mempool_free(pmb, phba->mbox_mem_pool);
7006 
7007 	return;
7008 
7009 disable_ras:
7010 	/* Free RAS DMA memory */
7011 	lpfc_sli4_ras_dma_free(phba);
7012 	mempool_free(pmb, phba->mbox_mem_pool);
7013 }
7014 
7015 /**
7016  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
7017  * @phba: pointer to lpfc hba data structure.
7018  * @fwlog_level: Logging verbosity level.
7019  * @fwlog_enable: Enable/Disable logging.
7020  *
7021  * Initialize memory and post mailbox command to enable FW logging in host
7022  * memory.
7023  **/
7024 int
7025 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
7026 			 uint32_t fwlog_level,
7027 			 uint32_t fwlog_enable)
7028 {
7029 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
7030 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
7031 	struct lpfc_dmabuf *dmabuf;
7032 	LPFC_MBOXQ_t *mbox;
7033 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
7034 	int rc = 0;
7035 
7036 	spin_lock_irq(&phba->hbalock);
7037 	ras_fwlog->state = INACTIVE;
7038 	spin_unlock_irq(&phba->hbalock);
7039 
7040 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
7041 			  phba->cfg_ras_fwlog_buffsize);
7042 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
7043 
7044 	/*
7045 	 * If re-enabling FW logging support use earlier allocated
7046 	 * DMA buffers while posting MBX command.
7047 	 **/
7048 	if (!ras_fwlog->lwpd.virt) {
7049 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
7050 		if (rc) {
7051 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7052 					"6189 FW Log Memory Allocation Failed");
7053 			return rc;
7054 		}
7055 	}
7056 
7057 	/* Setup Mailbox command */
7058 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7059 	if (!mbox) {
7060 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7061 				"6190 RAS MBX Alloc Failed");
7062 		rc = -ENOMEM;
7063 		goto mem_free;
7064 	}
7065 
7066 	ras_fwlog->fw_loglevel = fwlog_level;
7067 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
7068 		sizeof(struct lpfc_sli4_cfg_mhdr));
7069 
7070 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
7071 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
7072 			 len, LPFC_SLI4_MBX_EMBED);
7073 
7074 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
7075 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
7076 	       fwlog_enable);
7077 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
7078 	       ras_fwlog->fw_loglevel);
7079 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
7080 	       ras_fwlog->fw_buffcount);
7081 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
7082 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
7083 
7084 	/* Update DMA buffer address */
7085 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
7086 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
7087 
7088 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
7089 			putPaddrLow(dmabuf->phys);
7090 
7091 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
7092 			putPaddrHigh(dmabuf->phys);
7093 	}
7094 
7095 	/* Update LPWD address */
7096 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
7097 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
7098 
7099 	spin_lock_irq(&phba->hbalock);
7100 	ras_fwlog->state = REG_INPROGRESS;
7101 	spin_unlock_irq(&phba->hbalock);
7102 	mbox->vport = phba->pport;
7103 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
7104 
7105 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
7106 
7107 	if (rc == MBX_NOT_FINISHED) {
7108 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7109 				"6191 FW-Log Mailbox failed. "
7110 				"status %d mbxStatus : x%x", rc,
7111 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
7112 		mempool_free(mbox, phba->mbox_mem_pool);
7113 		rc = -EIO;
7114 		goto mem_free;
7115 	} else
7116 		rc = 0;
7117 mem_free:
7118 	if (rc)
7119 		lpfc_sli4_ras_dma_free(phba);
7120 
7121 	return rc;
7122 }
7123 
7124 /**
7125  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
7126  * @phba: Pointer to HBA context object.
7127  *
7128  * Check if RAS is supported on the adapter and initialize it.
7129  **/
7130 void
7131 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
7132 {
7133 	/* Check RAS FW Log needs to be enabled or not */
7134 	if (lpfc_check_fwlog_support(phba))
7135 		return;
7136 
7137 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
7138 				 LPFC_RAS_ENABLE_LOGGING);
7139 }
7140 
7141 /**
7142  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
7143  * @phba: Pointer to HBA context object.
7144  *
7145  * This function allocates all SLI4 resource identifiers.
7146  **/
7147 int
7148 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
7149 {
7150 	int i, rc, error = 0;
7151 	uint16_t count, base;
7152 	unsigned long longs;
7153 
7154 	if (!phba->sli4_hba.rpi_hdrs_in_use)
7155 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
7156 	if (phba->sli4_hba.extents_in_use) {
7157 		/*
7158 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
7159 		 * resource extent count must be read and allocated before
7160 		 * provisioning the resource id arrays.
7161 		 */
7162 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7163 		    LPFC_IDX_RSRC_RDY) {
7164 			/*
7165 			 * Extent-based resources are set - the driver could
7166 			 * be in a port reset. Figure out if any corrective
7167 			 * actions need to be taken.
7168 			 */
7169 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7170 						 LPFC_RSC_TYPE_FCOE_VFI);
7171 			if (rc != 0)
7172 				error++;
7173 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7174 						 LPFC_RSC_TYPE_FCOE_VPI);
7175 			if (rc != 0)
7176 				error++;
7177 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7178 						 LPFC_RSC_TYPE_FCOE_XRI);
7179 			if (rc != 0)
7180 				error++;
7181 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7182 						 LPFC_RSC_TYPE_FCOE_RPI);
7183 			if (rc != 0)
7184 				error++;
7185 
7186 			/*
7187 			 * It's possible that the number of resources
7188 			 * provided to this port instance changed between
7189 			 * resets.  Detect this condition and reallocate
7190 			 * resources.  Otherwise, there is no action.
7191 			 */
7192 			if (error) {
7193 				lpfc_printf_log(phba, KERN_INFO,
7194 						LOG_MBOX | LOG_INIT,
7195 						"2931 Detected extent resource "
7196 						"change.  Reallocating all "
7197 						"extents.\n");
7198 				rc = lpfc_sli4_dealloc_extent(phba,
7199 						 LPFC_RSC_TYPE_FCOE_VFI);
7200 				rc = lpfc_sli4_dealloc_extent(phba,
7201 						 LPFC_RSC_TYPE_FCOE_VPI);
7202 				rc = lpfc_sli4_dealloc_extent(phba,
7203 						 LPFC_RSC_TYPE_FCOE_XRI);
7204 				rc = lpfc_sli4_dealloc_extent(phba,
7205 						 LPFC_RSC_TYPE_FCOE_RPI);
7206 			} else
7207 				return 0;
7208 		}
7209 
7210 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7211 		if (unlikely(rc))
7212 			goto err_exit;
7213 
7214 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7215 		if (unlikely(rc))
7216 			goto err_exit;
7217 
7218 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7219 		if (unlikely(rc))
7220 			goto err_exit;
7221 
7222 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7223 		if (unlikely(rc))
7224 			goto err_exit;
7225 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7226 		       LPFC_IDX_RSRC_RDY);
7227 		return rc;
7228 	} else {
7229 		/*
7230 		 * The port does not support resource extents.  The XRI, VPI,
7231 		 * VFI, RPI resource ids were determined from READ_CONFIG.
7232 		 * Just allocate the bitmasks and provision the resource id
7233 		 * arrays.  If a port reset is active, the resources don't
7234 		 * need any action - just exit.
7235 		 */
7236 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7237 		    LPFC_IDX_RSRC_RDY) {
7238 			lpfc_sli4_dealloc_resource_identifiers(phba);
7239 			lpfc_sli4_remove_rpis(phba);
7240 		}
7241 		/* RPIs. */
7242 		count = phba->sli4_hba.max_cfg_param.max_rpi;
7243 		if (count <= 0) {
7244 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7245 					"3279 Invalid provisioning of "
7246 					"rpi:%d\n", count);
7247 			rc = -EINVAL;
7248 			goto err_exit;
7249 		}
7250 		base = phba->sli4_hba.max_cfg_param.rpi_base;
7251 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7252 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
7253 						   sizeof(unsigned long),
7254 						   GFP_KERNEL);
7255 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
7256 			rc = -ENOMEM;
7257 			goto err_exit;
7258 		}
7259 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
7260 						 GFP_KERNEL);
7261 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
7262 			rc = -ENOMEM;
7263 			goto free_rpi_bmask;
7264 		}
7265 
7266 		for (i = 0; i < count; i++)
7267 			phba->sli4_hba.rpi_ids[i] = base + i;
7268 
7269 		/* VPIs. */
7270 		count = phba->sli4_hba.max_cfg_param.max_vpi;
7271 		if (count <= 0) {
7272 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7273 					"3280 Invalid provisioning of "
7274 					"vpi:%d\n", count);
7275 			rc = -EINVAL;
7276 			goto free_rpi_ids;
7277 		}
7278 		base = phba->sli4_hba.max_cfg_param.vpi_base;
7279 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7280 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
7281 					  GFP_KERNEL);
7282 		if (unlikely(!phba->vpi_bmask)) {
7283 			rc = -ENOMEM;
7284 			goto free_rpi_ids;
7285 		}
7286 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
7287 					GFP_KERNEL);
7288 		if (unlikely(!phba->vpi_ids)) {
7289 			rc = -ENOMEM;
7290 			goto free_vpi_bmask;
7291 		}
7292 
7293 		for (i = 0; i < count; i++)
7294 			phba->vpi_ids[i] = base + i;
7295 
7296 		/* XRIs. */
7297 		count = phba->sli4_hba.max_cfg_param.max_xri;
7298 		if (count <= 0) {
7299 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7300 					"3281 Invalid provisioning of "
7301 					"xri:%d\n", count);
7302 			rc = -EINVAL;
7303 			goto free_vpi_ids;
7304 		}
7305 		base = phba->sli4_hba.max_cfg_param.xri_base;
7306 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7307 		phba->sli4_hba.xri_bmask = kcalloc(longs,
7308 						   sizeof(unsigned long),
7309 						   GFP_KERNEL);
7310 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
7311 			rc = -ENOMEM;
7312 			goto free_vpi_ids;
7313 		}
7314 		phba->sli4_hba.max_cfg_param.xri_used = 0;
7315 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
7316 						 GFP_KERNEL);
7317 		if (unlikely(!phba->sli4_hba.xri_ids)) {
7318 			rc = -ENOMEM;
7319 			goto free_xri_bmask;
7320 		}
7321 
7322 		for (i = 0; i < count; i++)
7323 			phba->sli4_hba.xri_ids[i] = base + i;
7324 
7325 		/* VFIs. */
7326 		count = phba->sli4_hba.max_cfg_param.max_vfi;
7327 		if (count <= 0) {
7328 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7329 					"3282 Invalid provisioning of "
7330 					"vfi:%d\n", count);
7331 			rc = -EINVAL;
7332 			goto free_xri_ids;
7333 		}
7334 		base = phba->sli4_hba.max_cfg_param.vfi_base;
7335 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7336 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
7337 						   sizeof(unsigned long),
7338 						   GFP_KERNEL);
7339 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
7340 			rc = -ENOMEM;
7341 			goto free_xri_ids;
7342 		}
7343 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
7344 						 GFP_KERNEL);
7345 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
7346 			rc = -ENOMEM;
7347 			goto free_vfi_bmask;
7348 		}
7349 
7350 		for (i = 0; i < count; i++)
7351 			phba->sli4_hba.vfi_ids[i] = base + i;
7352 
7353 		/*
7354 		 * Mark all resources ready.  An HBA reset doesn't need
7355 		 * to reset the initialization.
7356 		 */
7357 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7358 		       LPFC_IDX_RSRC_RDY);
7359 		return 0;
7360 	}
7361 
7362  free_vfi_bmask:
7363 	kfree(phba->sli4_hba.vfi_bmask);
7364 	phba->sli4_hba.vfi_bmask = NULL;
7365  free_xri_ids:
7366 	kfree(phba->sli4_hba.xri_ids);
7367 	phba->sli4_hba.xri_ids = NULL;
7368  free_xri_bmask:
7369 	kfree(phba->sli4_hba.xri_bmask);
7370 	phba->sli4_hba.xri_bmask = NULL;
7371  free_vpi_ids:
7372 	kfree(phba->vpi_ids);
7373 	phba->vpi_ids = NULL;
7374  free_vpi_bmask:
7375 	kfree(phba->vpi_bmask);
7376 	phba->vpi_bmask = NULL;
7377  free_rpi_ids:
7378 	kfree(phba->sli4_hba.rpi_ids);
7379 	phba->sli4_hba.rpi_ids = NULL;
7380  free_rpi_bmask:
7381 	kfree(phba->sli4_hba.rpi_bmask);
7382 	phba->sli4_hba.rpi_bmask = NULL;
7383  err_exit:
7384 	return rc;
7385 }
7386 
7387 /**
7388  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
7389  * @phba: Pointer to HBA context object.
7390  *
7391  * This function allocates the number of elements for the specified
7392  * resource type.
7393  **/
7394 int
7395 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7396 {
7397 	if (phba->sli4_hba.extents_in_use) {
7398 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7399 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7400 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7401 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7402 	} else {
7403 		kfree(phba->vpi_bmask);
7404 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
7405 		kfree(phba->vpi_ids);
7406 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7407 		kfree(phba->sli4_hba.xri_bmask);
7408 		kfree(phba->sli4_hba.xri_ids);
7409 		kfree(phba->sli4_hba.vfi_bmask);
7410 		kfree(phba->sli4_hba.vfi_ids);
7411 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7412 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7413 	}
7414 
7415 	return 0;
7416 }
7417 
7418 /**
7419  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7420  * @phba: Pointer to HBA context object.
7421  * @type: The resource extent type.
7422  * @extnt_cnt: buffer to hold port extent count response
7423  * @extnt_size: buffer to hold port extent size response.
7424  *
7425  * This function calls the port to read the host allocated extents
7426  * for a particular type.
7427  **/
7428 int
7429 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7430 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
7431 {
7432 	bool emb;
7433 	int rc = 0;
7434 	uint16_t curr_blks = 0;
7435 	uint32_t req_len, emb_len;
7436 	uint32_t alloc_len, mbox_tmo;
7437 	struct list_head *blk_list_head;
7438 	struct lpfc_rsrc_blks *rsrc_blk;
7439 	LPFC_MBOXQ_t *mbox;
7440 	void *virtaddr = NULL;
7441 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7442 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7443 	union  lpfc_sli4_cfg_shdr *shdr;
7444 
7445 	switch (type) {
7446 	case LPFC_RSC_TYPE_FCOE_VPI:
7447 		blk_list_head = &phba->lpfc_vpi_blk_list;
7448 		break;
7449 	case LPFC_RSC_TYPE_FCOE_XRI:
7450 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7451 		break;
7452 	case LPFC_RSC_TYPE_FCOE_VFI:
7453 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7454 		break;
7455 	case LPFC_RSC_TYPE_FCOE_RPI:
7456 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7457 		break;
7458 	default:
7459 		return -EIO;
7460 	}
7461 
7462 	/* Count the number of extents currently allocatd for this type. */
7463 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
7464 		if (curr_blks == 0) {
7465 			/*
7466 			 * The GET_ALLOCATED mailbox does not return the size,
7467 			 * just the count.  The size should be just the size
7468 			 * stored in the current allocated block and all sizes
7469 			 * for an extent type are the same so set the return
7470 			 * value now.
7471 			 */
7472 			*extnt_size = rsrc_blk->rsrc_size;
7473 		}
7474 		curr_blks++;
7475 	}
7476 
7477 	/*
7478 	 * Calculate the size of an embedded mailbox.  The uint32_t
7479 	 * accounts for extents-specific word.
7480 	 */
7481 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7482 		sizeof(uint32_t);
7483 
7484 	/*
7485 	 * Presume the allocation and response will fit into an embedded
7486 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7487 	 */
7488 	emb = LPFC_SLI4_MBX_EMBED;
7489 	req_len = emb_len;
7490 	if (req_len > emb_len) {
7491 		req_len = curr_blks * sizeof(uint16_t) +
7492 			sizeof(union lpfc_sli4_cfg_shdr) +
7493 			sizeof(uint32_t);
7494 		emb = LPFC_SLI4_MBX_NEMBED;
7495 	}
7496 
7497 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7498 	if (!mbox)
7499 		return -ENOMEM;
7500 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7501 
7502 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7503 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7504 				     req_len, emb);
7505 	if (alloc_len < req_len) {
7506 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7507 			"2983 Allocated DMA memory size (x%x) is "
7508 			"less than the requested DMA memory "
7509 			"size (x%x)\n", alloc_len, req_len);
7510 		rc = -ENOMEM;
7511 		goto err_exit;
7512 	}
7513 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7514 	if (unlikely(rc)) {
7515 		rc = -EIO;
7516 		goto err_exit;
7517 	}
7518 
7519 	if (!phba->sli4_hba.intr_enable)
7520 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7521 	else {
7522 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7523 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7524 	}
7525 
7526 	if (unlikely(rc)) {
7527 		rc = -EIO;
7528 		goto err_exit;
7529 	}
7530 
7531 	/*
7532 	 * Figure out where the response is located.  Then get local pointers
7533 	 * to the response data.  The port does not guarantee to respond to
7534 	 * all extents counts request so update the local variable with the
7535 	 * allocated count from the port.
7536 	 */
7537 	if (emb == LPFC_SLI4_MBX_EMBED) {
7538 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7539 		shdr = &rsrc_ext->header.cfg_shdr;
7540 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7541 	} else {
7542 		virtaddr = mbox->sge_array->addr[0];
7543 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7544 		shdr = &n_rsrc->cfg_shdr;
7545 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7546 	}
7547 
7548 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7549 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7550 			"2984 Failed to read allocated resources "
7551 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7552 			type,
7553 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7554 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7555 		rc = -EIO;
7556 		goto err_exit;
7557 	}
7558  err_exit:
7559 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7560 	return rc;
7561 }
7562 
7563 /**
7564  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7565  * @phba: pointer to lpfc hba data structure.
7566  * @sgl_list: linked link of sgl buffers to post
7567  * @cnt: number of linked list buffers
7568  *
7569  * This routine walks the list of buffers that have been allocated and
7570  * repost them to the port by using SGL block post. This is needed after a
7571  * pci_function_reset/warm_start or start. It attempts to construct blocks
7572  * of buffer sgls which contains contiguous xris and uses the non-embedded
7573  * SGL block post mailbox commands to post them to the port. For single
7574  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7575  * mailbox command for posting.
7576  *
7577  * Returns: 0 = success, non-zero failure.
7578  **/
7579 static int
7580 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7581 			  struct list_head *sgl_list, int cnt)
7582 {
7583 	struct lpfc_sglq *sglq_entry = NULL;
7584 	struct lpfc_sglq *sglq_entry_next = NULL;
7585 	struct lpfc_sglq *sglq_entry_first = NULL;
7586 	int status, total_cnt;
7587 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7588 	int last_xritag = NO_XRI;
7589 	LIST_HEAD(prep_sgl_list);
7590 	LIST_HEAD(blck_sgl_list);
7591 	LIST_HEAD(allc_sgl_list);
7592 	LIST_HEAD(post_sgl_list);
7593 	LIST_HEAD(free_sgl_list);
7594 
7595 	spin_lock_irq(&phba->hbalock);
7596 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7597 	list_splice_init(sgl_list, &allc_sgl_list);
7598 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7599 	spin_unlock_irq(&phba->hbalock);
7600 
7601 	total_cnt = cnt;
7602 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7603 				 &allc_sgl_list, list) {
7604 		list_del_init(&sglq_entry->list);
7605 		block_cnt++;
7606 		if ((last_xritag != NO_XRI) &&
7607 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7608 			/* a hole in xri block, form a sgl posting block */
7609 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7610 			post_cnt = block_cnt - 1;
7611 			/* prepare list for next posting block */
7612 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7613 			block_cnt = 1;
7614 		} else {
7615 			/* prepare list for next posting block */
7616 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7617 			/* enough sgls for non-embed sgl mbox command */
7618 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7619 				list_splice_init(&prep_sgl_list,
7620 						 &blck_sgl_list);
7621 				post_cnt = block_cnt;
7622 				block_cnt = 0;
7623 			}
7624 		}
7625 		num_posted++;
7626 
7627 		/* keep track of last sgl's xritag */
7628 		last_xritag = sglq_entry->sli4_xritag;
7629 
7630 		/* end of repost sgl list condition for buffers */
7631 		if (num_posted == total_cnt) {
7632 			if (post_cnt == 0) {
7633 				list_splice_init(&prep_sgl_list,
7634 						 &blck_sgl_list);
7635 				post_cnt = block_cnt;
7636 			} else if (block_cnt == 1) {
7637 				status = lpfc_sli4_post_sgl(phba,
7638 						sglq_entry->phys, 0,
7639 						sglq_entry->sli4_xritag);
7640 				if (!status) {
7641 					/* successful, put sgl to posted list */
7642 					list_add_tail(&sglq_entry->list,
7643 						      &post_sgl_list);
7644 				} else {
7645 					/* Failure, put sgl to free list */
7646 					lpfc_printf_log(phba, KERN_WARNING,
7647 						LOG_SLI,
7648 						"3159 Failed to post "
7649 						"sgl, xritag:x%x\n",
7650 						sglq_entry->sli4_xritag);
7651 					list_add_tail(&sglq_entry->list,
7652 						      &free_sgl_list);
7653 					total_cnt--;
7654 				}
7655 			}
7656 		}
7657 
7658 		/* continue until a nembed page worth of sgls */
7659 		if (post_cnt == 0)
7660 			continue;
7661 
7662 		/* post the buffer list sgls as a block */
7663 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7664 						 post_cnt);
7665 
7666 		if (!status) {
7667 			/* success, put sgl list to posted sgl list */
7668 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7669 		} else {
7670 			/* Failure, put sgl list to free sgl list */
7671 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7672 							    struct lpfc_sglq,
7673 							    list);
7674 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7675 					"3160 Failed to post sgl-list, "
7676 					"xritag:x%x-x%x\n",
7677 					sglq_entry_first->sli4_xritag,
7678 					(sglq_entry_first->sli4_xritag +
7679 					 post_cnt - 1));
7680 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7681 			total_cnt -= post_cnt;
7682 		}
7683 
7684 		/* don't reset xirtag due to hole in xri block */
7685 		if (block_cnt == 0)
7686 			last_xritag = NO_XRI;
7687 
7688 		/* reset sgl post count for next round of posting */
7689 		post_cnt = 0;
7690 	}
7691 
7692 	/* free the sgls failed to post */
7693 	lpfc_free_sgl_list(phba, &free_sgl_list);
7694 
7695 	/* push sgls posted to the available list */
7696 	if (!list_empty(&post_sgl_list)) {
7697 		spin_lock_irq(&phba->hbalock);
7698 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7699 		list_splice_init(&post_sgl_list, sgl_list);
7700 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7701 		spin_unlock_irq(&phba->hbalock);
7702 	} else {
7703 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7704 				"3161 Failure to post sgl to port.\n");
7705 		return -EIO;
7706 	}
7707 
7708 	/* return the number of XRIs actually posted */
7709 	return total_cnt;
7710 }
7711 
7712 /**
7713  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7714  * @phba: pointer to lpfc hba data structure.
7715  *
7716  * This routine walks the list of nvme buffers that have been allocated and
7717  * repost them to the port by using SGL block post. This is needed after a
7718  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7719  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7720  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7721  *
7722  * Returns: 0 = success, non-zero failure.
7723  **/
7724 static int
7725 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7726 {
7727 	LIST_HEAD(post_nblist);
7728 	int num_posted, rc = 0;
7729 
7730 	/* get all NVME buffers need to repost to a local list */
7731 	lpfc_io_buf_flush(phba, &post_nblist);
7732 
7733 	/* post the list of nvme buffer sgls to port if available */
7734 	if (!list_empty(&post_nblist)) {
7735 		num_posted = lpfc_sli4_post_io_sgl_list(
7736 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7737 		/* failed to post any nvme buffer, return error */
7738 		if (num_posted == 0)
7739 			rc = -EIO;
7740 	}
7741 	return rc;
7742 }
7743 
7744 static void
7745 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7746 {
7747 	uint32_t len;
7748 
7749 	len = sizeof(struct lpfc_mbx_set_host_data) -
7750 		sizeof(struct lpfc_sli4_cfg_mhdr);
7751 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7752 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7753 			 LPFC_SLI4_MBX_EMBED);
7754 
7755 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7756 	mbox->u.mqe.un.set_host_data.param_len =
7757 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7758 	snprintf(mbox->u.mqe.un.set_host_data.un.data,
7759 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7760 		 "Linux %s v"LPFC_DRIVER_VERSION,
7761 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7762 }
7763 
7764 int
7765 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7766 		    struct lpfc_queue *drq, int count, int idx)
7767 {
7768 	int rc, i;
7769 	struct lpfc_rqe hrqe;
7770 	struct lpfc_rqe drqe;
7771 	struct lpfc_rqb *rqbp;
7772 	unsigned long flags;
7773 	struct rqb_dmabuf *rqb_buffer;
7774 	LIST_HEAD(rqb_buf_list);
7775 
7776 	rqbp = hrq->rqbp;
7777 	for (i = 0; i < count; i++) {
7778 		spin_lock_irqsave(&phba->hbalock, flags);
7779 		/* IF RQ is already full, don't bother */
7780 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7781 			spin_unlock_irqrestore(&phba->hbalock, flags);
7782 			break;
7783 		}
7784 		spin_unlock_irqrestore(&phba->hbalock, flags);
7785 
7786 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7787 		if (!rqb_buffer)
7788 			break;
7789 		rqb_buffer->hrq = hrq;
7790 		rqb_buffer->drq = drq;
7791 		rqb_buffer->idx = idx;
7792 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7793 	}
7794 
7795 	spin_lock_irqsave(&phba->hbalock, flags);
7796 	while (!list_empty(&rqb_buf_list)) {
7797 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7798 				 hbuf.list);
7799 
7800 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7801 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7802 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7803 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7804 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7805 		if (rc < 0) {
7806 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7807 					"6421 Cannot post to HRQ %d: %x %x %x "
7808 					"DRQ %x %x\n",
7809 					hrq->queue_id,
7810 					hrq->host_index,
7811 					hrq->hba_index,
7812 					hrq->entry_count,
7813 					drq->host_index,
7814 					drq->hba_index);
7815 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7816 		} else {
7817 			list_add_tail(&rqb_buffer->hbuf.list,
7818 				      &rqbp->rqb_buffer_list);
7819 			rqbp->buffer_count++;
7820 		}
7821 	}
7822 	spin_unlock_irqrestore(&phba->hbalock, flags);
7823 	return 1;
7824 }
7825 
7826 static void
7827 lpfc_mbx_cmpl_cgn_set_ftrs(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7828 {
7829 	struct lpfc_vport *vport = pmb->vport;
7830 	union lpfc_sli4_cfg_shdr *shdr;
7831 	u32 shdr_status, shdr_add_status;
7832 	u32 sig, acqe;
7833 
7834 	/* Two outcomes. (1) Set featurs was successul and EDC negotiation
7835 	 * is done. (2) Mailbox failed and send FPIN support only.
7836 	 */
7837 	shdr = (union lpfc_sli4_cfg_shdr *)
7838 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7839 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7840 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7841 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7842 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
7843 				"2516 CGN SET_FEATURE mbox failed with "
7844 				"status x%x add_status x%x, mbx status x%x "
7845 				"Reset Congestion to FPINs only\n",
7846 				shdr_status, shdr_add_status,
7847 				pmb->u.mb.mbxStatus);
7848 		/* If there is a mbox error, move on to RDF */
7849 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7850 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7851 		goto out;
7852 	}
7853 
7854 	/* Zero out Congestion Signal ACQE counter */
7855 	phba->cgn_acqe_cnt = 0;
7856 
7857 	acqe = bf_get(lpfc_mbx_set_feature_CGN_acqe_freq,
7858 		      &pmb->u.mqe.un.set_feature);
7859 	sig = bf_get(lpfc_mbx_set_feature_CGN_warn_freq,
7860 		     &pmb->u.mqe.un.set_feature);
7861 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7862 			"4620 SET_FEATURES Success: Freq: %ds %dms "
7863 			" Reg: x%x x%x\n", acqe, sig,
7864 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7865 out:
7866 	mempool_free(pmb, phba->mbox_mem_pool);
7867 
7868 	/* Register for FPIN events from the fabric now that the
7869 	 * EDC common_set_features has completed.
7870 	 */
7871 	lpfc_issue_els_rdf(vport, 0);
7872 }
7873 
7874 int
7875 lpfc_config_cgn_signal(struct lpfc_hba *phba)
7876 {
7877 	LPFC_MBOXQ_t *mboxq;
7878 	u32 rc;
7879 
7880 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7881 	if (!mboxq)
7882 		goto out_rdf;
7883 
7884 	lpfc_set_features(phba, mboxq, LPFC_SET_CGN_SIGNAL);
7885 	mboxq->vport = phba->pport;
7886 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_cgn_set_ftrs;
7887 
7888 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7889 			"4621 SET_FEATURES: FREQ sig x%x acqe x%x: "
7890 			"Reg: x%x x%x\n",
7891 			phba->cgn_sig_freq, lpfc_acqe_cgn_frequency,
7892 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7893 
7894 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7895 	if (rc == MBX_NOT_FINISHED)
7896 		goto out;
7897 	return 0;
7898 
7899 out:
7900 	mempool_free(mboxq, phba->mbox_mem_pool);
7901 out_rdf:
7902 	/* If there is a mbox error, move on to RDF */
7903 	phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7904 	phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7905 	lpfc_issue_els_rdf(phba->pport, 0);
7906 	return -EIO;
7907 }
7908 
7909 /**
7910  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7911  * @phba: pointer to lpfc hba data structure.
7912  *
7913  * This routine initializes the per-cq idle_stat to dynamically dictate
7914  * polling decisions.
7915  *
7916  * Return codes:
7917  *   None
7918  **/
7919 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
7920 {
7921 	int i;
7922 	struct lpfc_sli4_hdw_queue *hdwq;
7923 	struct lpfc_queue *cq;
7924 	struct lpfc_idle_stat *idle_stat;
7925 	u64 wall;
7926 
7927 	for_each_present_cpu(i) {
7928 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
7929 		cq = hdwq->io_cq;
7930 
7931 		/* Skip if we've already handled this cq's primary CPU */
7932 		if (cq->chann != i)
7933 			continue;
7934 
7935 		idle_stat = &phba->sli4_hba.idle_stat[i];
7936 
7937 		idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
7938 		idle_stat->prev_wall = wall;
7939 
7940 		if (phba->nvmet_support ||
7941 		    phba->cmf_active_mode != LPFC_CFG_OFF)
7942 			cq->poll_mode = LPFC_QUEUE_WORK;
7943 		else
7944 			cq->poll_mode = LPFC_IRQ_POLL;
7945 	}
7946 
7947 	if (!phba->nvmet_support)
7948 		schedule_delayed_work(&phba->idle_stat_delay_work,
7949 				      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
7950 }
7951 
7952 static void lpfc_sli4_dip(struct lpfc_hba *phba)
7953 {
7954 	uint32_t if_type;
7955 
7956 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
7957 	if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
7958 	    if_type == LPFC_SLI_INTF_IF_TYPE_6) {
7959 		struct lpfc_register reg_data;
7960 
7961 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
7962 			       &reg_data.word0))
7963 			return;
7964 
7965 		if (bf_get(lpfc_sliport_status_dip, &reg_data))
7966 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7967 					"2904 Firmware Dump Image Present"
7968 					" on Adapter");
7969 	}
7970 }
7971 
7972 /**
7973  * lpfc_cmf_setup - Initialize idle_stat tracking
7974  * @phba: Pointer to HBA context object.
7975  *
7976  * This is called from HBA setup during driver load or when the HBA
7977  * comes online. this does all the initialization to support CMF and MI.
7978  **/
7979 static int
7980 lpfc_cmf_setup(struct lpfc_hba *phba)
7981 {
7982 	LPFC_MBOXQ_t *mboxq;
7983 	struct lpfc_dmabuf *mp;
7984 	struct lpfc_pc_sli4_params *sli4_params;
7985 	int rc, cmf, mi_ver;
7986 
7987 	rc = lpfc_sli4_refresh_params(phba);
7988 	if (unlikely(rc))
7989 		return rc;
7990 
7991 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7992 	if (!mboxq)
7993 		return -ENOMEM;
7994 
7995 	sli4_params = &phba->sli4_hba.pc_sli4_params;
7996 
7997 	/* Are we forcing MI off via module parameter? */
7998 	if (!phba->cfg_enable_mi)
7999 		sli4_params->mi_ver = 0;
8000 
8001 	/* Always try to enable MI feature if we can */
8002 	if (sli4_params->mi_ver) {
8003 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_MI);
8004 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8005 		mi_ver = bf_get(lpfc_mbx_set_feature_mi,
8006 				 &mboxq->u.mqe.un.set_feature);
8007 
8008 		if (rc == MBX_SUCCESS) {
8009 			if (mi_ver) {
8010 				lpfc_printf_log(phba,
8011 						KERN_WARNING, LOG_CGN_MGMT,
8012 						"6215 MI is enabled\n");
8013 				sli4_params->mi_ver = mi_ver;
8014 			} else {
8015 				lpfc_printf_log(phba,
8016 						KERN_WARNING, LOG_CGN_MGMT,
8017 						"6338 MI is disabled\n");
8018 				sli4_params->mi_ver = 0;
8019 			}
8020 		} else {
8021 			/* mi_ver is already set from GET_SLI4_PARAMETERS */
8022 			lpfc_printf_log(phba, KERN_INFO,
8023 					LOG_CGN_MGMT | LOG_INIT,
8024 					"6245 Enable MI Mailbox x%x (x%x/x%x) "
8025 					"failed, rc:x%x mi:x%x\n",
8026 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8027 					lpfc_sli_config_mbox_subsys_get
8028 						(phba, mboxq),
8029 					lpfc_sli_config_mbox_opcode_get
8030 						(phba, mboxq),
8031 					rc, sli4_params->mi_ver);
8032 		}
8033 	} else {
8034 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8035 				"6217 MI is disabled\n");
8036 	}
8037 
8038 	/* Ensure FDMI is enabled for MI if enable_mi is set */
8039 	if (sli4_params->mi_ver)
8040 		phba->cfg_fdmi_on = LPFC_FDMI_SUPPORT;
8041 
8042 	/* Always try to enable CMF feature if we can */
8043 	if (sli4_params->cmf) {
8044 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_CMF);
8045 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8046 		cmf = bf_get(lpfc_mbx_set_feature_cmf,
8047 			     &mboxq->u.mqe.un.set_feature);
8048 		if (rc == MBX_SUCCESS && cmf) {
8049 			lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8050 					"6218 CMF is enabled: mode %d\n",
8051 					phba->cmf_active_mode);
8052 		} else {
8053 			lpfc_printf_log(phba, KERN_WARNING,
8054 					LOG_CGN_MGMT | LOG_INIT,
8055 					"6219 Enable CMF Mailbox x%x (x%x/x%x) "
8056 					"failed, rc:x%x dd:x%x\n",
8057 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8058 					lpfc_sli_config_mbox_subsys_get
8059 						(phba, mboxq),
8060 					lpfc_sli_config_mbox_opcode_get
8061 						(phba, mboxq),
8062 					rc, cmf);
8063 			sli4_params->cmf = 0;
8064 			phba->cmf_active_mode = LPFC_CFG_OFF;
8065 			goto no_cmf;
8066 		}
8067 
8068 		/* Allocate Congestion Information Buffer */
8069 		if (!phba->cgn_i) {
8070 			mp = kmalloc(sizeof(*mp), GFP_KERNEL);
8071 			if (mp)
8072 				mp->virt = dma_alloc_coherent
8073 						(&phba->pcidev->dev,
8074 						sizeof(struct lpfc_cgn_info),
8075 						&mp->phys, GFP_KERNEL);
8076 			if (!mp || !mp->virt) {
8077 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8078 						"2640 Failed to alloc memory "
8079 						"for Congestion Info\n");
8080 				kfree(mp);
8081 				sli4_params->cmf = 0;
8082 				phba->cmf_active_mode = LPFC_CFG_OFF;
8083 				goto no_cmf;
8084 			}
8085 			phba->cgn_i = mp;
8086 
8087 			/* initialize congestion buffer info */
8088 			lpfc_init_congestion_buf(phba);
8089 			lpfc_init_congestion_stat(phba);
8090 
8091 			/* Zero out Congestion Signal counters */
8092 			atomic64_set(&phba->cgn_acqe_stat.alarm, 0);
8093 			atomic64_set(&phba->cgn_acqe_stat.warn, 0);
8094 		}
8095 
8096 		rc = lpfc_sli4_cgn_params_read(phba);
8097 		if (rc < 0) {
8098 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8099 					"6242 Error reading Cgn Params (%d)\n",
8100 					rc);
8101 			/* Ensure CGN Mode is off */
8102 			sli4_params->cmf = 0;
8103 		} else if (!rc) {
8104 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8105 					"6243 CGN Event empty object.\n");
8106 			/* Ensure CGN Mode is off */
8107 			sli4_params->cmf = 0;
8108 		}
8109 	} else {
8110 no_cmf:
8111 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8112 				"6220 CMF is disabled\n");
8113 	}
8114 
8115 	/* Only register congestion buffer with firmware if BOTH
8116 	 * CMF and E2E are enabled.
8117 	 */
8118 	if (sli4_params->cmf && sli4_params->mi_ver) {
8119 		rc = lpfc_reg_congestion_buf(phba);
8120 		if (rc) {
8121 			dma_free_coherent(&phba->pcidev->dev,
8122 					  sizeof(struct lpfc_cgn_info),
8123 					  phba->cgn_i->virt, phba->cgn_i->phys);
8124 			kfree(phba->cgn_i);
8125 			phba->cgn_i = NULL;
8126 			/* Ensure CGN Mode is off */
8127 			phba->cmf_active_mode = LPFC_CFG_OFF;
8128 			return 0;
8129 		}
8130 	}
8131 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8132 			"6470 Setup MI version %d CMF %d mode %d\n",
8133 			sli4_params->mi_ver, sli4_params->cmf,
8134 			phba->cmf_active_mode);
8135 
8136 	mempool_free(mboxq, phba->mbox_mem_pool);
8137 
8138 	/* Initialize atomic counters */
8139 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
8140 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
8141 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
8142 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
8143 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
8144 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
8145 	atomic64_set(&phba->cgn_latency_evt, 0);
8146 
8147 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
8148 
8149 	/* Allocate RX Monitor Buffer */
8150 	if (!phba->rxtable) {
8151 		phba->rxtable = kmalloc_array(LPFC_MAX_RXMONITOR_ENTRY,
8152 					      sizeof(struct rxtable_entry),
8153 					      GFP_KERNEL);
8154 		if (!phba->rxtable) {
8155 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8156 					"2644 Failed to alloc memory "
8157 					"for RX Monitor Buffer\n");
8158 			return -ENOMEM;
8159 		}
8160 	}
8161 	atomic_set(&phba->rxtable_idx_head, 0);
8162 	atomic_set(&phba->rxtable_idx_tail, 0);
8163 	return 0;
8164 }
8165 
8166 static int
8167 lpfc_set_host_tm(struct lpfc_hba *phba)
8168 {
8169 	LPFC_MBOXQ_t *mboxq;
8170 	uint32_t len, rc;
8171 	struct timespec64 cur_time;
8172 	struct tm broken;
8173 	uint32_t month, day, year;
8174 	uint32_t hour, minute, second;
8175 	struct lpfc_mbx_set_host_date_time *tm;
8176 
8177 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8178 	if (!mboxq)
8179 		return -ENOMEM;
8180 
8181 	len = sizeof(struct lpfc_mbx_set_host_data) -
8182 		sizeof(struct lpfc_sli4_cfg_mhdr);
8183 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
8184 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
8185 			 LPFC_SLI4_MBX_EMBED);
8186 
8187 	mboxq->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_DATE_TIME;
8188 	mboxq->u.mqe.un.set_host_data.param_len =
8189 			sizeof(struct lpfc_mbx_set_host_date_time);
8190 	tm = &mboxq->u.mqe.un.set_host_data.un.tm;
8191 	ktime_get_real_ts64(&cur_time);
8192 	time64_to_tm(cur_time.tv_sec, 0, &broken);
8193 	month = broken.tm_mon + 1;
8194 	day = broken.tm_mday;
8195 	year = broken.tm_year - 100;
8196 	hour = broken.tm_hour;
8197 	minute = broken.tm_min;
8198 	second = broken.tm_sec;
8199 	bf_set(lpfc_mbx_set_host_month, tm, month);
8200 	bf_set(lpfc_mbx_set_host_day, tm, day);
8201 	bf_set(lpfc_mbx_set_host_year, tm, year);
8202 	bf_set(lpfc_mbx_set_host_hour, tm, hour);
8203 	bf_set(lpfc_mbx_set_host_min, tm, minute);
8204 	bf_set(lpfc_mbx_set_host_sec, tm, second);
8205 
8206 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8207 	mempool_free(mboxq, phba->mbox_mem_pool);
8208 	return rc;
8209 }
8210 
8211 /**
8212  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
8213  * @phba: Pointer to HBA context object.
8214  *
8215  * This function is the main SLI4 device initialization PCI function. This
8216  * function is called by the HBA initialization code, HBA reset code and
8217  * HBA error attention handler code. Caller is not required to hold any
8218  * locks.
8219  **/
8220 int
8221 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
8222 {
8223 	int rc, i, cnt, len, dd;
8224 	LPFC_MBOXQ_t *mboxq;
8225 	struct lpfc_mqe *mqe;
8226 	uint8_t *vpd;
8227 	uint32_t vpd_size;
8228 	uint32_t ftr_rsp = 0;
8229 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
8230 	struct lpfc_vport *vport = phba->pport;
8231 	struct lpfc_dmabuf *mp;
8232 	struct lpfc_rqb *rqbp;
8233 	u32 flg;
8234 
8235 	/* Perform a PCI function reset to start from clean */
8236 	rc = lpfc_pci_function_reset(phba);
8237 	if (unlikely(rc))
8238 		return -ENODEV;
8239 
8240 	/* Check the HBA Host Status Register for readyness */
8241 	rc = lpfc_sli4_post_status_check(phba);
8242 	if (unlikely(rc))
8243 		return -ENODEV;
8244 	else {
8245 		spin_lock_irq(&phba->hbalock);
8246 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
8247 		flg = phba->sli.sli_flag;
8248 		spin_unlock_irq(&phba->hbalock);
8249 		/* Allow a little time after setting SLI_ACTIVE for any polled
8250 		 * MBX commands to complete via BSG.
8251 		 */
8252 		for (i = 0; i < 50 && (flg & LPFC_SLI_MBOX_ACTIVE); i++) {
8253 			msleep(20);
8254 			spin_lock_irq(&phba->hbalock);
8255 			flg = phba->sli.sli_flag;
8256 			spin_unlock_irq(&phba->hbalock);
8257 		}
8258 	}
8259 
8260 	lpfc_sli4_dip(phba);
8261 
8262 	/*
8263 	 * Allocate a single mailbox container for initializing the
8264 	 * port.
8265 	 */
8266 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8267 	if (!mboxq)
8268 		return -ENOMEM;
8269 
8270 	/* Issue READ_REV to collect vpd and FW information. */
8271 	vpd_size = SLI4_PAGE_SIZE;
8272 	vpd = kzalloc(vpd_size, GFP_KERNEL);
8273 	if (!vpd) {
8274 		rc = -ENOMEM;
8275 		goto out_free_mbox;
8276 	}
8277 
8278 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
8279 	if (unlikely(rc)) {
8280 		kfree(vpd);
8281 		goto out_free_mbox;
8282 	}
8283 
8284 	mqe = &mboxq->u.mqe;
8285 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
8286 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
8287 		phba->hba_flag |= HBA_FCOE_MODE;
8288 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
8289 	} else {
8290 		phba->hba_flag &= ~HBA_FCOE_MODE;
8291 	}
8292 
8293 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
8294 		LPFC_DCBX_CEE_MODE)
8295 		phba->hba_flag |= HBA_FIP_SUPPORT;
8296 	else
8297 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
8298 
8299 	phba->hba_flag &= ~HBA_IOQ_FLUSH;
8300 
8301 	if (phba->sli_rev != LPFC_SLI_REV4) {
8302 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8303 			"0376 READ_REV Error. SLI Level %d "
8304 			"FCoE enabled %d\n",
8305 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
8306 		rc = -EIO;
8307 		kfree(vpd);
8308 		goto out_free_mbox;
8309 	}
8310 
8311 	rc = lpfc_set_host_tm(phba);
8312 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
8313 			"6468 Set host date / time: Status x%x:\n", rc);
8314 
8315 	/*
8316 	 * Continue initialization with default values even if driver failed
8317 	 * to read FCoE param config regions, only read parameters if the
8318 	 * board is FCoE
8319 	 */
8320 	if (phba->hba_flag & HBA_FCOE_MODE &&
8321 	    lpfc_sli4_read_fcoe_params(phba))
8322 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
8323 			"2570 Failed to read FCoE parameters\n");
8324 
8325 	/*
8326 	 * Retrieve sli4 device physical port name, failure of doing it
8327 	 * is considered as non-fatal.
8328 	 */
8329 	rc = lpfc_sli4_retrieve_pport_name(phba);
8330 	if (!rc)
8331 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8332 				"3080 Successful retrieving SLI4 device "
8333 				"physical port name: %s.\n", phba->Port);
8334 
8335 	rc = lpfc_sli4_get_ctl_attr(phba);
8336 	if (!rc)
8337 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8338 				"8351 Successful retrieving SLI4 device "
8339 				"CTL ATTR\n");
8340 
8341 	/*
8342 	 * Evaluate the read rev and vpd data. Populate the driver
8343 	 * state with the results. If this routine fails, the failure
8344 	 * is not fatal as the driver will use generic values.
8345 	 */
8346 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
8347 	if (unlikely(!rc)) {
8348 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8349 				"0377 Error %d parsing vpd. "
8350 				"Using defaults.\n", rc);
8351 		rc = 0;
8352 	}
8353 	kfree(vpd);
8354 
8355 	/* Save information as VPD data */
8356 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
8357 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
8358 
8359 	/*
8360 	 * This is because first G7 ASIC doesn't support the standard
8361 	 * 0x5a NVME cmd descriptor type/subtype
8362 	 */
8363 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8364 			LPFC_SLI_INTF_IF_TYPE_6) &&
8365 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
8366 	    (phba->vpd.rev.smRev == 0) &&
8367 	    (phba->cfg_nvme_embed_cmd == 1))
8368 		phba->cfg_nvme_embed_cmd = 0;
8369 
8370 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
8371 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
8372 					 &mqe->un.read_rev);
8373 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
8374 				       &mqe->un.read_rev);
8375 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
8376 					    &mqe->un.read_rev);
8377 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
8378 					   &mqe->un.read_rev);
8379 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
8380 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
8381 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
8382 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
8383 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
8384 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
8385 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8386 			"(%d):0380 READ_REV Status x%x "
8387 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
8388 			mboxq->vport ? mboxq->vport->vpi : 0,
8389 			bf_get(lpfc_mqe_status, mqe),
8390 			phba->vpd.rev.opFwName,
8391 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
8392 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
8393 
8394 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8395 	    LPFC_SLI_INTF_IF_TYPE_0) {
8396 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
8397 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8398 		if (rc == MBX_SUCCESS) {
8399 			phba->hba_flag |= HBA_RECOVERABLE_UE;
8400 			/* Set 1Sec interval to detect UE */
8401 			phba->eratt_poll_interval = 1;
8402 			phba->sli4_hba.ue_to_sr = bf_get(
8403 					lpfc_mbx_set_feature_UESR,
8404 					&mboxq->u.mqe.un.set_feature);
8405 			phba->sli4_hba.ue_to_rp = bf_get(
8406 					lpfc_mbx_set_feature_UERP,
8407 					&mboxq->u.mqe.un.set_feature);
8408 		}
8409 	}
8410 
8411 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
8412 		/* Enable MDS Diagnostics only if the SLI Port supports it */
8413 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
8414 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8415 		if (rc != MBX_SUCCESS)
8416 			phba->mds_diags_support = 0;
8417 	}
8418 
8419 	/*
8420 	 * Discover the port's supported feature set and match it against the
8421 	 * hosts requests.
8422 	 */
8423 	lpfc_request_features(phba, mboxq);
8424 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8425 	if (unlikely(rc)) {
8426 		rc = -EIO;
8427 		goto out_free_mbox;
8428 	}
8429 
8430 	/* Disable VMID if app header is not supported */
8431 	if (phba->cfg_vmid_app_header && !(bf_get(lpfc_mbx_rq_ftr_rsp_ashdr,
8432 						  &mqe->un.req_ftrs))) {
8433 		bf_set(lpfc_ftr_ashdr, &phba->sli4_hba.sli4_flags, 0);
8434 		phba->cfg_vmid_app_header = 0;
8435 		lpfc_printf_log(phba, KERN_DEBUG, LOG_SLI,
8436 				"1242 vmid feature not supported\n");
8437 	}
8438 
8439 	/*
8440 	 * The port must support FCP initiator mode as this is the
8441 	 * only mode running in the host.
8442 	 */
8443 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
8444 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8445 				"0378 No support for fcpi mode.\n");
8446 		ftr_rsp++;
8447 	}
8448 
8449 	/* Performance Hints are ONLY for FCoE */
8450 	if (phba->hba_flag & HBA_FCOE_MODE) {
8451 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
8452 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
8453 		else
8454 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
8455 	}
8456 
8457 	/*
8458 	 * If the port cannot support the host's requested features
8459 	 * then turn off the global config parameters to disable the
8460 	 * feature in the driver.  This is not a fatal error.
8461 	 */
8462 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8463 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
8464 			phba->cfg_enable_bg = 0;
8465 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
8466 			ftr_rsp++;
8467 		}
8468 	}
8469 
8470 	if (phba->max_vpi && phba->cfg_enable_npiv &&
8471 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8472 		ftr_rsp++;
8473 
8474 	if (ftr_rsp) {
8475 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8476 				"0379 Feature Mismatch Data: x%08x %08x "
8477 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
8478 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
8479 				phba->cfg_enable_npiv, phba->max_vpi);
8480 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
8481 			phba->cfg_enable_bg = 0;
8482 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8483 			phba->cfg_enable_npiv = 0;
8484 	}
8485 
8486 	/* These SLI3 features are assumed in SLI4 */
8487 	spin_lock_irq(&phba->hbalock);
8488 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
8489 	spin_unlock_irq(&phba->hbalock);
8490 
8491 	/* Always try to enable dual dump feature if we can */
8492 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
8493 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8494 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
8495 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
8496 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8497 				"6448 Dual Dump is enabled\n");
8498 	else
8499 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
8500 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
8501 				"rc:x%x dd:x%x\n",
8502 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8503 				lpfc_sli_config_mbox_subsys_get(
8504 					phba, mboxq),
8505 				lpfc_sli_config_mbox_opcode_get(
8506 					phba, mboxq),
8507 				rc, dd);
8508 	/*
8509 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
8510 	 * calls depends on these resources to complete port setup.
8511 	 */
8512 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
8513 	if (rc) {
8514 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8515 				"2920 Failed to alloc Resource IDs "
8516 				"rc = x%x\n", rc);
8517 		goto out_free_mbox;
8518 	}
8519 
8520 	lpfc_set_host_data(phba, mboxq);
8521 
8522 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8523 	if (rc) {
8524 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8525 				"2134 Failed to set host os driver version %x",
8526 				rc);
8527 	}
8528 
8529 	/* Read the port's service parameters. */
8530 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
8531 	if (rc) {
8532 		phba->link_state = LPFC_HBA_ERROR;
8533 		rc = -ENOMEM;
8534 		goto out_free_mbox;
8535 	}
8536 
8537 	mboxq->vport = vport;
8538 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8539 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
8540 	if (rc == MBX_SUCCESS) {
8541 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
8542 		rc = 0;
8543 	}
8544 
8545 	/*
8546 	 * This memory was allocated by the lpfc_read_sparam routine. Release
8547 	 * it to the mbuf pool.
8548 	 */
8549 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
8550 	kfree(mp);
8551 	mboxq->ctx_buf = NULL;
8552 	if (unlikely(rc)) {
8553 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8554 				"0382 READ_SPARAM command failed "
8555 				"status %d, mbxStatus x%x\n",
8556 				rc, bf_get(lpfc_mqe_status, mqe));
8557 		phba->link_state = LPFC_HBA_ERROR;
8558 		rc = -EIO;
8559 		goto out_free_mbox;
8560 	}
8561 
8562 	lpfc_update_vport_wwn(vport);
8563 
8564 	/* Update the fc_host data structures with new wwn. */
8565 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
8566 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
8567 
8568 	/* Create all the SLI4 queues */
8569 	rc = lpfc_sli4_queue_create(phba);
8570 	if (rc) {
8571 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8572 				"3089 Failed to allocate queues\n");
8573 		rc = -ENODEV;
8574 		goto out_free_mbox;
8575 	}
8576 	/* Set up all the queues to the device */
8577 	rc = lpfc_sli4_queue_setup(phba);
8578 	if (unlikely(rc)) {
8579 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8580 				"0381 Error %d during queue setup.\n ", rc);
8581 		goto out_stop_timers;
8582 	}
8583 	/* Initialize the driver internal SLI layer lists. */
8584 	lpfc_sli4_setup(phba);
8585 	lpfc_sli4_queue_init(phba);
8586 
8587 	/* update host els xri-sgl sizes and mappings */
8588 	rc = lpfc_sli4_els_sgl_update(phba);
8589 	if (unlikely(rc)) {
8590 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8591 				"1400 Failed to update xri-sgl size and "
8592 				"mapping: %d\n", rc);
8593 		goto out_destroy_queue;
8594 	}
8595 
8596 	/* register the els sgl pool to the port */
8597 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
8598 				       phba->sli4_hba.els_xri_cnt);
8599 	if (unlikely(rc < 0)) {
8600 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8601 				"0582 Error %d during els sgl post "
8602 				"operation\n", rc);
8603 		rc = -ENODEV;
8604 		goto out_destroy_queue;
8605 	}
8606 	phba->sli4_hba.els_xri_cnt = rc;
8607 
8608 	if (phba->nvmet_support) {
8609 		/* update host nvmet xri-sgl sizes and mappings */
8610 		rc = lpfc_sli4_nvmet_sgl_update(phba);
8611 		if (unlikely(rc)) {
8612 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8613 					"6308 Failed to update nvmet-sgl size "
8614 					"and mapping: %d\n", rc);
8615 			goto out_destroy_queue;
8616 		}
8617 
8618 		/* register the nvmet sgl pool to the port */
8619 		rc = lpfc_sli4_repost_sgl_list(
8620 			phba,
8621 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
8622 			phba->sli4_hba.nvmet_xri_cnt);
8623 		if (unlikely(rc < 0)) {
8624 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8625 					"3117 Error %d during nvmet "
8626 					"sgl post\n", rc);
8627 			rc = -ENODEV;
8628 			goto out_destroy_queue;
8629 		}
8630 		phba->sli4_hba.nvmet_xri_cnt = rc;
8631 
8632 		/* We allocate an iocbq for every receive context SGL.
8633 		 * The additional allocation is for abort and ls handling.
8634 		 */
8635 		cnt = phba->sli4_hba.nvmet_xri_cnt +
8636 			phba->sli4_hba.max_cfg_param.max_xri;
8637 	} else {
8638 		/* update host common xri-sgl sizes and mappings */
8639 		rc = lpfc_sli4_io_sgl_update(phba);
8640 		if (unlikely(rc)) {
8641 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8642 					"6082 Failed to update nvme-sgl size "
8643 					"and mapping: %d\n", rc);
8644 			goto out_destroy_queue;
8645 		}
8646 
8647 		/* register the allocated common sgl pool to the port */
8648 		rc = lpfc_sli4_repost_io_sgl_list(phba);
8649 		if (unlikely(rc)) {
8650 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8651 					"6116 Error %d during nvme sgl post "
8652 					"operation\n", rc);
8653 			/* Some NVME buffers were moved to abort nvme list */
8654 			/* A pci function reset will repost them */
8655 			rc = -ENODEV;
8656 			goto out_destroy_queue;
8657 		}
8658 		/* Each lpfc_io_buf job structure has an iocbq element.
8659 		 * This cnt provides for abort, els, ct and ls requests.
8660 		 */
8661 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
8662 	}
8663 
8664 	if (!phba->sli.iocbq_lookup) {
8665 		/* Initialize and populate the iocb list per host */
8666 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8667 				"2821 initialize iocb list with %d entries\n",
8668 				cnt);
8669 		rc = lpfc_init_iocb_list(phba, cnt);
8670 		if (rc) {
8671 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8672 					"1413 Failed to init iocb list.\n");
8673 			goto out_destroy_queue;
8674 		}
8675 	}
8676 
8677 	if (phba->nvmet_support)
8678 		lpfc_nvmet_create_targetport(phba);
8679 
8680 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
8681 		/* Post initial buffers to all RQs created */
8682 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
8683 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
8684 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
8685 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
8686 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
8687 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
8688 			rqbp->buffer_count = 0;
8689 
8690 			lpfc_post_rq_buffer(
8691 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
8692 				phba->sli4_hba.nvmet_mrq_data[i],
8693 				phba->cfg_nvmet_mrq_post, i);
8694 		}
8695 	}
8696 
8697 	/* Post the rpi header region to the device. */
8698 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
8699 	if (unlikely(rc)) {
8700 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8701 				"0393 Error %d during rpi post operation\n",
8702 				rc);
8703 		rc = -ENODEV;
8704 		goto out_free_iocblist;
8705 	}
8706 	lpfc_sli4_node_prep(phba);
8707 
8708 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
8709 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
8710 			/*
8711 			 * The FC Port needs to register FCFI (index 0)
8712 			 */
8713 			lpfc_reg_fcfi(phba, mboxq);
8714 			mboxq->vport = phba->pport;
8715 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8716 			if (rc != MBX_SUCCESS)
8717 				goto out_unset_queue;
8718 			rc = 0;
8719 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
8720 						&mboxq->u.mqe.un.reg_fcfi);
8721 		} else {
8722 			/* We are a NVME Target mode with MRQ > 1 */
8723 
8724 			/* First register the FCFI */
8725 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
8726 			mboxq->vport = phba->pport;
8727 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8728 			if (rc != MBX_SUCCESS)
8729 				goto out_unset_queue;
8730 			rc = 0;
8731 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
8732 						&mboxq->u.mqe.un.reg_fcfi_mrq);
8733 
8734 			/* Next register the MRQs */
8735 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
8736 			mboxq->vport = phba->pport;
8737 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8738 			if (rc != MBX_SUCCESS)
8739 				goto out_unset_queue;
8740 			rc = 0;
8741 		}
8742 		/* Check if the port is configured to be disabled */
8743 		lpfc_sli_read_link_ste(phba);
8744 	}
8745 
8746 	/* Don't post more new bufs if repost already recovered
8747 	 * the nvme sgls.
8748 	 */
8749 	if (phba->nvmet_support == 0) {
8750 		if (phba->sli4_hba.io_xri_cnt == 0) {
8751 			len = lpfc_new_io_buf(
8752 					      phba, phba->sli4_hba.io_xri_max);
8753 			if (len == 0) {
8754 				rc = -ENOMEM;
8755 				goto out_unset_queue;
8756 			}
8757 
8758 			if (phba->cfg_xri_rebalancing)
8759 				lpfc_create_multixri_pools(phba);
8760 		}
8761 	} else {
8762 		phba->cfg_xri_rebalancing = 0;
8763 	}
8764 
8765 	/* Allow asynchronous mailbox command to go through */
8766 	spin_lock_irq(&phba->hbalock);
8767 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8768 	spin_unlock_irq(&phba->hbalock);
8769 
8770 	/* Post receive buffers to the device */
8771 	lpfc_sli4_rb_setup(phba);
8772 
8773 	/* Reset HBA FCF states after HBA reset */
8774 	phba->fcf.fcf_flag = 0;
8775 	phba->fcf.current_rec.flag = 0;
8776 
8777 	/* Start the ELS watchdog timer */
8778 	mod_timer(&vport->els_tmofunc,
8779 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
8780 
8781 	/* Start heart beat timer */
8782 	mod_timer(&phba->hb_tmofunc,
8783 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
8784 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
8785 	phba->last_completion_time = jiffies;
8786 
8787 	/* start eq_delay heartbeat */
8788 	if (phba->cfg_auto_imax)
8789 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
8790 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
8791 
8792 	/* start per phba idle_stat_delay heartbeat */
8793 	lpfc_init_idle_stat_hb(phba);
8794 
8795 	/* Start error attention (ERATT) polling timer */
8796 	mod_timer(&phba->eratt_poll,
8797 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
8798 
8799 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
8800 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
8801 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
8802 		if (!rc) {
8803 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8804 					"2829 This device supports "
8805 					"Advanced Error Reporting (AER)\n");
8806 			spin_lock_irq(&phba->hbalock);
8807 			phba->hba_flag |= HBA_AER_ENABLED;
8808 			spin_unlock_irq(&phba->hbalock);
8809 		} else {
8810 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8811 					"2830 This device does not support "
8812 					"Advanced Error Reporting (AER)\n");
8813 			phba->cfg_aer_support = 0;
8814 		}
8815 		rc = 0;
8816 	}
8817 
8818 	/*
8819 	 * The port is ready, set the host's link state to LINK_DOWN
8820 	 * in preparation for link interrupts.
8821 	 */
8822 	spin_lock_irq(&phba->hbalock);
8823 	phba->link_state = LPFC_LINK_DOWN;
8824 
8825 	/* Check if physical ports are trunked */
8826 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
8827 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
8828 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
8829 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
8830 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
8831 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
8832 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
8833 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
8834 	spin_unlock_irq(&phba->hbalock);
8835 
8836 	/* Arm the CQs and then EQs on device */
8837 	lpfc_sli4_arm_cqeq_intr(phba);
8838 
8839 	/* Indicate device interrupt mode */
8840 	phba->sli4_hba.intr_enable = 1;
8841 
8842 	/* Setup CMF after HBA is initialized */
8843 	lpfc_cmf_setup(phba);
8844 
8845 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
8846 	    (phba->hba_flag & LINK_DISABLED)) {
8847 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8848 				"3103 Adapter Link is disabled.\n");
8849 		lpfc_down_link(phba, mboxq);
8850 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8851 		if (rc != MBX_SUCCESS) {
8852 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8853 					"3104 Adapter failed to issue "
8854 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
8855 			goto out_io_buff_free;
8856 		}
8857 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
8858 		/* don't perform init_link on SLI4 FC port loopback test */
8859 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
8860 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
8861 			if (rc)
8862 				goto out_io_buff_free;
8863 		}
8864 	}
8865 	mempool_free(mboxq, phba->mbox_mem_pool);
8866 
8867 	phba->hba_flag |= HBA_SETUP;
8868 	return rc;
8869 
8870 out_io_buff_free:
8871 	/* Free allocated IO Buffers */
8872 	lpfc_io_free(phba);
8873 out_unset_queue:
8874 	/* Unset all the queues set up in this routine when error out */
8875 	lpfc_sli4_queue_unset(phba);
8876 out_free_iocblist:
8877 	lpfc_free_iocb_list(phba);
8878 out_destroy_queue:
8879 	lpfc_sli4_queue_destroy(phba);
8880 out_stop_timers:
8881 	lpfc_stop_hba_timers(phba);
8882 out_free_mbox:
8883 	mempool_free(mboxq, phba->mbox_mem_pool);
8884 	return rc;
8885 }
8886 
8887 /**
8888  * lpfc_mbox_timeout - Timeout call back function for mbox timer
8889  * @t: Context to fetch pointer to hba structure from.
8890  *
8891  * This is the callback function for mailbox timer. The mailbox
8892  * timer is armed when a new mailbox command is issued and the timer
8893  * is deleted when the mailbox complete. The function is called by
8894  * the kernel timer code when a mailbox does not complete within
8895  * expected time. This function wakes up the worker thread to
8896  * process the mailbox timeout and returns. All the processing is
8897  * done by the worker thread function lpfc_mbox_timeout_handler.
8898  **/
8899 void
8900 lpfc_mbox_timeout(struct timer_list *t)
8901 {
8902 	struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
8903 	unsigned long iflag;
8904 	uint32_t tmo_posted;
8905 
8906 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
8907 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
8908 	if (!tmo_posted)
8909 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
8910 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
8911 
8912 	if (!tmo_posted)
8913 		lpfc_worker_wake_up(phba);
8914 	return;
8915 }
8916 
8917 /**
8918  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
8919  *                                    are pending
8920  * @phba: Pointer to HBA context object.
8921  *
8922  * This function checks if any mailbox completions are present on the mailbox
8923  * completion queue.
8924  **/
8925 static bool
8926 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
8927 {
8928 
8929 	uint32_t idx;
8930 	struct lpfc_queue *mcq;
8931 	struct lpfc_mcqe *mcqe;
8932 	bool pending_completions = false;
8933 	uint8_t	qe_valid;
8934 
8935 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8936 		return false;
8937 
8938 	/* Check for completions on mailbox completion queue */
8939 
8940 	mcq = phba->sli4_hba.mbx_cq;
8941 	idx = mcq->hba_index;
8942 	qe_valid = mcq->qe_valid;
8943 	while (bf_get_le32(lpfc_cqe_valid,
8944 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
8945 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
8946 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
8947 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
8948 			pending_completions = true;
8949 			break;
8950 		}
8951 		idx = (idx + 1) % mcq->entry_count;
8952 		if (mcq->hba_index == idx)
8953 			break;
8954 
8955 		/* if the index wrapped around, toggle the valid bit */
8956 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
8957 			qe_valid = (qe_valid) ? 0 : 1;
8958 	}
8959 	return pending_completions;
8960 
8961 }
8962 
8963 /**
8964  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
8965  *					      that were missed.
8966  * @phba: Pointer to HBA context object.
8967  *
8968  * For sli4, it is possible to miss an interrupt. As such mbox completions
8969  * maybe missed causing erroneous mailbox timeouts to occur. This function
8970  * checks to see if mbox completions are on the mailbox completion queue
8971  * and will process all the completions associated with the eq for the
8972  * mailbox completion queue.
8973  **/
8974 static bool
8975 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
8976 {
8977 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
8978 	uint32_t eqidx;
8979 	struct lpfc_queue *fpeq = NULL;
8980 	struct lpfc_queue *eq;
8981 	bool mbox_pending;
8982 
8983 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8984 		return false;
8985 
8986 	/* Find the EQ associated with the mbox CQ */
8987 	if (sli4_hba->hdwq) {
8988 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
8989 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
8990 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
8991 				fpeq = eq;
8992 				break;
8993 			}
8994 		}
8995 	}
8996 	if (!fpeq)
8997 		return false;
8998 
8999 	/* Turn off interrupts from this EQ */
9000 
9001 	sli4_hba->sli4_eq_clr_intr(fpeq);
9002 
9003 	/* Check to see if a mbox completion is pending */
9004 
9005 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
9006 
9007 	/*
9008 	 * If a mbox completion is pending, process all the events on EQ
9009 	 * associated with the mbox completion queue (this could include
9010 	 * mailbox commands, async events, els commands, receive queue data
9011 	 * and fcp commands)
9012 	 */
9013 
9014 	if (mbox_pending)
9015 		/* process and rearm the EQ */
9016 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
9017 	else
9018 		/* Always clear and re-arm the EQ */
9019 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
9020 
9021 	return mbox_pending;
9022 
9023 }
9024 
9025 /**
9026  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
9027  * @phba: Pointer to HBA context object.
9028  *
9029  * This function is called from worker thread when a mailbox command times out.
9030  * The caller is not required to hold any locks. This function will reset the
9031  * HBA and recover all the pending commands.
9032  **/
9033 void
9034 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
9035 {
9036 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
9037 	MAILBOX_t *mb = NULL;
9038 
9039 	struct lpfc_sli *psli = &phba->sli;
9040 
9041 	/* If the mailbox completed, process the completion */
9042 	lpfc_sli4_process_missed_mbox_completions(phba);
9043 
9044 	if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
9045 		return;
9046 
9047 	if (pmbox != NULL)
9048 		mb = &pmbox->u.mb;
9049 	/* Check the pmbox pointer first.  There is a race condition
9050 	 * between the mbox timeout handler getting executed in the
9051 	 * worklist and the mailbox actually completing. When this
9052 	 * race condition occurs, the mbox_active will be NULL.
9053 	 */
9054 	spin_lock_irq(&phba->hbalock);
9055 	if (pmbox == NULL) {
9056 		lpfc_printf_log(phba, KERN_WARNING,
9057 				LOG_MBOX | LOG_SLI,
9058 				"0353 Active Mailbox cleared - mailbox timeout "
9059 				"exiting\n");
9060 		spin_unlock_irq(&phba->hbalock);
9061 		return;
9062 	}
9063 
9064 	/* Mbox cmd <mbxCommand> timeout */
9065 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9066 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
9067 			mb->mbxCommand,
9068 			phba->pport->port_state,
9069 			phba->sli.sli_flag,
9070 			phba->sli.mbox_active);
9071 	spin_unlock_irq(&phba->hbalock);
9072 
9073 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
9074 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
9075 	 * it to fail all outstanding SCSI IO.
9076 	 */
9077 	spin_lock_irq(&phba->pport->work_port_lock);
9078 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9079 	spin_unlock_irq(&phba->pport->work_port_lock);
9080 	spin_lock_irq(&phba->hbalock);
9081 	phba->link_state = LPFC_LINK_UNKNOWN;
9082 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
9083 	spin_unlock_irq(&phba->hbalock);
9084 
9085 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9086 			"0345 Resetting board due to mailbox timeout\n");
9087 
9088 	/* Reset the HBA device */
9089 	lpfc_reset_hba(phba);
9090 }
9091 
9092 /**
9093  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
9094  * @phba: Pointer to HBA context object.
9095  * @pmbox: Pointer to mailbox object.
9096  * @flag: Flag indicating how the mailbox need to be processed.
9097  *
9098  * This function is called by discovery code and HBA management code
9099  * to submit a mailbox command to firmware with SLI-3 interface spec. This
9100  * function gets the hbalock to protect the data structures.
9101  * The mailbox command can be submitted in polling mode, in which case
9102  * this function will wait in a polling loop for the completion of the
9103  * mailbox.
9104  * If the mailbox is submitted in no_wait mode (not polling) the
9105  * function will submit the command and returns immediately without waiting
9106  * for the mailbox completion. The no_wait is supported only when HBA
9107  * is in SLI2/SLI3 mode - interrupts are enabled.
9108  * The SLI interface allows only one mailbox pending at a time. If the
9109  * mailbox is issued in polling mode and there is already a mailbox
9110  * pending, then the function will return an error. If the mailbox is issued
9111  * in NO_WAIT mode and there is a mailbox pending already, the function
9112  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
9113  * The sli layer owns the mailbox object until the completion of mailbox
9114  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
9115  * return codes the caller owns the mailbox command after the return of
9116  * the function.
9117  **/
9118 static int
9119 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
9120 		       uint32_t flag)
9121 {
9122 	MAILBOX_t *mbx;
9123 	struct lpfc_sli *psli = &phba->sli;
9124 	uint32_t status, evtctr;
9125 	uint32_t ha_copy, hc_copy;
9126 	int i;
9127 	unsigned long timeout;
9128 	unsigned long drvr_flag = 0;
9129 	uint32_t word0, ldata;
9130 	void __iomem *to_slim;
9131 	int processing_queue = 0;
9132 
9133 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
9134 	if (!pmbox) {
9135 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9136 		/* processing mbox queue from intr_handler */
9137 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9138 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9139 			return MBX_SUCCESS;
9140 		}
9141 		processing_queue = 1;
9142 		pmbox = lpfc_mbox_get(phba);
9143 		if (!pmbox) {
9144 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9145 			return MBX_SUCCESS;
9146 		}
9147 	}
9148 
9149 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
9150 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
9151 		if(!pmbox->vport) {
9152 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9153 			lpfc_printf_log(phba, KERN_ERR,
9154 					LOG_MBOX | LOG_VPORT,
9155 					"1806 Mbox x%x failed. No vport\n",
9156 					pmbox->u.mb.mbxCommand);
9157 			dump_stack();
9158 			goto out_not_finished;
9159 		}
9160 	}
9161 
9162 	/* If the PCI channel is in offline state, do not post mbox. */
9163 	if (unlikely(pci_channel_offline(phba->pcidev))) {
9164 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9165 		goto out_not_finished;
9166 	}
9167 
9168 	/* If HBA has a deferred error attention, fail the iocb. */
9169 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
9170 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9171 		goto out_not_finished;
9172 	}
9173 
9174 	psli = &phba->sli;
9175 
9176 	mbx = &pmbox->u.mb;
9177 	status = MBX_SUCCESS;
9178 
9179 	if (phba->link_state == LPFC_HBA_ERROR) {
9180 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9181 
9182 		/* Mbox command <mbxCommand> cannot issue */
9183 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9184 				"(%d):0311 Mailbox command x%x cannot "
9185 				"issue Data: x%x x%x\n",
9186 				pmbox->vport ? pmbox->vport->vpi : 0,
9187 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9188 		goto out_not_finished;
9189 	}
9190 
9191 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
9192 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
9193 			!(hc_copy & HC_MBINT_ENA)) {
9194 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9195 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9196 				"(%d):2528 Mailbox command x%x cannot "
9197 				"issue Data: x%x x%x\n",
9198 				pmbox->vport ? pmbox->vport->vpi : 0,
9199 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9200 			goto out_not_finished;
9201 		}
9202 	}
9203 
9204 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9205 		/* Polling for a mbox command when another one is already active
9206 		 * is not allowed in SLI. Also, the driver must have established
9207 		 * SLI2 mode to queue and process multiple mbox commands.
9208 		 */
9209 
9210 		if (flag & MBX_POLL) {
9211 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9212 
9213 			/* Mbox command <mbxCommand> cannot issue */
9214 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9215 					"(%d):2529 Mailbox command x%x "
9216 					"cannot issue Data: x%x x%x\n",
9217 					pmbox->vport ? pmbox->vport->vpi : 0,
9218 					pmbox->u.mb.mbxCommand,
9219 					psli->sli_flag, flag);
9220 			goto out_not_finished;
9221 		}
9222 
9223 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
9224 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9225 			/* Mbox command <mbxCommand> cannot issue */
9226 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9227 					"(%d):2530 Mailbox command x%x "
9228 					"cannot issue Data: x%x x%x\n",
9229 					pmbox->vport ? pmbox->vport->vpi : 0,
9230 					pmbox->u.mb.mbxCommand,
9231 					psli->sli_flag, flag);
9232 			goto out_not_finished;
9233 		}
9234 
9235 		/* Another mailbox command is still being processed, queue this
9236 		 * command to be processed later.
9237 		 */
9238 		lpfc_mbox_put(phba, pmbox);
9239 
9240 		/* Mbox cmd issue - BUSY */
9241 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9242 				"(%d):0308 Mbox cmd issue - BUSY Data: "
9243 				"x%x x%x x%x x%x\n",
9244 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
9245 				mbx->mbxCommand,
9246 				phba->pport ? phba->pport->port_state : 0xff,
9247 				psli->sli_flag, flag);
9248 
9249 		psli->slistat.mbox_busy++;
9250 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9251 
9252 		if (pmbox->vport) {
9253 			lpfc_debugfs_disc_trc(pmbox->vport,
9254 				LPFC_DISC_TRC_MBOX_VPORT,
9255 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
9256 				(uint32_t)mbx->mbxCommand,
9257 				mbx->un.varWords[0], mbx->un.varWords[1]);
9258 		}
9259 		else {
9260 			lpfc_debugfs_disc_trc(phba->pport,
9261 				LPFC_DISC_TRC_MBOX,
9262 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
9263 				(uint32_t)mbx->mbxCommand,
9264 				mbx->un.varWords[0], mbx->un.varWords[1]);
9265 		}
9266 
9267 		return MBX_BUSY;
9268 	}
9269 
9270 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9271 
9272 	/* If we are not polling, we MUST be in SLI2 mode */
9273 	if (flag != MBX_POLL) {
9274 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
9275 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
9276 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9277 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9278 			/* Mbox command <mbxCommand> cannot issue */
9279 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9280 					"(%d):2531 Mailbox command x%x "
9281 					"cannot issue Data: x%x x%x\n",
9282 					pmbox->vport ? pmbox->vport->vpi : 0,
9283 					pmbox->u.mb.mbxCommand,
9284 					psli->sli_flag, flag);
9285 			goto out_not_finished;
9286 		}
9287 		/* timeout active mbox command */
9288 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9289 					   1000);
9290 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
9291 	}
9292 
9293 	/* Mailbox cmd <cmd> issue */
9294 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9295 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
9296 			"x%x\n",
9297 			pmbox->vport ? pmbox->vport->vpi : 0,
9298 			mbx->mbxCommand,
9299 			phba->pport ? phba->pport->port_state : 0xff,
9300 			psli->sli_flag, flag);
9301 
9302 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
9303 		if (pmbox->vport) {
9304 			lpfc_debugfs_disc_trc(pmbox->vport,
9305 				LPFC_DISC_TRC_MBOX_VPORT,
9306 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9307 				(uint32_t)mbx->mbxCommand,
9308 				mbx->un.varWords[0], mbx->un.varWords[1]);
9309 		}
9310 		else {
9311 			lpfc_debugfs_disc_trc(phba->pport,
9312 				LPFC_DISC_TRC_MBOX,
9313 				"MBOX Send:       cmd:x%x mb:x%x x%x",
9314 				(uint32_t)mbx->mbxCommand,
9315 				mbx->un.varWords[0], mbx->un.varWords[1]);
9316 		}
9317 	}
9318 
9319 	psli->slistat.mbox_cmd++;
9320 	evtctr = psli->slistat.mbox_event;
9321 
9322 	/* next set own bit for the adapter and copy over command word */
9323 	mbx->mbxOwner = OWN_CHIP;
9324 
9325 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9326 		/* Populate mbox extension offset word. */
9327 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
9328 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9329 				= (uint8_t *)phba->mbox_ext
9330 				  - (uint8_t *)phba->mbox;
9331 		}
9332 
9333 		/* Copy the mailbox extension data */
9334 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
9335 			lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
9336 					      (uint8_t *)phba->mbox_ext,
9337 					      pmbox->in_ext_byte_len);
9338 		}
9339 		/* Copy command data to host SLIM area */
9340 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
9341 	} else {
9342 		/* Populate mbox extension offset word. */
9343 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
9344 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9345 				= MAILBOX_HBA_EXT_OFFSET;
9346 
9347 		/* Copy the mailbox extension data */
9348 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
9349 			lpfc_memcpy_to_slim(phba->MBslimaddr +
9350 				MAILBOX_HBA_EXT_OFFSET,
9351 				pmbox->ctx_buf, pmbox->in_ext_byte_len);
9352 
9353 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9354 			/* copy command data into host mbox for cmpl */
9355 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
9356 					      MAILBOX_CMD_SIZE);
9357 
9358 		/* First copy mbox command data to HBA SLIM, skip past first
9359 		   word */
9360 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
9361 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
9362 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
9363 
9364 		/* Next copy over first word, with mbxOwner set */
9365 		ldata = *((uint32_t *)mbx);
9366 		to_slim = phba->MBslimaddr;
9367 		writel(ldata, to_slim);
9368 		readl(to_slim); /* flush */
9369 
9370 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9371 			/* switch over to host mailbox */
9372 			psli->sli_flag |= LPFC_SLI_ACTIVE;
9373 	}
9374 
9375 	wmb();
9376 
9377 	switch (flag) {
9378 	case MBX_NOWAIT:
9379 		/* Set up reference to mailbox command */
9380 		psli->mbox_active = pmbox;
9381 		/* Interrupt board to do it */
9382 		writel(CA_MBATT, phba->CAregaddr);
9383 		readl(phba->CAregaddr); /* flush */
9384 		/* Don't wait for it to finish, just return */
9385 		break;
9386 
9387 	case MBX_POLL:
9388 		/* Set up null reference to mailbox command */
9389 		psli->mbox_active = NULL;
9390 		/* Interrupt board to do it */
9391 		writel(CA_MBATT, phba->CAregaddr);
9392 		readl(phba->CAregaddr); /* flush */
9393 
9394 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9395 			/* First read mbox status word */
9396 			word0 = *((uint32_t *)phba->mbox);
9397 			word0 = le32_to_cpu(word0);
9398 		} else {
9399 			/* First read mbox status word */
9400 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
9401 				spin_unlock_irqrestore(&phba->hbalock,
9402 						       drvr_flag);
9403 				goto out_not_finished;
9404 			}
9405 		}
9406 
9407 		/* Read the HBA Host Attention Register */
9408 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9409 			spin_unlock_irqrestore(&phba->hbalock,
9410 						       drvr_flag);
9411 			goto out_not_finished;
9412 		}
9413 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9414 							1000) + jiffies;
9415 		i = 0;
9416 		/* Wait for command to complete */
9417 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
9418 		       (!(ha_copy & HA_MBATT) &&
9419 			(phba->link_state > LPFC_WARM_START))) {
9420 			if (time_after(jiffies, timeout)) {
9421 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9422 				spin_unlock_irqrestore(&phba->hbalock,
9423 						       drvr_flag);
9424 				goto out_not_finished;
9425 			}
9426 
9427 			/* Check if we took a mbox interrupt while we were
9428 			   polling */
9429 			if (((word0 & OWN_CHIP) != OWN_CHIP)
9430 			    && (evtctr != psli->slistat.mbox_event))
9431 				break;
9432 
9433 			if (i++ > 10) {
9434 				spin_unlock_irqrestore(&phba->hbalock,
9435 						       drvr_flag);
9436 				msleep(1);
9437 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
9438 			}
9439 
9440 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9441 				/* First copy command data */
9442 				word0 = *((uint32_t *)phba->mbox);
9443 				word0 = le32_to_cpu(word0);
9444 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
9445 					MAILBOX_t *slimmb;
9446 					uint32_t slimword0;
9447 					/* Check real SLIM for any errors */
9448 					slimword0 = readl(phba->MBslimaddr);
9449 					slimmb = (MAILBOX_t *) & slimword0;
9450 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
9451 					    && slimmb->mbxStatus) {
9452 						psli->sli_flag &=
9453 						    ~LPFC_SLI_ACTIVE;
9454 						word0 = slimword0;
9455 					}
9456 				}
9457 			} else {
9458 				/* First copy command data */
9459 				word0 = readl(phba->MBslimaddr);
9460 			}
9461 			/* Read the HBA Host Attention Register */
9462 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9463 				spin_unlock_irqrestore(&phba->hbalock,
9464 						       drvr_flag);
9465 				goto out_not_finished;
9466 			}
9467 		}
9468 
9469 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9470 			/* copy results back to user */
9471 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
9472 						MAILBOX_CMD_SIZE);
9473 			/* Copy the mailbox extension data */
9474 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9475 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
9476 						      pmbox->ctx_buf,
9477 						      pmbox->out_ext_byte_len);
9478 			}
9479 		} else {
9480 			/* First copy command data */
9481 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
9482 						MAILBOX_CMD_SIZE);
9483 			/* Copy the mailbox extension data */
9484 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9485 				lpfc_memcpy_from_slim(
9486 					pmbox->ctx_buf,
9487 					phba->MBslimaddr +
9488 					MAILBOX_HBA_EXT_OFFSET,
9489 					pmbox->out_ext_byte_len);
9490 			}
9491 		}
9492 
9493 		writel(HA_MBATT, phba->HAregaddr);
9494 		readl(phba->HAregaddr); /* flush */
9495 
9496 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9497 		status = mbx->mbxStatus;
9498 	}
9499 
9500 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9501 	return status;
9502 
9503 out_not_finished:
9504 	if (processing_queue) {
9505 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
9506 		lpfc_mbox_cmpl_put(phba, pmbox);
9507 	}
9508 	return MBX_NOT_FINISHED;
9509 }
9510 
9511 /**
9512  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
9513  * @phba: Pointer to HBA context object.
9514  *
9515  * The function blocks the posting of SLI4 asynchronous mailbox commands from
9516  * the driver internal pending mailbox queue. It will then try to wait out the
9517  * possible outstanding mailbox command before return.
9518  *
9519  * Returns:
9520  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
9521  * 	the outstanding mailbox command timed out.
9522  **/
9523 static int
9524 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
9525 {
9526 	struct lpfc_sli *psli = &phba->sli;
9527 	LPFC_MBOXQ_t *mboxq;
9528 	int rc = 0;
9529 	unsigned long timeout = 0;
9530 	u32 sli_flag;
9531 	u8 cmd, subsys, opcode;
9532 
9533 	/* Mark the asynchronous mailbox command posting as blocked */
9534 	spin_lock_irq(&phba->hbalock);
9535 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
9536 	/* Determine how long we might wait for the active mailbox
9537 	 * command to be gracefully completed by firmware.
9538 	 */
9539 	if (phba->sli.mbox_active)
9540 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
9541 						phba->sli.mbox_active) *
9542 						1000) + jiffies;
9543 	spin_unlock_irq(&phba->hbalock);
9544 
9545 	/* Make sure the mailbox is really active */
9546 	if (timeout)
9547 		lpfc_sli4_process_missed_mbox_completions(phba);
9548 
9549 	/* Wait for the outstanding mailbox command to complete */
9550 	while (phba->sli.mbox_active) {
9551 		/* Check active mailbox complete status every 2ms */
9552 		msleep(2);
9553 		if (time_after(jiffies, timeout)) {
9554 			/* Timeout, mark the outstanding cmd not complete */
9555 
9556 			/* Sanity check sli.mbox_active has not completed or
9557 			 * cancelled from another context during last 2ms sleep,
9558 			 * so take hbalock to be sure before logging.
9559 			 */
9560 			spin_lock_irq(&phba->hbalock);
9561 			if (phba->sli.mbox_active) {
9562 				mboxq = phba->sli.mbox_active;
9563 				cmd = mboxq->u.mb.mbxCommand;
9564 				subsys = lpfc_sli_config_mbox_subsys_get(phba,
9565 									 mboxq);
9566 				opcode = lpfc_sli_config_mbox_opcode_get(phba,
9567 									 mboxq);
9568 				sli_flag = psli->sli_flag;
9569 				spin_unlock_irq(&phba->hbalock);
9570 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9571 						"2352 Mailbox command x%x "
9572 						"(x%x/x%x) sli_flag x%x could "
9573 						"not complete\n",
9574 						cmd, subsys, opcode,
9575 						sli_flag);
9576 			} else {
9577 				spin_unlock_irq(&phba->hbalock);
9578 			}
9579 
9580 			rc = 1;
9581 			break;
9582 		}
9583 	}
9584 
9585 	/* Can not cleanly block async mailbox command, fails it */
9586 	if (rc) {
9587 		spin_lock_irq(&phba->hbalock);
9588 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9589 		spin_unlock_irq(&phba->hbalock);
9590 	}
9591 	return rc;
9592 }
9593 
9594 /**
9595  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
9596  * @phba: Pointer to HBA context object.
9597  *
9598  * The function unblocks and resume posting of SLI4 asynchronous mailbox
9599  * commands from the driver internal pending mailbox queue. It makes sure
9600  * that there is no outstanding mailbox command before resuming posting
9601  * asynchronous mailbox commands. If, for any reason, there is outstanding
9602  * mailbox command, it will try to wait it out before resuming asynchronous
9603  * mailbox command posting.
9604  **/
9605 static void
9606 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
9607 {
9608 	struct lpfc_sli *psli = &phba->sli;
9609 
9610 	spin_lock_irq(&phba->hbalock);
9611 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9612 		/* Asynchronous mailbox posting is not blocked, do nothing */
9613 		spin_unlock_irq(&phba->hbalock);
9614 		return;
9615 	}
9616 
9617 	/* Outstanding synchronous mailbox command is guaranteed to be done,
9618 	 * successful or timeout, after timing-out the outstanding mailbox
9619 	 * command shall always be removed, so just unblock posting async
9620 	 * mailbox command and resume
9621 	 */
9622 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9623 	spin_unlock_irq(&phba->hbalock);
9624 
9625 	/* wake up worker thread to post asynchronous mailbox command */
9626 	lpfc_worker_wake_up(phba);
9627 }
9628 
9629 /**
9630  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
9631  * @phba: Pointer to HBA context object.
9632  * @mboxq: Pointer to mailbox object.
9633  *
9634  * The function waits for the bootstrap mailbox register ready bit from
9635  * port for twice the regular mailbox command timeout value.
9636  *
9637  *      0 - no timeout on waiting for bootstrap mailbox register ready.
9638  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
9639  **/
9640 static int
9641 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9642 {
9643 	uint32_t db_ready;
9644 	unsigned long timeout;
9645 	struct lpfc_register bmbx_reg;
9646 
9647 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
9648 				   * 1000) + jiffies;
9649 
9650 	do {
9651 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
9652 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
9653 		if (!db_ready)
9654 			mdelay(2);
9655 
9656 		if (time_after(jiffies, timeout))
9657 			return MBXERR_ERROR;
9658 	} while (!db_ready);
9659 
9660 	return 0;
9661 }
9662 
9663 /**
9664  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
9665  * @phba: Pointer to HBA context object.
9666  * @mboxq: Pointer to mailbox object.
9667  *
9668  * The function posts a mailbox to the port.  The mailbox is expected
9669  * to be comletely filled in and ready for the port to operate on it.
9670  * This routine executes a synchronous completion operation on the
9671  * mailbox by polling for its completion.
9672  *
9673  * The caller must not be holding any locks when calling this routine.
9674  *
9675  * Returns:
9676  *	MBX_SUCCESS - mailbox posted successfully
9677  *	Any of the MBX error values.
9678  **/
9679 static int
9680 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9681 {
9682 	int rc = MBX_SUCCESS;
9683 	unsigned long iflag;
9684 	uint32_t mcqe_status;
9685 	uint32_t mbx_cmnd;
9686 	struct lpfc_sli *psli = &phba->sli;
9687 	struct lpfc_mqe *mb = &mboxq->u.mqe;
9688 	struct lpfc_bmbx_create *mbox_rgn;
9689 	struct dma_address *dma_address;
9690 
9691 	/*
9692 	 * Only one mailbox can be active to the bootstrap mailbox region
9693 	 * at a time and there is no queueing provided.
9694 	 */
9695 	spin_lock_irqsave(&phba->hbalock, iflag);
9696 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9697 		spin_unlock_irqrestore(&phba->hbalock, iflag);
9698 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9699 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
9700 				"cannot issue Data: x%x x%x\n",
9701 				mboxq->vport ? mboxq->vport->vpi : 0,
9702 				mboxq->u.mb.mbxCommand,
9703 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9704 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9705 				psli->sli_flag, MBX_POLL);
9706 		return MBXERR_ERROR;
9707 	}
9708 	/* The server grabs the token and owns it until release */
9709 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9710 	phba->sli.mbox_active = mboxq;
9711 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9712 
9713 	/* wait for bootstrap mbox register for readyness */
9714 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9715 	if (rc)
9716 		goto exit;
9717 	/*
9718 	 * Initialize the bootstrap memory region to avoid stale data areas
9719 	 * in the mailbox post.  Then copy the caller's mailbox contents to
9720 	 * the bmbx mailbox region.
9721 	 */
9722 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
9723 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
9724 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
9725 			       sizeof(struct lpfc_mqe));
9726 
9727 	/* Post the high mailbox dma address to the port and wait for ready. */
9728 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9729 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
9730 
9731 	/* wait for bootstrap mbox register for hi-address write done */
9732 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9733 	if (rc)
9734 		goto exit;
9735 
9736 	/* Post the low mailbox dma address to the port. */
9737 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
9738 
9739 	/* wait for bootstrap mbox register for low address write done */
9740 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9741 	if (rc)
9742 		goto exit;
9743 
9744 	/*
9745 	 * Read the CQ to ensure the mailbox has completed.
9746 	 * If so, update the mailbox status so that the upper layers
9747 	 * can complete the request normally.
9748 	 */
9749 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
9750 			       sizeof(struct lpfc_mqe));
9751 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
9752 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
9753 			       sizeof(struct lpfc_mcqe));
9754 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
9755 	/*
9756 	 * When the CQE status indicates a failure and the mailbox status
9757 	 * indicates success then copy the CQE status into the mailbox status
9758 	 * (and prefix it with x4000).
9759 	 */
9760 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
9761 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
9762 			bf_set(lpfc_mqe_status, mb,
9763 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
9764 		rc = MBXERR_ERROR;
9765 	} else
9766 		lpfc_sli4_swap_str(phba, mboxq);
9767 
9768 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9769 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
9770 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
9771 			" x%x x%x CQ: x%x x%x x%x x%x\n",
9772 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
9773 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9774 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9775 			bf_get(lpfc_mqe_status, mb),
9776 			mb->un.mb_words[0], mb->un.mb_words[1],
9777 			mb->un.mb_words[2], mb->un.mb_words[3],
9778 			mb->un.mb_words[4], mb->un.mb_words[5],
9779 			mb->un.mb_words[6], mb->un.mb_words[7],
9780 			mb->un.mb_words[8], mb->un.mb_words[9],
9781 			mb->un.mb_words[10], mb->un.mb_words[11],
9782 			mb->un.mb_words[12], mboxq->mcqe.word0,
9783 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
9784 			mboxq->mcqe.trailer);
9785 exit:
9786 	/* We are holding the token, no needed for lock when release */
9787 	spin_lock_irqsave(&phba->hbalock, iflag);
9788 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9789 	phba->sli.mbox_active = NULL;
9790 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9791 	return rc;
9792 }
9793 
9794 /**
9795  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
9796  * @phba: Pointer to HBA context object.
9797  * @mboxq: Pointer to mailbox object.
9798  * @flag: Flag indicating how the mailbox need to be processed.
9799  *
9800  * This function is called by discovery code and HBA management code to submit
9801  * a mailbox command to firmware with SLI-4 interface spec.
9802  *
9803  * Return codes the caller owns the mailbox command after the return of the
9804  * function.
9805  **/
9806 static int
9807 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
9808 		       uint32_t flag)
9809 {
9810 	struct lpfc_sli *psli = &phba->sli;
9811 	unsigned long iflags;
9812 	int rc;
9813 
9814 	/* dump from issue mailbox command if setup */
9815 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
9816 
9817 	rc = lpfc_mbox_dev_check(phba);
9818 	if (unlikely(rc)) {
9819 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9820 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
9821 				"cannot issue Data: x%x x%x\n",
9822 				mboxq->vport ? mboxq->vport->vpi : 0,
9823 				mboxq->u.mb.mbxCommand,
9824 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9825 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9826 				psli->sli_flag, flag);
9827 		goto out_not_finished;
9828 	}
9829 
9830 	/* Detect polling mode and jump to a handler */
9831 	if (!phba->sli4_hba.intr_enable) {
9832 		if (flag == MBX_POLL)
9833 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
9834 		else
9835 			rc = -EIO;
9836 		if (rc != MBX_SUCCESS)
9837 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
9838 					"(%d):2541 Mailbox command x%x "
9839 					"(x%x/x%x) failure: "
9840 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
9841 					"Data: x%x x%x\n",
9842 					mboxq->vport ? mboxq->vport->vpi : 0,
9843 					mboxq->u.mb.mbxCommand,
9844 					lpfc_sli_config_mbox_subsys_get(phba,
9845 									mboxq),
9846 					lpfc_sli_config_mbox_opcode_get(phba,
9847 									mboxq),
9848 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
9849 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
9850 					bf_get(lpfc_mcqe_ext_status,
9851 					       &mboxq->mcqe),
9852 					psli->sli_flag, flag);
9853 		return rc;
9854 	} else if (flag == MBX_POLL) {
9855 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
9856 				"(%d):2542 Try to issue mailbox command "
9857 				"x%x (x%x/x%x) synchronously ahead of async "
9858 				"mailbox command queue: x%x x%x\n",
9859 				mboxq->vport ? mboxq->vport->vpi : 0,
9860 				mboxq->u.mb.mbxCommand,
9861 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9862 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9863 				psli->sli_flag, flag);
9864 		/* Try to block the asynchronous mailbox posting */
9865 		rc = lpfc_sli4_async_mbox_block(phba);
9866 		if (!rc) {
9867 			/* Successfully blocked, now issue sync mbox cmd */
9868 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
9869 			if (rc != MBX_SUCCESS)
9870 				lpfc_printf_log(phba, KERN_WARNING,
9871 					LOG_MBOX | LOG_SLI,
9872 					"(%d):2597 Sync Mailbox command "
9873 					"x%x (x%x/x%x) failure: "
9874 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
9875 					"Data: x%x x%x\n",
9876 					mboxq->vport ? mboxq->vport->vpi : 0,
9877 					mboxq->u.mb.mbxCommand,
9878 					lpfc_sli_config_mbox_subsys_get(phba,
9879 									mboxq),
9880 					lpfc_sli_config_mbox_opcode_get(phba,
9881 									mboxq),
9882 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
9883 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
9884 					bf_get(lpfc_mcqe_ext_status,
9885 					       &mboxq->mcqe),
9886 					psli->sli_flag, flag);
9887 			/* Unblock the async mailbox posting afterward */
9888 			lpfc_sli4_async_mbox_unblock(phba);
9889 		}
9890 		return rc;
9891 	}
9892 
9893 	/* Now, interrupt mode asynchronous mailbox command */
9894 	rc = lpfc_mbox_cmd_check(phba, mboxq);
9895 	if (rc) {
9896 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9897 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
9898 				"cannot issue Data: x%x x%x\n",
9899 				mboxq->vport ? mboxq->vport->vpi : 0,
9900 				mboxq->u.mb.mbxCommand,
9901 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9902 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9903 				psli->sli_flag, flag);
9904 		goto out_not_finished;
9905 	}
9906 
9907 	/* Put the mailbox command to the driver internal FIFO */
9908 	psli->slistat.mbox_busy++;
9909 	spin_lock_irqsave(&phba->hbalock, iflags);
9910 	lpfc_mbox_put(phba, mboxq);
9911 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9912 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9913 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
9914 			"x%x (x%x/x%x) x%x x%x x%x\n",
9915 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
9916 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
9917 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9918 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9919 			phba->pport->port_state,
9920 			psli->sli_flag, MBX_NOWAIT);
9921 	/* Wake up worker thread to transport mailbox command from head */
9922 	lpfc_worker_wake_up(phba);
9923 
9924 	return MBX_BUSY;
9925 
9926 out_not_finished:
9927 	return MBX_NOT_FINISHED;
9928 }
9929 
9930 /**
9931  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
9932  * @phba: Pointer to HBA context object.
9933  *
9934  * This function is called by worker thread to send a mailbox command to
9935  * SLI4 HBA firmware.
9936  *
9937  **/
9938 int
9939 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
9940 {
9941 	struct lpfc_sli *psli = &phba->sli;
9942 	LPFC_MBOXQ_t *mboxq;
9943 	int rc = MBX_SUCCESS;
9944 	unsigned long iflags;
9945 	struct lpfc_mqe *mqe;
9946 	uint32_t mbx_cmnd;
9947 
9948 	/* Check interrupt mode before post async mailbox command */
9949 	if (unlikely(!phba->sli4_hba.intr_enable))
9950 		return MBX_NOT_FINISHED;
9951 
9952 	/* Check for mailbox command service token */
9953 	spin_lock_irqsave(&phba->hbalock, iflags);
9954 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9955 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9956 		return MBX_NOT_FINISHED;
9957 	}
9958 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9959 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9960 		return MBX_NOT_FINISHED;
9961 	}
9962 	if (unlikely(phba->sli.mbox_active)) {
9963 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9964 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9965 				"0384 There is pending active mailbox cmd\n");
9966 		return MBX_NOT_FINISHED;
9967 	}
9968 	/* Take the mailbox command service token */
9969 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9970 
9971 	/* Get the next mailbox command from head of queue */
9972 	mboxq = lpfc_mbox_get(phba);
9973 
9974 	/* If no more mailbox command waiting for post, we're done */
9975 	if (!mboxq) {
9976 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9977 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9978 		return MBX_SUCCESS;
9979 	}
9980 	phba->sli.mbox_active = mboxq;
9981 	spin_unlock_irqrestore(&phba->hbalock, iflags);
9982 
9983 	/* Check device readiness for posting mailbox command */
9984 	rc = lpfc_mbox_dev_check(phba);
9985 	if (unlikely(rc))
9986 		/* Driver clean routine will clean up pending mailbox */
9987 		goto out_not_finished;
9988 
9989 	/* Prepare the mbox command to be posted */
9990 	mqe = &mboxq->u.mqe;
9991 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
9992 
9993 	/* Start timer for the mbox_tmo and log some mailbox post messages */
9994 	mod_timer(&psli->mbox_tmo, (jiffies +
9995 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
9996 
9997 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9998 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
9999 			"x%x x%x\n",
10000 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10001 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10002 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10003 			phba->pport->port_state, psli->sli_flag);
10004 
10005 	if (mbx_cmnd != MBX_HEARTBEAT) {
10006 		if (mboxq->vport) {
10007 			lpfc_debugfs_disc_trc(mboxq->vport,
10008 				LPFC_DISC_TRC_MBOX_VPORT,
10009 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
10010 				mbx_cmnd, mqe->un.mb_words[0],
10011 				mqe->un.mb_words[1]);
10012 		} else {
10013 			lpfc_debugfs_disc_trc(phba->pport,
10014 				LPFC_DISC_TRC_MBOX,
10015 				"MBOX Send: cmd:x%x mb:x%x x%x",
10016 				mbx_cmnd, mqe->un.mb_words[0],
10017 				mqe->un.mb_words[1]);
10018 		}
10019 	}
10020 	psli->slistat.mbox_cmd++;
10021 
10022 	/* Post the mailbox command to the port */
10023 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
10024 	if (rc != MBX_SUCCESS) {
10025 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10026 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
10027 				"cannot issue Data: x%x x%x\n",
10028 				mboxq->vport ? mboxq->vport->vpi : 0,
10029 				mboxq->u.mb.mbxCommand,
10030 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10031 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10032 				psli->sli_flag, MBX_NOWAIT);
10033 		goto out_not_finished;
10034 	}
10035 
10036 	return rc;
10037 
10038 out_not_finished:
10039 	spin_lock_irqsave(&phba->hbalock, iflags);
10040 	if (phba->sli.mbox_active) {
10041 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
10042 		__lpfc_mbox_cmpl_put(phba, mboxq);
10043 		/* Release the token */
10044 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10045 		phba->sli.mbox_active = NULL;
10046 	}
10047 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10048 
10049 	return MBX_NOT_FINISHED;
10050 }
10051 
10052 /**
10053  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
10054  * @phba: Pointer to HBA context object.
10055  * @pmbox: Pointer to mailbox object.
10056  * @flag: Flag indicating how the mailbox need to be processed.
10057  *
10058  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
10059  * the API jump table function pointer from the lpfc_hba struct.
10060  *
10061  * Return codes the caller owns the mailbox command after the return of the
10062  * function.
10063  **/
10064 int
10065 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
10066 {
10067 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
10068 }
10069 
10070 /**
10071  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
10072  * @phba: The hba struct for which this call is being executed.
10073  * @dev_grp: The HBA PCI-Device group number.
10074  *
10075  * This routine sets up the mbox interface API function jump table in @phba
10076  * struct.
10077  * Returns: 0 - success, -ENODEV - failure.
10078  **/
10079 int
10080 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10081 {
10082 
10083 	switch (dev_grp) {
10084 	case LPFC_PCI_DEV_LP:
10085 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
10086 		phba->lpfc_sli_handle_slow_ring_event =
10087 				lpfc_sli_handle_slow_ring_event_s3;
10088 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
10089 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
10090 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
10091 		break;
10092 	case LPFC_PCI_DEV_OC:
10093 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
10094 		phba->lpfc_sli_handle_slow_ring_event =
10095 				lpfc_sli_handle_slow_ring_event_s4;
10096 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
10097 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
10098 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
10099 		break;
10100 	default:
10101 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10102 				"1420 Invalid HBA PCI-device group: 0x%x\n",
10103 				dev_grp);
10104 		return -ENODEV;
10105 	}
10106 	return 0;
10107 }
10108 
10109 /**
10110  * __lpfc_sli_ringtx_put - Add an iocb to the txq
10111  * @phba: Pointer to HBA context object.
10112  * @pring: Pointer to driver SLI ring object.
10113  * @piocb: Pointer to address of newly added command iocb.
10114  *
10115  * This function is called with hbalock held for SLI3 ports or
10116  * the ring lock held for SLI4 ports to add a command
10117  * iocb to the txq when SLI layer cannot submit the command iocb
10118  * to the ring.
10119  **/
10120 void
10121 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10122 		    struct lpfc_iocbq *piocb)
10123 {
10124 	if (phba->sli_rev == LPFC_SLI_REV4)
10125 		lockdep_assert_held(&pring->ring_lock);
10126 	else
10127 		lockdep_assert_held(&phba->hbalock);
10128 	/* Insert the caller's iocb in the txq tail for later processing. */
10129 	list_add_tail(&piocb->list, &pring->txq);
10130 }
10131 
10132 /**
10133  * lpfc_sli_next_iocb - Get the next iocb in the txq
10134  * @phba: Pointer to HBA context object.
10135  * @pring: Pointer to driver SLI ring object.
10136  * @piocb: Pointer to address of newly added command iocb.
10137  *
10138  * This function is called with hbalock held before a new
10139  * iocb is submitted to the firmware. This function checks
10140  * txq to flush the iocbs in txq to Firmware before
10141  * submitting new iocbs to the Firmware.
10142  * If there are iocbs in the txq which need to be submitted
10143  * to firmware, lpfc_sli_next_iocb returns the first element
10144  * of the txq after dequeuing it from txq.
10145  * If there is no iocb in the txq then the function will return
10146  * *piocb and *piocb is set to NULL. Caller needs to check
10147  * *piocb to find if there are more commands in the txq.
10148  **/
10149 static struct lpfc_iocbq *
10150 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10151 		   struct lpfc_iocbq **piocb)
10152 {
10153 	struct lpfc_iocbq * nextiocb;
10154 
10155 	lockdep_assert_held(&phba->hbalock);
10156 
10157 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
10158 	if (!nextiocb) {
10159 		nextiocb = *piocb;
10160 		*piocb = NULL;
10161 	}
10162 
10163 	return nextiocb;
10164 }
10165 
10166 /**
10167  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
10168  * @phba: Pointer to HBA context object.
10169  * @ring_number: SLI ring number to issue iocb on.
10170  * @piocb: Pointer to command iocb.
10171  * @flag: Flag indicating if this command can be put into txq.
10172  *
10173  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
10174  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
10175  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
10176  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
10177  * this function allows only iocbs for posting buffers. This function finds
10178  * next available slot in the command ring and posts the command to the
10179  * available slot and writes the port attention register to request HBA start
10180  * processing new iocb. If there is no slot available in the ring and
10181  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
10182  * the function returns IOCB_BUSY.
10183  *
10184  * This function is called with hbalock held. The function will return success
10185  * after it successfully submit the iocb to firmware or after adding to the
10186  * txq.
10187  **/
10188 static int
10189 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
10190 		    struct lpfc_iocbq *piocb, uint32_t flag)
10191 {
10192 	struct lpfc_iocbq *nextiocb;
10193 	IOCB_t *iocb;
10194 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
10195 
10196 	lockdep_assert_held(&phba->hbalock);
10197 
10198 	if (piocb->cmd_cmpl && (!piocb->vport) &&
10199 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
10200 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
10201 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10202 				"1807 IOCB x%x failed. No vport\n",
10203 				piocb->iocb.ulpCommand);
10204 		dump_stack();
10205 		return IOCB_ERROR;
10206 	}
10207 
10208 
10209 	/* If the PCI channel is in offline state, do not post iocbs. */
10210 	if (unlikely(pci_channel_offline(phba->pcidev)))
10211 		return IOCB_ERROR;
10212 
10213 	/* If HBA has a deferred error attention, fail the iocb. */
10214 	if (unlikely(phba->hba_flag & DEFER_ERATT))
10215 		return IOCB_ERROR;
10216 
10217 	/*
10218 	 * We should never get an IOCB if we are in a < LINK_DOWN state
10219 	 */
10220 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
10221 		return IOCB_ERROR;
10222 
10223 	/*
10224 	 * Check to see if we are blocking IOCB processing because of a
10225 	 * outstanding event.
10226 	 */
10227 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
10228 		goto iocb_busy;
10229 
10230 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
10231 		/*
10232 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
10233 		 * can be issued if the link is not up.
10234 		 */
10235 		switch (piocb->iocb.ulpCommand) {
10236 		case CMD_GEN_REQUEST64_CR:
10237 		case CMD_GEN_REQUEST64_CX:
10238 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
10239 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
10240 					FC_RCTL_DD_UNSOL_CMD) ||
10241 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
10242 					MENLO_TRANSPORT_TYPE))
10243 
10244 				goto iocb_busy;
10245 			break;
10246 		case CMD_QUE_RING_BUF_CN:
10247 		case CMD_QUE_RING_BUF64_CN:
10248 			/*
10249 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
10250 			 * completion, cmd_cmpl MUST be 0.
10251 			 */
10252 			if (piocb->cmd_cmpl)
10253 				piocb->cmd_cmpl = NULL;
10254 			fallthrough;
10255 		case CMD_CREATE_XRI_CR:
10256 		case CMD_CLOSE_XRI_CN:
10257 		case CMD_CLOSE_XRI_CX:
10258 			break;
10259 		default:
10260 			goto iocb_busy;
10261 		}
10262 
10263 	/*
10264 	 * For FCP commands, we must be in a state where we can process link
10265 	 * attention events.
10266 	 */
10267 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
10268 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
10269 		goto iocb_busy;
10270 	}
10271 
10272 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
10273 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
10274 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
10275 
10276 	if (iocb)
10277 		lpfc_sli_update_ring(phba, pring);
10278 	else
10279 		lpfc_sli_update_full_ring(phba, pring);
10280 
10281 	if (!piocb)
10282 		return IOCB_SUCCESS;
10283 
10284 	goto out_busy;
10285 
10286  iocb_busy:
10287 	pring->stats.iocb_cmd_delay++;
10288 
10289  out_busy:
10290 
10291 	if (!(flag & SLI_IOCB_RET_IOCB)) {
10292 		__lpfc_sli_ringtx_put(phba, pring, piocb);
10293 		return IOCB_SUCCESS;
10294 	}
10295 
10296 	return IOCB_BUSY;
10297 }
10298 
10299 /**
10300  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10301  * @phba: Pointer to HBA context object.
10302  * @ring_number: SLI ring number to issue wqe on.
10303  * @piocb: Pointer to command iocb.
10304  * @flag: Flag indicating if this command can be put into txq.
10305  *
10306  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10307  * send  an iocb command to an HBA with SLI-4 interface spec.
10308  *
10309  * This function takes the hbalock before invoking the lockless version.
10310  * The function will return success after it successfully submit the wqe to
10311  * firmware or after adding to the txq.
10312  **/
10313 static int
10314 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10315 			   struct lpfc_iocbq *piocb, uint32_t flag)
10316 {
10317 	unsigned long iflags;
10318 	int rc;
10319 
10320 	spin_lock_irqsave(&phba->hbalock, iflags);
10321 	rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10322 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10323 
10324 	return rc;
10325 }
10326 
10327 /**
10328  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10329  * @phba: Pointer to HBA context object.
10330  * @ring_number: SLI ring number to issue wqe on.
10331  * @piocb: Pointer to command iocb.
10332  * @flag: Flag indicating if this command can be put into txq.
10333  *
10334  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10335  * an wqe command to an HBA with SLI-4 interface spec.
10336  *
10337  * This function is a lockless version. The function will return success
10338  * after it successfully submit the wqe to firmware or after adding to the
10339  * txq.
10340  **/
10341 static int
10342 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10343 			   struct lpfc_iocbq *piocb, uint32_t flag)
10344 {
10345 	int rc;
10346 	struct lpfc_io_buf *lpfc_cmd =
10347 		(struct lpfc_io_buf *)piocb->context1;
10348 
10349 	lpfc_prep_embed_io(phba, lpfc_cmd);
10350 	rc = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
10351 	return rc;
10352 }
10353 
10354 void
10355 lpfc_prep_embed_io(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
10356 {
10357 	struct lpfc_iocbq *piocb = &lpfc_cmd->cur_iocbq;
10358 	union lpfc_wqe128 *wqe = &lpfc_cmd->cur_iocbq.wqe;
10359 	struct sli4_sge *sgl;
10360 
10361 	/* 128 byte wqe support here */
10362 	sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10363 
10364 	if (phba->fcp_embed_io) {
10365 		struct fcp_cmnd *fcp_cmnd;
10366 		u32 *ptr;
10367 
10368 		fcp_cmnd = lpfc_cmd->fcp_cmnd;
10369 
10370 		/* Word 0-2 - FCP_CMND */
10371 		wqe->generic.bde.tus.f.bdeFlags =
10372 			BUFF_TYPE_BDE_IMMED;
10373 		wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10374 		wqe->generic.bde.addrHigh = 0;
10375 		wqe->generic.bde.addrLow =  88;  /* Word 22 */
10376 
10377 		bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10378 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10379 
10380 		/* Word 22-29  FCP CMND Payload */
10381 		ptr = &wqe->words[22];
10382 		memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10383 	} else {
10384 		/* Word 0-2 - Inline BDE */
10385 		wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
10386 		wqe->generic.bde.tus.f.bdeSize = sizeof(struct fcp_cmnd);
10387 		wqe->generic.bde.addrHigh = sgl->addr_hi;
10388 		wqe->generic.bde.addrLow =  sgl->addr_lo;
10389 
10390 		/* Word 10 */
10391 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10392 		bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
10393 	}
10394 
10395 	/* add the VMID tags as per switch response */
10396 	if (unlikely(piocb->cmd_flag & LPFC_IO_VMID)) {
10397 		if (phba->pport->vmid_priority_tagging) {
10398 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
10399 			bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10400 					(piocb->vmid_tag.cs_ctl_vmid));
10401 		} else {
10402 			bf_set(wqe_appid, &wqe->fcp_iwrite.wqe_com, 1);
10403 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10404 			wqe->words[31] = piocb->vmid_tag.app_id;
10405 		}
10406 	}
10407 }
10408 
10409 /**
10410  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10411  * @phba: Pointer to HBA context object.
10412  * @ring_number: SLI ring number to issue iocb on.
10413  * @piocb: Pointer to command iocb.
10414  * @flag: Flag indicating if this command can be put into txq.
10415  *
10416  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10417  * an iocb command to an HBA with SLI-4 interface spec.
10418  *
10419  * This function is called with ringlock held. The function will return success
10420  * after it successfully submit the iocb to firmware or after adding to the
10421  * txq.
10422  **/
10423 static int
10424 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10425 			 struct lpfc_iocbq *piocb, uint32_t flag)
10426 {
10427 	struct lpfc_sglq *sglq;
10428 	union lpfc_wqe128 *wqe;
10429 	struct lpfc_queue *wq;
10430 	struct lpfc_sli_ring *pring;
10431 	u32 ulp_command = get_job_cmnd(phba, piocb);
10432 
10433 	/* Get the WQ */
10434 	if ((piocb->cmd_flag & LPFC_IO_FCP) ||
10435 	    (piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
10436 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10437 	} else {
10438 		wq = phba->sli4_hba.els_wq;
10439 	}
10440 
10441 	/* Get corresponding ring */
10442 	pring = wq->pring;
10443 
10444 	/*
10445 	 * The WQE can be either 64 or 128 bytes,
10446 	 */
10447 
10448 	lockdep_assert_held(&pring->ring_lock);
10449 	wqe = &piocb->wqe;
10450 	if (piocb->sli4_xritag == NO_XRI) {
10451 		if (ulp_command == CMD_ABORT_XRI_CX)
10452 			sglq = NULL;
10453 		else {
10454 			sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10455 			if (!sglq) {
10456 				if (!(flag & SLI_IOCB_RET_IOCB)) {
10457 					__lpfc_sli_ringtx_put(phba,
10458 							pring,
10459 							piocb);
10460 					return IOCB_SUCCESS;
10461 				} else {
10462 					return IOCB_BUSY;
10463 				}
10464 			}
10465 		}
10466 	} else if (piocb->cmd_flag &  LPFC_IO_FCP) {
10467 		/* These IO's already have an XRI and a mapped sgl. */
10468 		sglq = NULL;
10469 	}
10470 	else {
10471 		/*
10472 		 * This is a continuation of a commandi,(CX) so this
10473 		 * sglq is on the active list
10474 		 */
10475 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10476 		if (!sglq)
10477 			return IOCB_ERROR;
10478 	}
10479 
10480 	if (sglq) {
10481 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10482 		piocb->sli4_xritag = sglq->sli4_xritag;
10483 
10484 		/* ABTS sent by initiator to CT exchange, the
10485 		 * RX_ID field will be filled with the newly
10486 		 * allocated responder XRI.
10487 		 */
10488 		if (ulp_command == CMD_XMIT_BLS_RSP64_CX &&
10489 		    piocb->abort_bls == LPFC_ABTS_UNSOL_INT)
10490 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10491 			       piocb->sli4_xritag);
10492 
10493 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com,
10494 		       piocb->sli4_xritag);
10495 
10496 		if (lpfc_wqe_bpl2sgl(phba, piocb, sglq) == NO_XRI)
10497 			return IOCB_ERROR;
10498 	}
10499 
10500 	if (lpfc_sli4_wq_put(wq, wqe))
10501 		return IOCB_ERROR;
10502 
10503 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10504 
10505 	return 0;
10506 }
10507 
10508 /*
10509  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
10510  *
10511  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
10512  * or IOCB for sli-3  function.
10513  * pointer from the lpfc_hba struct.
10514  *
10515  * Return codes:
10516  * IOCB_ERROR - Error
10517  * IOCB_SUCCESS - Success
10518  * IOCB_BUSY - Busy
10519  **/
10520 int
10521 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
10522 		      struct lpfc_iocbq *piocb, uint32_t flag)
10523 {
10524 	return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
10525 }
10526 
10527 /*
10528  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10529  *
10530  * This routine wraps the actual lockless version for issusing IOCB function
10531  * pointer from the lpfc_hba struct.
10532  *
10533  * Return codes:
10534  * IOCB_ERROR - Error
10535  * IOCB_SUCCESS - Success
10536  * IOCB_BUSY - Busy
10537  **/
10538 int
10539 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10540 		struct lpfc_iocbq *piocb, uint32_t flag)
10541 {
10542 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10543 }
10544 
10545 static void
10546 __lpfc_sli_prep_els_req_rsp_s3(struct lpfc_iocbq *cmdiocbq,
10547 			       struct lpfc_vport *vport,
10548 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10549 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10550 {
10551 	struct lpfc_hba *phba = vport->phba;
10552 	IOCB_t *cmd;
10553 
10554 	cmd = &cmdiocbq->iocb;
10555 	memset(cmd, 0, sizeof(*cmd));
10556 
10557 	cmd->un.elsreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10558 	cmd->un.elsreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10559 	cmd->un.elsreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10560 
10561 	if (expect_rsp) {
10562 		cmd->un.elsreq64.bdl.bdeSize = (2 * sizeof(struct ulp_bde64));
10563 		cmd->un.elsreq64.remoteID = did; /* DID */
10564 		cmd->ulpCommand = CMD_ELS_REQUEST64_CR;
10565 		cmd->ulpTimeout = tmo;
10566 	} else {
10567 		cmd->un.elsreq64.bdl.bdeSize = sizeof(struct ulp_bde64);
10568 		cmd->un.genreq64.xmit_els_remoteID = did; /* DID */
10569 		cmd->ulpCommand = CMD_XMIT_ELS_RSP64_CX;
10570 	}
10571 	cmd->ulpBdeCount = 1;
10572 	cmd->ulpLe = 1;
10573 	cmd->ulpClass = CLASS3;
10574 
10575 	/* If we have NPIV enabled, we want to send ELS traffic by VPI. */
10576 	if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) {
10577 		if (expect_rsp) {
10578 			cmd->un.elsreq64.myID = vport->fc_myDID;
10579 
10580 			/* For ELS_REQUEST64_CR, use the VPI by default */
10581 			cmd->ulpContext = phba->vpi_ids[vport->vpi];
10582 		}
10583 
10584 		cmd->ulpCt_h = 0;
10585 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10586 		if (elscmd == ELS_CMD_ECHO)
10587 			cmd->ulpCt_l = 0; /* context = invalid RPI */
10588 		else
10589 			cmd->ulpCt_l = 1; /* context = VPI */
10590 	}
10591 }
10592 
10593 static void
10594 __lpfc_sli_prep_els_req_rsp_s4(struct lpfc_iocbq *cmdiocbq,
10595 			       struct lpfc_vport *vport,
10596 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10597 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10598 {
10599 	struct lpfc_hba  *phba = vport->phba;
10600 	union lpfc_wqe128 *wqe;
10601 	struct ulp_bde64_le *bde;
10602 
10603 	wqe = &cmdiocbq->wqe;
10604 	memset(wqe, 0, sizeof(*wqe));
10605 
10606 	/* Word 0 - 2 BDE */
10607 	bde = (struct ulp_bde64_le *)&wqe->generic.bde;
10608 	bde->addr_low = cpu_to_le32(putPaddrLow(bmp->phys));
10609 	bde->addr_high = cpu_to_le32(putPaddrHigh(bmp->phys));
10610 	bde->type_size = cpu_to_le32(cmd_size);
10611 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10612 
10613 	if (expect_rsp) {
10614 		bf_set(wqe_cmnd, &wqe->els_req.wqe_com, CMD_ELS_REQUEST64_CR);
10615 
10616 		/* Transfer length */
10617 		wqe->els_req.payload_len = cmd_size;
10618 		wqe->els_req.max_response_payload_len = FCELSSIZE;
10619 
10620 		/* DID */
10621 		bf_set(wqe_els_did, &wqe->els_req.wqe_dest, did);
10622 	} else {
10623 		/* DID */
10624 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest, did);
10625 
10626 		/* Transfer length */
10627 		wqe->xmit_els_rsp.response_payload_len = cmd_size;
10628 
10629 		bf_set(wqe_cmnd, &wqe->xmit_els_rsp.wqe_com,
10630 		       CMD_XMIT_ELS_RSP64_CX);
10631 	}
10632 
10633 	bf_set(wqe_tmo, &wqe->generic.wqe_com, tmo);
10634 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, cmdiocbq->iotag);
10635 	bf_set(wqe_class, &wqe->generic.wqe_com, CLASS3);
10636 
10637 	/* If we have NPIV enabled, we want to send ELS traffic by VPI.
10638 	 * For SLI4, since the driver controls VPIs we also want to include
10639 	 * all ELS pt2pt protocol traffic as well.
10640 	 */
10641 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) ||
10642 	    (vport->fc_flag & FC_PT2PT)) {
10643 		if (expect_rsp) {
10644 			bf_set(els_req64_sid, &wqe->els_req, vport->fc_myDID);
10645 
10646 			/* For ELS_REQUEST64_CR, use the VPI by default */
10647 			bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10648 			       phba->vpi_ids[vport->vpi]);
10649 		}
10650 
10651 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10652 		if (elscmd == ELS_CMD_ECHO)
10653 			bf_set(wqe_ct, &wqe->generic.wqe_com, 0);
10654 		else
10655 			bf_set(wqe_ct, &wqe->generic.wqe_com, 1);
10656 	}
10657 }
10658 
10659 void
10660 lpfc_sli_prep_els_req_rsp(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
10661 			  struct lpfc_vport *vport, struct lpfc_dmabuf *bmp,
10662 			  u16 cmd_size, u32 did, u32 elscmd, u8 tmo,
10663 			  u8 expect_rsp)
10664 {
10665 	phba->__lpfc_sli_prep_els_req_rsp(cmdiocbq, vport, bmp, cmd_size, did,
10666 					  elscmd, tmo, expect_rsp);
10667 }
10668 
10669 static void
10670 __lpfc_sli_prep_gen_req_s3(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10671 			   u16 rpi, u32 num_entry, u8 tmo)
10672 {
10673 	IOCB_t *cmd;
10674 
10675 	cmd = &cmdiocbq->iocb;
10676 	memset(cmd, 0, sizeof(*cmd));
10677 
10678 	cmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10679 	cmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10680 	cmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10681 	cmd->un.genreq64.bdl.bdeSize = num_entry * sizeof(struct ulp_bde64);
10682 
10683 	cmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
10684 	cmd->un.genreq64.w5.hcsw.Type = FC_TYPE_CT;
10685 	cmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
10686 
10687 	cmd->ulpContext = rpi;
10688 	cmd->ulpClass = CLASS3;
10689 	cmd->ulpCommand = CMD_GEN_REQUEST64_CR;
10690 	cmd->ulpBdeCount = 1;
10691 	cmd->ulpLe = 1;
10692 	cmd->ulpOwner = OWN_CHIP;
10693 	cmd->ulpTimeout = tmo;
10694 }
10695 
10696 static void
10697 __lpfc_sli_prep_gen_req_s4(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10698 			   u16 rpi, u32 num_entry, u8 tmo)
10699 {
10700 	union lpfc_wqe128 *cmdwqe;
10701 	struct ulp_bde64_le *bde, *bpl;
10702 	u32 xmit_len = 0, total_len = 0, size, type, i;
10703 
10704 	cmdwqe = &cmdiocbq->wqe;
10705 	memset(cmdwqe, 0, sizeof(*cmdwqe));
10706 
10707 	/* Calculate total_len and xmit_len */
10708 	bpl = (struct ulp_bde64_le *)bmp->virt;
10709 	for (i = 0; i < num_entry; i++) {
10710 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10711 		total_len += size;
10712 	}
10713 	for (i = 0; i < num_entry; i++) {
10714 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10715 		type = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_TYPE_MASK;
10716 		if (type != ULP_BDE64_TYPE_BDE_64)
10717 			break;
10718 		xmit_len += size;
10719 	}
10720 
10721 	/* Words 0 - 2 */
10722 	bde = (struct ulp_bde64_le *)&cmdwqe->generic.bde;
10723 	bde->addr_low = bpl->addr_low;
10724 	bde->addr_high = bpl->addr_high;
10725 	bde->type_size = cpu_to_le32(xmit_len);
10726 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10727 
10728 	/* Word 3 */
10729 	cmdwqe->gen_req.request_payload_len = xmit_len;
10730 
10731 	/* Word 5 */
10732 	bf_set(wqe_type, &cmdwqe->gen_req.wge_ctl, FC_TYPE_CT);
10733 	bf_set(wqe_rctl, &cmdwqe->gen_req.wge_ctl, FC_RCTL_DD_UNSOL_CTL);
10734 	bf_set(wqe_si, &cmdwqe->gen_req.wge_ctl, 1);
10735 	bf_set(wqe_la, &cmdwqe->gen_req.wge_ctl, 1);
10736 
10737 	/* Word 6 */
10738 	bf_set(wqe_ctxt_tag, &cmdwqe->gen_req.wqe_com, rpi);
10739 
10740 	/* Word 7 */
10741 	bf_set(wqe_tmo, &cmdwqe->gen_req.wqe_com, tmo);
10742 	bf_set(wqe_class, &cmdwqe->gen_req.wqe_com, CLASS3);
10743 	bf_set(wqe_cmnd, &cmdwqe->gen_req.wqe_com, CMD_GEN_REQUEST64_CR);
10744 	bf_set(wqe_ct, &cmdwqe->gen_req.wqe_com, SLI4_CT_RPI);
10745 
10746 	/* Word 12 */
10747 	cmdwqe->gen_req.max_response_payload_len = total_len - xmit_len;
10748 }
10749 
10750 void
10751 lpfc_sli_prep_gen_req(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
10752 		      struct lpfc_dmabuf *bmp, u16 rpi, u32 num_entry, u8 tmo)
10753 {
10754 	phba->__lpfc_sli_prep_gen_req(cmdiocbq, bmp, rpi, num_entry, tmo);
10755 }
10756 
10757 static void
10758 __lpfc_sli_prep_xmit_seq64_s3(struct lpfc_iocbq *cmdiocbq,
10759 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
10760 			      u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
10761 {
10762 	IOCB_t *icmd;
10763 
10764 	icmd = &cmdiocbq->iocb;
10765 	memset(icmd, 0, sizeof(*icmd));
10766 
10767 	icmd->un.xseq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10768 	icmd->un.xseq64.bdl.addrLow = putPaddrLow(bmp->phys);
10769 	icmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10770 	icmd->un.xseq64.bdl.bdeSize = (num_entry * sizeof(struct ulp_bde64));
10771 	icmd->un.xseq64.w5.hcsw.Fctl = LA;
10772 	if (last_seq)
10773 		icmd->un.xseq64.w5.hcsw.Fctl |= LS;
10774 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
10775 	icmd->un.xseq64.w5.hcsw.Rctl = rctl;
10776 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
10777 
10778 	icmd->ulpBdeCount = 1;
10779 	icmd->ulpLe = 1;
10780 	icmd->ulpClass = CLASS3;
10781 
10782 	switch (cr_cx_cmd) {
10783 	case CMD_XMIT_SEQUENCE64_CR:
10784 		icmd->ulpContext = rpi;
10785 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CR;
10786 		break;
10787 	case CMD_XMIT_SEQUENCE64_CX:
10788 		icmd->ulpContext = ox_id;
10789 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CX;
10790 		break;
10791 	default:
10792 		break;
10793 	}
10794 }
10795 
10796 static void
10797 __lpfc_sli_prep_xmit_seq64_s4(struct lpfc_iocbq *cmdiocbq,
10798 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
10799 			      u32 full_size, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
10800 {
10801 	union lpfc_wqe128 *wqe;
10802 	struct ulp_bde64 *bpl;
10803 	struct ulp_bde64_le *bde;
10804 
10805 	wqe = &cmdiocbq->wqe;
10806 	memset(wqe, 0, sizeof(*wqe));
10807 
10808 	/* Words 0 - 2 */
10809 	bpl = (struct ulp_bde64 *)bmp->virt;
10810 	if (cmdiocbq->cmd_flag & (LPFC_IO_LIBDFC | LPFC_IO_LOOPBACK)) {
10811 		wqe->xmit_sequence.bde.addrHigh = bpl->addrHigh;
10812 		wqe->xmit_sequence.bde.addrLow = bpl->addrLow;
10813 		wqe->xmit_sequence.bde.tus.w = bpl->tus.w;
10814 	} else {
10815 		bde = (struct ulp_bde64_le *)&wqe->xmit_sequence.bde;
10816 		bde->addr_low = cpu_to_le32(putPaddrLow(bmp->phys));
10817 		bde->addr_high = cpu_to_le32(putPaddrHigh(bmp->phys));
10818 		bde->type_size = cpu_to_le32(bpl->tus.f.bdeSize);
10819 		bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10820 	}
10821 
10822 	/* Word 5 */
10823 	bf_set(wqe_ls, &wqe->xmit_sequence.wge_ctl, last_seq);
10824 	bf_set(wqe_la, &wqe->xmit_sequence.wge_ctl, 1);
10825 	bf_set(wqe_dfctl, &wqe->xmit_sequence.wge_ctl, 0);
10826 	bf_set(wqe_rctl, &wqe->xmit_sequence.wge_ctl, rctl);
10827 	bf_set(wqe_type, &wqe->xmit_sequence.wge_ctl, FC_TYPE_CT);
10828 
10829 	/* Word 6 */
10830 	bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com, rpi);
10831 
10832 	bf_set(wqe_cmnd, &wqe->xmit_sequence.wqe_com,
10833 	       CMD_XMIT_SEQUENCE64_WQE);
10834 
10835 	/* Word 7 */
10836 	bf_set(wqe_class, &wqe->xmit_sequence.wqe_com, CLASS3);
10837 
10838 	/* Word 9 */
10839 	bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com, ox_id);
10840 
10841 	/* Word 12 */
10842 	if (cmdiocbq->cmd_flag & (LPFC_IO_LIBDFC | LPFC_IO_LOOPBACK))
10843 		wqe->xmit_sequence.xmit_len = full_size;
10844 	else
10845 		wqe->xmit_sequence.xmit_len =
10846 			wqe->xmit_sequence.bde.tus.f.bdeSize;
10847 }
10848 
10849 void
10850 lpfc_sli_prep_xmit_seq64(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
10851 			 struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
10852 			 u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
10853 {
10854 	phba->__lpfc_sli_prep_xmit_seq64(cmdiocbq, bmp, rpi, ox_id, num_entry,
10855 					 rctl, last_seq, cr_cx_cmd);
10856 }
10857 
10858 static void
10859 __lpfc_sli_prep_abort_xri_s3(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
10860 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia)
10861 {
10862 	IOCB_t *icmd = NULL;
10863 
10864 	icmd = &cmdiocbq->iocb;
10865 	memset(icmd, 0, sizeof(*icmd));
10866 
10867 	/* Word 5 */
10868 	icmd->un.acxri.abortContextTag = ulp_context;
10869 	icmd->un.acxri.abortIoTag = iotag;
10870 
10871 	if (ia) {
10872 		/* Word 7 */
10873 		icmd->ulpCommand = CMD_CLOSE_XRI_CN;
10874 	} else {
10875 		/* Word 3 */
10876 		icmd->un.acxri.abortType = ABORT_TYPE_ABTS;
10877 
10878 		/* Word 7 */
10879 		icmd->ulpClass = ulp_class;
10880 		icmd->ulpCommand = CMD_ABORT_XRI_CN;
10881 	}
10882 
10883 	/* Word 7 */
10884 	icmd->ulpLe = 1;
10885 }
10886 
10887 static void
10888 __lpfc_sli_prep_abort_xri_s4(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
10889 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia)
10890 {
10891 	union lpfc_wqe128 *wqe;
10892 
10893 	wqe = &cmdiocbq->wqe;
10894 	memset(wqe, 0, sizeof(*wqe));
10895 
10896 	/* Word 3 */
10897 	bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
10898 	if (ia)
10899 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
10900 	else
10901 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
10902 
10903 	/* Word 7 */
10904 	bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_WQE);
10905 
10906 	/* Word 8 */
10907 	wqe->abort_cmd.wqe_com.abort_tag = ulp_context;
10908 
10909 	/* Word 9 */
10910 	bf_set(wqe_reqtag, &wqe->abort_cmd.wqe_com, iotag);
10911 
10912 	/* Word 10 */
10913 	bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
10914 
10915 	/* Word 11 */
10916 	bf_set(wqe_cqid, &wqe->abort_cmd.wqe_com, cqid);
10917 	bf_set(wqe_cmd_type, &wqe->abort_cmd.wqe_com, OTHER_COMMAND);
10918 }
10919 
10920 void
10921 lpfc_sli_prep_abort_xri(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
10922 			u16 ulp_context, u16 iotag, u8 ulp_class, u16 cqid,
10923 			bool ia)
10924 {
10925 	phba->__lpfc_sli_prep_abort_xri(cmdiocbq, ulp_context, iotag, ulp_class,
10926 					cqid, ia);
10927 }
10928 
10929 /**
10930  * lpfc_sli_api_table_setup - Set up sli api function jump table
10931  * @phba: The hba struct for which this call is being executed.
10932  * @dev_grp: The HBA PCI-Device group number.
10933  *
10934  * This routine sets up the SLI interface API function jump table in @phba
10935  * struct.
10936  * Returns: 0 - success, -ENODEV - failure.
10937  **/
10938 int
10939 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10940 {
10941 
10942 	switch (dev_grp) {
10943 	case LPFC_PCI_DEV_LP:
10944 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
10945 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
10946 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
10947 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s3;
10948 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s3;
10949 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s3;
10950 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s3;
10951 		break;
10952 	case LPFC_PCI_DEV_OC:
10953 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
10954 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
10955 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
10956 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s4;
10957 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s4;
10958 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s4;
10959 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s4;
10960 		break;
10961 	default:
10962 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10963 				"1419 Invalid HBA PCI-device group: 0x%x\n",
10964 				dev_grp);
10965 		return -ENODEV;
10966 	}
10967 	return 0;
10968 }
10969 
10970 /**
10971  * lpfc_sli4_calc_ring - Calculates which ring to use
10972  * @phba: Pointer to HBA context object.
10973  * @piocb: Pointer to command iocb.
10974  *
10975  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
10976  * hba_wqidx, thus we need to calculate the corresponding ring.
10977  * Since ABORTS must go on the same WQ of the command they are
10978  * aborting, we use command's hba_wqidx.
10979  */
10980 struct lpfc_sli_ring *
10981 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
10982 {
10983 	struct lpfc_io_buf *lpfc_cmd;
10984 
10985 	if (piocb->cmd_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
10986 		if (unlikely(!phba->sli4_hba.hdwq))
10987 			return NULL;
10988 		/*
10989 		 * for abort iocb hba_wqidx should already
10990 		 * be setup based on what work queue we used.
10991 		 */
10992 		if (!(piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
10993 			lpfc_cmd = (struct lpfc_io_buf *)piocb->context1;
10994 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
10995 		}
10996 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
10997 	} else {
10998 		if (unlikely(!phba->sli4_hba.els_wq))
10999 			return NULL;
11000 		piocb->hba_wqidx = 0;
11001 		return phba->sli4_hba.els_wq->pring;
11002 	}
11003 }
11004 
11005 /**
11006  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
11007  * @phba: Pointer to HBA context object.
11008  * @ring_number: Ring number
11009  * @piocb: Pointer to command iocb.
11010  * @flag: Flag indicating if this command can be put into txq.
11011  *
11012  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
11013  * function. This function gets the hbalock and calls
11014  * __lpfc_sli_issue_iocb function and will return the error returned
11015  * by __lpfc_sli_issue_iocb function. This wrapper is used by
11016  * functions which do not hold hbalock.
11017  **/
11018 int
11019 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
11020 		    struct lpfc_iocbq *piocb, uint32_t flag)
11021 {
11022 	struct lpfc_sli_ring *pring;
11023 	struct lpfc_queue *eq;
11024 	unsigned long iflags;
11025 	int rc;
11026 
11027 	/* If the PCI channel is in offline state, do not post iocbs. */
11028 	if (unlikely(pci_channel_offline(phba->pcidev)))
11029 		return IOCB_ERROR;
11030 
11031 	if (phba->sli_rev == LPFC_SLI_REV4) {
11032 		lpfc_sli_prep_wqe(phba, piocb);
11033 
11034 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
11035 
11036 		pring = lpfc_sli4_calc_ring(phba, piocb);
11037 		if (unlikely(pring == NULL))
11038 			return IOCB_ERROR;
11039 
11040 		spin_lock_irqsave(&pring->ring_lock, iflags);
11041 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11042 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11043 
11044 		lpfc_sli4_poll_eq(eq, LPFC_POLL_FASTPATH);
11045 	} else {
11046 		/* For now, SLI2/3 will still use hbalock */
11047 		spin_lock_irqsave(&phba->hbalock, iflags);
11048 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11049 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11050 	}
11051 	return rc;
11052 }
11053 
11054 /**
11055  * lpfc_extra_ring_setup - Extra ring setup function
11056  * @phba: Pointer to HBA context object.
11057  *
11058  * This function is called while driver attaches with the
11059  * HBA to setup the extra ring. The extra ring is used
11060  * only when driver needs to support target mode functionality
11061  * or IP over FC functionalities.
11062  *
11063  * This function is called with no lock held. SLI3 only.
11064  **/
11065 static int
11066 lpfc_extra_ring_setup( struct lpfc_hba *phba)
11067 {
11068 	struct lpfc_sli *psli;
11069 	struct lpfc_sli_ring *pring;
11070 
11071 	psli = &phba->sli;
11072 
11073 	/* Adjust cmd/rsp ring iocb entries more evenly */
11074 
11075 	/* Take some away from the FCP ring */
11076 	pring = &psli->sli3_ring[LPFC_FCP_RING];
11077 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11078 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11079 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11080 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11081 
11082 	/* and give them to the extra ring */
11083 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
11084 
11085 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11086 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11087 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11088 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11089 
11090 	/* Setup default profile for this ring */
11091 	pring->iotag_max = 4096;
11092 	pring->num_mask = 1;
11093 	pring->prt[0].profile = 0;      /* Mask 0 */
11094 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
11095 	pring->prt[0].type = phba->cfg_multi_ring_type;
11096 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
11097 	return 0;
11098 }
11099 
11100 static void
11101 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
11102 			     struct lpfc_nodelist *ndlp)
11103 {
11104 	unsigned long iflags;
11105 	struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
11106 
11107 	spin_lock_irqsave(&phba->hbalock, iflags);
11108 	if (!list_empty(&evtp->evt_listp)) {
11109 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11110 		return;
11111 	}
11112 
11113 	/* Incrementing the reference count until the queued work is done. */
11114 	evtp->evt_arg1  = lpfc_nlp_get(ndlp);
11115 	if (!evtp->evt_arg1) {
11116 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11117 		return;
11118 	}
11119 	evtp->evt = LPFC_EVT_RECOVER_PORT;
11120 	list_add_tail(&evtp->evt_listp, &phba->work_list);
11121 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11122 
11123 	lpfc_worker_wake_up(phba);
11124 }
11125 
11126 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
11127  * @phba: Pointer to HBA context object.
11128  * @iocbq: Pointer to iocb object.
11129  *
11130  * The async_event handler calls this routine when it receives
11131  * an ASYNC_STATUS_CN event from the port.  The port generates
11132  * this event when an Abort Sequence request to an rport fails
11133  * twice in succession.  The abort could be originated by the
11134  * driver or by the port.  The ABTS could have been for an ELS
11135  * or FCP IO.  The port only generates this event when an ABTS
11136  * fails to complete after one retry.
11137  */
11138 static void
11139 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
11140 			  struct lpfc_iocbq *iocbq)
11141 {
11142 	struct lpfc_nodelist *ndlp = NULL;
11143 	uint16_t rpi = 0, vpi = 0;
11144 	struct lpfc_vport *vport = NULL;
11145 
11146 	/* The rpi in the ulpContext is vport-sensitive. */
11147 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
11148 	rpi = iocbq->iocb.ulpContext;
11149 
11150 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11151 			"3092 Port generated ABTS async event "
11152 			"on vpi %d rpi %d status 0x%x\n",
11153 			vpi, rpi, iocbq->iocb.ulpStatus);
11154 
11155 	vport = lpfc_find_vport_by_vpid(phba, vpi);
11156 	if (!vport)
11157 		goto err_exit;
11158 	ndlp = lpfc_findnode_rpi(vport, rpi);
11159 	if (!ndlp)
11160 		goto err_exit;
11161 
11162 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
11163 		lpfc_sli_abts_recover_port(vport, ndlp);
11164 	return;
11165 
11166  err_exit:
11167 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11168 			"3095 Event Context not found, no "
11169 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
11170 			vpi, rpi, iocbq->iocb.ulpStatus,
11171 			iocbq->iocb.ulpContext);
11172 }
11173 
11174 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
11175  * @phba: pointer to HBA context object.
11176  * @ndlp: nodelist pointer for the impacted rport.
11177  * @axri: pointer to the wcqe containing the failed exchange.
11178  *
11179  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
11180  * port.  The port generates this event when an abort exchange request to an
11181  * rport fails twice in succession with no reply.  The abort could be originated
11182  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
11183  */
11184 void
11185 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
11186 			   struct lpfc_nodelist *ndlp,
11187 			   struct sli4_wcqe_xri_aborted *axri)
11188 {
11189 	uint32_t ext_status = 0;
11190 
11191 	if (!ndlp) {
11192 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11193 				"3115 Node Context not found, driver "
11194 				"ignoring abts err event\n");
11195 		return;
11196 	}
11197 
11198 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11199 			"3116 Port generated FCP XRI ABORT event on "
11200 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
11201 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
11202 			bf_get(lpfc_wcqe_xa_xri, axri),
11203 			bf_get(lpfc_wcqe_xa_status, axri),
11204 			axri->parameter);
11205 
11206 	/*
11207 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
11208 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
11209 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
11210 	 */
11211 	ext_status = axri->parameter & IOERR_PARAM_MASK;
11212 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
11213 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
11214 		lpfc_sli_post_recovery_event(phba, ndlp);
11215 }
11216 
11217 /**
11218  * lpfc_sli_async_event_handler - ASYNC iocb handler function
11219  * @phba: Pointer to HBA context object.
11220  * @pring: Pointer to driver SLI ring object.
11221  * @iocbq: Pointer to iocb object.
11222  *
11223  * This function is called by the slow ring event handler
11224  * function when there is an ASYNC event iocb in the ring.
11225  * This function is called with no lock held.
11226  * Currently this function handles only temperature related
11227  * ASYNC events. The function decodes the temperature sensor
11228  * event message and posts events for the management applications.
11229  **/
11230 static void
11231 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
11232 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
11233 {
11234 	IOCB_t *icmd;
11235 	uint16_t evt_code;
11236 	struct temp_event temp_event_data;
11237 	struct Scsi_Host *shost;
11238 	uint32_t *iocb_w;
11239 
11240 	icmd = &iocbq->iocb;
11241 	evt_code = icmd->un.asyncstat.evt_code;
11242 
11243 	switch (evt_code) {
11244 	case ASYNC_TEMP_WARN:
11245 	case ASYNC_TEMP_SAFE:
11246 		temp_event_data.data = (uint32_t) icmd->ulpContext;
11247 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
11248 		if (evt_code == ASYNC_TEMP_WARN) {
11249 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
11250 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11251 				"0347 Adapter is very hot, please take "
11252 				"corrective action. temperature : %d Celsius\n",
11253 				(uint32_t) icmd->ulpContext);
11254 		} else {
11255 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
11256 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11257 				"0340 Adapter temperature is OK now. "
11258 				"temperature : %d Celsius\n",
11259 				(uint32_t) icmd->ulpContext);
11260 		}
11261 
11262 		/* Send temperature change event to applications */
11263 		shost = lpfc_shost_from_vport(phba->pport);
11264 		fc_host_post_vendor_event(shost, fc_get_event_number(),
11265 			sizeof(temp_event_data), (char *) &temp_event_data,
11266 			LPFC_NL_VENDOR_ID);
11267 		break;
11268 	case ASYNC_STATUS_CN:
11269 		lpfc_sli_abts_err_handler(phba, iocbq);
11270 		break;
11271 	default:
11272 		iocb_w = (uint32_t *) icmd;
11273 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11274 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
11275 			" evt_code 0x%x\n"
11276 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
11277 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
11278 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
11279 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
11280 			pring->ringno, icmd->un.asyncstat.evt_code,
11281 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
11282 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
11283 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
11284 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
11285 
11286 		break;
11287 	}
11288 }
11289 
11290 
11291 /**
11292  * lpfc_sli4_setup - SLI ring setup function
11293  * @phba: Pointer to HBA context object.
11294  *
11295  * lpfc_sli_setup sets up rings of the SLI interface with
11296  * number of iocbs per ring and iotags. This function is
11297  * called while driver attach to the HBA and before the
11298  * interrupts are enabled. So there is no need for locking.
11299  *
11300  * This function always returns 0.
11301  **/
11302 int
11303 lpfc_sli4_setup(struct lpfc_hba *phba)
11304 {
11305 	struct lpfc_sli_ring *pring;
11306 
11307 	pring = phba->sli4_hba.els_wq->pring;
11308 	pring->num_mask = LPFC_MAX_RING_MASK;
11309 	pring->prt[0].profile = 0;	/* Mask 0 */
11310 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11311 	pring->prt[0].type = FC_TYPE_ELS;
11312 	pring->prt[0].lpfc_sli_rcv_unsol_event =
11313 	    lpfc_els_unsol_event;
11314 	pring->prt[1].profile = 0;	/* Mask 1 */
11315 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
11316 	pring->prt[1].type = FC_TYPE_ELS;
11317 	pring->prt[1].lpfc_sli_rcv_unsol_event =
11318 	    lpfc_els_unsol_event;
11319 	pring->prt[2].profile = 0;	/* Mask 2 */
11320 	/* NameServer Inquiry */
11321 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11322 	/* NameServer */
11323 	pring->prt[2].type = FC_TYPE_CT;
11324 	pring->prt[2].lpfc_sli_rcv_unsol_event =
11325 	    lpfc_ct_unsol_event;
11326 	pring->prt[3].profile = 0;	/* Mask 3 */
11327 	/* NameServer response */
11328 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11329 	/* NameServer */
11330 	pring->prt[3].type = FC_TYPE_CT;
11331 	pring->prt[3].lpfc_sli_rcv_unsol_event =
11332 	    lpfc_ct_unsol_event;
11333 	return 0;
11334 }
11335 
11336 /**
11337  * lpfc_sli_setup - SLI ring setup function
11338  * @phba: Pointer to HBA context object.
11339  *
11340  * lpfc_sli_setup sets up rings of the SLI interface with
11341  * number of iocbs per ring and iotags. This function is
11342  * called while driver attach to the HBA and before the
11343  * interrupts are enabled. So there is no need for locking.
11344  *
11345  * This function always returns 0. SLI3 only.
11346  **/
11347 int
11348 lpfc_sli_setup(struct lpfc_hba *phba)
11349 {
11350 	int i, totiocbsize = 0;
11351 	struct lpfc_sli *psli = &phba->sli;
11352 	struct lpfc_sli_ring *pring;
11353 
11354 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
11355 	psli->sli_flag = 0;
11356 
11357 	psli->iocbq_lookup = NULL;
11358 	psli->iocbq_lookup_len = 0;
11359 	psli->last_iotag = 0;
11360 
11361 	for (i = 0; i < psli->num_rings; i++) {
11362 		pring = &psli->sli3_ring[i];
11363 		switch (i) {
11364 		case LPFC_FCP_RING:	/* ring 0 - FCP */
11365 			/* numCiocb and numRiocb are used in config_port */
11366 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
11367 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
11368 			pring->sli.sli3.numCiocb +=
11369 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11370 			pring->sli.sli3.numRiocb +=
11371 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11372 			pring->sli.sli3.numCiocb +=
11373 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11374 			pring->sli.sli3.numRiocb +=
11375 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11376 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11377 							SLI3_IOCB_CMD_SIZE :
11378 							SLI2_IOCB_CMD_SIZE;
11379 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11380 							SLI3_IOCB_RSP_SIZE :
11381 							SLI2_IOCB_RSP_SIZE;
11382 			pring->iotag_ctr = 0;
11383 			pring->iotag_max =
11384 			    (phba->cfg_hba_queue_depth * 2);
11385 			pring->fast_iotag = pring->iotag_max;
11386 			pring->num_mask = 0;
11387 			break;
11388 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
11389 			/* numCiocb and numRiocb are used in config_port */
11390 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
11391 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
11392 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11393 							SLI3_IOCB_CMD_SIZE :
11394 							SLI2_IOCB_CMD_SIZE;
11395 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11396 							SLI3_IOCB_RSP_SIZE :
11397 							SLI2_IOCB_RSP_SIZE;
11398 			pring->iotag_max = phba->cfg_hba_queue_depth;
11399 			pring->num_mask = 0;
11400 			break;
11401 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
11402 			/* numCiocb and numRiocb are used in config_port */
11403 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
11404 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
11405 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11406 							SLI3_IOCB_CMD_SIZE :
11407 							SLI2_IOCB_CMD_SIZE;
11408 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11409 							SLI3_IOCB_RSP_SIZE :
11410 							SLI2_IOCB_RSP_SIZE;
11411 			pring->fast_iotag = 0;
11412 			pring->iotag_ctr = 0;
11413 			pring->iotag_max = 4096;
11414 			pring->lpfc_sli_rcv_async_status =
11415 				lpfc_sli_async_event_handler;
11416 			pring->num_mask = LPFC_MAX_RING_MASK;
11417 			pring->prt[0].profile = 0;	/* Mask 0 */
11418 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11419 			pring->prt[0].type = FC_TYPE_ELS;
11420 			pring->prt[0].lpfc_sli_rcv_unsol_event =
11421 			    lpfc_els_unsol_event;
11422 			pring->prt[1].profile = 0;	/* Mask 1 */
11423 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
11424 			pring->prt[1].type = FC_TYPE_ELS;
11425 			pring->prt[1].lpfc_sli_rcv_unsol_event =
11426 			    lpfc_els_unsol_event;
11427 			pring->prt[2].profile = 0;	/* Mask 2 */
11428 			/* NameServer Inquiry */
11429 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11430 			/* NameServer */
11431 			pring->prt[2].type = FC_TYPE_CT;
11432 			pring->prt[2].lpfc_sli_rcv_unsol_event =
11433 			    lpfc_ct_unsol_event;
11434 			pring->prt[3].profile = 0;	/* Mask 3 */
11435 			/* NameServer response */
11436 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11437 			/* NameServer */
11438 			pring->prt[3].type = FC_TYPE_CT;
11439 			pring->prt[3].lpfc_sli_rcv_unsol_event =
11440 			    lpfc_ct_unsol_event;
11441 			break;
11442 		}
11443 		totiocbsize += (pring->sli.sli3.numCiocb *
11444 			pring->sli.sli3.sizeCiocb) +
11445 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
11446 	}
11447 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
11448 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
11449 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
11450 		       "SLI2 SLIM Data: x%x x%lx\n",
11451 		       phba->brd_no, totiocbsize,
11452 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
11453 	}
11454 	if (phba->cfg_multi_ring_support == 2)
11455 		lpfc_extra_ring_setup(phba);
11456 
11457 	return 0;
11458 }
11459 
11460 /**
11461  * lpfc_sli4_queue_init - Queue initialization function
11462  * @phba: Pointer to HBA context object.
11463  *
11464  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
11465  * ring. This function also initializes ring indices of each ring.
11466  * This function is called during the initialization of the SLI
11467  * interface of an HBA.
11468  * This function is called with no lock held and always returns
11469  * 1.
11470  **/
11471 void
11472 lpfc_sli4_queue_init(struct lpfc_hba *phba)
11473 {
11474 	struct lpfc_sli *psli;
11475 	struct lpfc_sli_ring *pring;
11476 	int i;
11477 
11478 	psli = &phba->sli;
11479 	spin_lock_irq(&phba->hbalock);
11480 	INIT_LIST_HEAD(&psli->mboxq);
11481 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11482 	/* Initialize list headers for txq and txcmplq as double linked lists */
11483 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
11484 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
11485 		pring->flag = 0;
11486 		pring->ringno = LPFC_FCP_RING;
11487 		pring->txcmplq_cnt = 0;
11488 		INIT_LIST_HEAD(&pring->txq);
11489 		INIT_LIST_HEAD(&pring->txcmplq);
11490 		INIT_LIST_HEAD(&pring->iocb_continueq);
11491 		spin_lock_init(&pring->ring_lock);
11492 	}
11493 	pring = phba->sli4_hba.els_wq->pring;
11494 	pring->flag = 0;
11495 	pring->ringno = LPFC_ELS_RING;
11496 	pring->txcmplq_cnt = 0;
11497 	INIT_LIST_HEAD(&pring->txq);
11498 	INIT_LIST_HEAD(&pring->txcmplq);
11499 	INIT_LIST_HEAD(&pring->iocb_continueq);
11500 	spin_lock_init(&pring->ring_lock);
11501 
11502 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11503 		pring = phba->sli4_hba.nvmels_wq->pring;
11504 		pring->flag = 0;
11505 		pring->ringno = LPFC_ELS_RING;
11506 		pring->txcmplq_cnt = 0;
11507 		INIT_LIST_HEAD(&pring->txq);
11508 		INIT_LIST_HEAD(&pring->txcmplq);
11509 		INIT_LIST_HEAD(&pring->iocb_continueq);
11510 		spin_lock_init(&pring->ring_lock);
11511 	}
11512 
11513 	spin_unlock_irq(&phba->hbalock);
11514 }
11515 
11516 /**
11517  * lpfc_sli_queue_init - Queue initialization function
11518  * @phba: Pointer to HBA context object.
11519  *
11520  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11521  * ring. This function also initializes ring indices of each ring.
11522  * This function is called during the initialization of the SLI
11523  * interface of an HBA.
11524  * This function is called with no lock held and always returns
11525  * 1.
11526  **/
11527 void
11528 lpfc_sli_queue_init(struct lpfc_hba *phba)
11529 {
11530 	struct lpfc_sli *psli;
11531 	struct lpfc_sli_ring *pring;
11532 	int i;
11533 
11534 	psli = &phba->sli;
11535 	spin_lock_irq(&phba->hbalock);
11536 	INIT_LIST_HEAD(&psli->mboxq);
11537 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11538 	/* Initialize list headers for txq and txcmplq as double linked lists */
11539 	for (i = 0; i < psli->num_rings; i++) {
11540 		pring = &psli->sli3_ring[i];
11541 		pring->ringno = i;
11542 		pring->sli.sli3.next_cmdidx  = 0;
11543 		pring->sli.sli3.local_getidx = 0;
11544 		pring->sli.sli3.cmdidx = 0;
11545 		INIT_LIST_HEAD(&pring->iocb_continueq);
11546 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11547 		INIT_LIST_HEAD(&pring->postbufq);
11548 		pring->flag = 0;
11549 		INIT_LIST_HEAD(&pring->txq);
11550 		INIT_LIST_HEAD(&pring->txcmplq);
11551 		spin_lock_init(&pring->ring_lock);
11552 	}
11553 	spin_unlock_irq(&phba->hbalock);
11554 }
11555 
11556 /**
11557  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11558  * @phba: Pointer to HBA context object.
11559  *
11560  * This routine flushes the mailbox command subsystem. It will unconditionally
11561  * flush all the mailbox commands in the three possible stages in the mailbox
11562  * command sub-system: pending mailbox command queue; the outstanding mailbox
11563  * command; and completed mailbox command queue. It is caller's responsibility
11564  * to make sure that the driver is in the proper state to flush the mailbox
11565  * command sub-system. Namely, the posting of mailbox commands into the
11566  * pending mailbox command queue from the various clients must be stopped;
11567  * either the HBA is in a state that it will never works on the outstanding
11568  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11569  * mailbox command has been completed.
11570  **/
11571 static void
11572 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11573 {
11574 	LIST_HEAD(completions);
11575 	struct lpfc_sli *psli = &phba->sli;
11576 	LPFC_MBOXQ_t *pmb;
11577 	unsigned long iflag;
11578 
11579 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11580 	local_bh_disable();
11581 
11582 	/* Flush all the mailbox commands in the mbox system */
11583 	spin_lock_irqsave(&phba->hbalock, iflag);
11584 
11585 	/* The pending mailbox command queue */
11586 	list_splice_init(&phba->sli.mboxq, &completions);
11587 	/* The outstanding active mailbox command */
11588 	if (psli->mbox_active) {
11589 		list_add_tail(&psli->mbox_active->list, &completions);
11590 		psli->mbox_active = NULL;
11591 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11592 	}
11593 	/* The completed mailbox command queue */
11594 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11595 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11596 
11597 	/* Enable softirqs again, done with phba->hbalock */
11598 	local_bh_enable();
11599 
11600 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11601 	while (!list_empty(&completions)) {
11602 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11603 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11604 		if (pmb->mbox_cmpl)
11605 			pmb->mbox_cmpl(phba, pmb);
11606 	}
11607 }
11608 
11609 /**
11610  * lpfc_sli_host_down - Vport cleanup function
11611  * @vport: Pointer to virtual port object.
11612  *
11613  * lpfc_sli_host_down is called to clean up the resources
11614  * associated with a vport before destroying virtual
11615  * port data structures.
11616  * This function does following operations:
11617  * - Free discovery resources associated with this virtual
11618  *   port.
11619  * - Free iocbs associated with this virtual port in
11620  *   the txq.
11621  * - Send abort for all iocb commands associated with this
11622  *   vport in txcmplq.
11623  *
11624  * This function is called with no lock held and always returns 1.
11625  **/
11626 int
11627 lpfc_sli_host_down(struct lpfc_vport *vport)
11628 {
11629 	LIST_HEAD(completions);
11630 	struct lpfc_hba *phba = vport->phba;
11631 	struct lpfc_sli *psli = &phba->sli;
11632 	struct lpfc_queue *qp = NULL;
11633 	struct lpfc_sli_ring *pring;
11634 	struct lpfc_iocbq *iocb, *next_iocb;
11635 	int i;
11636 	unsigned long flags = 0;
11637 	uint16_t prev_pring_flag;
11638 
11639 	lpfc_cleanup_discovery_resources(vport);
11640 
11641 	spin_lock_irqsave(&phba->hbalock, flags);
11642 
11643 	/*
11644 	 * Error everything on the txq since these iocbs
11645 	 * have not been given to the FW yet.
11646 	 * Also issue ABTS for everything on the txcmplq
11647 	 */
11648 	if (phba->sli_rev != LPFC_SLI_REV4) {
11649 		for (i = 0; i < psli->num_rings; i++) {
11650 			pring = &psli->sli3_ring[i];
11651 			prev_pring_flag = pring->flag;
11652 			/* Only slow rings */
11653 			if (pring->ringno == LPFC_ELS_RING) {
11654 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11655 				/* Set the lpfc data pending flag */
11656 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11657 			}
11658 			list_for_each_entry_safe(iocb, next_iocb,
11659 						 &pring->txq, list) {
11660 				if (iocb->vport != vport)
11661 					continue;
11662 				list_move_tail(&iocb->list, &completions);
11663 			}
11664 			list_for_each_entry_safe(iocb, next_iocb,
11665 						 &pring->txcmplq, list) {
11666 				if (iocb->vport != vport)
11667 					continue;
11668 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11669 							   NULL);
11670 			}
11671 			pring->flag = prev_pring_flag;
11672 		}
11673 	} else {
11674 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11675 			pring = qp->pring;
11676 			if (!pring)
11677 				continue;
11678 			if (pring == phba->sli4_hba.els_wq->pring) {
11679 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11680 				/* Set the lpfc data pending flag */
11681 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11682 			}
11683 			prev_pring_flag = pring->flag;
11684 			spin_lock(&pring->ring_lock);
11685 			list_for_each_entry_safe(iocb, next_iocb,
11686 						 &pring->txq, list) {
11687 				if (iocb->vport != vport)
11688 					continue;
11689 				list_move_tail(&iocb->list, &completions);
11690 			}
11691 			spin_unlock(&pring->ring_lock);
11692 			list_for_each_entry_safe(iocb, next_iocb,
11693 						 &pring->txcmplq, list) {
11694 				if (iocb->vport != vport)
11695 					continue;
11696 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11697 							   NULL);
11698 			}
11699 			pring->flag = prev_pring_flag;
11700 		}
11701 	}
11702 	spin_unlock_irqrestore(&phba->hbalock, flags);
11703 
11704 	/* Make sure HBA is alive */
11705 	lpfc_issue_hb_tmo(phba);
11706 
11707 	/* Cancel all the IOCBs from the completions list */
11708 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11709 			      IOERR_SLI_DOWN);
11710 	return 1;
11711 }
11712 
11713 /**
11714  * lpfc_sli_hba_down - Resource cleanup function for the HBA
11715  * @phba: Pointer to HBA context object.
11716  *
11717  * This function cleans up all iocb, buffers, mailbox commands
11718  * while shutting down the HBA. This function is called with no
11719  * lock held and always returns 1.
11720  * This function does the following to cleanup driver resources:
11721  * - Free discovery resources for each virtual port
11722  * - Cleanup any pending fabric iocbs
11723  * - Iterate through the iocb txq and free each entry
11724  *   in the list.
11725  * - Free up any buffer posted to the HBA
11726  * - Free mailbox commands in the mailbox queue.
11727  **/
11728 int
11729 lpfc_sli_hba_down(struct lpfc_hba *phba)
11730 {
11731 	LIST_HEAD(completions);
11732 	struct lpfc_sli *psli = &phba->sli;
11733 	struct lpfc_queue *qp = NULL;
11734 	struct lpfc_sli_ring *pring;
11735 	struct lpfc_dmabuf *buf_ptr;
11736 	unsigned long flags = 0;
11737 	int i;
11738 
11739 	/* Shutdown the mailbox command sub-system */
11740 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
11741 
11742 	lpfc_hba_down_prep(phba);
11743 
11744 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11745 	local_bh_disable();
11746 
11747 	lpfc_fabric_abort_hba(phba);
11748 
11749 	spin_lock_irqsave(&phba->hbalock, flags);
11750 
11751 	/*
11752 	 * Error everything on the txq since these iocbs
11753 	 * have not been given to the FW yet.
11754 	 */
11755 	if (phba->sli_rev != LPFC_SLI_REV4) {
11756 		for (i = 0; i < psli->num_rings; i++) {
11757 			pring = &psli->sli3_ring[i];
11758 			/* Only slow rings */
11759 			if (pring->ringno == LPFC_ELS_RING) {
11760 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11761 				/* Set the lpfc data pending flag */
11762 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11763 			}
11764 			list_splice_init(&pring->txq, &completions);
11765 		}
11766 	} else {
11767 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11768 			pring = qp->pring;
11769 			if (!pring)
11770 				continue;
11771 			spin_lock(&pring->ring_lock);
11772 			list_splice_init(&pring->txq, &completions);
11773 			spin_unlock(&pring->ring_lock);
11774 			if (pring == phba->sli4_hba.els_wq->pring) {
11775 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11776 				/* Set the lpfc data pending flag */
11777 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11778 			}
11779 		}
11780 	}
11781 	spin_unlock_irqrestore(&phba->hbalock, flags);
11782 
11783 	/* Cancel all the IOCBs from the completions list */
11784 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11785 			      IOERR_SLI_DOWN);
11786 
11787 	spin_lock_irqsave(&phba->hbalock, flags);
11788 	list_splice_init(&phba->elsbuf, &completions);
11789 	phba->elsbuf_cnt = 0;
11790 	phba->elsbuf_prev_cnt = 0;
11791 	spin_unlock_irqrestore(&phba->hbalock, flags);
11792 
11793 	while (!list_empty(&completions)) {
11794 		list_remove_head(&completions, buf_ptr,
11795 			struct lpfc_dmabuf, list);
11796 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
11797 		kfree(buf_ptr);
11798 	}
11799 
11800 	/* Enable softirqs again, done with phba->hbalock */
11801 	local_bh_enable();
11802 
11803 	/* Return any active mbox cmds */
11804 	del_timer_sync(&psli->mbox_tmo);
11805 
11806 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
11807 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
11808 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
11809 
11810 	return 1;
11811 }
11812 
11813 /**
11814  * lpfc_sli_pcimem_bcopy - SLI memory copy function
11815  * @srcp: Source memory pointer.
11816  * @destp: Destination memory pointer.
11817  * @cnt: Number of words required to be copied.
11818  *
11819  * This function is used for copying data between driver memory
11820  * and the SLI memory. This function also changes the endianness
11821  * of each word if native endianness is different from SLI
11822  * endianness. This function can be called with or without
11823  * lock.
11824  **/
11825 void
11826 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
11827 {
11828 	uint32_t *src = srcp;
11829 	uint32_t *dest = destp;
11830 	uint32_t ldata;
11831 	int i;
11832 
11833 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
11834 		ldata = *src;
11835 		ldata = le32_to_cpu(ldata);
11836 		*dest = ldata;
11837 		src++;
11838 		dest++;
11839 	}
11840 }
11841 
11842 
11843 /**
11844  * lpfc_sli_bemem_bcopy - SLI memory copy function
11845  * @srcp: Source memory pointer.
11846  * @destp: Destination memory pointer.
11847  * @cnt: Number of words required to be copied.
11848  *
11849  * This function is used for copying data between a data structure
11850  * with big endian representation to local endianness.
11851  * This function can be called with or without lock.
11852  **/
11853 void
11854 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
11855 {
11856 	uint32_t *src = srcp;
11857 	uint32_t *dest = destp;
11858 	uint32_t ldata;
11859 	int i;
11860 
11861 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
11862 		ldata = *src;
11863 		ldata = be32_to_cpu(ldata);
11864 		*dest = ldata;
11865 		src++;
11866 		dest++;
11867 	}
11868 }
11869 
11870 /**
11871  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
11872  * @phba: Pointer to HBA context object.
11873  * @pring: Pointer to driver SLI ring object.
11874  * @mp: Pointer to driver buffer object.
11875  *
11876  * This function is called with no lock held.
11877  * It always return zero after adding the buffer to the postbufq
11878  * buffer list.
11879  **/
11880 int
11881 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11882 			 struct lpfc_dmabuf *mp)
11883 {
11884 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
11885 	   later */
11886 	spin_lock_irq(&phba->hbalock);
11887 	list_add_tail(&mp->list, &pring->postbufq);
11888 	pring->postbufq_cnt++;
11889 	spin_unlock_irq(&phba->hbalock);
11890 	return 0;
11891 }
11892 
11893 /**
11894  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
11895  * @phba: Pointer to HBA context object.
11896  *
11897  * When HBQ is enabled, buffers are searched based on tags. This function
11898  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
11899  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
11900  * does not conflict with tags of buffer posted for unsolicited events.
11901  * The function returns the allocated tag. The function is called with
11902  * no locks held.
11903  **/
11904 uint32_t
11905 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
11906 {
11907 	spin_lock_irq(&phba->hbalock);
11908 	phba->buffer_tag_count++;
11909 	/*
11910 	 * Always set the QUE_BUFTAG_BIT to distiguish between
11911 	 * a tag assigned by HBQ.
11912 	 */
11913 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
11914 	spin_unlock_irq(&phba->hbalock);
11915 	return phba->buffer_tag_count;
11916 }
11917 
11918 /**
11919  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
11920  * @phba: Pointer to HBA context object.
11921  * @pring: Pointer to driver SLI ring object.
11922  * @tag: Buffer tag.
11923  *
11924  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
11925  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
11926  * iocb is posted to the response ring with the tag of the buffer.
11927  * This function searches the pring->postbufq list using the tag
11928  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
11929  * iocb. If the buffer is found then lpfc_dmabuf object of the
11930  * buffer is returned to the caller else NULL is returned.
11931  * This function is called with no lock held.
11932  **/
11933 struct lpfc_dmabuf *
11934 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11935 			uint32_t tag)
11936 {
11937 	struct lpfc_dmabuf *mp, *next_mp;
11938 	struct list_head *slp = &pring->postbufq;
11939 
11940 	/* Search postbufq, from the beginning, looking for a match on tag */
11941 	spin_lock_irq(&phba->hbalock);
11942 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11943 		if (mp->buffer_tag == tag) {
11944 			list_del_init(&mp->list);
11945 			pring->postbufq_cnt--;
11946 			spin_unlock_irq(&phba->hbalock);
11947 			return mp;
11948 		}
11949 	}
11950 
11951 	spin_unlock_irq(&phba->hbalock);
11952 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11953 			"0402 Cannot find virtual addr for buffer tag on "
11954 			"ring %d Data x%lx x%px x%px x%x\n",
11955 			pring->ringno, (unsigned long) tag,
11956 			slp->next, slp->prev, pring->postbufq_cnt);
11957 
11958 	return NULL;
11959 }
11960 
11961 /**
11962  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
11963  * @phba: Pointer to HBA context object.
11964  * @pring: Pointer to driver SLI ring object.
11965  * @phys: DMA address of the buffer.
11966  *
11967  * This function searches the buffer list using the dma_address
11968  * of unsolicited event to find the driver's lpfc_dmabuf object
11969  * corresponding to the dma_address. The function returns the
11970  * lpfc_dmabuf object if a buffer is found else it returns NULL.
11971  * This function is called by the ct and els unsolicited event
11972  * handlers to get the buffer associated with the unsolicited
11973  * event.
11974  *
11975  * This function is called with no lock held.
11976  **/
11977 struct lpfc_dmabuf *
11978 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11979 			 dma_addr_t phys)
11980 {
11981 	struct lpfc_dmabuf *mp, *next_mp;
11982 	struct list_head *slp = &pring->postbufq;
11983 
11984 	/* Search postbufq, from the beginning, looking for a match on phys */
11985 	spin_lock_irq(&phba->hbalock);
11986 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11987 		if (mp->phys == phys) {
11988 			list_del_init(&mp->list);
11989 			pring->postbufq_cnt--;
11990 			spin_unlock_irq(&phba->hbalock);
11991 			return mp;
11992 		}
11993 	}
11994 
11995 	spin_unlock_irq(&phba->hbalock);
11996 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11997 			"0410 Cannot find virtual addr for mapped buf on "
11998 			"ring %d Data x%llx x%px x%px x%x\n",
11999 			pring->ringno, (unsigned long long)phys,
12000 			slp->next, slp->prev, pring->postbufq_cnt);
12001 	return NULL;
12002 }
12003 
12004 /**
12005  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
12006  * @phba: Pointer to HBA context object.
12007  * @cmdiocb: Pointer to driver command iocb object.
12008  * @rspiocb: Pointer to driver response iocb object.
12009  *
12010  * This function is the completion handler for the abort iocbs for
12011  * ELS commands. This function is called from the ELS ring event
12012  * handler with no lock held. This function frees memory resources
12013  * associated with the abort iocb.
12014  **/
12015 static void
12016 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12017 			struct lpfc_iocbq *rspiocb)
12018 {
12019 	u32 ulp_status = get_job_ulpstatus(phba, rspiocb);
12020 	u32 ulp_word4 = get_job_word4(phba, rspiocb);
12021 	u8 cmnd = get_job_cmnd(phba, cmdiocb);
12022 
12023 	if (ulp_status) {
12024 		/*
12025 		 * Assume that the port already completed and returned, or
12026 		 * will return the iocb. Just Log the message.
12027 		 */
12028 		if (phba->sli_rev < LPFC_SLI_REV4) {
12029 			if (cmnd == CMD_ABORT_XRI_CX &&
12030 			    ulp_status == IOSTAT_LOCAL_REJECT &&
12031 			    ulp_word4 == IOERR_ABORT_REQUESTED) {
12032 				goto release_iocb;
12033 			}
12034 		}
12035 
12036 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
12037 				"0327 Cannot abort els iocb x%px "
12038 				"with io cmd xri %x abort tag : x%x, "
12039 				"abort status %x abort code %x\n",
12040 				cmdiocb, get_job_abtsiotag(phba, cmdiocb),
12041 				(phba->sli_rev == LPFC_SLI_REV4) ?
12042 				get_wqe_reqtag(cmdiocb) :
12043 				cmdiocb->iocb.un.acxri.abortContextTag,
12044 				ulp_status, ulp_word4);
12045 
12046 	}
12047 release_iocb:
12048 	lpfc_sli_release_iocbq(phba, cmdiocb);
12049 	return;
12050 }
12051 
12052 /**
12053  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
12054  * @phba: Pointer to HBA context object.
12055  * @cmdiocb: Pointer to driver command iocb object.
12056  * @rspiocb: Pointer to driver response iocb object.
12057  *
12058  * The function is called from SLI ring event handler with no
12059  * lock held. This function is the completion handler for ELS commands
12060  * which are aborted. The function frees memory resources used for
12061  * the aborted ELS commands.
12062  **/
12063 void
12064 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12065 		     struct lpfc_iocbq *rspiocb)
12066 {
12067 	struct lpfc_nodelist *ndlp = NULL;
12068 	IOCB_t *irsp;
12069 	u32 ulp_command, ulp_status, ulp_word4, iotag;
12070 
12071 	ulp_command = get_job_cmnd(phba, cmdiocb);
12072 	ulp_status = get_job_ulpstatus(phba, rspiocb);
12073 	ulp_word4 = get_job_word4(phba, rspiocb);
12074 
12075 	if (phba->sli_rev == LPFC_SLI_REV4) {
12076 		iotag = get_wqe_reqtag(cmdiocb);
12077 	} else {
12078 		irsp = &rspiocb->iocb;
12079 		iotag = irsp->ulpIoTag;
12080 	}
12081 
12082 	/* ELS cmd tag <ulpIoTag> completes */
12083 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
12084 			"0139 Ignoring ELS cmd code x%x completion Data: "
12085 			"x%x x%x x%x\n",
12086 			ulp_command, ulp_status, ulp_word4, iotag);
12087 
12088 	/*
12089 	 * Deref the ndlp after free_iocb. sli_release_iocb will access the ndlp
12090 	 * if exchange is busy.
12091 	 */
12092 	if (ulp_command == CMD_GEN_REQUEST64_CR) {
12093 		ndlp = cmdiocb->context_un.ndlp;
12094 		lpfc_ct_free_iocb(phba, cmdiocb);
12095 	} else {
12096 		ndlp = (struct lpfc_nodelist *) cmdiocb->context1;
12097 		lpfc_els_free_iocb(phba, cmdiocb);
12098 	}
12099 
12100 	lpfc_nlp_put(ndlp);
12101 }
12102 
12103 /**
12104  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
12105  * @phba: Pointer to HBA context object.
12106  * @pring: Pointer to driver SLI ring object.
12107  * @cmdiocb: Pointer to driver command iocb object.
12108  * @cmpl: completion function.
12109  *
12110  * This function issues an abort iocb for the provided command iocb. In case
12111  * of unloading, the abort iocb will not be issued to commands on the ELS
12112  * ring. Instead, the callback function shall be changed to those commands
12113  * so that nothing happens when them finishes. This function is called with
12114  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
12115  * when the command iocb is an abort request.
12116  *
12117  **/
12118 int
12119 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12120 			   struct lpfc_iocbq *cmdiocb, void *cmpl)
12121 {
12122 	struct lpfc_vport *vport = cmdiocb->vport;
12123 	struct lpfc_iocbq *abtsiocbp;
12124 	int retval = IOCB_ERROR;
12125 	unsigned long iflags;
12126 	struct lpfc_nodelist *ndlp = NULL;
12127 	u32 ulp_command = get_job_cmnd(phba, cmdiocb);
12128 	u16 ulp_context, iotag;
12129 	bool ia;
12130 
12131 	/*
12132 	 * There are certain command types we don't want to abort.  And we
12133 	 * don't want to abort commands that are already in the process of
12134 	 * being aborted.
12135 	 */
12136 	if (ulp_command == CMD_ABORT_XRI_WQE ||
12137 	    ulp_command == CMD_ABORT_XRI_CN ||
12138 	    ulp_command == CMD_CLOSE_XRI_CN ||
12139 	    cmdiocb->cmd_flag & LPFC_DRIVER_ABORTED)
12140 		return IOCB_ABORTING;
12141 
12142 	if (!pring) {
12143 		if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12144 			cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12145 		else
12146 			cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12147 		return retval;
12148 	}
12149 
12150 	/*
12151 	 * If we're unloading, don't abort iocb on the ELS ring, but change
12152 	 * the callback so that nothing happens when it finishes.
12153 	 */
12154 	if ((vport->load_flag & FC_UNLOADING) &&
12155 	    pring->ringno == LPFC_ELS_RING) {
12156 		if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12157 			cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12158 		else
12159 			cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12160 		return retval;
12161 	}
12162 
12163 	/* issue ABTS for this IOCB based on iotag */
12164 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
12165 	if (abtsiocbp == NULL)
12166 		return IOCB_NORESOURCE;
12167 
12168 	/* This signals the response to set the correct status
12169 	 * before calling the completion handler
12170 	 */
12171 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
12172 
12173 	if (phba->sli_rev == LPFC_SLI_REV4) {
12174 		ulp_context = cmdiocb->sli4_xritag;
12175 		iotag = abtsiocbp->iotag;
12176 	} else {
12177 		iotag = cmdiocb->iocb.ulpIoTag;
12178 		if (pring->ringno == LPFC_ELS_RING) {
12179 			ndlp = (struct lpfc_nodelist *)(cmdiocb->context1);
12180 			ulp_context = ndlp->nlp_rpi;
12181 		} else {
12182 			ulp_context = cmdiocb->iocb.ulpContext;
12183 		}
12184 	}
12185 
12186 	if (phba->link_state < LPFC_LINK_UP ||
12187 	    (phba->sli_rev == LPFC_SLI_REV4 &&
12188 	     phba->sli4_hba.link_state.status == LPFC_FC_LA_TYPE_LINK_DOWN))
12189 		ia = true;
12190 	else
12191 		ia = false;
12192 
12193 	lpfc_sli_prep_abort_xri(phba, abtsiocbp, ulp_context, iotag,
12194 				cmdiocb->iocb.ulpClass,
12195 				LPFC_WQE_CQ_ID_DEFAULT, ia);
12196 
12197 	abtsiocbp->vport = vport;
12198 
12199 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12200 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
12201 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
12202 		abtsiocbp->cmd_flag |= (LPFC_IO_FCP | LPFC_USE_FCPWQIDX);
12203 
12204 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
12205 		abtsiocbp->cmd_flag |= LPFC_IO_FOF;
12206 
12207 	if (cmpl)
12208 		abtsiocbp->cmd_cmpl = cmpl;
12209 	else
12210 		abtsiocbp->cmd_cmpl = lpfc_sli_abort_els_cmpl;
12211 	abtsiocbp->vport = vport;
12212 
12213 	if (phba->sli_rev == LPFC_SLI_REV4) {
12214 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
12215 		if (unlikely(pring == NULL))
12216 			goto abort_iotag_exit;
12217 		/* Note: both hbalock and ring_lock need to be set here */
12218 		spin_lock_irqsave(&pring->ring_lock, iflags);
12219 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12220 			abtsiocbp, 0);
12221 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
12222 	} else {
12223 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12224 			abtsiocbp, 0);
12225 	}
12226 
12227 abort_iotag_exit:
12228 
12229 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
12230 			 "0339 Abort IO XRI x%x, Original iotag x%x, "
12231 			 "abort tag x%x Cmdjob : x%px Abortjob : x%px "
12232 			 "retval x%x\n",
12233 			 ulp_context, (phba->sli_rev == LPFC_SLI_REV4) ?
12234 			 cmdiocb->iotag : iotag, iotag, cmdiocb, abtsiocbp,
12235 			 retval);
12236 	if (retval) {
12237 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
12238 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
12239 	}
12240 
12241 	/*
12242 	 * Caller to this routine should check for IOCB_ERROR
12243 	 * and handle it properly.  This routine no longer removes
12244 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
12245 	 */
12246 	return retval;
12247 }
12248 
12249 /**
12250  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
12251  * @phba: pointer to lpfc HBA data structure.
12252  *
12253  * This routine will abort all pending and outstanding iocbs to an HBA.
12254  **/
12255 void
12256 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
12257 {
12258 	struct lpfc_sli *psli = &phba->sli;
12259 	struct lpfc_sli_ring *pring;
12260 	struct lpfc_queue *qp = NULL;
12261 	int i;
12262 
12263 	if (phba->sli_rev != LPFC_SLI_REV4) {
12264 		for (i = 0; i < psli->num_rings; i++) {
12265 			pring = &psli->sli3_ring[i];
12266 			lpfc_sli_abort_iocb_ring(phba, pring);
12267 		}
12268 		return;
12269 	}
12270 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12271 		pring = qp->pring;
12272 		if (!pring)
12273 			continue;
12274 		lpfc_sli_abort_iocb_ring(phba, pring);
12275 	}
12276 }
12277 
12278 /**
12279  * lpfc_sli_validate_fcp_iocb_for_abort - filter iocbs appropriate for FCP aborts
12280  * @iocbq: Pointer to iocb object.
12281  * @vport: Pointer to driver virtual port object.
12282  *
12283  * This function acts as an iocb filter for functions which abort FCP iocbs.
12284  *
12285  * Return values
12286  * -ENODEV, if a null iocb or vport ptr is encountered
12287  * -EINVAL, if the iocb is not an FCP I/O, not on the TX cmpl queue, premarked as
12288  *          driver already started the abort process, or is an abort iocb itself
12289  * 0, passes criteria for aborting the FCP I/O iocb
12290  **/
12291 static int
12292 lpfc_sli_validate_fcp_iocb_for_abort(struct lpfc_iocbq *iocbq,
12293 				     struct lpfc_vport *vport)
12294 {
12295 	u8 ulp_command;
12296 
12297 	/* No null ptr vports */
12298 	if (!iocbq || iocbq->vport != vport)
12299 		return -ENODEV;
12300 
12301 	/* iocb must be for FCP IO, already exists on the TX cmpl queue,
12302 	 * can't be premarked as driver aborted, nor be an ABORT iocb itself
12303 	 */
12304 	ulp_command = get_job_cmnd(vport->phba, iocbq);
12305 	if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12306 	    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ) ||
12307 	    (iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12308 	    (ulp_command == CMD_ABORT_XRI_CN ||
12309 	     ulp_command == CMD_CLOSE_XRI_CN ||
12310 	     ulp_command == CMD_ABORT_XRI_WQE))
12311 		return -EINVAL;
12312 
12313 	return 0;
12314 }
12315 
12316 /**
12317  * lpfc_sli_validate_fcp_iocb - validate commands associated with a SCSI target
12318  * @iocbq: Pointer to driver iocb object.
12319  * @vport: Pointer to driver virtual port object.
12320  * @tgt_id: SCSI ID of the target.
12321  * @lun_id: LUN ID of the scsi device.
12322  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
12323  *
12324  * This function acts as an iocb filter for validating a lun/SCSI target/SCSI
12325  * host.
12326  *
12327  * It will return
12328  * 0 if the filtering criteria is met for the given iocb and will return
12329  * 1 if the filtering criteria is not met.
12330  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
12331  * given iocb is for the SCSI device specified by vport, tgt_id and
12332  * lun_id parameter.
12333  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
12334  * given iocb is for the SCSI target specified by vport and tgt_id
12335  * parameters.
12336  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
12337  * given iocb is for the SCSI host associated with the given vport.
12338  * This function is called with no locks held.
12339  **/
12340 static int
12341 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
12342 			   uint16_t tgt_id, uint64_t lun_id,
12343 			   lpfc_ctx_cmd ctx_cmd)
12344 {
12345 	struct lpfc_io_buf *lpfc_cmd;
12346 	int rc = 1;
12347 
12348 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12349 
12350 	if (lpfc_cmd->pCmd == NULL)
12351 		return rc;
12352 
12353 	switch (ctx_cmd) {
12354 	case LPFC_CTX_LUN:
12355 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12356 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
12357 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
12358 			rc = 0;
12359 		break;
12360 	case LPFC_CTX_TGT:
12361 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12362 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
12363 			rc = 0;
12364 		break;
12365 	case LPFC_CTX_HOST:
12366 		rc = 0;
12367 		break;
12368 	default:
12369 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
12370 			__func__, ctx_cmd);
12371 		break;
12372 	}
12373 
12374 	return rc;
12375 }
12376 
12377 /**
12378  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
12379  * @vport: Pointer to virtual port.
12380  * @tgt_id: SCSI ID of the target.
12381  * @lun_id: LUN ID of the scsi device.
12382  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12383  *
12384  * This function returns number of FCP commands pending for the vport.
12385  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
12386  * commands pending on the vport associated with SCSI device specified
12387  * by tgt_id and lun_id parameters.
12388  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
12389  * commands pending on the vport associated with SCSI target specified
12390  * by tgt_id parameter.
12391  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
12392  * commands pending on the vport.
12393  * This function returns the number of iocbs which satisfy the filter.
12394  * This function is called without any lock held.
12395  **/
12396 int
12397 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
12398 		  lpfc_ctx_cmd ctx_cmd)
12399 {
12400 	struct lpfc_hba *phba = vport->phba;
12401 	struct lpfc_iocbq *iocbq;
12402 	int sum, i;
12403 	unsigned long iflags;
12404 	u8 ulp_command;
12405 
12406 	spin_lock_irqsave(&phba->hbalock, iflags);
12407 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
12408 		iocbq = phba->sli.iocbq_lookup[i];
12409 
12410 		if (!iocbq || iocbq->vport != vport)
12411 			continue;
12412 		if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12413 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ))
12414 			continue;
12415 
12416 		/* Include counting outstanding aborts */
12417 		ulp_command = get_job_cmnd(phba, iocbq);
12418 		if (ulp_command == CMD_ABORT_XRI_CN ||
12419 		    ulp_command == CMD_CLOSE_XRI_CN ||
12420 		    ulp_command == CMD_ABORT_XRI_WQE) {
12421 			sum++;
12422 			continue;
12423 		}
12424 
12425 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12426 					       ctx_cmd) == 0)
12427 			sum++;
12428 	}
12429 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12430 
12431 	return sum;
12432 }
12433 
12434 /**
12435  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
12436  * @phba: Pointer to HBA context object
12437  * @cmdiocb: Pointer to command iocb object.
12438  * @rspiocb: Pointer to response iocb object.
12439  *
12440  * This function is called when an aborted FCP iocb completes. This
12441  * function is called by the ring event handler with no lock held.
12442  * This function frees the iocb.
12443  **/
12444 void
12445 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12446 			struct lpfc_iocbq *rspiocb)
12447 {
12448 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12449 			"3096 ABORT_XRI_CX completing on rpi x%x "
12450 			"original iotag x%x, abort cmd iotag x%x "
12451 			"status 0x%x, reason 0x%x\n",
12452 			(phba->sli_rev == LPFC_SLI_REV4) ?
12453 			cmdiocb->sli4_xritag :
12454 			cmdiocb->iocb.un.acxri.abortContextTag,
12455 			get_job_abtsiotag(phba, cmdiocb),
12456 			cmdiocb->iotag, get_job_ulpstatus(phba, rspiocb),
12457 			get_job_word4(phba, rspiocb));
12458 	lpfc_sli_release_iocbq(phba, cmdiocb);
12459 	return;
12460 }
12461 
12462 /**
12463  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
12464  * @vport: Pointer to virtual port.
12465  * @tgt_id: SCSI ID of the target.
12466  * @lun_id: LUN ID of the scsi device.
12467  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12468  *
12469  * This function sends an abort command for every SCSI command
12470  * associated with the given virtual port pending on the ring
12471  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12472  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12473  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12474  * followed by lpfc_sli_validate_fcp_iocb.
12475  *
12476  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
12477  * FCP iocbs associated with lun specified by tgt_id and lun_id
12478  * parameters
12479  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
12480  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12481  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
12482  * FCP iocbs associated with virtual port.
12483  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
12484  * lpfc_sli4_calc_ring is used.
12485  * This function returns number of iocbs it failed to abort.
12486  * This function is called with no locks held.
12487  **/
12488 int
12489 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
12490 		    lpfc_ctx_cmd abort_cmd)
12491 {
12492 	struct lpfc_hba *phba = vport->phba;
12493 	struct lpfc_sli_ring *pring = NULL;
12494 	struct lpfc_iocbq *iocbq;
12495 	int errcnt = 0, ret_val = 0;
12496 	unsigned long iflags;
12497 	int i;
12498 
12499 	/* all I/Os are in process of being flushed */
12500 	if (phba->hba_flag & HBA_IOQ_FLUSH)
12501 		return errcnt;
12502 
12503 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12504 		iocbq = phba->sli.iocbq_lookup[i];
12505 
12506 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12507 			continue;
12508 
12509 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12510 					       abort_cmd) != 0)
12511 			continue;
12512 
12513 		spin_lock_irqsave(&phba->hbalock, iflags);
12514 		if (phba->sli_rev == LPFC_SLI_REV3) {
12515 			pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12516 		} else if (phba->sli_rev == LPFC_SLI_REV4) {
12517 			pring = lpfc_sli4_calc_ring(phba, iocbq);
12518 		}
12519 		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
12520 						     lpfc_sli_abort_fcp_cmpl);
12521 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12522 		if (ret_val != IOCB_SUCCESS)
12523 			errcnt++;
12524 	}
12525 
12526 	return errcnt;
12527 }
12528 
12529 /**
12530  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12531  * @vport: Pointer to virtual port.
12532  * @pring: Pointer to driver SLI ring object.
12533  * @tgt_id: SCSI ID of the target.
12534  * @lun_id: LUN ID of the scsi device.
12535  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12536  *
12537  * This function sends an abort command for every SCSI command
12538  * associated with the given virtual port pending on the ring
12539  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12540  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12541  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12542  * followed by lpfc_sli_validate_fcp_iocb.
12543  *
12544  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12545  * FCP iocbs associated with lun specified by tgt_id and lun_id
12546  * parameters
12547  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12548  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12549  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12550  * FCP iocbs associated with virtual port.
12551  * This function returns number of iocbs it aborted .
12552  * This function is called with no locks held right after a taskmgmt
12553  * command is sent.
12554  **/
12555 int
12556 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12557 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12558 {
12559 	struct lpfc_hba *phba = vport->phba;
12560 	struct lpfc_io_buf *lpfc_cmd;
12561 	struct lpfc_iocbq *abtsiocbq;
12562 	struct lpfc_nodelist *ndlp = NULL;
12563 	struct lpfc_iocbq *iocbq;
12564 	int sum, i, ret_val;
12565 	unsigned long iflags;
12566 	struct lpfc_sli_ring *pring_s4 = NULL;
12567 	u16 ulp_context, iotag, cqid = LPFC_WQE_CQ_ID_DEFAULT;
12568 	bool ia;
12569 
12570 	spin_lock_irqsave(&phba->hbalock, iflags);
12571 
12572 	/* all I/Os are in process of being flushed */
12573 	if (phba->hba_flag & HBA_IOQ_FLUSH) {
12574 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12575 		return 0;
12576 	}
12577 	sum = 0;
12578 
12579 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12580 		iocbq = phba->sli.iocbq_lookup[i];
12581 
12582 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12583 			continue;
12584 
12585 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12586 					       cmd) != 0)
12587 			continue;
12588 
12589 		/* Guard against IO completion being called at same time */
12590 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12591 		spin_lock(&lpfc_cmd->buf_lock);
12592 
12593 		if (!lpfc_cmd->pCmd) {
12594 			spin_unlock(&lpfc_cmd->buf_lock);
12595 			continue;
12596 		}
12597 
12598 		if (phba->sli_rev == LPFC_SLI_REV4) {
12599 			pring_s4 =
12600 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12601 			if (!pring_s4) {
12602 				spin_unlock(&lpfc_cmd->buf_lock);
12603 				continue;
12604 			}
12605 			/* Note: both hbalock and ring_lock must be set here */
12606 			spin_lock(&pring_s4->ring_lock);
12607 		}
12608 
12609 		/*
12610 		 * If the iocbq is already being aborted, don't take a second
12611 		 * action, but do count it.
12612 		 */
12613 		if ((iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12614 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ)) {
12615 			if (phba->sli_rev == LPFC_SLI_REV4)
12616 				spin_unlock(&pring_s4->ring_lock);
12617 			spin_unlock(&lpfc_cmd->buf_lock);
12618 			continue;
12619 		}
12620 
12621 		/* issue ABTS for this IOCB based on iotag */
12622 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
12623 		if (!abtsiocbq) {
12624 			if (phba->sli_rev == LPFC_SLI_REV4)
12625 				spin_unlock(&pring_s4->ring_lock);
12626 			spin_unlock(&lpfc_cmd->buf_lock);
12627 			continue;
12628 		}
12629 
12630 		if (phba->sli_rev == LPFC_SLI_REV4) {
12631 			iotag = abtsiocbq->iotag;
12632 			ulp_context = iocbq->sli4_xritag;
12633 			cqid = lpfc_cmd->hdwq->io_cq_map;
12634 		} else {
12635 			iotag = iocbq->iocb.ulpIoTag;
12636 			if (pring->ringno == LPFC_ELS_RING) {
12637 				ndlp = (struct lpfc_nodelist *)(iocbq->context1);
12638 				ulp_context = ndlp->nlp_rpi;
12639 			} else {
12640 				ulp_context = iocbq->iocb.ulpContext;
12641 			}
12642 		}
12643 
12644 		ndlp = lpfc_cmd->rdata->pnode;
12645 
12646 		if (lpfc_is_link_up(phba) &&
12647 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
12648 			ia = false;
12649 		else
12650 			ia = true;
12651 
12652 		lpfc_sli_prep_abort_xri(phba, abtsiocbq, ulp_context, iotag,
12653 					iocbq->iocb.ulpClass, cqid,
12654 					ia);
12655 
12656 		abtsiocbq->vport = vport;
12657 
12658 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12659 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12660 		if (iocbq->cmd_flag & LPFC_IO_FCP)
12661 			abtsiocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
12662 		if (iocbq->cmd_flag & LPFC_IO_FOF)
12663 			abtsiocbq->cmd_flag |= LPFC_IO_FOF;
12664 
12665 		/* Setup callback routine and issue the command. */
12666 		abtsiocbq->cmd_cmpl = lpfc_sli_abort_fcp_cmpl;
12667 
12668 		/*
12669 		 * Indicate the IO is being aborted by the driver and set
12670 		 * the caller's flag into the aborted IO.
12671 		 */
12672 		iocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
12673 
12674 		if (phba->sli_rev == LPFC_SLI_REV4) {
12675 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
12676 							abtsiocbq, 0);
12677 			spin_unlock(&pring_s4->ring_lock);
12678 		} else {
12679 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
12680 							abtsiocbq, 0);
12681 		}
12682 
12683 		spin_unlock(&lpfc_cmd->buf_lock);
12684 
12685 		if (ret_val == IOCB_ERROR)
12686 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
12687 		else
12688 			sum++;
12689 	}
12690 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12691 	return sum;
12692 }
12693 
12694 /**
12695  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
12696  * @phba: Pointer to HBA context object.
12697  * @cmdiocbq: Pointer to command iocb.
12698  * @rspiocbq: Pointer to response iocb.
12699  *
12700  * This function is the completion handler for iocbs issued using
12701  * lpfc_sli_issue_iocb_wait function. This function is called by the
12702  * ring event handler function without any lock held. This function
12703  * can be called from both worker thread context and interrupt
12704  * context. This function also can be called from other thread which
12705  * cleans up the SLI layer objects.
12706  * This function copy the contents of the response iocb to the
12707  * response iocb memory object provided by the caller of
12708  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
12709  * sleeps for the iocb completion.
12710  **/
12711 static void
12712 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
12713 			struct lpfc_iocbq *cmdiocbq,
12714 			struct lpfc_iocbq *rspiocbq)
12715 {
12716 	wait_queue_head_t *pdone_q;
12717 	unsigned long iflags;
12718 	struct lpfc_io_buf *lpfc_cmd;
12719 	size_t offset = offsetof(struct lpfc_iocbq, wqe);
12720 
12721 	spin_lock_irqsave(&phba->hbalock, iflags);
12722 	if (cmdiocbq->cmd_flag & LPFC_IO_WAKE_TMO) {
12723 
12724 		/*
12725 		 * A time out has occurred for the iocb.  If a time out
12726 		 * completion handler has been supplied, call it.  Otherwise,
12727 		 * just free the iocbq.
12728 		 */
12729 
12730 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12731 		cmdiocbq->cmd_cmpl = cmdiocbq->wait_cmd_cmpl;
12732 		cmdiocbq->wait_cmd_cmpl = NULL;
12733 		if (cmdiocbq->cmd_cmpl)
12734 			(cmdiocbq->cmd_cmpl)(phba, cmdiocbq, NULL);
12735 		else
12736 			lpfc_sli_release_iocbq(phba, cmdiocbq);
12737 		return;
12738 	}
12739 
12740 	/* Copy the contents of the local rspiocb into the caller's buffer. */
12741 	cmdiocbq->cmd_flag |= LPFC_IO_WAKE;
12742 	if (cmdiocbq->context2 && rspiocbq)
12743 		memcpy((char *)cmdiocbq->context2 + offset,
12744 		       (char *)rspiocbq + offset, sizeof(*rspiocbq) - offset);
12745 
12746 	/* Set the exchange busy flag for task management commands */
12747 	if ((cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
12748 		!(cmdiocbq->cmd_flag & LPFC_IO_LIBDFC)) {
12749 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
12750 			cur_iocbq);
12751 		if (rspiocbq && (rspiocbq->cmd_flag & LPFC_EXCHANGE_BUSY))
12752 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
12753 		else
12754 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
12755 	}
12756 
12757 	pdone_q = cmdiocbq->context_un.wait_queue;
12758 	if (pdone_q)
12759 		wake_up(pdone_q);
12760 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12761 	return;
12762 }
12763 
12764 /**
12765  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
12766  * @phba: Pointer to HBA context object..
12767  * @piocbq: Pointer to command iocb.
12768  * @flag: Flag to test.
12769  *
12770  * This routine grabs the hbalock and then test the cmd_flag to
12771  * see if the passed in flag is set.
12772  * Returns:
12773  * 1 if flag is set.
12774  * 0 if flag is not set.
12775  **/
12776 static int
12777 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
12778 		 struct lpfc_iocbq *piocbq, uint32_t flag)
12779 {
12780 	unsigned long iflags;
12781 	int ret;
12782 
12783 	spin_lock_irqsave(&phba->hbalock, iflags);
12784 	ret = piocbq->cmd_flag & flag;
12785 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12786 	return ret;
12787 
12788 }
12789 
12790 /**
12791  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
12792  * @phba: Pointer to HBA context object..
12793  * @ring_number: Ring number
12794  * @piocb: Pointer to command iocb.
12795  * @prspiocbq: Pointer to response iocb.
12796  * @timeout: Timeout in number of seconds.
12797  *
12798  * This function issues the iocb to firmware and waits for the
12799  * iocb to complete. The cmd_cmpl field of the shall be used
12800  * to handle iocbs which time out. If the field is NULL, the
12801  * function shall free the iocbq structure.  If more clean up is
12802  * needed, the caller is expected to provide a completion function
12803  * that will provide the needed clean up.  If the iocb command is
12804  * not completed within timeout seconds, the function will either
12805  * free the iocbq structure (if cmd_cmpl == NULL) or execute the
12806  * completion function set in the cmd_cmpl field and then return
12807  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
12808  * resources if this function returns IOCB_TIMEDOUT.
12809  * The function waits for the iocb completion using an
12810  * non-interruptible wait.
12811  * This function will sleep while waiting for iocb completion.
12812  * So, this function should not be called from any context which
12813  * does not allow sleeping. Due to the same reason, this function
12814  * cannot be called with interrupt disabled.
12815  * This function assumes that the iocb completions occur while
12816  * this function sleep. So, this function cannot be called from
12817  * the thread which process iocb completion for this ring.
12818  * This function clears the cmd_flag of the iocb object before
12819  * issuing the iocb and the iocb completion handler sets this
12820  * flag and wakes this thread when the iocb completes.
12821  * The contents of the response iocb will be copied to prspiocbq
12822  * by the completion handler when the command completes.
12823  * This function returns IOCB_SUCCESS when success.
12824  * This function is called with no lock held.
12825  **/
12826 int
12827 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
12828 			 uint32_t ring_number,
12829 			 struct lpfc_iocbq *piocb,
12830 			 struct lpfc_iocbq *prspiocbq,
12831 			 uint32_t timeout)
12832 {
12833 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
12834 	long timeleft, timeout_req = 0;
12835 	int retval = IOCB_SUCCESS;
12836 	uint32_t creg_val;
12837 	struct lpfc_iocbq *iocb;
12838 	int txq_cnt = 0;
12839 	int txcmplq_cnt = 0;
12840 	struct lpfc_sli_ring *pring;
12841 	unsigned long iflags;
12842 	bool iocb_completed = true;
12843 
12844 	if (phba->sli_rev >= LPFC_SLI_REV4) {
12845 		lpfc_sli_prep_wqe(phba, piocb);
12846 
12847 		pring = lpfc_sli4_calc_ring(phba, piocb);
12848 	} else
12849 		pring = &phba->sli.sli3_ring[ring_number];
12850 	/*
12851 	 * If the caller has provided a response iocbq buffer, then context2
12852 	 * is NULL or its an error.
12853 	 */
12854 	if (prspiocbq) {
12855 		if (piocb->context2)
12856 			return IOCB_ERROR;
12857 		piocb->context2 = prspiocbq;
12858 	}
12859 
12860 	piocb->wait_cmd_cmpl = piocb->cmd_cmpl;
12861 	piocb->cmd_cmpl = lpfc_sli_wake_iocb_wait;
12862 	piocb->context_un.wait_queue = &done_q;
12863 	piocb->cmd_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
12864 
12865 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12866 		if (lpfc_readl(phba->HCregaddr, &creg_val))
12867 			return IOCB_ERROR;
12868 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
12869 		writel(creg_val, phba->HCregaddr);
12870 		readl(phba->HCregaddr); /* flush */
12871 	}
12872 
12873 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
12874 				     SLI_IOCB_RET_IOCB);
12875 	if (retval == IOCB_SUCCESS) {
12876 		timeout_req = msecs_to_jiffies(timeout * 1000);
12877 		timeleft = wait_event_timeout(done_q,
12878 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
12879 				timeout_req);
12880 		spin_lock_irqsave(&phba->hbalock, iflags);
12881 		if (!(piocb->cmd_flag & LPFC_IO_WAKE)) {
12882 
12883 			/*
12884 			 * IOCB timed out.  Inform the wake iocb wait
12885 			 * completion function and set local status
12886 			 */
12887 
12888 			iocb_completed = false;
12889 			piocb->cmd_flag |= LPFC_IO_WAKE_TMO;
12890 		}
12891 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12892 		if (iocb_completed) {
12893 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12894 					"0331 IOCB wake signaled\n");
12895 			/* Note: we are not indicating if the IOCB has a success
12896 			 * status or not - that's for the caller to check.
12897 			 * IOCB_SUCCESS means just that the command was sent and
12898 			 * completed. Not that it completed successfully.
12899 			 * */
12900 		} else if (timeleft == 0) {
12901 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12902 					"0338 IOCB wait timeout error - no "
12903 					"wake response Data x%x\n", timeout);
12904 			retval = IOCB_TIMEDOUT;
12905 		} else {
12906 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12907 					"0330 IOCB wake NOT set, "
12908 					"Data x%x x%lx\n",
12909 					timeout, (timeleft / jiffies));
12910 			retval = IOCB_TIMEDOUT;
12911 		}
12912 	} else if (retval == IOCB_BUSY) {
12913 		if (phba->cfg_log_verbose & LOG_SLI) {
12914 			list_for_each_entry(iocb, &pring->txq, list) {
12915 				txq_cnt++;
12916 			}
12917 			list_for_each_entry(iocb, &pring->txcmplq, list) {
12918 				txcmplq_cnt++;
12919 			}
12920 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12921 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
12922 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
12923 		}
12924 		return retval;
12925 	} else {
12926 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12927 				"0332 IOCB wait issue failed, Data x%x\n",
12928 				retval);
12929 		retval = IOCB_ERROR;
12930 	}
12931 
12932 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12933 		if (lpfc_readl(phba->HCregaddr, &creg_val))
12934 			return IOCB_ERROR;
12935 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
12936 		writel(creg_val, phba->HCregaddr);
12937 		readl(phba->HCregaddr); /* flush */
12938 	}
12939 
12940 	if (prspiocbq)
12941 		piocb->context2 = NULL;
12942 
12943 	piocb->context_un.wait_queue = NULL;
12944 	piocb->cmd_cmpl = NULL;
12945 	return retval;
12946 }
12947 
12948 /**
12949  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
12950  * @phba: Pointer to HBA context object.
12951  * @pmboxq: Pointer to driver mailbox object.
12952  * @timeout: Timeout in number of seconds.
12953  *
12954  * This function issues the mailbox to firmware and waits for the
12955  * mailbox command to complete. If the mailbox command is not
12956  * completed within timeout seconds, it returns MBX_TIMEOUT.
12957  * The function waits for the mailbox completion using an
12958  * interruptible wait. If the thread is woken up due to a
12959  * signal, MBX_TIMEOUT error is returned to the caller. Caller
12960  * should not free the mailbox resources, if this function returns
12961  * MBX_TIMEOUT.
12962  * This function will sleep while waiting for mailbox completion.
12963  * So, this function should not be called from any context which
12964  * does not allow sleeping. Due to the same reason, this function
12965  * cannot be called with interrupt disabled.
12966  * This function assumes that the mailbox completion occurs while
12967  * this function sleep. So, this function cannot be called from
12968  * the worker thread which processes mailbox completion.
12969  * This function is called in the context of HBA management
12970  * applications.
12971  * This function returns MBX_SUCCESS when successful.
12972  * This function is called with no lock held.
12973  **/
12974 int
12975 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
12976 			 uint32_t timeout)
12977 {
12978 	struct completion mbox_done;
12979 	int retval;
12980 	unsigned long flag;
12981 
12982 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
12983 	/* setup wake call as IOCB callback */
12984 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
12985 
12986 	/* setup context3 field to pass wait_queue pointer to wake function  */
12987 	init_completion(&mbox_done);
12988 	pmboxq->context3 = &mbox_done;
12989 	/* now issue the command */
12990 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
12991 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
12992 		wait_for_completion_timeout(&mbox_done,
12993 					    msecs_to_jiffies(timeout * 1000));
12994 
12995 		spin_lock_irqsave(&phba->hbalock, flag);
12996 		pmboxq->context3 = NULL;
12997 		/*
12998 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
12999 		 * else do not free the resources.
13000 		 */
13001 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
13002 			retval = MBX_SUCCESS;
13003 		} else {
13004 			retval = MBX_TIMEOUT;
13005 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13006 		}
13007 		spin_unlock_irqrestore(&phba->hbalock, flag);
13008 	}
13009 	return retval;
13010 }
13011 
13012 /**
13013  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
13014  * @phba: Pointer to HBA context.
13015  * @mbx_action: Mailbox shutdown options.
13016  *
13017  * This function is called to shutdown the driver's mailbox sub-system.
13018  * It first marks the mailbox sub-system is in a block state to prevent
13019  * the asynchronous mailbox command from issued off the pending mailbox
13020  * command queue. If the mailbox command sub-system shutdown is due to
13021  * HBA error conditions such as EEH or ERATT, this routine shall invoke
13022  * the mailbox sub-system flush routine to forcefully bring down the
13023  * mailbox sub-system. Otherwise, if it is due to normal condition (such
13024  * as with offline or HBA function reset), this routine will wait for the
13025  * outstanding mailbox command to complete before invoking the mailbox
13026  * sub-system flush routine to gracefully bring down mailbox sub-system.
13027  **/
13028 void
13029 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
13030 {
13031 	struct lpfc_sli *psli = &phba->sli;
13032 	unsigned long timeout;
13033 
13034 	if (mbx_action == LPFC_MBX_NO_WAIT) {
13035 		/* delay 100ms for port state */
13036 		msleep(100);
13037 		lpfc_sli_mbox_sys_flush(phba);
13038 		return;
13039 	}
13040 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
13041 
13042 	/* Disable softirqs, including timers from obtaining phba->hbalock */
13043 	local_bh_disable();
13044 
13045 	spin_lock_irq(&phba->hbalock);
13046 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13047 
13048 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
13049 		/* Determine how long we might wait for the active mailbox
13050 		 * command to be gracefully completed by firmware.
13051 		 */
13052 		if (phba->sli.mbox_active)
13053 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
13054 						phba->sli.mbox_active) *
13055 						1000) + jiffies;
13056 		spin_unlock_irq(&phba->hbalock);
13057 
13058 		/* Enable softirqs again, done with phba->hbalock */
13059 		local_bh_enable();
13060 
13061 		while (phba->sli.mbox_active) {
13062 			/* Check active mailbox complete status every 2ms */
13063 			msleep(2);
13064 			if (time_after(jiffies, timeout))
13065 				/* Timeout, let the mailbox flush routine to
13066 				 * forcefully release active mailbox command
13067 				 */
13068 				break;
13069 		}
13070 	} else {
13071 		spin_unlock_irq(&phba->hbalock);
13072 
13073 		/* Enable softirqs again, done with phba->hbalock */
13074 		local_bh_enable();
13075 	}
13076 
13077 	lpfc_sli_mbox_sys_flush(phba);
13078 }
13079 
13080 /**
13081  * lpfc_sli_eratt_read - read sli-3 error attention events
13082  * @phba: Pointer to HBA context.
13083  *
13084  * This function is called to read the SLI3 device error attention registers
13085  * for possible error attention events. The caller must hold the hostlock
13086  * with spin_lock_irq().
13087  *
13088  * This function returns 1 when there is Error Attention in the Host Attention
13089  * Register and returns 0 otherwise.
13090  **/
13091 static int
13092 lpfc_sli_eratt_read(struct lpfc_hba *phba)
13093 {
13094 	uint32_t ha_copy;
13095 
13096 	/* Read chip Host Attention (HA) register */
13097 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
13098 		goto unplug_err;
13099 
13100 	if (ha_copy & HA_ERATT) {
13101 		/* Read host status register to retrieve error event */
13102 		if (lpfc_sli_read_hs(phba))
13103 			goto unplug_err;
13104 
13105 		/* Check if there is a deferred error condition is active */
13106 		if ((HS_FFER1 & phba->work_hs) &&
13107 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13108 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
13109 			phba->hba_flag |= DEFER_ERATT;
13110 			/* Clear all interrupt enable conditions */
13111 			writel(0, phba->HCregaddr);
13112 			readl(phba->HCregaddr);
13113 		}
13114 
13115 		/* Set the driver HA work bitmap */
13116 		phba->work_ha |= HA_ERATT;
13117 		/* Indicate polling handles this ERATT */
13118 		phba->hba_flag |= HBA_ERATT_HANDLED;
13119 		return 1;
13120 	}
13121 	return 0;
13122 
13123 unplug_err:
13124 	/* Set the driver HS work bitmap */
13125 	phba->work_hs |= UNPLUG_ERR;
13126 	/* Set the driver HA work bitmap */
13127 	phba->work_ha |= HA_ERATT;
13128 	/* Indicate polling handles this ERATT */
13129 	phba->hba_flag |= HBA_ERATT_HANDLED;
13130 	return 1;
13131 }
13132 
13133 /**
13134  * lpfc_sli4_eratt_read - read sli-4 error attention events
13135  * @phba: Pointer to HBA context.
13136  *
13137  * This function is called to read the SLI4 device error attention registers
13138  * for possible error attention events. The caller must hold the hostlock
13139  * with spin_lock_irq().
13140  *
13141  * This function returns 1 when there is Error Attention in the Host Attention
13142  * Register and returns 0 otherwise.
13143  **/
13144 static int
13145 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
13146 {
13147 	uint32_t uerr_sta_hi, uerr_sta_lo;
13148 	uint32_t if_type, portsmphr;
13149 	struct lpfc_register portstat_reg;
13150 	u32 logmask;
13151 
13152 	/*
13153 	 * For now, use the SLI4 device internal unrecoverable error
13154 	 * registers for error attention. This can be changed later.
13155 	 */
13156 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
13157 	switch (if_type) {
13158 	case LPFC_SLI_INTF_IF_TYPE_0:
13159 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
13160 			&uerr_sta_lo) ||
13161 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
13162 			&uerr_sta_hi)) {
13163 			phba->work_hs |= UNPLUG_ERR;
13164 			phba->work_ha |= HA_ERATT;
13165 			phba->hba_flag |= HBA_ERATT_HANDLED;
13166 			return 1;
13167 		}
13168 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
13169 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
13170 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13171 					"1423 HBA Unrecoverable error: "
13172 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
13173 					"ue_mask_lo_reg=0x%x, "
13174 					"ue_mask_hi_reg=0x%x\n",
13175 					uerr_sta_lo, uerr_sta_hi,
13176 					phba->sli4_hba.ue_mask_lo,
13177 					phba->sli4_hba.ue_mask_hi);
13178 			phba->work_status[0] = uerr_sta_lo;
13179 			phba->work_status[1] = uerr_sta_hi;
13180 			phba->work_ha |= HA_ERATT;
13181 			phba->hba_flag |= HBA_ERATT_HANDLED;
13182 			return 1;
13183 		}
13184 		break;
13185 	case LPFC_SLI_INTF_IF_TYPE_2:
13186 	case LPFC_SLI_INTF_IF_TYPE_6:
13187 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
13188 			&portstat_reg.word0) ||
13189 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
13190 			&portsmphr)){
13191 			phba->work_hs |= UNPLUG_ERR;
13192 			phba->work_ha |= HA_ERATT;
13193 			phba->hba_flag |= HBA_ERATT_HANDLED;
13194 			return 1;
13195 		}
13196 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
13197 			phba->work_status[0] =
13198 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
13199 			phba->work_status[1] =
13200 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
13201 			logmask = LOG_TRACE_EVENT;
13202 			if (phba->work_status[0] ==
13203 				SLIPORT_ERR1_REG_ERR_CODE_2 &&
13204 			    phba->work_status[1] == SLIPORT_ERR2_REG_FW_RESTART)
13205 				logmask = LOG_SLI;
13206 			lpfc_printf_log(phba, KERN_ERR, logmask,
13207 					"2885 Port Status Event: "
13208 					"port status reg 0x%x, "
13209 					"port smphr reg 0x%x, "
13210 					"error 1=0x%x, error 2=0x%x\n",
13211 					portstat_reg.word0,
13212 					portsmphr,
13213 					phba->work_status[0],
13214 					phba->work_status[1]);
13215 			phba->work_ha |= HA_ERATT;
13216 			phba->hba_flag |= HBA_ERATT_HANDLED;
13217 			return 1;
13218 		}
13219 		break;
13220 	case LPFC_SLI_INTF_IF_TYPE_1:
13221 	default:
13222 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13223 				"2886 HBA Error Attention on unsupported "
13224 				"if type %d.", if_type);
13225 		return 1;
13226 	}
13227 
13228 	return 0;
13229 }
13230 
13231 /**
13232  * lpfc_sli_check_eratt - check error attention events
13233  * @phba: Pointer to HBA context.
13234  *
13235  * This function is called from timer soft interrupt context to check HBA's
13236  * error attention register bit for error attention events.
13237  *
13238  * This function returns 1 when there is Error Attention in the Host Attention
13239  * Register and returns 0 otherwise.
13240  **/
13241 int
13242 lpfc_sli_check_eratt(struct lpfc_hba *phba)
13243 {
13244 	uint32_t ha_copy;
13245 
13246 	/* If somebody is waiting to handle an eratt, don't process it
13247 	 * here. The brdkill function will do this.
13248 	 */
13249 	if (phba->link_flag & LS_IGNORE_ERATT)
13250 		return 0;
13251 
13252 	/* Check if interrupt handler handles this ERATT */
13253 	spin_lock_irq(&phba->hbalock);
13254 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
13255 		/* Interrupt handler has handled ERATT */
13256 		spin_unlock_irq(&phba->hbalock);
13257 		return 0;
13258 	}
13259 
13260 	/*
13261 	 * If there is deferred error attention, do not check for error
13262 	 * attention
13263 	 */
13264 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13265 		spin_unlock_irq(&phba->hbalock);
13266 		return 0;
13267 	}
13268 
13269 	/* If PCI channel is offline, don't process it */
13270 	if (unlikely(pci_channel_offline(phba->pcidev))) {
13271 		spin_unlock_irq(&phba->hbalock);
13272 		return 0;
13273 	}
13274 
13275 	switch (phba->sli_rev) {
13276 	case LPFC_SLI_REV2:
13277 	case LPFC_SLI_REV3:
13278 		/* Read chip Host Attention (HA) register */
13279 		ha_copy = lpfc_sli_eratt_read(phba);
13280 		break;
13281 	case LPFC_SLI_REV4:
13282 		/* Read device Uncoverable Error (UERR) registers */
13283 		ha_copy = lpfc_sli4_eratt_read(phba);
13284 		break;
13285 	default:
13286 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13287 				"0299 Invalid SLI revision (%d)\n",
13288 				phba->sli_rev);
13289 		ha_copy = 0;
13290 		break;
13291 	}
13292 	spin_unlock_irq(&phba->hbalock);
13293 
13294 	return ha_copy;
13295 }
13296 
13297 /**
13298  * lpfc_intr_state_check - Check device state for interrupt handling
13299  * @phba: Pointer to HBA context.
13300  *
13301  * This inline routine checks whether a device or its PCI slot is in a state
13302  * that the interrupt should be handled.
13303  *
13304  * This function returns 0 if the device or the PCI slot is in a state that
13305  * interrupt should be handled, otherwise -EIO.
13306  */
13307 static inline int
13308 lpfc_intr_state_check(struct lpfc_hba *phba)
13309 {
13310 	/* If the pci channel is offline, ignore all the interrupts */
13311 	if (unlikely(pci_channel_offline(phba->pcidev)))
13312 		return -EIO;
13313 
13314 	/* Update device level interrupt statistics */
13315 	phba->sli.slistat.sli_intr++;
13316 
13317 	/* Ignore all interrupts during initialization. */
13318 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
13319 		return -EIO;
13320 
13321 	return 0;
13322 }
13323 
13324 /**
13325  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
13326  * @irq: Interrupt number.
13327  * @dev_id: The device context pointer.
13328  *
13329  * This function is directly called from the PCI layer as an interrupt
13330  * service routine when device with SLI-3 interface spec is enabled with
13331  * MSI-X multi-message interrupt mode and there are slow-path events in
13332  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
13333  * interrupt mode, this function is called as part of the device-level
13334  * interrupt handler. When the PCI slot is in error recovery or the HBA
13335  * is undergoing initialization, the interrupt handler will not process
13336  * the interrupt. The link attention and ELS ring attention events are
13337  * handled by the worker thread. The interrupt handler signals the worker
13338  * thread and returns for these events. This function is called without
13339  * any lock held. It gets the hbalock to access and update SLI data
13340  * structures.
13341  *
13342  * This function returns IRQ_HANDLED when interrupt is handled else it
13343  * returns IRQ_NONE.
13344  **/
13345 irqreturn_t
13346 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
13347 {
13348 	struct lpfc_hba  *phba;
13349 	uint32_t ha_copy, hc_copy;
13350 	uint32_t work_ha_copy;
13351 	unsigned long status;
13352 	unsigned long iflag;
13353 	uint32_t control;
13354 
13355 	MAILBOX_t *mbox, *pmbox;
13356 	struct lpfc_vport *vport;
13357 	struct lpfc_nodelist *ndlp;
13358 	struct lpfc_dmabuf *mp;
13359 	LPFC_MBOXQ_t *pmb;
13360 	int rc;
13361 
13362 	/*
13363 	 * Get the driver's phba structure from the dev_id and
13364 	 * assume the HBA is not interrupting.
13365 	 */
13366 	phba = (struct lpfc_hba *)dev_id;
13367 
13368 	if (unlikely(!phba))
13369 		return IRQ_NONE;
13370 
13371 	/*
13372 	 * Stuff needs to be attented to when this function is invoked as an
13373 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13374 	 */
13375 	if (phba->intr_type == MSIX) {
13376 		/* Check device state for handling interrupt */
13377 		if (lpfc_intr_state_check(phba))
13378 			return IRQ_NONE;
13379 		/* Need to read HA REG for slow-path events */
13380 		spin_lock_irqsave(&phba->hbalock, iflag);
13381 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13382 			goto unplug_error;
13383 		/* If somebody is waiting to handle an eratt don't process it
13384 		 * here. The brdkill function will do this.
13385 		 */
13386 		if (phba->link_flag & LS_IGNORE_ERATT)
13387 			ha_copy &= ~HA_ERATT;
13388 		/* Check the need for handling ERATT in interrupt handler */
13389 		if (ha_copy & HA_ERATT) {
13390 			if (phba->hba_flag & HBA_ERATT_HANDLED)
13391 				/* ERATT polling has handled ERATT */
13392 				ha_copy &= ~HA_ERATT;
13393 			else
13394 				/* Indicate interrupt handler handles ERATT */
13395 				phba->hba_flag |= HBA_ERATT_HANDLED;
13396 		}
13397 
13398 		/*
13399 		 * If there is deferred error attention, do not check for any
13400 		 * interrupt.
13401 		 */
13402 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13403 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13404 			return IRQ_NONE;
13405 		}
13406 
13407 		/* Clear up only attention source related to slow-path */
13408 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
13409 			goto unplug_error;
13410 
13411 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
13412 			HC_LAINT_ENA | HC_ERINT_ENA),
13413 			phba->HCregaddr);
13414 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
13415 			phba->HAregaddr);
13416 		writel(hc_copy, phba->HCregaddr);
13417 		readl(phba->HAregaddr); /* flush */
13418 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13419 	} else
13420 		ha_copy = phba->ha_copy;
13421 
13422 	work_ha_copy = ha_copy & phba->work_ha_mask;
13423 
13424 	if (work_ha_copy) {
13425 		if (work_ha_copy & HA_LATT) {
13426 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
13427 				/*
13428 				 * Turn off Link Attention interrupts
13429 				 * until CLEAR_LA done
13430 				 */
13431 				spin_lock_irqsave(&phba->hbalock, iflag);
13432 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
13433 				if (lpfc_readl(phba->HCregaddr, &control))
13434 					goto unplug_error;
13435 				control &= ~HC_LAINT_ENA;
13436 				writel(control, phba->HCregaddr);
13437 				readl(phba->HCregaddr); /* flush */
13438 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13439 			}
13440 			else
13441 				work_ha_copy &= ~HA_LATT;
13442 		}
13443 
13444 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
13445 			/*
13446 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
13447 			 * the only slow ring.
13448 			 */
13449 			status = (work_ha_copy &
13450 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
13451 			status >>= (4*LPFC_ELS_RING);
13452 			if (status & HA_RXMASK) {
13453 				spin_lock_irqsave(&phba->hbalock, iflag);
13454 				if (lpfc_readl(phba->HCregaddr, &control))
13455 					goto unplug_error;
13456 
13457 				lpfc_debugfs_slow_ring_trc(phba,
13458 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
13459 				control, status,
13460 				(uint32_t)phba->sli.slistat.sli_intr);
13461 
13462 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
13463 					lpfc_debugfs_slow_ring_trc(phba,
13464 						"ISR Disable ring:"
13465 						"pwork:x%x hawork:x%x wait:x%x",
13466 						phba->work_ha, work_ha_copy,
13467 						(uint32_t)((unsigned long)
13468 						&phba->work_waitq));
13469 
13470 					control &=
13471 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
13472 					writel(control, phba->HCregaddr);
13473 					readl(phba->HCregaddr); /* flush */
13474 				}
13475 				else {
13476 					lpfc_debugfs_slow_ring_trc(phba,
13477 						"ISR slow ring:   pwork:"
13478 						"x%x hawork:x%x wait:x%x",
13479 						phba->work_ha, work_ha_copy,
13480 						(uint32_t)((unsigned long)
13481 						&phba->work_waitq));
13482 				}
13483 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13484 			}
13485 		}
13486 		spin_lock_irqsave(&phba->hbalock, iflag);
13487 		if (work_ha_copy & HA_ERATT) {
13488 			if (lpfc_sli_read_hs(phba))
13489 				goto unplug_error;
13490 			/*
13491 			 * Check if there is a deferred error condition
13492 			 * is active
13493 			 */
13494 			if ((HS_FFER1 & phba->work_hs) &&
13495 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13496 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
13497 				  phba->work_hs)) {
13498 				phba->hba_flag |= DEFER_ERATT;
13499 				/* Clear all interrupt enable conditions */
13500 				writel(0, phba->HCregaddr);
13501 				readl(phba->HCregaddr);
13502 			}
13503 		}
13504 
13505 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
13506 			pmb = phba->sli.mbox_active;
13507 			pmbox = &pmb->u.mb;
13508 			mbox = phba->mbox;
13509 			vport = pmb->vport;
13510 
13511 			/* First check out the status word */
13512 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
13513 			if (pmbox->mbxOwner != OWN_HOST) {
13514 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13515 				/*
13516 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
13517 				 * mbxStatus <status>
13518 				 */
13519 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13520 						"(%d):0304 Stray Mailbox "
13521 						"Interrupt mbxCommand x%x "
13522 						"mbxStatus x%x\n",
13523 						(vport ? vport->vpi : 0),
13524 						pmbox->mbxCommand,
13525 						pmbox->mbxStatus);
13526 				/* clear mailbox attention bit */
13527 				work_ha_copy &= ~HA_MBATT;
13528 			} else {
13529 				phba->sli.mbox_active = NULL;
13530 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13531 				phba->last_completion_time = jiffies;
13532 				del_timer(&phba->sli.mbox_tmo);
13533 				if (pmb->mbox_cmpl) {
13534 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
13535 							MAILBOX_CMD_SIZE);
13536 					if (pmb->out_ext_byte_len &&
13537 						pmb->ctx_buf)
13538 						lpfc_sli_pcimem_bcopy(
13539 						phba->mbox_ext,
13540 						pmb->ctx_buf,
13541 						pmb->out_ext_byte_len);
13542 				}
13543 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13544 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13545 
13546 					lpfc_debugfs_disc_trc(vport,
13547 						LPFC_DISC_TRC_MBOX_VPORT,
13548 						"MBOX dflt rpi: : "
13549 						"status:x%x rpi:x%x",
13550 						(uint32_t)pmbox->mbxStatus,
13551 						pmbox->un.varWords[0], 0);
13552 
13553 					if (!pmbox->mbxStatus) {
13554 						mp = (struct lpfc_dmabuf *)
13555 							(pmb->ctx_buf);
13556 						ndlp = (struct lpfc_nodelist *)
13557 							pmb->ctx_ndlp;
13558 
13559 						/* Reg_LOGIN of dflt RPI was
13560 						 * successful. new lets get
13561 						 * rid of the RPI using the
13562 						 * same mbox buffer.
13563 						 */
13564 						lpfc_unreg_login(phba,
13565 							vport->vpi,
13566 							pmbox->un.varWords[0],
13567 							pmb);
13568 						pmb->mbox_cmpl =
13569 							lpfc_mbx_cmpl_dflt_rpi;
13570 						pmb->ctx_buf = mp;
13571 						pmb->ctx_ndlp = ndlp;
13572 						pmb->vport = vport;
13573 						rc = lpfc_sli_issue_mbox(phba,
13574 								pmb,
13575 								MBX_NOWAIT);
13576 						if (rc != MBX_BUSY)
13577 							lpfc_printf_log(phba,
13578 							KERN_ERR,
13579 							LOG_TRACE_EVENT,
13580 							"0350 rc should have"
13581 							"been MBX_BUSY\n");
13582 						if (rc != MBX_NOT_FINISHED)
13583 							goto send_current_mbox;
13584 					}
13585 				}
13586 				spin_lock_irqsave(
13587 						&phba->pport->work_port_lock,
13588 						iflag);
13589 				phba->pport->work_port_events &=
13590 					~WORKER_MBOX_TMO;
13591 				spin_unlock_irqrestore(
13592 						&phba->pport->work_port_lock,
13593 						iflag);
13594 
13595 				/* Do NOT queue MBX_HEARTBEAT to the worker
13596 				 * thread for processing.
13597 				 */
13598 				if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13599 					/* Process mbox now */
13600 					phba->sli.mbox_active = NULL;
13601 					phba->sli.sli_flag &=
13602 						~LPFC_SLI_MBOX_ACTIVE;
13603 					if (pmb->mbox_cmpl)
13604 						pmb->mbox_cmpl(phba, pmb);
13605 				} else {
13606 					/* Queue to worker thread to process */
13607 					lpfc_mbox_cmpl_put(phba, pmb);
13608 				}
13609 			}
13610 		} else
13611 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13612 
13613 		if ((work_ha_copy & HA_MBATT) &&
13614 		    (phba->sli.mbox_active == NULL)) {
13615 send_current_mbox:
13616 			/* Process next mailbox command if there is one */
13617 			do {
13618 				rc = lpfc_sli_issue_mbox(phba, NULL,
13619 							 MBX_NOWAIT);
13620 			} while (rc == MBX_NOT_FINISHED);
13621 			if (rc != MBX_SUCCESS)
13622 				lpfc_printf_log(phba, KERN_ERR,
13623 						LOG_TRACE_EVENT,
13624 						"0349 rc should be "
13625 						"MBX_SUCCESS\n");
13626 		}
13627 
13628 		spin_lock_irqsave(&phba->hbalock, iflag);
13629 		phba->work_ha |= work_ha_copy;
13630 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13631 		lpfc_worker_wake_up(phba);
13632 	}
13633 	return IRQ_HANDLED;
13634 unplug_error:
13635 	spin_unlock_irqrestore(&phba->hbalock, iflag);
13636 	return IRQ_HANDLED;
13637 
13638 } /* lpfc_sli_sp_intr_handler */
13639 
13640 /**
13641  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13642  * @irq: Interrupt number.
13643  * @dev_id: The device context pointer.
13644  *
13645  * This function is directly called from the PCI layer as an interrupt
13646  * service routine when device with SLI-3 interface spec is enabled with
13647  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13648  * ring event in the HBA. However, when the device is enabled with either
13649  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13650  * device-level interrupt handler. When the PCI slot is in error recovery
13651  * or the HBA is undergoing initialization, the interrupt handler will not
13652  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13653  * the intrrupt context. This function is called without any lock held.
13654  * It gets the hbalock to access and update SLI data structures.
13655  *
13656  * This function returns IRQ_HANDLED when interrupt is handled else it
13657  * returns IRQ_NONE.
13658  **/
13659 irqreturn_t
13660 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13661 {
13662 	struct lpfc_hba  *phba;
13663 	uint32_t ha_copy;
13664 	unsigned long status;
13665 	unsigned long iflag;
13666 	struct lpfc_sli_ring *pring;
13667 
13668 	/* Get the driver's phba structure from the dev_id and
13669 	 * assume the HBA is not interrupting.
13670 	 */
13671 	phba = (struct lpfc_hba *) dev_id;
13672 
13673 	if (unlikely(!phba))
13674 		return IRQ_NONE;
13675 
13676 	/*
13677 	 * Stuff needs to be attented to when this function is invoked as an
13678 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13679 	 */
13680 	if (phba->intr_type == MSIX) {
13681 		/* Check device state for handling interrupt */
13682 		if (lpfc_intr_state_check(phba))
13683 			return IRQ_NONE;
13684 		/* Need to read HA REG for FCP ring and other ring events */
13685 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13686 			return IRQ_HANDLED;
13687 		/* Clear up only attention source related to fast-path */
13688 		spin_lock_irqsave(&phba->hbalock, iflag);
13689 		/*
13690 		 * If there is deferred error attention, do not check for
13691 		 * any interrupt.
13692 		 */
13693 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13694 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13695 			return IRQ_NONE;
13696 		}
13697 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
13698 			phba->HAregaddr);
13699 		readl(phba->HAregaddr); /* flush */
13700 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13701 	} else
13702 		ha_copy = phba->ha_copy;
13703 
13704 	/*
13705 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
13706 	 */
13707 	ha_copy &= ~(phba->work_ha_mask);
13708 
13709 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13710 	status >>= (4*LPFC_FCP_RING);
13711 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
13712 	if (status & HA_RXMASK)
13713 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
13714 
13715 	if (phba->cfg_multi_ring_support == 2) {
13716 		/*
13717 		 * Process all events on extra ring. Take the optimized path
13718 		 * for extra ring IO.
13719 		 */
13720 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13721 		status >>= (4*LPFC_EXTRA_RING);
13722 		if (status & HA_RXMASK) {
13723 			lpfc_sli_handle_fast_ring_event(phba,
13724 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
13725 					status);
13726 		}
13727 	}
13728 	return IRQ_HANDLED;
13729 }  /* lpfc_sli_fp_intr_handler */
13730 
13731 /**
13732  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
13733  * @irq: Interrupt number.
13734  * @dev_id: The device context pointer.
13735  *
13736  * This function is the HBA device-level interrupt handler to device with
13737  * SLI-3 interface spec, called from the PCI layer when either MSI or
13738  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
13739  * requires driver attention. This function invokes the slow-path interrupt
13740  * attention handling function and fast-path interrupt attention handling
13741  * function in turn to process the relevant HBA attention events. This
13742  * function is called without any lock held. It gets the hbalock to access
13743  * and update SLI data structures.
13744  *
13745  * This function returns IRQ_HANDLED when interrupt is handled, else it
13746  * returns IRQ_NONE.
13747  **/
13748 irqreturn_t
13749 lpfc_sli_intr_handler(int irq, void *dev_id)
13750 {
13751 	struct lpfc_hba  *phba;
13752 	irqreturn_t sp_irq_rc, fp_irq_rc;
13753 	unsigned long status1, status2;
13754 	uint32_t hc_copy;
13755 
13756 	/*
13757 	 * Get the driver's phba structure from the dev_id and
13758 	 * assume the HBA is not interrupting.
13759 	 */
13760 	phba = (struct lpfc_hba *) dev_id;
13761 
13762 	if (unlikely(!phba))
13763 		return IRQ_NONE;
13764 
13765 	/* Check device state for handling interrupt */
13766 	if (lpfc_intr_state_check(phba))
13767 		return IRQ_NONE;
13768 
13769 	spin_lock(&phba->hbalock);
13770 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
13771 		spin_unlock(&phba->hbalock);
13772 		return IRQ_HANDLED;
13773 	}
13774 
13775 	if (unlikely(!phba->ha_copy)) {
13776 		spin_unlock(&phba->hbalock);
13777 		return IRQ_NONE;
13778 	} else if (phba->ha_copy & HA_ERATT) {
13779 		if (phba->hba_flag & HBA_ERATT_HANDLED)
13780 			/* ERATT polling has handled ERATT */
13781 			phba->ha_copy &= ~HA_ERATT;
13782 		else
13783 			/* Indicate interrupt handler handles ERATT */
13784 			phba->hba_flag |= HBA_ERATT_HANDLED;
13785 	}
13786 
13787 	/*
13788 	 * If there is deferred error attention, do not check for any interrupt.
13789 	 */
13790 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13791 		spin_unlock(&phba->hbalock);
13792 		return IRQ_NONE;
13793 	}
13794 
13795 	/* Clear attention sources except link and error attentions */
13796 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
13797 		spin_unlock(&phba->hbalock);
13798 		return IRQ_HANDLED;
13799 	}
13800 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
13801 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
13802 		phba->HCregaddr);
13803 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
13804 	writel(hc_copy, phba->HCregaddr);
13805 	readl(phba->HAregaddr); /* flush */
13806 	spin_unlock(&phba->hbalock);
13807 
13808 	/*
13809 	 * Invokes slow-path host attention interrupt handling as appropriate.
13810 	 */
13811 
13812 	/* status of events with mailbox and link attention */
13813 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
13814 
13815 	/* status of events with ELS ring */
13816 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
13817 	status2 >>= (4*LPFC_ELS_RING);
13818 
13819 	if (status1 || (status2 & HA_RXMASK))
13820 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
13821 	else
13822 		sp_irq_rc = IRQ_NONE;
13823 
13824 	/*
13825 	 * Invoke fast-path host attention interrupt handling as appropriate.
13826 	 */
13827 
13828 	/* status of events with FCP ring */
13829 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13830 	status1 >>= (4*LPFC_FCP_RING);
13831 
13832 	/* status of events with extra ring */
13833 	if (phba->cfg_multi_ring_support == 2) {
13834 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13835 		status2 >>= (4*LPFC_EXTRA_RING);
13836 	} else
13837 		status2 = 0;
13838 
13839 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
13840 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
13841 	else
13842 		fp_irq_rc = IRQ_NONE;
13843 
13844 	/* Return device-level interrupt handling status */
13845 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
13846 }  /* lpfc_sli_intr_handler */
13847 
13848 /**
13849  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
13850  * @phba: pointer to lpfc hba data structure.
13851  *
13852  * This routine is invoked by the worker thread to process all the pending
13853  * SLI4 els abort xri events.
13854  **/
13855 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
13856 {
13857 	struct lpfc_cq_event *cq_event;
13858 	unsigned long iflags;
13859 
13860 	/* First, declare the els xri abort event has been handled */
13861 	spin_lock_irqsave(&phba->hbalock, iflags);
13862 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
13863 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13864 
13865 	/* Now, handle all the els xri abort events */
13866 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
13867 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
13868 		/* Get the first event from the head of the event queue */
13869 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
13870 				 cq_event, struct lpfc_cq_event, list);
13871 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
13872 				       iflags);
13873 		/* Notify aborted XRI for ELS work queue */
13874 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
13875 
13876 		/* Free the event processed back to the free pool */
13877 		lpfc_sli4_cq_event_release(phba, cq_event);
13878 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
13879 				  iflags);
13880 	}
13881 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
13882 }
13883 
13884 /**
13885  * lpfc_sli4_els_preprocess_rspiocbq - Get response iocbq from els wcqe
13886  * @phba: Pointer to HBA context object.
13887  * @irspiocbq: Pointer to work-queue completion queue entry.
13888  *
13889  * This routine handles an ELS work-queue completion event and construct
13890  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
13891  * discovery engine to handle.
13892  *
13893  * Return: Pointer to the receive IOCBQ, NULL otherwise.
13894  **/
13895 static struct lpfc_iocbq *
13896 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
13897 				  struct lpfc_iocbq *irspiocbq)
13898 {
13899 	struct lpfc_sli_ring *pring;
13900 	struct lpfc_iocbq *cmdiocbq;
13901 	struct lpfc_wcqe_complete *wcqe;
13902 	unsigned long iflags;
13903 
13904 	pring = lpfc_phba_elsring(phba);
13905 	if (unlikely(!pring))
13906 		return NULL;
13907 
13908 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
13909 	spin_lock_irqsave(&pring->ring_lock, iflags);
13910 	pring->stats.iocb_event++;
13911 	/* Look up the ELS command IOCB and create pseudo response IOCB */
13912 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
13913 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13914 	if (unlikely(!cmdiocbq)) {
13915 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
13916 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13917 				"0386 ELS complete with no corresponding "
13918 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
13919 				wcqe->word0, wcqe->total_data_placed,
13920 				wcqe->parameter, wcqe->word3);
13921 		lpfc_sli_release_iocbq(phba, irspiocbq);
13922 		return NULL;
13923 	}
13924 
13925 	memcpy(&irspiocbq->wqe, &cmdiocbq->wqe, sizeof(union lpfc_wqe128));
13926 	memcpy(&irspiocbq->wcqe_cmpl, wcqe, sizeof(*wcqe));
13927 
13928 	/* Put the iocb back on the txcmplq */
13929 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
13930 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
13931 
13932 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
13933 		spin_lock_irqsave(&phba->hbalock, iflags);
13934 		cmdiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
13935 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13936 	}
13937 
13938 	return irspiocbq;
13939 }
13940 
13941 inline struct lpfc_cq_event *
13942 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
13943 {
13944 	struct lpfc_cq_event *cq_event;
13945 
13946 	/* Allocate a new internal CQ_EVENT entry */
13947 	cq_event = lpfc_sli4_cq_event_alloc(phba);
13948 	if (!cq_event) {
13949 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13950 				"0602 Failed to alloc CQ_EVENT entry\n");
13951 		return NULL;
13952 	}
13953 
13954 	/* Move the CQE into the event */
13955 	memcpy(&cq_event->cqe, entry, size);
13956 	return cq_event;
13957 }
13958 
13959 /**
13960  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
13961  * @phba: Pointer to HBA context object.
13962  * @mcqe: Pointer to mailbox completion queue entry.
13963  *
13964  * This routine process a mailbox completion queue entry with asynchronous
13965  * event.
13966  *
13967  * Return: true if work posted to worker thread, otherwise false.
13968  **/
13969 static bool
13970 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13971 {
13972 	struct lpfc_cq_event *cq_event;
13973 	unsigned long iflags;
13974 
13975 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13976 			"0392 Async Event: word0:x%x, word1:x%x, "
13977 			"word2:x%x, word3:x%x\n", mcqe->word0,
13978 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
13979 
13980 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
13981 	if (!cq_event)
13982 		return false;
13983 
13984 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
13985 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
13986 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
13987 
13988 	/* Set the async event flag */
13989 	spin_lock_irqsave(&phba->hbalock, iflags);
13990 	phba->hba_flag |= ASYNC_EVENT;
13991 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13992 
13993 	return true;
13994 }
13995 
13996 /**
13997  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
13998  * @phba: Pointer to HBA context object.
13999  * @mcqe: Pointer to mailbox completion queue entry.
14000  *
14001  * This routine process a mailbox completion queue entry with mailbox
14002  * completion event.
14003  *
14004  * Return: true if work posted to worker thread, otherwise false.
14005  **/
14006 static bool
14007 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14008 {
14009 	uint32_t mcqe_status;
14010 	MAILBOX_t *mbox, *pmbox;
14011 	struct lpfc_mqe *mqe;
14012 	struct lpfc_vport *vport;
14013 	struct lpfc_nodelist *ndlp;
14014 	struct lpfc_dmabuf *mp;
14015 	unsigned long iflags;
14016 	LPFC_MBOXQ_t *pmb;
14017 	bool workposted = false;
14018 	int rc;
14019 
14020 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
14021 	if (!bf_get(lpfc_trailer_completed, mcqe))
14022 		goto out_no_mqe_complete;
14023 
14024 	/* Get the reference to the active mbox command */
14025 	spin_lock_irqsave(&phba->hbalock, iflags);
14026 	pmb = phba->sli.mbox_active;
14027 	if (unlikely(!pmb)) {
14028 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14029 				"1832 No pending MBOX command to handle\n");
14030 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14031 		goto out_no_mqe_complete;
14032 	}
14033 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14034 	mqe = &pmb->u.mqe;
14035 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
14036 	mbox = phba->mbox;
14037 	vport = pmb->vport;
14038 
14039 	/* Reset heartbeat timer */
14040 	phba->last_completion_time = jiffies;
14041 	del_timer(&phba->sli.mbox_tmo);
14042 
14043 	/* Move mbox data to caller's mailbox region, do endian swapping */
14044 	if (pmb->mbox_cmpl && mbox)
14045 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
14046 
14047 	/*
14048 	 * For mcqe errors, conditionally move a modified error code to
14049 	 * the mbox so that the error will not be missed.
14050 	 */
14051 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
14052 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
14053 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
14054 			bf_set(lpfc_mqe_status, mqe,
14055 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
14056 	}
14057 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
14058 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
14059 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
14060 				      "MBOX dflt rpi: status:x%x rpi:x%x",
14061 				      mcqe_status,
14062 				      pmbox->un.varWords[0], 0);
14063 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
14064 			mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
14065 			ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
14066 
14067 			/* Reg_LOGIN of dflt RPI was successful. Mark the
14068 			 * node as having an UNREG_LOGIN in progress to stop
14069 			 * an unsolicited PLOGI from the same NPortId from
14070 			 * starting another mailbox transaction.
14071 			 */
14072 			spin_lock_irqsave(&ndlp->lock, iflags);
14073 			ndlp->nlp_flag |= NLP_UNREG_INP;
14074 			spin_unlock_irqrestore(&ndlp->lock, iflags);
14075 			lpfc_unreg_login(phba, vport->vpi,
14076 					 pmbox->un.varWords[0], pmb);
14077 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
14078 			pmb->ctx_buf = mp;
14079 
14080 			/* No reference taken here.  This is a default
14081 			 * RPI reg/immediate unreg cycle. The reference was
14082 			 * taken in the reg rpi path and is released when
14083 			 * this mailbox completes.
14084 			 */
14085 			pmb->ctx_ndlp = ndlp;
14086 			pmb->vport = vport;
14087 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
14088 			if (rc != MBX_BUSY)
14089 				lpfc_printf_log(phba, KERN_ERR,
14090 						LOG_TRACE_EVENT,
14091 						"0385 rc should "
14092 						"have been MBX_BUSY\n");
14093 			if (rc != MBX_NOT_FINISHED)
14094 				goto send_current_mbox;
14095 		}
14096 	}
14097 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
14098 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
14099 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
14100 
14101 	/* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
14102 	if (pmbox->mbxCommand == MBX_HEARTBEAT) {
14103 		spin_lock_irqsave(&phba->hbalock, iflags);
14104 		/* Release the mailbox command posting token */
14105 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14106 		phba->sli.mbox_active = NULL;
14107 		if (bf_get(lpfc_trailer_consumed, mcqe))
14108 			lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14109 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14110 
14111 		/* Post the next mbox command, if there is one */
14112 		lpfc_sli4_post_async_mbox(phba);
14113 
14114 		/* Process cmpl now */
14115 		if (pmb->mbox_cmpl)
14116 			pmb->mbox_cmpl(phba, pmb);
14117 		return false;
14118 	}
14119 
14120 	/* There is mailbox completion work to queue to the worker thread */
14121 	spin_lock_irqsave(&phba->hbalock, iflags);
14122 	__lpfc_mbox_cmpl_put(phba, pmb);
14123 	phba->work_ha |= HA_MBATT;
14124 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14125 	workposted = true;
14126 
14127 send_current_mbox:
14128 	spin_lock_irqsave(&phba->hbalock, iflags);
14129 	/* Release the mailbox command posting token */
14130 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14131 	/* Setting active mailbox pointer need to be in sync to flag clear */
14132 	phba->sli.mbox_active = NULL;
14133 	if (bf_get(lpfc_trailer_consumed, mcqe))
14134 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14135 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14136 	/* Wake up worker thread to post the next pending mailbox command */
14137 	lpfc_worker_wake_up(phba);
14138 	return workposted;
14139 
14140 out_no_mqe_complete:
14141 	spin_lock_irqsave(&phba->hbalock, iflags);
14142 	if (bf_get(lpfc_trailer_consumed, mcqe))
14143 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14144 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14145 	return false;
14146 }
14147 
14148 /**
14149  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
14150  * @phba: Pointer to HBA context object.
14151  * @cq: Pointer to associated CQ
14152  * @cqe: Pointer to mailbox completion queue entry.
14153  *
14154  * This routine process a mailbox completion queue entry, it invokes the
14155  * proper mailbox complete handling or asynchronous event handling routine
14156  * according to the MCQE's async bit.
14157  *
14158  * Return: true if work posted to worker thread, otherwise false.
14159  **/
14160 static bool
14161 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14162 			 struct lpfc_cqe *cqe)
14163 {
14164 	struct lpfc_mcqe mcqe;
14165 	bool workposted;
14166 
14167 	cq->CQ_mbox++;
14168 
14169 	/* Copy the mailbox MCQE and convert endian order as needed */
14170 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
14171 
14172 	/* Invoke the proper event handling routine */
14173 	if (!bf_get(lpfc_trailer_async, &mcqe))
14174 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
14175 	else
14176 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
14177 	return workposted;
14178 }
14179 
14180 /**
14181  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
14182  * @phba: Pointer to HBA context object.
14183  * @cq: Pointer to associated CQ
14184  * @wcqe: Pointer to work-queue completion queue entry.
14185  *
14186  * This routine handles an ELS work-queue completion event.
14187  *
14188  * Return: true if work posted to worker thread, otherwise false.
14189  **/
14190 static bool
14191 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14192 			     struct lpfc_wcqe_complete *wcqe)
14193 {
14194 	struct lpfc_iocbq *irspiocbq;
14195 	unsigned long iflags;
14196 	struct lpfc_sli_ring *pring = cq->pring;
14197 	int txq_cnt = 0;
14198 	int txcmplq_cnt = 0;
14199 
14200 	/* Check for response status */
14201 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14202 		/* Log the error status */
14203 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14204 				"0357 ELS CQE error: status=x%x: "
14205 				"CQE: %08x %08x %08x %08x\n",
14206 				bf_get(lpfc_wcqe_c_status, wcqe),
14207 				wcqe->word0, wcqe->total_data_placed,
14208 				wcqe->parameter, wcqe->word3);
14209 	}
14210 
14211 	/* Get an irspiocbq for later ELS response processing use */
14212 	irspiocbq = lpfc_sli_get_iocbq(phba);
14213 	if (!irspiocbq) {
14214 		if (!list_empty(&pring->txq))
14215 			txq_cnt++;
14216 		if (!list_empty(&pring->txcmplq))
14217 			txcmplq_cnt++;
14218 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14219 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
14220 			"els_txcmplq_cnt=%d\n",
14221 			txq_cnt, phba->iocb_cnt,
14222 			txcmplq_cnt);
14223 		return false;
14224 	}
14225 
14226 	/* Save off the slow-path queue event for work thread to process */
14227 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
14228 	spin_lock_irqsave(&phba->hbalock, iflags);
14229 	list_add_tail(&irspiocbq->cq_event.list,
14230 		      &phba->sli4_hba.sp_queue_event);
14231 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
14232 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14233 
14234 	return true;
14235 }
14236 
14237 /**
14238  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
14239  * @phba: Pointer to HBA context object.
14240  * @wcqe: Pointer to work-queue completion queue entry.
14241  *
14242  * This routine handles slow-path WQ entry consumed event by invoking the
14243  * proper WQ release routine to the slow-path WQ.
14244  **/
14245 static void
14246 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
14247 			     struct lpfc_wcqe_release *wcqe)
14248 {
14249 	/* sanity check on queue memory */
14250 	if (unlikely(!phba->sli4_hba.els_wq))
14251 		return;
14252 	/* Check for the slow-path ELS work queue */
14253 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
14254 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
14255 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14256 	else
14257 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14258 				"2579 Slow-path wqe consume event carries "
14259 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
14260 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
14261 				phba->sli4_hba.els_wq->queue_id);
14262 }
14263 
14264 /**
14265  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
14266  * @phba: Pointer to HBA context object.
14267  * @cq: Pointer to a WQ completion queue.
14268  * @wcqe: Pointer to work-queue completion queue entry.
14269  *
14270  * This routine handles an XRI abort event.
14271  *
14272  * Return: true if work posted to worker thread, otherwise false.
14273  **/
14274 static bool
14275 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
14276 				   struct lpfc_queue *cq,
14277 				   struct sli4_wcqe_xri_aborted *wcqe)
14278 {
14279 	bool workposted = false;
14280 	struct lpfc_cq_event *cq_event;
14281 	unsigned long iflags;
14282 
14283 	switch (cq->subtype) {
14284 	case LPFC_IO:
14285 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
14286 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14287 			/* Notify aborted XRI for NVME work queue */
14288 			if (phba->nvmet_support)
14289 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
14290 		}
14291 		workposted = false;
14292 		break;
14293 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
14294 	case LPFC_ELS:
14295 		cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
14296 		if (!cq_event) {
14297 			workposted = false;
14298 			break;
14299 		}
14300 		cq_event->hdwq = cq->hdwq;
14301 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14302 				  iflags);
14303 		list_add_tail(&cq_event->list,
14304 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
14305 		/* Set the els xri abort event flag */
14306 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
14307 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14308 				       iflags);
14309 		workposted = true;
14310 		break;
14311 	default:
14312 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14313 				"0603 Invalid CQ subtype %d: "
14314 				"%08x %08x %08x %08x\n",
14315 				cq->subtype, wcqe->word0, wcqe->parameter,
14316 				wcqe->word2, wcqe->word3);
14317 		workposted = false;
14318 		break;
14319 	}
14320 	return workposted;
14321 }
14322 
14323 #define FC_RCTL_MDS_DIAGS	0xF4
14324 
14325 /**
14326  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
14327  * @phba: Pointer to HBA context object.
14328  * @rcqe: Pointer to receive-queue completion queue entry.
14329  *
14330  * This routine process a receive-queue completion queue entry.
14331  *
14332  * Return: true if work posted to worker thread, otherwise false.
14333  **/
14334 static bool
14335 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
14336 {
14337 	bool workposted = false;
14338 	struct fc_frame_header *fc_hdr;
14339 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
14340 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
14341 	struct lpfc_nvmet_tgtport *tgtp;
14342 	struct hbq_dmabuf *dma_buf;
14343 	uint32_t status, rq_id;
14344 	unsigned long iflags;
14345 
14346 	/* sanity check on queue memory */
14347 	if (unlikely(!hrq) || unlikely(!drq))
14348 		return workposted;
14349 
14350 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14351 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14352 	else
14353 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14354 	if (rq_id != hrq->queue_id)
14355 		goto out;
14356 
14357 	status = bf_get(lpfc_rcqe_status, rcqe);
14358 	switch (status) {
14359 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14360 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14361 				"2537 Receive Frame Truncated!!\n");
14362 		fallthrough;
14363 	case FC_STATUS_RQ_SUCCESS:
14364 		spin_lock_irqsave(&phba->hbalock, iflags);
14365 		lpfc_sli4_rq_release(hrq, drq);
14366 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14367 		if (!dma_buf) {
14368 			hrq->RQ_no_buf_found++;
14369 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14370 			goto out;
14371 		}
14372 		hrq->RQ_rcv_buf++;
14373 		hrq->RQ_buf_posted--;
14374 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
14375 
14376 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14377 
14378 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
14379 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
14380 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14381 			/* Handle MDS Loopback frames */
14382 			if  (!(phba->pport->load_flag & FC_UNLOADING))
14383 				lpfc_sli4_handle_mds_loopback(phba->pport,
14384 							      dma_buf);
14385 			else
14386 				lpfc_in_buf_free(phba, &dma_buf->dbuf);
14387 			break;
14388 		}
14389 
14390 		/* save off the frame for the work thread to process */
14391 		list_add_tail(&dma_buf->cq_event.list,
14392 			      &phba->sli4_hba.sp_queue_event);
14393 		/* Frame received */
14394 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
14395 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14396 		workposted = true;
14397 		break;
14398 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14399 		if (phba->nvmet_support) {
14400 			tgtp = phba->targetport->private;
14401 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14402 					"6402 RQE Error x%x, posted %d err_cnt "
14403 					"%d: %x %x %x\n",
14404 					status, hrq->RQ_buf_posted,
14405 					hrq->RQ_no_posted_buf,
14406 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14407 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14408 					atomic_read(&tgtp->xmt_fcp_release));
14409 		}
14410 		fallthrough;
14411 
14412 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14413 		hrq->RQ_no_posted_buf++;
14414 		/* Post more buffers if possible */
14415 		spin_lock_irqsave(&phba->hbalock, iflags);
14416 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
14417 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14418 		workposted = true;
14419 		break;
14420 	}
14421 out:
14422 	return workposted;
14423 }
14424 
14425 /**
14426  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
14427  * @phba: Pointer to HBA context object.
14428  * @cq: Pointer to the completion queue.
14429  * @cqe: Pointer to a completion queue entry.
14430  *
14431  * This routine process a slow-path work-queue or receive queue completion queue
14432  * entry.
14433  *
14434  * Return: true if work posted to worker thread, otherwise false.
14435  **/
14436 static bool
14437 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14438 			 struct lpfc_cqe *cqe)
14439 {
14440 	struct lpfc_cqe cqevt;
14441 	bool workposted = false;
14442 
14443 	/* Copy the work queue CQE and convert endian order if needed */
14444 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14445 
14446 	/* Check and process for different type of WCQE and dispatch */
14447 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
14448 	case CQE_CODE_COMPL_WQE:
14449 		/* Process the WQ/RQ complete event */
14450 		phba->last_completion_time = jiffies;
14451 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14452 				(struct lpfc_wcqe_complete *)&cqevt);
14453 		break;
14454 	case CQE_CODE_RELEASE_WQE:
14455 		/* Process the WQ release event */
14456 		lpfc_sli4_sp_handle_rel_wcqe(phba,
14457 				(struct lpfc_wcqe_release *)&cqevt);
14458 		break;
14459 	case CQE_CODE_XRI_ABORTED:
14460 		/* Process the WQ XRI abort event */
14461 		phba->last_completion_time = jiffies;
14462 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14463 				(struct sli4_wcqe_xri_aborted *)&cqevt);
14464 		break;
14465 	case CQE_CODE_RECEIVE:
14466 	case CQE_CODE_RECEIVE_V1:
14467 		/* Process the RQ event */
14468 		phba->last_completion_time = jiffies;
14469 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
14470 				(struct lpfc_rcqe *)&cqevt);
14471 		break;
14472 	default:
14473 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14474 				"0388 Not a valid WCQE code: x%x\n",
14475 				bf_get(lpfc_cqe_code, &cqevt));
14476 		break;
14477 	}
14478 	return workposted;
14479 }
14480 
14481 /**
14482  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14483  * @phba: Pointer to HBA context object.
14484  * @eqe: Pointer to fast-path event queue entry.
14485  * @speq: Pointer to slow-path event queue.
14486  *
14487  * This routine process a event queue entry from the slow-path event queue.
14488  * It will check the MajorCode and MinorCode to determine this is for a
14489  * completion event on a completion queue, if not, an error shall be logged
14490  * and just return. Otherwise, it will get to the corresponding completion
14491  * queue and process all the entries on that completion queue, rearm the
14492  * completion queue, and then return.
14493  *
14494  **/
14495 static void
14496 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14497 	struct lpfc_queue *speq)
14498 {
14499 	struct lpfc_queue *cq = NULL, *childq;
14500 	uint16_t cqid;
14501 	int ret = 0;
14502 
14503 	/* Get the reference to the corresponding CQ */
14504 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14505 
14506 	list_for_each_entry(childq, &speq->child_list, list) {
14507 		if (childq->queue_id == cqid) {
14508 			cq = childq;
14509 			break;
14510 		}
14511 	}
14512 	if (unlikely(!cq)) {
14513 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14514 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14515 					"0365 Slow-path CQ identifier "
14516 					"(%d) does not exist\n", cqid);
14517 		return;
14518 	}
14519 
14520 	/* Save EQ associated with this CQ */
14521 	cq->assoc_qp = speq;
14522 
14523 	if (is_kdump_kernel())
14524 		ret = queue_work(phba->wq, &cq->spwork);
14525 	else
14526 		ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14527 
14528 	if (!ret)
14529 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14530 				"0390 Cannot schedule queue work "
14531 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14532 				cqid, cq->queue_id, raw_smp_processor_id());
14533 }
14534 
14535 /**
14536  * __lpfc_sli4_process_cq - Process elements of a CQ
14537  * @phba: Pointer to HBA context object.
14538  * @cq: Pointer to CQ to be processed
14539  * @handler: Routine to process each cqe
14540  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14541  * @poll_mode: Polling mode we were called from
14542  *
14543  * This routine processes completion queue entries in a CQ. While a valid
14544  * queue element is found, the handler is called. During processing checks
14545  * are made for periodic doorbell writes to let the hardware know of
14546  * element consumption.
14547  *
14548  * If the max limit on cqes to process is hit, or there are no more valid
14549  * entries, the loop stops. If we processed a sufficient number of elements,
14550  * meaning there is sufficient load, rather than rearming and generating
14551  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14552  * indicates no rescheduling.
14553  *
14554  * Returns True if work scheduled, False otherwise.
14555  **/
14556 static bool
14557 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14558 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14559 			struct lpfc_cqe *), unsigned long *delay,
14560 			enum lpfc_poll_mode poll_mode)
14561 {
14562 	struct lpfc_cqe *cqe;
14563 	bool workposted = false;
14564 	int count = 0, consumed = 0;
14565 	bool arm = true;
14566 
14567 	/* default - no reschedule */
14568 	*delay = 0;
14569 
14570 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14571 		goto rearm_and_exit;
14572 
14573 	/* Process all the entries to the CQ */
14574 	cq->q_flag = 0;
14575 	cqe = lpfc_sli4_cq_get(cq);
14576 	while (cqe) {
14577 		workposted |= handler(phba, cq, cqe);
14578 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
14579 
14580 		consumed++;
14581 		if (!(++count % cq->max_proc_limit))
14582 			break;
14583 
14584 		if (!(count % cq->notify_interval)) {
14585 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14586 						LPFC_QUEUE_NOARM);
14587 			consumed = 0;
14588 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14589 		}
14590 
14591 		if (count == LPFC_NVMET_CQ_NOTIFY)
14592 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14593 
14594 		cqe = lpfc_sli4_cq_get(cq);
14595 	}
14596 	if (count >= phba->cfg_cq_poll_threshold) {
14597 		*delay = 1;
14598 		arm = false;
14599 	}
14600 
14601 	/* Note: complete the irq_poll softirq before rearming CQ */
14602 	if (poll_mode == LPFC_IRQ_POLL)
14603 		irq_poll_complete(&cq->iop);
14604 
14605 	/* Track the max number of CQEs processed in 1 EQ */
14606 	if (count > cq->CQ_max_cqe)
14607 		cq->CQ_max_cqe = count;
14608 
14609 	cq->assoc_qp->EQ_cqe_cnt += count;
14610 
14611 	/* Catch the no cq entry condition */
14612 	if (unlikely(count == 0))
14613 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14614 				"0369 No entry from completion queue "
14615 				"qid=%d\n", cq->queue_id);
14616 
14617 	xchg(&cq->queue_claimed, 0);
14618 
14619 rearm_and_exit:
14620 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14621 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14622 
14623 	return workposted;
14624 }
14625 
14626 /**
14627  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14628  * @cq: pointer to CQ to process
14629  *
14630  * This routine calls the cq processing routine with a handler specific
14631  * to the type of queue bound to it.
14632  *
14633  * The CQ routine returns two values: the first is the calling status,
14634  * which indicates whether work was queued to the  background discovery
14635  * thread. If true, the routine should wakeup the discovery thread;
14636  * the second is the delay parameter. If non-zero, rather than rearming
14637  * the CQ and yet another interrupt, the CQ handler should be queued so
14638  * that it is processed in a subsequent polling action. The value of
14639  * the delay indicates when to reschedule it.
14640  **/
14641 static void
14642 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14643 {
14644 	struct lpfc_hba *phba = cq->phba;
14645 	unsigned long delay;
14646 	bool workposted = false;
14647 	int ret = 0;
14648 
14649 	/* Process and rearm the CQ */
14650 	switch (cq->type) {
14651 	case LPFC_MCQ:
14652 		workposted |= __lpfc_sli4_process_cq(phba, cq,
14653 						lpfc_sli4_sp_handle_mcqe,
14654 						&delay, LPFC_QUEUE_WORK);
14655 		break;
14656 	case LPFC_WCQ:
14657 		if (cq->subtype == LPFC_IO)
14658 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14659 						lpfc_sli4_fp_handle_cqe,
14660 						&delay, LPFC_QUEUE_WORK);
14661 		else
14662 			workposted |= __lpfc_sli4_process_cq(phba, cq,
14663 						lpfc_sli4_sp_handle_cqe,
14664 						&delay, LPFC_QUEUE_WORK);
14665 		break;
14666 	default:
14667 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14668 				"0370 Invalid completion queue type (%d)\n",
14669 				cq->type);
14670 		return;
14671 	}
14672 
14673 	if (delay) {
14674 		if (is_kdump_kernel())
14675 			ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
14676 						delay);
14677 		else
14678 			ret = queue_delayed_work_on(cq->chann, phba->wq,
14679 						&cq->sched_spwork, delay);
14680 		if (!ret)
14681 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14682 				"0394 Cannot schedule queue work "
14683 				"for cqid=%d on CPU %d\n",
14684 				cq->queue_id, cq->chann);
14685 	}
14686 
14687 	/* wake up worker thread if there are works to be done */
14688 	if (workposted)
14689 		lpfc_worker_wake_up(phba);
14690 }
14691 
14692 /**
14693  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
14694  *   interrupt
14695  * @work: pointer to work element
14696  *
14697  * translates from the work handler and calls the slow-path handler.
14698  **/
14699 static void
14700 lpfc_sli4_sp_process_cq(struct work_struct *work)
14701 {
14702 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
14703 
14704 	__lpfc_sli4_sp_process_cq(cq);
14705 }
14706 
14707 /**
14708  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
14709  * @work: pointer to work element
14710  *
14711  * translates from the work handler and calls the slow-path handler.
14712  **/
14713 static void
14714 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
14715 {
14716 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
14717 					struct lpfc_queue, sched_spwork);
14718 
14719 	__lpfc_sli4_sp_process_cq(cq);
14720 }
14721 
14722 /**
14723  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
14724  * @phba: Pointer to HBA context object.
14725  * @cq: Pointer to associated CQ
14726  * @wcqe: Pointer to work-queue completion queue entry.
14727  *
14728  * This routine process a fast-path work queue completion entry from fast-path
14729  * event queue for FCP command response completion.
14730  **/
14731 static void
14732 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14733 			     struct lpfc_wcqe_complete *wcqe)
14734 {
14735 	struct lpfc_sli_ring *pring = cq->pring;
14736 	struct lpfc_iocbq *cmdiocbq;
14737 	unsigned long iflags;
14738 
14739 	/* Check for response status */
14740 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14741 		/* If resource errors reported from HBA, reduce queue
14742 		 * depth of the SCSI device.
14743 		 */
14744 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
14745 		     IOSTAT_LOCAL_REJECT)) &&
14746 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
14747 		     IOERR_NO_RESOURCES))
14748 			phba->lpfc_rampdown_queue_depth(phba);
14749 
14750 		/* Log the cmpl status */
14751 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14752 				"0373 FCP CQE cmpl: status=x%x: "
14753 				"CQE: %08x %08x %08x %08x\n",
14754 				bf_get(lpfc_wcqe_c_status, wcqe),
14755 				wcqe->word0, wcqe->total_data_placed,
14756 				wcqe->parameter, wcqe->word3);
14757 	}
14758 
14759 	/* Look up the FCP command IOCB and create pseudo response IOCB */
14760 	spin_lock_irqsave(&pring->ring_lock, iflags);
14761 	pring->stats.iocb_event++;
14762 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14763 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14764 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
14765 	if (unlikely(!cmdiocbq)) {
14766 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14767 				"0374 FCP complete with no corresponding "
14768 				"cmdiocb: iotag (%d)\n",
14769 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14770 		return;
14771 	}
14772 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
14773 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
14774 #endif
14775 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
14776 		spin_lock_irqsave(&phba->hbalock, iflags);
14777 		cmdiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
14778 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14779 	}
14780 
14781 	if (cmdiocbq->cmd_cmpl) {
14782 		/* For FCP the flag is cleared in cmd_cmpl */
14783 		if (!(cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
14784 		    cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED) {
14785 			spin_lock_irqsave(&phba->hbalock, iflags);
14786 			cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
14787 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14788 		}
14789 
14790 		/* Pass the cmd_iocb and the wcqe to the upper layer */
14791 		memcpy(&cmdiocbq->wcqe_cmpl, wcqe,
14792 		       sizeof(struct lpfc_wcqe_complete));
14793 		(cmdiocbq->cmd_cmpl)(phba, cmdiocbq, cmdiocbq);
14794 	} else {
14795 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14796 				"0375 FCP cmdiocb not callback function "
14797 				"iotag: (%d)\n",
14798 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14799 	}
14800 }
14801 
14802 /**
14803  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
14804  * @phba: Pointer to HBA context object.
14805  * @cq: Pointer to completion queue.
14806  * @wcqe: Pointer to work-queue completion queue entry.
14807  *
14808  * This routine handles an fast-path WQ entry consumed event by invoking the
14809  * proper WQ release routine to the slow-path WQ.
14810  **/
14811 static void
14812 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14813 			     struct lpfc_wcqe_release *wcqe)
14814 {
14815 	struct lpfc_queue *childwq;
14816 	bool wqid_matched = false;
14817 	uint16_t hba_wqid;
14818 
14819 	/* Check for fast-path FCP work queue release */
14820 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
14821 	list_for_each_entry(childwq, &cq->child_list, list) {
14822 		if (childwq->queue_id == hba_wqid) {
14823 			lpfc_sli4_wq_release(childwq,
14824 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14825 			if (childwq->q_flag & HBA_NVMET_WQFULL)
14826 				lpfc_nvmet_wqfull_process(phba, childwq);
14827 			wqid_matched = true;
14828 			break;
14829 		}
14830 	}
14831 	/* Report warning log message if no match found */
14832 	if (wqid_matched != true)
14833 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14834 				"2580 Fast-path wqe consume event carries "
14835 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
14836 }
14837 
14838 /**
14839  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
14840  * @phba: Pointer to HBA context object.
14841  * @cq: Pointer to completion queue.
14842  * @rcqe: Pointer to receive-queue completion queue entry.
14843  *
14844  * This routine process a receive-queue completion queue entry.
14845  *
14846  * Return: true if work posted to worker thread, otherwise false.
14847  **/
14848 static bool
14849 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14850 			    struct lpfc_rcqe *rcqe)
14851 {
14852 	bool workposted = false;
14853 	struct lpfc_queue *hrq;
14854 	struct lpfc_queue *drq;
14855 	struct rqb_dmabuf *dma_buf;
14856 	struct fc_frame_header *fc_hdr;
14857 	struct lpfc_nvmet_tgtport *tgtp;
14858 	uint32_t status, rq_id;
14859 	unsigned long iflags;
14860 	uint32_t fctl, idx;
14861 
14862 	if ((phba->nvmet_support == 0) ||
14863 	    (phba->sli4_hba.nvmet_cqset == NULL))
14864 		return workposted;
14865 
14866 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
14867 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
14868 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
14869 
14870 	/* sanity check on queue memory */
14871 	if (unlikely(!hrq) || unlikely(!drq))
14872 		return workposted;
14873 
14874 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14875 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14876 	else
14877 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14878 
14879 	if ((phba->nvmet_support == 0) ||
14880 	    (rq_id != hrq->queue_id))
14881 		return workposted;
14882 
14883 	status = bf_get(lpfc_rcqe_status, rcqe);
14884 	switch (status) {
14885 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14886 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14887 				"6126 Receive Frame Truncated!!\n");
14888 		fallthrough;
14889 	case FC_STATUS_RQ_SUCCESS:
14890 		spin_lock_irqsave(&phba->hbalock, iflags);
14891 		lpfc_sli4_rq_release(hrq, drq);
14892 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
14893 		if (!dma_buf) {
14894 			hrq->RQ_no_buf_found++;
14895 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14896 			goto out;
14897 		}
14898 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14899 		hrq->RQ_rcv_buf++;
14900 		hrq->RQ_buf_posted--;
14901 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14902 
14903 		/* Just some basic sanity checks on FCP Command frame */
14904 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
14905 			fc_hdr->fh_f_ctl[1] << 8 |
14906 			fc_hdr->fh_f_ctl[2]);
14907 		if (((fctl &
14908 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
14909 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
14910 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
14911 			goto drop;
14912 
14913 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
14914 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
14915 			lpfc_nvmet_unsol_fcp_event(
14916 				phba, idx, dma_buf, cq->isr_timestamp,
14917 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
14918 			return false;
14919 		}
14920 drop:
14921 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
14922 		break;
14923 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14924 		if (phba->nvmet_support) {
14925 			tgtp = phba->targetport->private;
14926 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14927 					"6401 RQE Error x%x, posted %d err_cnt "
14928 					"%d: %x %x %x\n",
14929 					status, hrq->RQ_buf_posted,
14930 					hrq->RQ_no_posted_buf,
14931 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14932 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14933 					atomic_read(&tgtp->xmt_fcp_release));
14934 		}
14935 		fallthrough;
14936 
14937 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14938 		hrq->RQ_no_posted_buf++;
14939 		/* Post more buffers if possible */
14940 		break;
14941 	}
14942 out:
14943 	return workposted;
14944 }
14945 
14946 /**
14947  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
14948  * @phba: adapter with cq
14949  * @cq: Pointer to the completion queue.
14950  * @cqe: Pointer to fast-path completion queue entry.
14951  *
14952  * This routine process a fast-path work queue completion entry from fast-path
14953  * event queue for FCP command response completion.
14954  *
14955  * Return: true if work posted to worker thread, otherwise false.
14956  **/
14957 static bool
14958 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14959 			 struct lpfc_cqe *cqe)
14960 {
14961 	struct lpfc_wcqe_release wcqe;
14962 	bool workposted = false;
14963 
14964 	/* Copy the work queue CQE and convert endian order if needed */
14965 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
14966 
14967 	/* Check and process for different type of WCQE and dispatch */
14968 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
14969 	case CQE_CODE_COMPL_WQE:
14970 	case CQE_CODE_NVME_ERSP:
14971 		cq->CQ_wq++;
14972 		/* Process the WQ complete event */
14973 		phba->last_completion_time = jiffies;
14974 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
14975 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
14976 				(struct lpfc_wcqe_complete *)&wcqe);
14977 		break;
14978 	case CQE_CODE_RELEASE_WQE:
14979 		cq->CQ_release_wqe++;
14980 		/* Process the WQ release event */
14981 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
14982 				(struct lpfc_wcqe_release *)&wcqe);
14983 		break;
14984 	case CQE_CODE_XRI_ABORTED:
14985 		cq->CQ_xri_aborted++;
14986 		/* Process the WQ XRI abort event */
14987 		phba->last_completion_time = jiffies;
14988 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14989 				(struct sli4_wcqe_xri_aborted *)&wcqe);
14990 		break;
14991 	case CQE_CODE_RECEIVE_V1:
14992 	case CQE_CODE_RECEIVE:
14993 		phba->last_completion_time = jiffies;
14994 		if (cq->subtype == LPFC_NVMET) {
14995 			workposted = lpfc_sli4_nvmet_handle_rcqe(
14996 				phba, cq, (struct lpfc_rcqe *)&wcqe);
14997 		}
14998 		break;
14999 	default:
15000 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15001 				"0144 Not a valid CQE code: x%x\n",
15002 				bf_get(lpfc_wcqe_c_code, &wcqe));
15003 		break;
15004 	}
15005 	return workposted;
15006 }
15007 
15008 /**
15009  * lpfc_sli4_sched_cq_work - Schedules cq work
15010  * @phba: Pointer to HBA context object.
15011  * @cq: Pointer to CQ
15012  * @cqid: CQ ID
15013  *
15014  * This routine checks the poll mode of the CQ corresponding to
15015  * cq->chann, then either schedules a softirq or queue_work to complete
15016  * cq work.
15017  *
15018  * queue_work path is taken if in NVMET mode, or if poll_mode is in
15019  * LPFC_QUEUE_WORK mode.  Otherwise, softirq path is taken.
15020  *
15021  **/
15022 static void lpfc_sli4_sched_cq_work(struct lpfc_hba *phba,
15023 				    struct lpfc_queue *cq, uint16_t cqid)
15024 {
15025 	int ret = 0;
15026 
15027 	switch (cq->poll_mode) {
15028 	case LPFC_IRQ_POLL:
15029 		/* CGN mgmt is mutually exclusive from softirq processing */
15030 		if (phba->cmf_active_mode == LPFC_CFG_OFF) {
15031 			irq_poll_sched(&cq->iop);
15032 			break;
15033 		}
15034 		fallthrough;
15035 	case LPFC_QUEUE_WORK:
15036 	default:
15037 		if (is_kdump_kernel())
15038 			ret = queue_work(phba->wq, &cq->irqwork);
15039 		else
15040 			ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
15041 		if (!ret)
15042 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15043 					"0383 Cannot schedule queue work "
15044 					"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
15045 					cqid, cq->queue_id,
15046 					raw_smp_processor_id());
15047 	}
15048 }
15049 
15050 /**
15051  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
15052  * @phba: Pointer to HBA context object.
15053  * @eq: Pointer to the queue structure.
15054  * @eqe: Pointer to fast-path event queue entry.
15055  *
15056  * This routine process a event queue entry from the fast-path event queue.
15057  * It will check the MajorCode and MinorCode to determine this is for a
15058  * completion event on a completion queue, if not, an error shall be logged
15059  * and just return. Otherwise, it will get to the corresponding completion
15060  * queue and process all the entries on the completion queue, rearm the
15061  * completion queue, and then return.
15062  **/
15063 static void
15064 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
15065 			 struct lpfc_eqe *eqe)
15066 {
15067 	struct lpfc_queue *cq = NULL;
15068 	uint32_t qidx = eq->hdwq;
15069 	uint16_t cqid, id;
15070 
15071 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
15072 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15073 				"0366 Not a valid completion "
15074 				"event: majorcode=x%x, minorcode=x%x\n",
15075 				bf_get_le32(lpfc_eqe_major_code, eqe),
15076 				bf_get_le32(lpfc_eqe_minor_code, eqe));
15077 		return;
15078 	}
15079 
15080 	/* Get the reference to the corresponding CQ */
15081 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
15082 
15083 	/* Use the fast lookup method first */
15084 	if (cqid <= phba->sli4_hba.cq_max) {
15085 		cq = phba->sli4_hba.cq_lookup[cqid];
15086 		if (cq)
15087 			goto  work_cq;
15088 	}
15089 
15090 	/* Next check for NVMET completion */
15091 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
15092 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
15093 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
15094 			/* Process NVMET unsol rcv */
15095 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
15096 			goto  process_cq;
15097 		}
15098 	}
15099 
15100 	if (phba->sli4_hba.nvmels_cq &&
15101 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
15102 		/* Process NVME unsol rcv */
15103 		cq = phba->sli4_hba.nvmels_cq;
15104 	}
15105 
15106 	/* Otherwise this is a Slow path event */
15107 	if (cq == NULL) {
15108 		lpfc_sli4_sp_handle_eqe(phba, eqe,
15109 					phba->sli4_hba.hdwq[qidx].hba_eq);
15110 		return;
15111 	}
15112 
15113 process_cq:
15114 	if (unlikely(cqid != cq->queue_id)) {
15115 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15116 				"0368 Miss-matched fast-path completion "
15117 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
15118 				cqid, cq->queue_id);
15119 		return;
15120 	}
15121 
15122 work_cq:
15123 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
15124 	if (phba->ktime_on)
15125 		cq->isr_timestamp = ktime_get_ns();
15126 	else
15127 		cq->isr_timestamp = 0;
15128 #endif
15129 	lpfc_sli4_sched_cq_work(phba, cq, cqid);
15130 }
15131 
15132 /**
15133  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
15134  * @cq: Pointer to CQ to be processed
15135  * @poll_mode: Enum lpfc_poll_state to determine poll mode
15136  *
15137  * This routine calls the cq processing routine with the handler for
15138  * fast path CQEs.
15139  *
15140  * The CQ routine returns two values: the first is the calling status,
15141  * which indicates whether work was queued to the  background discovery
15142  * thread. If true, the routine should wakeup the discovery thread;
15143  * the second is the delay parameter. If non-zero, rather than rearming
15144  * the CQ and yet another interrupt, the CQ handler should be queued so
15145  * that it is processed in a subsequent polling action. The value of
15146  * the delay indicates when to reschedule it.
15147  **/
15148 static void
15149 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq,
15150 			   enum lpfc_poll_mode poll_mode)
15151 {
15152 	struct lpfc_hba *phba = cq->phba;
15153 	unsigned long delay;
15154 	bool workposted = false;
15155 	int ret = 0;
15156 
15157 	/* process and rearm the CQ */
15158 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
15159 					     &delay, poll_mode);
15160 
15161 	if (delay) {
15162 		if (is_kdump_kernel())
15163 			ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
15164 						delay);
15165 		else
15166 			ret = queue_delayed_work_on(cq->chann, phba->wq,
15167 						&cq->sched_irqwork, delay);
15168 		if (!ret)
15169 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15170 					"0367 Cannot schedule queue work "
15171 					"for cqid=%d on CPU %d\n",
15172 					cq->queue_id, cq->chann);
15173 	}
15174 
15175 	/* wake up worker thread if there are works to be done */
15176 	if (workposted)
15177 		lpfc_worker_wake_up(phba);
15178 }
15179 
15180 /**
15181  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
15182  *   interrupt
15183  * @work: pointer to work element
15184  *
15185  * translates from the work handler and calls the fast-path handler.
15186  **/
15187 static void
15188 lpfc_sli4_hba_process_cq(struct work_struct *work)
15189 {
15190 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
15191 
15192 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
15193 }
15194 
15195 /**
15196  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
15197  * @work: pointer to work element
15198  *
15199  * translates from the work handler and calls the fast-path handler.
15200  **/
15201 static void
15202 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
15203 {
15204 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15205 					struct lpfc_queue, sched_irqwork);
15206 
15207 	__lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
15208 }
15209 
15210 /**
15211  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
15212  * @irq: Interrupt number.
15213  * @dev_id: The device context pointer.
15214  *
15215  * This function is directly called from the PCI layer as an interrupt
15216  * service routine when device with SLI-4 interface spec is enabled with
15217  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
15218  * ring event in the HBA. However, when the device is enabled with either
15219  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
15220  * device-level interrupt handler. When the PCI slot is in error recovery
15221  * or the HBA is undergoing initialization, the interrupt handler will not
15222  * process the interrupt. The SCSI FCP fast-path ring event are handled in
15223  * the intrrupt context. This function is called without any lock held.
15224  * It gets the hbalock to access and update SLI data structures. Note that,
15225  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
15226  * equal to that of FCP CQ index.
15227  *
15228  * The link attention and ELS ring attention events are handled
15229  * by the worker thread. The interrupt handler signals the worker thread
15230  * and returns for these events. This function is called without any lock
15231  * held. It gets the hbalock to access and update SLI data structures.
15232  *
15233  * This function returns IRQ_HANDLED when interrupt is handled else it
15234  * returns IRQ_NONE.
15235  **/
15236 irqreturn_t
15237 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
15238 {
15239 	struct lpfc_hba *phba;
15240 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
15241 	struct lpfc_queue *fpeq;
15242 	unsigned long iflag;
15243 	int ecount = 0;
15244 	int hba_eqidx;
15245 	struct lpfc_eq_intr_info *eqi;
15246 
15247 	/* Get the driver's phba structure from the dev_id */
15248 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
15249 	phba = hba_eq_hdl->phba;
15250 	hba_eqidx = hba_eq_hdl->idx;
15251 
15252 	if (unlikely(!phba))
15253 		return IRQ_NONE;
15254 	if (unlikely(!phba->sli4_hba.hdwq))
15255 		return IRQ_NONE;
15256 
15257 	/* Get to the EQ struct associated with this vector */
15258 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
15259 	if (unlikely(!fpeq))
15260 		return IRQ_NONE;
15261 
15262 	/* Check device state for handling interrupt */
15263 	if (unlikely(lpfc_intr_state_check(phba))) {
15264 		/* Check again for link_state with lock held */
15265 		spin_lock_irqsave(&phba->hbalock, iflag);
15266 		if (phba->link_state < LPFC_LINK_DOWN)
15267 			/* Flush, clear interrupt, and rearm the EQ */
15268 			lpfc_sli4_eqcq_flush(phba, fpeq);
15269 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15270 		return IRQ_NONE;
15271 	}
15272 
15273 	eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
15274 	eqi->icnt++;
15275 
15276 	fpeq->last_cpu = raw_smp_processor_id();
15277 
15278 	if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
15279 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
15280 	    phba->cfg_auto_imax &&
15281 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
15282 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
15283 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
15284 
15285 	/* process and rearm the EQ */
15286 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
15287 
15288 	if (unlikely(ecount == 0)) {
15289 		fpeq->EQ_no_entry++;
15290 		if (phba->intr_type == MSIX)
15291 			/* MSI-X treated interrupt served as no EQ share INT */
15292 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15293 					"0358 MSI-X interrupt with no EQE\n");
15294 		else
15295 			/* Non MSI-X treated on interrupt as EQ share INT */
15296 			return IRQ_NONE;
15297 	}
15298 
15299 	return IRQ_HANDLED;
15300 } /* lpfc_sli4_hba_intr_handler */
15301 
15302 /**
15303  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
15304  * @irq: Interrupt number.
15305  * @dev_id: The device context pointer.
15306  *
15307  * This function is the device-level interrupt handler to device with SLI-4
15308  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
15309  * interrupt mode is enabled and there is an event in the HBA which requires
15310  * driver attention. This function invokes the slow-path interrupt attention
15311  * handling function and fast-path interrupt attention handling function in
15312  * turn to process the relevant HBA attention events. This function is called
15313  * without any lock held. It gets the hbalock to access and update SLI data
15314  * structures.
15315  *
15316  * This function returns IRQ_HANDLED when interrupt is handled, else it
15317  * returns IRQ_NONE.
15318  **/
15319 irqreturn_t
15320 lpfc_sli4_intr_handler(int irq, void *dev_id)
15321 {
15322 	struct lpfc_hba  *phba;
15323 	irqreturn_t hba_irq_rc;
15324 	bool hba_handled = false;
15325 	int qidx;
15326 
15327 	/* Get the driver's phba structure from the dev_id */
15328 	phba = (struct lpfc_hba *)dev_id;
15329 
15330 	if (unlikely(!phba))
15331 		return IRQ_NONE;
15332 
15333 	/*
15334 	 * Invoke fast-path host attention interrupt handling as appropriate.
15335 	 */
15336 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
15337 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
15338 					&phba->sli4_hba.hba_eq_hdl[qidx]);
15339 		if (hba_irq_rc == IRQ_HANDLED)
15340 			hba_handled |= true;
15341 	}
15342 
15343 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
15344 } /* lpfc_sli4_intr_handler */
15345 
15346 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
15347 {
15348 	struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
15349 	struct lpfc_queue *eq;
15350 	int i = 0;
15351 
15352 	rcu_read_lock();
15353 
15354 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
15355 		i += lpfc_sli4_poll_eq(eq, LPFC_POLL_SLOWPATH);
15356 	if (!list_empty(&phba->poll_list))
15357 		mod_timer(&phba->cpuhp_poll_timer,
15358 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15359 
15360 	rcu_read_unlock();
15361 }
15362 
15363 inline int lpfc_sli4_poll_eq(struct lpfc_queue *eq, uint8_t path)
15364 {
15365 	struct lpfc_hba *phba = eq->phba;
15366 	int i = 0;
15367 
15368 	/*
15369 	 * Unlocking an irq is one of the entry point to check
15370 	 * for re-schedule, but we are good for io submission
15371 	 * path as midlayer does a get_cpu to glue us in. Flush
15372 	 * out the invalidate queue so we can see the updated
15373 	 * value for flag.
15374 	 */
15375 	smp_rmb();
15376 
15377 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
15378 		/* We will not likely get the completion for the caller
15379 		 * during this iteration but i guess that's fine.
15380 		 * Future io's coming on this eq should be able to
15381 		 * pick it up.  As for the case of single io's, they
15382 		 * will be handled through a sched from polling timer
15383 		 * function which is currently triggered every 1msec.
15384 		 */
15385 		i = lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM);
15386 
15387 	return i;
15388 }
15389 
15390 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
15391 {
15392 	struct lpfc_hba *phba = eq->phba;
15393 
15394 	/* kickstart slowpath processing if needed */
15395 	if (list_empty(&phba->poll_list))
15396 		mod_timer(&phba->cpuhp_poll_timer,
15397 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15398 
15399 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
15400 	synchronize_rcu();
15401 }
15402 
15403 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
15404 {
15405 	struct lpfc_hba *phba = eq->phba;
15406 
15407 	/* Disable slowpath processing for this eq.  Kick start the eq
15408 	 * by RE-ARMING the eq's ASAP
15409 	 */
15410 	list_del_rcu(&eq->_poll_list);
15411 	synchronize_rcu();
15412 
15413 	if (list_empty(&phba->poll_list))
15414 		del_timer_sync(&phba->cpuhp_poll_timer);
15415 }
15416 
15417 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
15418 {
15419 	struct lpfc_queue *eq, *next;
15420 
15421 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
15422 		list_del(&eq->_poll_list);
15423 
15424 	INIT_LIST_HEAD(&phba->poll_list);
15425 	synchronize_rcu();
15426 }
15427 
15428 static inline void
15429 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
15430 {
15431 	if (mode == eq->mode)
15432 		return;
15433 	/*
15434 	 * currently this function is only called during a hotplug
15435 	 * event and the cpu on which this function is executing
15436 	 * is going offline.  By now the hotplug has instructed
15437 	 * the scheduler to remove this cpu from cpu active mask.
15438 	 * So we don't need to work about being put aside by the
15439 	 * scheduler for a high priority process.  Yes, the inte-
15440 	 * rrupts could come but they are known to retire ASAP.
15441 	 */
15442 
15443 	/* Disable polling in the fastpath */
15444 	WRITE_ONCE(eq->mode, mode);
15445 	/* flush out the store buffer */
15446 	smp_wmb();
15447 
15448 	/*
15449 	 * Add this eq to the polling list and start polling. For
15450 	 * a grace period both interrupt handler and poller will
15451 	 * try to process the eq _but_ that's fine.  We have a
15452 	 * synchronization mechanism in place (queue_claimed) to
15453 	 * deal with it.  This is just a draining phase for int-
15454 	 * errupt handler (not eq's) as we have guranteed through
15455 	 * barrier that all the CPUs have seen the new CQ_POLLED
15456 	 * state. which will effectively disable the REARMING of
15457 	 * the EQ.  The whole idea is eq's die off eventually as
15458 	 * we are not rearming EQ's anymore.
15459 	 */
15460 	mode ? lpfc_sli4_add_to_poll_list(eq) :
15461 	       lpfc_sli4_remove_from_poll_list(eq);
15462 }
15463 
15464 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15465 {
15466 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15467 }
15468 
15469 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15470 {
15471 	struct lpfc_hba *phba = eq->phba;
15472 
15473 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15474 
15475 	/* Kick start for the pending io's in h/w.
15476 	 * Once we switch back to interrupt processing on a eq
15477 	 * the io path completion will only arm eq's when it
15478 	 * receives a completion.  But since eq's are in disa-
15479 	 * rmed state it doesn't receive a completion.  This
15480 	 * creates a deadlock scenaro.
15481 	 */
15482 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15483 }
15484 
15485 /**
15486  * lpfc_sli4_queue_free - free a queue structure and associated memory
15487  * @queue: The queue structure to free.
15488  *
15489  * This function frees a queue structure and the DMAable memory used for
15490  * the host resident queue. This function must be called after destroying the
15491  * queue on the HBA.
15492  **/
15493 void
15494 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15495 {
15496 	struct lpfc_dmabuf *dmabuf;
15497 
15498 	if (!queue)
15499 		return;
15500 
15501 	if (!list_empty(&queue->wq_list))
15502 		list_del(&queue->wq_list);
15503 
15504 	while (!list_empty(&queue->page_list)) {
15505 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15506 				 list);
15507 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15508 				  dmabuf->virt, dmabuf->phys);
15509 		kfree(dmabuf);
15510 	}
15511 	if (queue->rqbp) {
15512 		lpfc_free_rq_buffer(queue->phba, queue);
15513 		kfree(queue->rqbp);
15514 	}
15515 
15516 	if (!list_empty(&queue->cpu_list))
15517 		list_del(&queue->cpu_list);
15518 
15519 	kfree(queue);
15520 	return;
15521 }
15522 
15523 /**
15524  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15525  * @phba: The HBA that this queue is being created on.
15526  * @page_size: The size of a queue page
15527  * @entry_size: The size of each queue entry for this queue.
15528  * @entry_count: The number of entries that this queue will handle.
15529  * @cpu: The cpu that will primarily utilize this queue.
15530  *
15531  * This function allocates a queue structure and the DMAable memory used for
15532  * the host resident queue. This function must be called before creating the
15533  * queue on the HBA.
15534  **/
15535 struct lpfc_queue *
15536 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15537 		      uint32_t entry_size, uint32_t entry_count, int cpu)
15538 {
15539 	struct lpfc_queue *queue;
15540 	struct lpfc_dmabuf *dmabuf;
15541 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15542 	uint16_t x, pgcnt;
15543 
15544 	if (!phba->sli4_hba.pc_sli4_params.supported)
15545 		hw_page_size = page_size;
15546 
15547 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15548 
15549 	/* If needed, Adjust page count to match the max the adapter supports */
15550 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15551 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15552 
15553 	queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
15554 			     GFP_KERNEL, cpu_to_node(cpu));
15555 	if (!queue)
15556 		return NULL;
15557 
15558 	INIT_LIST_HEAD(&queue->list);
15559 	INIT_LIST_HEAD(&queue->_poll_list);
15560 	INIT_LIST_HEAD(&queue->wq_list);
15561 	INIT_LIST_HEAD(&queue->wqfull_list);
15562 	INIT_LIST_HEAD(&queue->page_list);
15563 	INIT_LIST_HEAD(&queue->child_list);
15564 	INIT_LIST_HEAD(&queue->cpu_list);
15565 
15566 	/* Set queue parameters now.  If the system cannot provide memory
15567 	 * resources, the free routine needs to know what was allocated.
15568 	 */
15569 	queue->page_count = pgcnt;
15570 	queue->q_pgs = (void **)&queue[1];
15571 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
15572 	queue->entry_size = entry_size;
15573 	queue->entry_count = entry_count;
15574 	queue->page_size = hw_page_size;
15575 	queue->phba = phba;
15576 
15577 	for (x = 0; x < queue->page_count; x++) {
15578 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15579 				      dev_to_node(&phba->pcidev->dev));
15580 		if (!dmabuf)
15581 			goto out_fail;
15582 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15583 						  hw_page_size, &dmabuf->phys,
15584 						  GFP_KERNEL);
15585 		if (!dmabuf->virt) {
15586 			kfree(dmabuf);
15587 			goto out_fail;
15588 		}
15589 		dmabuf->buffer_tag = x;
15590 		list_add_tail(&dmabuf->list, &queue->page_list);
15591 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
15592 		queue->q_pgs[x] = dmabuf->virt;
15593 	}
15594 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15595 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15596 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15597 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15598 
15599 	/* notify_interval will be set during q creation */
15600 
15601 	return queue;
15602 out_fail:
15603 	lpfc_sli4_queue_free(queue);
15604 	return NULL;
15605 }
15606 
15607 /**
15608  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15609  * @phba: HBA structure that indicates port to create a queue on.
15610  * @pci_barset: PCI BAR set flag.
15611  *
15612  * This function shall perform iomap of the specified PCI BAR address to host
15613  * memory address if not already done so and return it. The returned host
15614  * memory address can be NULL.
15615  */
15616 static void __iomem *
15617 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15618 {
15619 	if (!phba->pcidev)
15620 		return NULL;
15621 
15622 	switch (pci_barset) {
15623 	case WQ_PCI_BAR_0_AND_1:
15624 		return phba->pci_bar0_memmap_p;
15625 	case WQ_PCI_BAR_2_AND_3:
15626 		return phba->pci_bar2_memmap_p;
15627 	case WQ_PCI_BAR_4_AND_5:
15628 		return phba->pci_bar4_memmap_p;
15629 	default:
15630 		break;
15631 	}
15632 	return NULL;
15633 }
15634 
15635 /**
15636  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
15637  * @phba: HBA structure that EQs are on.
15638  * @startq: The starting EQ index to modify
15639  * @numq: The number of EQs (consecutive indexes) to modify
15640  * @usdelay: amount of delay
15641  *
15642  * This function revises the EQ delay on 1 or more EQs. The EQ delay
15643  * is set either by writing to a register (if supported by the SLI Port)
15644  * or by mailbox command. The mailbox command allows several EQs to be
15645  * updated at once.
15646  *
15647  * The @phba struct is used to send a mailbox command to HBA. The @startq
15648  * is used to get the starting EQ index to change. The @numq value is
15649  * used to specify how many consecutive EQ indexes, starting at EQ index,
15650  * are to be changed. This function is asynchronous and will wait for any
15651  * mailbox commands to finish before returning.
15652  *
15653  * On success this function will return a zero. If unable to allocate
15654  * enough memory this function will return -ENOMEM. If a mailbox command
15655  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
15656  * have had their delay multipler changed.
15657  **/
15658 void
15659 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
15660 			 uint32_t numq, uint32_t usdelay)
15661 {
15662 	struct lpfc_mbx_modify_eq_delay *eq_delay;
15663 	LPFC_MBOXQ_t *mbox;
15664 	struct lpfc_queue *eq;
15665 	int cnt = 0, rc, length;
15666 	uint32_t shdr_status, shdr_add_status;
15667 	uint32_t dmult;
15668 	int qidx;
15669 	union lpfc_sli4_cfg_shdr *shdr;
15670 
15671 	if (startq >= phba->cfg_irq_chann)
15672 		return;
15673 
15674 	if (usdelay > 0xFFFF) {
15675 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
15676 				"6429 usdelay %d too large. Scaled down to "
15677 				"0xFFFF.\n", usdelay);
15678 		usdelay = 0xFFFF;
15679 	}
15680 
15681 	/* set values by EQ_DELAY register if supported */
15682 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
15683 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15684 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15685 			if (!eq)
15686 				continue;
15687 
15688 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
15689 
15690 			if (++cnt >= numq)
15691 				break;
15692 		}
15693 		return;
15694 	}
15695 
15696 	/* Otherwise, set values by mailbox cmd */
15697 
15698 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15699 	if (!mbox) {
15700 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15701 				"6428 Failed allocating mailbox cmd buffer."
15702 				" EQ delay was not set.\n");
15703 		return;
15704 	}
15705 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
15706 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15707 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15708 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
15709 			 length, LPFC_SLI4_MBX_EMBED);
15710 	eq_delay = &mbox->u.mqe.un.eq_delay;
15711 
15712 	/* Calculate delay multiper from maximum interrupt per second */
15713 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
15714 	if (dmult)
15715 		dmult--;
15716 	if (dmult > LPFC_DMULT_MAX)
15717 		dmult = LPFC_DMULT_MAX;
15718 
15719 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15720 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15721 		if (!eq)
15722 			continue;
15723 		eq->q_mode = usdelay;
15724 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
15725 		eq_delay->u.request.eq[cnt].phase = 0;
15726 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
15727 
15728 		if (++cnt >= numq)
15729 			break;
15730 	}
15731 	eq_delay->u.request.num_eq = cnt;
15732 
15733 	mbox->vport = phba->pport;
15734 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15735 	mbox->ctx_buf = NULL;
15736 	mbox->ctx_ndlp = NULL;
15737 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15738 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
15739 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15740 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15741 	if (shdr_status || shdr_add_status || rc) {
15742 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15743 				"2512 MODIFY_EQ_DELAY mailbox failed with "
15744 				"status x%x add_status x%x, mbx status x%x\n",
15745 				shdr_status, shdr_add_status, rc);
15746 	}
15747 	mempool_free(mbox, phba->mbox_mem_pool);
15748 	return;
15749 }
15750 
15751 /**
15752  * lpfc_eq_create - Create an Event Queue on the HBA
15753  * @phba: HBA structure that indicates port to create a queue on.
15754  * @eq: The queue structure to use to create the event queue.
15755  * @imax: The maximum interrupt per second limit.
15756  *
15757  * This function creates an event queue, as detailed in @eq, on a port,
15758  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
15759  *
15760  * The @phba struct is used to send mailbox command to HBA. The @eq struct
15761  * is used to get the entry count and entry size that are necessary to
15762  * determine the number of pages to allocate and use for this queue. This
15763  * function will send the EQ_CREATE mailbox command to the HBA to setup the
15764  * event queue. This function is asynchronous and will wait for the mailbox
15765  * command to finish before continuing.
15766  *
15767  * On success this function will return a zero. If unable to allocate enough
15768  * memory this function will return -ENOMEM. If the queue create mailbox command
15769  * fails this function will return -ENXIO.
15770  **/
15771 int
15772 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
15773 {
15774 	struct lpfc_mbx_eq_create *eq_create;
15775 	LPFC_MBOXQ_t *mbox;
15776 	int rc, length, status = 0;
15777 	struct lpfc_dmabuf *dmabuf;
15778 	uint32_t shdr_status, shdr_add_status;
15779 	union lpfc_sli4_cfg_shdr *shdr;
15780 	uint16_t dmult;
15781 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15782 
15783 	/* sanity check on queue memory */
15784 	if (!eq)
15785 		return -ENODEV;
15786 	if (!phba->sli4_hba.pc_sli4_params.supported)
15787 		hw_page_size = SLI4_PAGE_SIZE;
15788 
15789 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15790 	if (!mbox)
15791 		return -ENOMEM;
15792 	length = (sizeof(struct lpfc_mbx_eq_create) -
15793 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15794 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15795 			 LPFC_MBOX_OPCODE_EQ_CREATE,
15796 			 length, LPFC_SLI4_MBX_EMBED);
15797 	eq_create = &mbox->u.mqe.un.eq_create;
15798 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
15799 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
15800 	       eq->page_count);
15801 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
15802 	       LPFC_EQE_SIZE);
15803 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
15804 
15805 	/* Use version 2 of CREATE_EQ if eqav is set */
15806 	if (phba->sli4_hba.pc_sli4_params.eqav) {
15807 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
15808 		       LPFC_Q_CREATE_VERSION_2);
15809 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
15810 		       phba->sli4_hba.pc_sli4_params.eqav);
15811 	}
15812 
15813 	/* don't setup delay multiplier using EQ_CREATE */
15814 	dmult = 0;
15815 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
15816 	       dmult);
15817 	switch (eq->entry_count) {
15818 	default:
15819 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15820 				"0360 Unsupported EQ count. (%d)\n",
15821 				eq->entry_count);
15822 		if (eq->entry_count < 256) {
15823 			status = -EINVAL;
15824 			goto out;
15825 		}
15826 		fallthrough;	/* otherwise default to smallest count */
15827 	case 256:
15828 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15829 		       LPFC_EQ_CNT_256);
15830 		break;
15831 	case 512:
15832 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15833 		       LPFC_EQ_CNT_512);
15834 		break;
15835 	case 1024:
15836 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15837 		       LPFC_EQ_CNT_1024);
15838 		break;
15839 	case 2048:
15840 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15841 		       LPFC_EQ_CNT_2048);
15842 		break;
15843 	case 4096:
15844 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
15845 		       LPFC_EQ_CNT_4096);
15846 		break;
15847 	}
15848 	list_for_each_entry(dmabuf, &eq->page_list, list) {
15849 		memset(dmabuf->virt, 0, hw_page_size);
15850 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15851 					putPaddrLow(dmabuf->phys);
15852 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15853 					putPaddrHigh(dmabuf->phys);
15854 	}
15855 	mbox->vport = phba->pport;
15856 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
15857 	mbox->ctx_buf = NULL;
15858 	mbox->ctx_ndlp = NULL;
15859 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15860 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15861 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15862 	if (shdr_status || shdr_add_status || rc) {
15863 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15864 				"2500 EQ_CREATE mailbox failed with "
15865 				"status x%x add_status x%x, mbx status x%x\n",
15866 				shdr_status, shdr_add_status, rc);
15867 		status = -ENXIO;
15868 	}
15869 	eq->type = LPFC_EQ;
15870 	eq->subtype = LPFC_NONE;
15871 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
15872 	if (eq->queue_id == 0xFFFF)
15873 		status = -ENXIO;
15874 	eq->host_index = 0;
15875 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
15876 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
15877 out:
15878 	mempool_free(mbox, phba->mbox_mem_pool);
15879 	return status;
15880 }
15881 
15882 static int lpfc_cq_poll_hdler(struct irq_poll *iop, int budget)
15883 {
15884 	struct lpfc_queue *cq = container_of(iop, struct lpfc_queue, iop);
15885 
15886 	__lpfc_sli4_hba_process_cq(cq, LPFC_IRQ_POLL);
15887 
15888 	return 1;
15889 }
15890 
15891 /**
15892  * lpfc_cq_create - Create a Completion Queue on the HBA
15893  * @phba: HBA structure that indicates port to create a queue on.
15894  * @cq: The queue structure to use to create the completion queue.
15895  * @eq: The event queue to bind this completion queue to.
15896  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
15897  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
15898  *
15899  * This function creates a completion queue, as detailed in @wq, on a port,
15900  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
15901  *
15902  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15903  * is used to get the entry count and entry size that are necessary to
15904  * determine the number of pages to allocate and use for this queue. The @eq
15905  * is used to indicate which event queue to bind this completion queue to. This
15906  * function will send the CQ_CREATE mailbox command to the HBA to setup the
15907  * completion queue. This function is asynchronous and will wait for the mailbox
15908  * command to finish before continuing.
15909  *
15910  * On success this function will return a zero. If unable to allocate enough
15911  * memory this function will return -ENOMEM. If the queue create mailbox command
15912  * fails this function will return -ENXIO.
15913  **/
15914 int
15915 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
15916 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
15917 {
15918 	struct lpfc_mbx_cq_create *cq_create;
15919 	struct lpfc_dmabuf *dmabuf;
15920 	LPFC_MBOXQ_t *mbox;
15921 	int rc, length, status = 0;
15922 	uint32_t shdr_status, shdr_add_status;
15923 	union lpfc_sli4_cfg_shdr *shdr;
15924 
15925 	/* sanity check on queue memory */
15926 	if (!cq || !eq)
15927 		return -ENODEV;
15928 
15929 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15930 	if (!mbox)
15931 		return -ENOMEM;
15932 	length = (sizeof(struct lpfc_mbx_cq_create) -
15933 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15934 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15935 			 LPFC_MBOX_OPCODE_CQ_CREATE,
15936 			 length, LPFC_SLI4_MBX_EMBED);
15937 	cq_create = &mbox->u.mqe.un.cq_create;
15938 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
15939 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
15940 		    cq->page_count);
15941 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
15942 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
15943 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15944 	       phba->sli4_hba.pc_sli4_params.cqv);
15945 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
15946 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
15947 		       (cq->page_size / SLI4_PAGE_SIZE));
15948 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
15949 		       eq->queue_id);
15950 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
15951 		       phba->sli4_hba.pc_sli4_params.cqav);
15952 	} else {
15953 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
15954 		       eq->queue_id);
15955 	}
15956 	switch (cq->entry_count) {
15957 	case 2048:
15958 	case 4096:
15959 		if (phba->sli4_hba.pc_sli4_params.cqv ==
15960 		    LPFC_Q_CREATE_VERSION_2) {
15961 			cq_create->u.request.context.lpfc_cq_context_count =
15962 				cq->entry_count;
15963 			bf_set(lpfc_cq_context_count,
15964 			       &cq_create->u.request.context,
15965 			       LPFC_CQ_CNT_WORD7);
15966 			break;
15967 		}
15968 		fallthrough;
15969 	default:
15970 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15971 				"0361 Unsupported CQ count: "
15972 				"entry cnt %d sz %d pg cnt %d\n",
15973 				cq->entry_count, cq->entry_size,
15974 				cq->page_count);
15975 		if (cq->entry_count < 256) {
15976 			status = -EINVAL;
15977 			goto out;
15978 		}
15979 		fallthrough;	/* otherwise default to smallest count */
15980 	case 256:
15981 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15982 		       LPFC_CQ_CNT_256);
15983 		break;
15984 	case 512:
15985 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15986 		       LPFC_CQ_CNT_512);
15987 		break;
15988 	case 1024:
15989 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15990 		       LPFC_CQ_CNT_1024);
15991 		break;
15992 	}
15993 	list_for_each_entry(dmabuf, &cq->page_list, list) {
15994 		memset(dmabuf->virt, 0, cq->page_size);
15995 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15996 					putPaddrLow(dmabuf->phys);
15997 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15998 					putPaddrHigh(dmabuf->phys);
15999 	}
16000 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16001 
16002 	/* The IOCTL status is embedded in the mailbox subheader. */
16003 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16004 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16005 	if (shdr_status || shdr_add_status || rc) {
16006 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16007 				"2501 CQ_CREATE mailbox failed with "
16008 				"status x%x add_status x%x, mbx status x%x\n",
16009 				shdr_status, shdr_add_status, rc);
16010 		status = -ENXIO;
16011 		goto out;
16012 	}
16013 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16014 	if (cq->queue_id == 0xFFFF) {
16015 		status = -ENXIO;
16016 		goto out;
16017 	}
16018 	/* link the cq onto the parent eq child list */
16019 	list_add_tail(&cq->list, &eq->child_list);
16020 	/* Set up completion queue's type and subtype */
16021 	cq->type = type;
16022 	cq->subtype = subtype;
16023 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16024 	cq->assoc_qid = eq->queue_id;
16025 	cq->assoc_qp = eq;
16026 	cq->host_index = 0;
16027 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16028 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
16029 
16030 	if (cq->queue_id > phba->sli4_hba.cq_max)
16031 		phba->sli4_hba.cq_max = cq->queue_id;
16032 
16033 	irq_poll_init(&cq->iop, LPFC_IRQ_POLL_WEIGHT, lpfc_cq_poll_hdler);
16034 out:
16035 	mempool_free(mbox, phba->mbox_mem_pool);
16036 	return status;
16037 }
16038 
16039 /**
16040  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
16041  * @phba: HBA structure that indicates port to create a queue on.
16042  * @cqp: The queue structure array to use to create the completion queues.
16043  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
16044  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16045  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16046  *
16047  * This function creates a set of  completion queue, s to support MRQ
16048  * as detailed in @cqp, on a port,
16049  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
16050  *
16051  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16052  * is used to get the entry count and entry size that are necessary to
16053  * determine the number of pages to allocate and use for this queue. The @eq
16054  * is used to indicate which event queue to bind this completion queue to. This
16055  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
16056  * completion queue. This function is asynchronous and will wait for the mailbox
16057  * command to finish before continuing.
16058  *
16059  * On success this function will return a zero. If unable to allocate enough
16060  * memory this function will return -ENOMEM. If the queue create mailbox command
16061  * fails this function will return -ENXIO.
16062  **/
16063 int
16064 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
16065 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
16066 		   uint32_t subtype)
16067 {
16068 	struct lpfc_queue *cq;
16069 	struct lpfc_queue *eq;
16070 	struct lpfc_mbx_cq_create_set *cq_set;
16071 	struct lpfc_dmabuf *dmabuf;
16072 	LPFC_MBOXQ_t *mbox;
16073 	int rc, length, alloclen, status = 0;
16074 	int cnt, idx, numcq, page_idx = 0;
16075 	uint32_t shdr_status, shdr_add_status;
16076 	union lpfc_sli4_cfg_shdr *shdr;
16077 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16078 
16079 	/* sanity check on queue memory */
16080 	numcq = phba->cfg_nvmet_mrq;
16081 	if (!cqp || !hdwq || !numcq)
16082 		return -ENODEV;
16083 
16084 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16085 	if (!mbox)
16086 		return -ENOMEM;
16087 
16088 	length = sizeof(struct lpfc_mbx_cq_create_set);
16089 	length += ((numcq * cqp[0]->page_count) *
16090 		   sizeof(struct dma_address));
16091 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16092 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
16093 			LPFC_SLI4_MBX_NEMBED);
16094 	if (alloclen < length) {
16095 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16096 				"3098 Allocated DMA memory size (%d) is "
16097 				"less than the requested DMA memory size "
16098 				"(%d)\n", alloclen, length);
16099 		status = -ENOMEM;
16100 		goto out;
16101 	}
16102 	cq_set = mbox->sge_array->addr[0];
16103 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
16104 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
16105 
16106 	for (idx = 0; idx < numcq; idx++) {
16107 		cq = cqp[idx];
16108 		eq = hdwq[idx].hba_eq;
16109 		if (!cq || !eq) {
16110 			status = -ENOMEM;
16111 			goto out;
16112 		}
16113 		if (!phba->sli4_hba.pc_sli4_params.supported)
16114 			hw_page_size = cq->page_size;
16115 
16116 		switch (idx) {
16117 		case 0:
16118 			bf_set(lpfc_mbx_cq_create_set_page_size,
16119 			       &cq_set->u.request,
16120 			       (hw_page_size / SLI4_PAGE_SIZE));
16121 			bf_set(lpfc_mbx_cq_create_set_num_pages,
16122 			       &cq_set->u.request, cq->page_count);
16123 			bf_set(lpfc_mbx_cq_create_set_evt,
16124 			       &cq_set->u.request, 1);
16125 			bf_set(lpfc_mbx_cq_create_set_valid,
16126 			       &cq_set->u.request, 1);
16127 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
16128 			       &cq_set->u.request, 0);
16129 			bf_set(lpfc_mbx_cq_create_set_num_cq,
16130 			       &cq_set->u.request, numcq);
16131 			bf_set(lpfc_mbx_cq_create_set_autovalid,
16132 			       &cq_set->u.request,
16133 			       phba->sli4_hba.pc_sli4_params.cqav);
16134 			switch (cq->entry_count) {
16135 			case 2048:
16136 			case 4096:
16137 				if (phba->sli4_hba.pc_sli4_params.cqv ==
16138 				    LPFC_Q_CREATE_VERSION_2) {
16139 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16140 					       &cq_set->u.request,
16141 						cq->entry_count);
16142 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16143 					       &cq_set->u.request,
16144 					       LPFC_CQ_CNT_WORD7);
16145 					break;
16146 				}
16147 				fallthrough;
16148 			default:
16149 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16150 						"3118 Bad CQ count. (%d)\n",
16151 						cq->entry_count);
16152 				if (cq->entry_count < 256) {
16153 					status = -EINVAL;
16154 					goto out;
16155 				}
16156 				fallthrough;	/* otherwise default to smallest */
16157 			case 256:
16158 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16159 				       &cq_set->u.request, LPFC_CQ_CNT_256);
16160 				break;
16161 			case 512:
16162 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16163 				       &cq_set->u.request, LPFC_CQ_CNT_512);
16164 				break;
16165 			case 1024:
16166 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16167 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
16168 				break;
16169 			}
16170 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
16171 			       &cq_set->u.request, eq->queue_id);
16172 			break;
16173 		case 1:
16174 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
16175 			       &cq_set->u.request, eq->queue_id);
16176 			break;
16177 		case 2:
16178 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
16179 			       &cq_set->u.request, eq->queue_id);
16180 			break;
16181 		case 3:
16182 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
16183 			       &cq_set->u.request, eq->queue_id);
16184 			break;
16185 		case 4:
16186 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
16187 			       &cq_set->u.request, eq->queue_id);
16188 			break;
16189 		case 5:
16190 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
16191 			       &cq_set->u.request, eq->queue_id);
16192 			break;
16193 		case 6:
16194 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
16195 			       &cq_set->u.request, eq->queue_id);
16196 			break;
16197 		case 7:
16198 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
16199 			       &cq_set->u.request, eq->queue_id);
16200 			break;
16201 		case 8:
16202 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
16203 			       &cq_set->u.request, eq->queue_id);
16204 			break;
16205 		case 9:
16206 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
16207 			       &cq_set->u.request, eq->queue_id);
16208 			break;
16209 		case 10:
16210 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
16211 			       &cq_set->u.request, eq->queue_id);
16212 			break;
16213 		case 11:
16214 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
16215 			       &cq_set->u.request, eq->queue_id);
16216 			break;
16217 		case 12:
16218 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
16219 			       &cq_set->u.request, eq->queue_id);
16220 			break;
16221 		case 13:
16222 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
16223 			       &cq_set->u.request, eq->queue_id);
16224 			break;
16225 		case 14:
16226 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
16227 			       &cq_set->u.request, eq->queue_id);
16228 			break;
16229 		case 15:
16230 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
16231 			       &cq_set->u.request, eq->queue_id);
16232 			break;
16233 		}
16234 
16235 		/* link the cq onto the parent eq child list */
16236 		list_add_tail(&cq->list, &eq->child_list);
16237 		/* Set up completion queue's type and subtype */
16238 		cq->type = type;
16239 		cq->subtype = subtype;
16240 		cq->assoc_qid = eq->queue_id;
16241 		cq->assoc_qp = eq;
16242 		cq->host_index = 0;
16243 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16244 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
16245 					 cq->entry_count);
16246 		cq->chann = idx;
16247 
16248 		rc = 0;
16249 		list_for_each_entry(dmabuf, &cq->page_list, list) {
16250 			memset(dmabuf->virt, 0, hw_page_size);
16251 			cnt = page_idx + dmabuf->buffer_tag;
16252 			cq_set->u.request.page[cnt].addr_lo =
16253 					putPaddrLow(dmabuf->phys);
16254 			cq_set->u.request.page[cnt].addr_hi =
16255 					putPaddrHigh(dmabuf->phys);
16256 			rc++;
16257 		}
16258 		page_idx += rc;
16259 	}
16260 
16261 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16262 
16263 	/* The IOCTL status is embedded in the mailbox subheader. */
16264 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16265 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16266 	if (shdr_status || shdr_add_status || rc) {
16267 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16268 				"3119 CQ_CREATE_SET mailbox failed with "
16269 				"status x%x add_status x%x, mbx status x%x\n",
16270 				shdr_status, shdr_add_status, rc);
16271 		status = -ENXIO;
16272 		goto out;
16273 	}
16274 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
16275 	if (rc == 0xFFFF) {
16276 		status = -ENXIO;
16277 		goto out;
16278 	}
16279 
16280 	for (idx = 0; idx < numcq; idx++) {
16281 		cq = cqp[idx];
16282 		cq->queue_id = rc + idx;
16283 		if (cq->queue_id > phba->sli4_hba.cq_max)
16284 			phba->sli4_hba.cq_max = cq->queue_id;
16285 	}
16286 
16287 out:
16288 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16289 	return status;
16290 }
16291 
16292 /**
16293  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
16294  * @phba: HBA structure that indicates port to create a queue on.
16295  * @mq: The queue structure to use to create the mailbox queue.
16296  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
16297  * @cq: The completion queue to associate with this cq.
16298  *
16299  * This function provides failback (fb) functionality when the
16300  * mq_create_ext fails on older FW generations.  It's purpose is identical
16301  * to mq_create_ext otherwise.
16302  *
16303  * This routine cannot fail as all attributes were previously accessed and
16304  * initialized in mq_create_ext.
16305  **/
16306 static void
16307 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
16308 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
16309 {
16310 	struct lpfc_mbx_mq_create *mq_create;
16311 	struct lpfc_dmabuf *dmabuf;
16312 	int length;
16313 
16314 	length = (sizeof(struct lpfc_mbx_mq_create) -
16315 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16316 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16317 			 LPFC_MBOX_OPCODE_MQ_CREATE,
16318 			 length, LPFC_SLI4_MBX_EMBED);
16319 	mq_create = &mbox->u.mqe.un.mq_create;
16320 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
16321 	       mq->page_count);
16322 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
16323 	       cq->queue_id);
16324 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
16325 	switch (mq->entry_count) {
16326 	case 16:
16327 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16328 		       LPFC_MQ_RING_SIZE_16);
16329 		break;
16330 	case 32:
16331 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16332 		       LPFC_MQ_RING_SIZE_32);
16333 		break;
16334 	case 64:
16335 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16336 		       LPFC_MQ_RING_SIZE_64);
16337 		break;
16338 	case 128:
16339 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16340 		       LPFC_MQ_RING_SIZE_128);
16341 		break;
16342 	}
16343 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16344 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16345 			putPaddrLow(dmabuf->phys);
16346 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16347 			putPaddrHigh(dmabuf->phys);
16348 	}
16349 }
16350 
16351 /**
16352  * lpfc_mq_create - Create a mailbox Queue on the HBA
16353  * @phba: HBA structure that indicates port to create a queue on.
16354  * @mq: The queue structure to use to create the mailbox queue.
16355  * @cq: The completion queue to associate with this cq.
16356  * @subtype: The queue's subtype.
16357  *
16358  * This function creates a mailbox queue, as detailed in @mq, on a port,
16359  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
16360  *
16361  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16362  * is used to get the entry count and entry size that are necessary to
16363  * determine the number of pages to allocate and use for this queue. This
16364  * function will send the MQ_CREATE mailbox command to the HBA to setup the
16365  * mailbox queue. This function is asynchronous and will wait for the mailbox
16366  * command to finish before continuing.
16367  *
16368  * On success this function will return a zero. If unable to allocate enough
16369  * memory this function will return -ENOMEM. If the queue create mailbox command
16370  * fails this function will return -ENXIO.
16371  **/
16372 int32_t
16373 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
16374 	       struct lpfc_queue *cq, uint32_t subtype)
16375 {
16376 	struct lpfc_mbx_mq_create *mq_create;
16377 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
16378 	struct lpfc_dmabuf *dmabuf;
16379 	LPFC_MBOXQ_t *mbox;
16380 	int rc, length, status = 0;
16381 	uint32_t shdr_status, shdr_add_status;
16382 	union lpfc_sli4_cfg_shdr *shdr;
16383 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16384 
16385 	/* sanity check on queue memory */
16386 	if (!mq || !cq)
16387 		return -ENODEV;
16388 	if (!phba->sli4_hba.pc_sli4_params.supported)
16389 		hw_page_size = SLI4_PAGE_SIZE;
16390 
16391 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16392 	if (!mbox)
16393 		return -ENOMEM;
16394 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
16395 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16396 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16397 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
16398 			 length, LPFC_SLI4_MBX_EMBED);
16399 
16400 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
16401 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
16402 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
16403 	       &mq_create_ext->u.request, mq->page_count);
16404 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
16405 	       &mq_create_ext->u.request, 1);
16406 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
16407 	       &mq_create_ext->u.request, 1);
16408 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
16409 	       &mq_create_ext->u.request, 1);
16410 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
16411 	       &mq_create_ext->u.request, 1);
16412 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
16413 	       &mq_create_ext->u.request, 1);
16414 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
16415 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16416 	       phba->sli4_hba.pc_sli4_params.mqv);
16417 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
16418 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
16419 		       cq->queue_id);
16420 	else
16421 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
16422 		       cq->queue_id);
16423 	switch (mq->entry_count) {
16424 	default:
16425 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16426 				"0362 Unsupported MQ count. (%d)\n",
16427 				mq->entry_count);
16428 		if (mq->entry_count < 16) {
16429 			status = -EINVAL;
16430 			goto out;
16431 		}
16432 		fallthrough;	/* otherwise default to smallest count */
16433 	case 16:
16434 		bf_set(lpfc_mq_context_ring_size,
16435 		       &mq_create_ext->u.request.context,
16436 		       LPFC_MQ_RING_SIZE_16);
16437 		break;
16438 	case 32:
16439 		bf_set(lpfc_mq_context_ring_size,
16440 		       &mq_create_ext->u.request.context,
16441 		       LPFC_MQ_RING_SIZE_32);
16442 		break;
16443 	case 64:
16444 		bf_set(lpfc_mq_context_ring_size,
16445 		       &mq_create_ext->u.request.context,
16446 		       LPFC_MQ_RING_SIZE_64);
16447 		break;
16448 	case 128:
16449 		bf_set(lpfc_mq_context_ring_size,
16450 		       &mq_create_ext->u.request.context,
16451 		       LPFC_MQ_RING_SIZE_128);
16452 		break;
16453 	}
16454 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16455 		memset(dmabuf->virt, 0, hw_page_size);
16456 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16457 					putPaddrLow(dmabuf->phys);
16458 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16459 					putPaddrHigh(dmabuf->phys);
16460 	}
16461 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16462 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16463 			      &mq_create_ext->u.response);
16464 	if (rc != MBX_SUCCESS) {
16465 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16466 				"2795 MQ_CREATE_EXT failed with "
16467 				"status x%x. Failback to MQ_CREATE.\n",
16468 				rc);
16469 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16470 		mq_create = &mbox->u.mqe.un.mq_create;
16471 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16472 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16473 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16474 				      &mq_create->u.response);
16475 	}
16476 
16477 	/* The IOCTL status is embedded in the mailbox subheader. */
16478 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16479 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16480 	if (shdr_status || shdr_add_status || rc) {
16481 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16482 				"2502 MQ_CREATE mailbox failed with "
16483 				"status x%x add_status x%x, mbx status x%x\n",
16484 				shdr_status, shdr_add_status, rc);
16485 		status = -ENXIO;
16486 		goto out;
16487 	}
16488 	if (mq->queue_id == 0xFFFF) {
16489 		status = -ENXIO;
16490 		goto out;
16491 	}
16492 	mq->type = LPFC_MQ;
16493 	mq->assoc_qid = cq->queue_id;
16494 	mq->subtype = subtype;
16495 	mq->host_index = 0;
16496 	mq->hba_index = 0;
16497 
16498 	/* link the mq onto the parent cq child list */
16499 	list_add_tail(&mq->list, &cq->child_list);
16500 out:
16501 	mempool_free(mbox, phba->mbox_mem_pool);
16502 	return status;
16503 }
16504 
16505 /**
16506  * lpfc_wq_create - Create a Work Queue on the HBA
16507  * @phba: HBA structure that indicates port to create a queue on.
16508  * @wq: The queue structure to use to create the work queue.
16509  * @cq: The completion queue to bind this work queue to.
16510  * @subtype: The subtype of the work queue indicating its functionality.
16511  *
16512  * This function creates a work queue, as detailed in @wq, on a port, described
16513  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16514  *
16515  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16516  * is used to get the entry count and entry size that are necessary to
16517  * determine the number of pages to allocate and use for this queue. The @cq
16518  * is used to indicate which completion queue to bind this work queue to. This
16519  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16520  * work queue. This function is asynchronous and will wait for the mailbox
16521  * command to finish before continuing.
16522  *
16523  * On success this function will return a zero. If unable to allocate enough
16524  * memory this function will return -ENOMEM. If the queue create mailbox command
16525  * fails this function will return -ENXIO.
16526  **/
16527 int
16528 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16529 	       struct lpfc_queue *cq, uint32_t subtype)
16530 {
16531 	struct lpfc_mbx_wq_create *wq_create;
16532 	struct lpfc_dmabuf *dmabuf;
16533 	LPFC_MBOXQ_t *mbox;
16534 	int rc, length, status = 0;
16535 	uint32_t shdr_status, shdr_add_status;
16536 	union lpfc_sli4_cfg_shdr *shdr;
16537 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16538 	struct dma_address *page;
16539 	void __iomem *bar_memmap_p;
16540 	uint32_t db_offset;
16541 	uint16_t pci_barset;
16542 	uint8_t dpp_barset;
16543 	uint32_t dpp_offset;
16544 	uint8_t wq_create_version;
16545 #ifdef CONFIG_X86
16546 	unsigned long pg_addr;
16547 #endif
16548 
16549 	/* sanity check on queue memory */
16550 	if (!wq || !cq)
16551 		return -ENODEV;
16552 	if (!phba->sli4_hba.pc_sli4_params.supported)
16553 		hw_page_size = wq->page_size;
16554 
16555 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16556 	if (!mbox)
16557 		return -ENOMEM;
16558 	length = (sizeof(struct lpfc_mbx_wq_create) -
16559 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16560 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16561 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16562 			 length, LPFC_SLI4_MBX_EMBED);
16563 	wq_create = &mbox->u.mqe.un.wq_create;
16564 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16565 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16566 		    wq->page_count);
16567 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16568 		    cq->queue_id);
16569 
16570 	/* wqv is the earliest version supported, NOT the latest */
16571 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16572 	       phba->sli4_hba.pc_sli4_params.wqv);
16573 
16574 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16575 	    (wq->page_size > SLI4_PAGE_SIZE))
16576 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
16577 	else
16578 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
16579 
16580 	switch (wq_create_version) {
16581 	case LPFC_Q_CREATE_VERSION_1:
16582 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
16583 		       wq->entry_count);
16584 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16585 		       LPFC_Q_CREATE_VERSION_1);
16586 
16587 		switch (wq->entry_size) {
16588 		default:
16589 		case 64:
16590 			bf_set(lpfc_mbx_wq_create_wqe_size,
16591 			       &wq_create->u.request_1,
16592 			       LPFC_WQ_WQE_SIZE_64);
16593 			break;
16594 		case 128:
16595 			bf_set(lpfc_mbx_wq_create_wqe_size,
16596 			       &wq_create->u.request_1,
16597 			       LPFC_WQ_WQE_SIZE_128);
16598 			break;
16599 		}
16600 		/* Request DPP by default */
16601 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
16602 		bf_set(lpfc_mbx_wq_create_page_size,
16603 		       &wq_create->u.request_1,
16604 		       (wq->page_size / SLI4_PAGE_SIZE));
16605 		page = wq_create->u.request_1.page;
16606 		break;
16607 	default:
16608 		page = wq_create->u.request.page;
16609 		break;
16610 	}
16611 
16612 	list_for_each_entry(dmabuf, &wq->page_list, list) {
16613 		memset(dmabuf->virt, 0, hw_page_size);
16614 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
16615 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
16616 	}
16617 
16618 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16619 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
16620 
16621 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16622 	/* The IOCTL status is embedded in the mailbox subheader. */
16623 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16624 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16625 	if (shdr_status || shdr_add_status || rc) {
16626 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16627 				"2503 WQ_CREATE mailbox failed with "
16628 				"status x%x add_status x%x, mbx status x%x\n",
16629 				shdr_status, shdr_add_status, rc);
16630 		status = -ENXIO;
16631 		goto out;
16632 	}
16633 
16634 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
16635 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
16636 					&wq_create->u.response);
16637 	else
16638 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
16639 					&wq_create->u.response_1);
16640 
16641 	if (wq->queue_id == 0xFFFF) {
16642 		status = -ENXIO;
16643 		goto out;
16644 	}
16645 
16646 	wq->db_format = LPFC_DB_LIST_FORMAT;
16647 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
16648 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16649 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
16650 					       &wq_create->u.response);
16651 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
16652 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
16653 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16654 						"3265 WQ[%d] doorbell format "
16655 						"not supported: x%x\n",
16656 						wq->queue_id, wq->db_format);
16657 				status = -EINVAL;
16658 				goto out;
16659 			}
16660 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
16661 					    &wq_create->u.response);
16662 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16663 								   pci_barset);
16664 			if (!bar_memmap_p) {
16665 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16666 						"3263 WQ[%d] failed to memmap "
16667 						"pci barset:x%x\n",
16668 						wq->queue_id, pci_barset);
16669 				status = -ENOMEM;
16670 				goto out;
16671 			}
16672 			db_offset = wq_create->u.response.doorbell_offset;
16673 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
16674 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
16675 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16676 						"3252 WQ[%d] doorbell offset "
16677 						"not supported: x%x\n",
16678 						wq->queue_id, db_offset);
16679 				status = -EINVAL;
16680 				goto out;
16681 			}
16682 			wq->db_regaddr = bar_memmap_p + db_offset;
16683 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16684 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
16685 					"format:x%x\n", wq->queue_id,
16686 					pci_barset, db_offset, wq->db_format);
16687 		} else
16688 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
16689 	} else {
16690 		/* Check if DPP was honored by the firmware */
16691 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
16692 				    &wq_create->u.response_1);
16693 		if (wq->dpp_enable) {
16694 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
16695 					    &wq_create->u.response_1);
16696 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16697 								   pci_barset);
16698 			if (!bar_memmap_p) {
16699 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16700 						"3267 WQ[%d] failed to memmap "
16701 						"pci barset:x%x\n",
16702 						wq->queue_id, pci_barset);
16703 				status = -ENOMEM;
16704 				goto out;
16705 			}
16706 			db_offset = wq_create->u.response_1.doorbell_offset;
16707 			wq->db_regaddr = bar_memmap_p + db_offset;
16708 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
16709 					    &wq_create->u.response_1);
16710 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
16711 					    &wq_create->u.response_1);
16712 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16713 								   dpp_barset);
16714 			if (!bar_memmap_p) {
16715 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16716 						"3268 WQ[%d] failed to memmap "
16717 						"pci barset:x%x\n",
16718 						wq->queue_id, dpp_barset);
16719 				status = -ENOMEM;
16720 				goto out;
16721 			}
16722 			dpp_offset = wq_create->u.response_1.dpp_offset;
16723 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
16724 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16725 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
16726 					"dpp_id:x%x dpp_barset:x%x "
16727 					"dpp_offset:x%x\n",
16728 					wq->queue_id, pci_barset, db_offset,
16729 					wq->dpp_id, dpp_barset, dpp_offset);
16730 
16731 #ifdef CONFIG_X86
16732 			/* Enable combined writes for DPP aperture */
16733 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
16734 			rc = set_memory_wc(pg_addr, 1);
16735 			if (rc) {
16736 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16737 					"3272 Cannot setup Combined "
16738 					"Write on WQ[%d] - disable DPP\n",
16739 					wq->queue_id);
16740 				phba->cfg_enable_dpp = 0;
16741 			}
16742 #else
16743 			phba->cfg_enable_dpp = 0;
16744 #endif
16745 		} else
16746 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
16747 	}
16748 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
16749 	if (wq->pring == NULL) {
16750 		status = -ENOMEM;
16751 		goto out;
16752 	}
16753 	wq->type = LPFC_WQ;
16754 	wq->assoc_qid = cq->queue_id;
16755 	wq->subtype = subtype;
16756 	wq->host_index = 0;
16757 	wq->hba_index = 0;
16758 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
16759 
16760 	/* link the wq onto the parent cq child list */
16761 	list_add_tail(&wq->list, &cq->child_list);
16762 out:
16763 	mempool_free(mbox, phba->mbox_mem_pool);
16764 	return status;
16765 }
16766 
16767 /**
16768  * lpfc_rq_create - Create a Receive Queue on the HBA
16769  * @phba: HBA structure that indicates port to create a queue on.
16770  * @hrq: The queue structure to use to create the header receive queue.
16771  * @drq: The queue structure to use to create the data receive queue.
16772  * @cq: The completion queue to bind this work queue to.
16773  * @subtype: The subtype of the work queue indicating its functionality.
16774  *
16775  * This function creates a receive buffer queue pair , as detailed in @hrq and
16776  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
16777  * to the HBA.
16778  *
16779  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
16780  * struct is used to get the entry count that is necessary to determine the
16781  * number of pages to use for this queue. The @cq is used to indicate which
16782  * completion queue to bind received buffers that are posted to these queues to.
16783  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
16784  * receive queue pair. This function is asynchronous and will wait for the
16785  * mailbox command to finish before continuing.
16786  *
16787  * On success this function will return a zero. If unable to allocate enough
16788  * memory this function will return -ENOMEM. If the queue create mailbox command
16789  * fails this function will return -ENXIO.
16790  **/
16791 int
16792 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
16793 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
16794 {
16795 	struct lpfc_mbx_rq_create *rq_create;
16796 	struct lpfc_dmabuf *dmabuf;
16797 	LPFC_MBOXQ_t *mbox;
16798 	int rc, length, status = 0;
16799 	uint32_t shdr_status, shdr_add_status;
16800 	union lpfc_sli4_cfg_shdr *shdr;
16801 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16802 	void __iomem *bar_memmap_p;
16803 	uint32_t db_offset;
16804 	uint16_t pci_barset;
16805 
16806 	/* sanity check on queue memory */
16807 	if (!hrq || !drq || !cq)
16808 		return -ENODEV;
16809 	if (!phba->sli4_hba.pc_sli4_params.supported)
16810 		hw_page_size = SLI4_PAGE_SIZE;
16811 
16812 	if (hrq->entry_count != drq->entry_count)
16813 		return -EINVAL;
16814 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16815 	if (!mbox)
16816 		return -ENOMEM;
16817 	length = (sizeof(struct lpfc_mbx_rq_create) -
16818 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16819 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16820 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
16821 			 length, LPFC_SLI4_MBX_EMBED);
16822 	rq_create = &mbox->u.mqe.un.rq_create;
16823 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
16824 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16825 	       phba->sli4_hba.pc_sli4_params.rqv);
16826 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
16827 		bf_set(lpfc_rq_context_rqe_count_1,
16828 		       &rq_create->u.request.context,
16829 		       hrq->entry_count);
16830 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
16831 		bf_set(lpfc_rq_context_rqe_size,
16832 		       &rq_create->u.request.context,
16833 		       LPFC_RQE_SIZE_8);
16834 		bf_set(lpfc_rq_context_page_size,
16835 		       &rq_create->u.request.context,
16836 		       LPFC_RQ_PAGE_SIZE_4096);
16837 	} else {
16838 		switch (hrq->entry_count) {
16839 		default:
16840 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16841 					"2535 Unsupported RQ count. (%d)\n",
16842 					hrq->entry_count);
16843 			if (hrq->entry_count < 512) {
16844 				status = -EINVAL;
16845 				goto out;
16846 			}
16847 			fallthrough;	/* otherwise default to smallest count */
16848 		case 512:
16849 			bf_set(lpfc_rq_context_rqe_count,
16850 			       &rq_create->u.request.context,
16851 			       LPFC_RQ_RING_SIZE_512);
16852 			break;
16853 		case 1024:
16854 			bf_set(lpfc_rq_context_rqe_count,
16855 			       &rq_create->u.request.context,
16856 			       LPFC_RQ_RING_SIZE_1024);
16857 			break;
16858 		case 2048:
16859 			bf_set(lpfc_rq_context_rqe_count,
16860 			       &rq_create->u.request.context,
16861 			       LPFC_RQ_RING_SIZE_2048);
16862 			break;
16863 		case 4096:
16864 			bf_set(lpfc_rq_context_rqe_count,
16865 			       &rq_create->u.request.context,
16866 			       LPFC_RQ_RING_SIZE_4096);
16867 			break;
16868 		}
16869 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
16870 		       LPFC_HDR_BUF_SIZE);
16871 	}
16872 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16873 	       cq->queue_id);
16874 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16875 	       hrq->page_count);
16876 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
16877 		memset(dmabuf->virt, 0, hw_page_size);
16878 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16879 					putPaddrLow(dmabuf->phys);
16880 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16881 					putPaddrHigh(dmabuf->phys);
16882 	}
16883 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16884 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16885 
16886 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16887 	/* The IOCTL status is embedded in the mailbox subheader. */
16888 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16889 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16890 	if (shdr_status || shdr_add_status || rc) {
16891 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16892 				"2504 RQ_CREATE mailbox failed with "
16893 				"status x%x add_status x%x, mbx status x%x\n",
16894 				shdr_status, shdr_add_status, rc);
16895 		status = -ENXIO;
16896 		goto out;
16897 	}
16898 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16899 	if (hrq->queue_id == 0xFFFF) {
16900 		status = -ENXIO;
16901 		goto out;
16902 	}
16903 
16904 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16905 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
16906 					&rq_create->u.response);
16907 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
16908 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
16909 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16910 					"3262 RQ [%d] doorbell format not "
16911 					"supported: x%x\n", hrq->queue_id,
16912 					hrq->db_format);
16913 			status = -EINVAL;
16914 			goto out;
16915 		}
16916 
16917 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
16918 				    &rq_create->u.response);
16919 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
16920 		if (!bar_memmap_p) {
16921 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16922 					"3269 RQ[%d] failed to memmap pci "
16923 					"barset:x%x\n", hrq->queue_id,
16924 					pci_barset);
16925 			status = -ENOMEM;
16926 			goto out;
16927 		}
16928 
16929 		db_offset = rq_create->u.response.doorbell_offset;
16930 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
16931 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
16932 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16933 					"3270 RQ[%d] doorbell offset not "
16934 					"supported: x%x\n", hrq->queue_id,
16935 					db_offset);
16936 			status = -EINVAL;
16937 			goto out;
16938 		}
16939 		hrq->db_regaddr = bar_memmap_p + db_offset;
16940 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16941 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
16942 				"format:x%x\n", hrq->queue_id, pci_barset,
16943 				db_offset, hrq->db_format);
16944 	} else {
16945 		hrq->db_format = LPFC_DB_RING_FORMAT;
16946 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16947 	}
16948 	hrq->type = LPFC_HRQ;
16949 	hrq->assoc_qid = cq->queue_id;
16950 	hrq->subtype = subtype;
16951 	hrq->host_index = 0;
16952 	hrq->hba_index = 0;
16953 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16954 
16955 	/* now create the data queue */
16956 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16957 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
16958 			 length, LPFC_SLI4_MBX_EMBED);
16959 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16960 	       phba->sli4_hba.pc_sli4_params.rqv);
16961 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
16962 		bf_set(lpfc_rq_context_rqe_count_1,
16963 		       &rq_create->u.request.context, hrq->entry_count);
16964 		if (subtype == LPFC_NVMET)
16965 			rq_create->u.request.context.buffer_size =
16966 				LPFC_NVMET_DATA_BUF_SIZE;
16967 		else
16968 			rq_create->u.request.context.buffer_size =
16969 				LPFC_DATA_BUF_SIZE;
16970 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
16971 		       LPFC_RQE_SIZE_8);
16972 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
16973 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
16974 	} else {
16975 		switch (drq->entry_count) {
16976 		default:
16977 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16978 					"2536 Unsupported RQ count. (%d)\n",
16979 					drq->entry_count);
16980 			if (drq->entry_count < 512) {
16981 				status = -EINVAL;
16982 				goto out;
16983 			}
16984 			fallthrough;	/* otherwise default to smallest count */
16985 		case 512:
16986 			bf_set(lpfc_rq_context_rqe_count,
16987 			       &rq_create->u.request.context,
16988 			       LPFC_RQ_RING_SIZE_512);
16989 			break;
16990 		case 1024:
16991 			bf_set(lpfc_rq_context_rqe_count,
16992 			       &rq_create->u.request.context,
16993 			       LPFC_RQ_RING_SIZE_1024);
16994 			break;
16995 		case 2048:
16996 			bf_set(lpfc_rq_context_rqe_count,
16997 			       &rq_create->u.request.context,
16998 			       LPFC_RQ_RING_SIZE_2048);
16999 			break;
17000 		case 4096:
17001 			bf_set(lpfc_rq_context_rqe_count,
17002 			       &rq_create->u.request.context,
17003 			       LPFC_RQ_RING_SIZE_4096);
17004 			break;
17005 		}
17006 		if (subtype == LPFC_NVMET)
17007 			bf_set(lpfc_rq_context_buf_size,
17008 			       &rq_create->u.request.context,
17009 			       LPFC_NVMET_DATA_BUF_SIZE);
17010 		else
17011 			bf_set(lpfc_rq_context_buf_size,
17012 			       &rq_create->u.request.context,
17013 			       LPFC_DATA_BUF_SIZE);
17014 	}
17015 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17016 	       cq->queue_id);
17017 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17018 	       drq->page_count);
17019 	list_for_each_entry(dmabuf, &drq->page_list, list) {
17020 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17021 					putPaddrLow(dmabuf->phys);
17022 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17023 					putPaddrHigh(dmabuf->phys);
17024 	}
17025 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17026 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17027 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17028 	/* The IOCTL status is embedded in the mailbox subheader. */
17029 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17030 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17031 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17032 	if (shdr_status || shdr_add_status || rc) {
17033 		status = -ENXIO;
17034 		goto out;
17035 	}
17036 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17037 	if (drq->queue_id == 0xFFFF) {
17038 		status = -ENXIO;
17039 		goto out;
17040 	}
17041 	drq->type = LPFC_DRQ;
17042 	drq->assoc_qid = cq->queue_id;
17043 	drq->subtype = subtype;
17044 	drq->host_index = 0;
17045 	drq->hba_index = 0;
17046 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17047 
17048 	/* link the header and data RQs onto the parent cq child list */
17049 	list_add_tail(&hrq->list, &cq->child_list);
17050 	list_add_tail(&drq->list, &cq->child_list);
17051 
17052 out:
17053 	mempool_free(mbox, phba->mbox_mem_pool);
17054 	return status;
17055 }
17056 
17057 /**
17058  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
17059  * @phba: HBA structure that indicates port to create a queue on.
17060  * @hrqp: The queue structure array to use to create the header receive queues.
17061  * @drqp: The queue structure array to use to create the data receive queues.
17062  * @cqp: The completion queue array to bind these receive queues to.
17063  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
17064  *
17065  * This function creates a receive buffer queue pair , as detailed in @hrq and
17066  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17067  * to the HBA.
17068  *
17069  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17070  * struct is used to get the entry count that is necessary to determine the
17071  * number of pages to use for this queue. The @cq is used to indicate which
17072  * completion queue to bind received buffers that are posted to these queues to.
17073  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17074  * receive queue pair. This function is asynchronous and will wait for the
17075  * mailbox command to finish before continuing.
17076  *
17077  * On success this function will return a zero. If unable to allocate enough
17078  * memory this function will return -ENOMEM. If the queue create mailbox command
17079  * fails this function will return -ENXIO.
17080  **/
17081 int
17082 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
17083 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
17084 		uint32_t subtype)
17085 {
17086 	struct lpfc_queue *hrq, *drq, *cq;
17087 	struct lpfc_mbx_rq_create_v2 *rq_create;
17088 	struct lpfc_dmabuf *dmabuf;
17089 	LPFC_MBOXQ_t *mbox;
17090 	int rc, length, alloclen, status = 0;
17091 	int cnt, idx, numrq, page_idx = 0;
17092 	uint32_t shdr_status, shdr_add_status;
17093 	union lpfc_sli4_cfg_shdr *shdr;
17094 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17095 
17096 	numrq = phba->cfg_nvmet_mrq;
17097 	/* sanity check on array memory */
17098 	if (!hrqp || !drqp || !cqp || !numrq)
17099 		return -ENODEV;
17100 	if (!phba->sli4_hba.pc_sli4_params.supported)
17101 		hw_page_size = SLI4_PAGE_SIZE;
17102 
17103 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17104 	if (!mbox)
17105 		return -ENOMEM;
17106 
17107 	length = sizeof(struct lpfc_mbx_rq_create_v2);
17108 	length += ((2 * numrq * hrqp[0]->page_count) *
17109 		   sizeof(struct dma_address));
17110 
17111 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17112 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
17113 				    LPFC_SLI4_MBX_NEMBED);
17114 	if (alloclen < length) {
17115 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17116 				"3099 Allocated DMA memory size (%d) is "
17117 				"less than the requested DMA memory size "
17118 				"(%d)\n", alloclen, length);
17119 		status = -ENOMEM;
17120 		goto out;
17121 	}
17122 
17123 
17124 
17125 	rq_create = mbox->sge_array->addr[0];
17126 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
17127 
17128 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
17129 	cnt = 0;
17130 
17131 	for (idx = 0; idx < numrq; idx++) {
17132 		hrq = hrqp[idx];
17133 		drq = drqp[idx];
17134 		cq  = cqp[idx];
17135 
17136 		/* sanity check on queue memory */
17137 		if (!hrq || !drq || !cq) {
17138 			status = -ENODEV;
17139 			goto out;
17140 		}
17141 
17142 		if (hrq->entry_count != drq->entry_count) {
17143 			status = -EINVAL;
17144 			goto out;
17145 		}
17146 
17147 		if (idx == 0) {
17148 			bf_set(lpfc_mbx_rq_create_num_pages,
17149 			       &rq_create->u.request,
17150 			       hrq->page_count);
17151 			bf_set(lpfc_mbx_rq_create_rq_cnt,
17152 			       &rq_create->u.request, (numrq * 2));
17153 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
17154 			       1);
17155 			bf_set(lpfc_rq_context_base_cq,
17156 			       &rq_create->u.request.context,
17157 			       cq->queue_id);
17158 			bf_set(lpfc_rq_context_data_size,
17159 			       &rq_create->u.request.context,
17160 			       LPFC_NVMET_DATA_BUF_SIZE);
17161 			bf_set(lpfc_rq_context_hdr_size,
17162 			       &rq_create->u.request.context,
17163 			       LPFC_HDR_BUF_SIZE);
17164 			bf_set(lpfc_rq_context_rqe_count_1,
17165 			       &rq_create->u.request.context,
17166 			       hrq->entry_count);
17167 			bf_set(lpfc_rq_context_rqe_size,
17168 			       &rq_create->u.request.context,
17169 			       LPFC_RQE_SIZE_8);
17170 			bf_set(lpfc_rq_context_page_size,
17171 			       &rq_create->u.request.context,
17172 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
17173 		}
17174 		rc = 0;
17175 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
17176 			memset(dmabuf->virt, 0, hw_page_size);
17177 			cnt = page_idx + dmabuf->buffer_tag;
17178 			rq_create->u.request.page[cnt].addr_lo =
17179 					putPaddrLow(dmabuf->phys);
17180 			rq_create->u.request.page[cnt].addr_hi =
17181 					putPaddrHigh(dmabuf->phys);
17182 			rc++;
17183 		}
17184 		page_idx += rc;
17185 
17186 		rc = 0;
17187 		list_for_each_entry(dmabuf, &drq->page_list, list) {
17188 			memset(dmabuf->virt, 0, hw_page_size);
17189 			cnt = page_idx + dmabuf->buffer_tag;
17190 			rq_create->u.request.page[cnt].addr_lo =
17191 					putPaddrLow(dmabuf->phys);
17192 			rq_create->u.request.page[cnt].addr_hi =
17193 					putPaddrHigh(dmabuf->phys);
17194 			rc++;
17195 		}
17196 		page_idx += rc;
17197 
17198 		hrq->db_format = LPFC_DB_RING_FORMAT;
17199 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17200 		hrq->type = LPFC_HRQ;
17201 		hrq->assoc_qid = cq->queue_id;
17202 		hrq->subtype = subtype;
17203 		hrq->host_index = 0;
17204 		hrq->hba_index = 0;
17205 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17206 
17207 		drq->db_format = LPFC_DB_RING_FORMAT;
17208 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17209 		drq->type = LPFC_DRQ;
17210 		drq->assoc_qid = cq->queue_id;
17211 		drq->subtype = subtype;
17212 		drq->host_index = 0;
17213 		drq->hba_index = 0;
17214 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17215 
17216 		list_add_tail(&hrq->list, &cq->child_list);
17217 		list_add_tail(&drq->list, &cq->child_list);
17218 	}
17219 
17220 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17221 	/* The IOCTL status is embedded in the mailbox subheader. */
17222 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17223 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17224 	if (shdr_status || shdr_add_status || rc) {
17225 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17226 				"3120 RQ_CREATE mailbox failed with "
17227 				"status x%x add_status x%x, mbx status x%x\n",
17228 				shdr_status, shdr_add_status, rc);
17229 		status = -ENXIO;
17230 		goto out;
17231 	}
17232 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17233 	if (rc == 0xFFFF) {
17234 		status = -ENXIO;
17235 		goto out;
17236 	}
17237 
17238 	/* Initialize all RQs with associated queue id */
17239 	for (idx = 0; idx < numrq; idx++) {
17240 		hrq = hrqp[idx];
17241 		hrq->queue_id = rc + (2 * idx);
17242 		drq = drqp[idx];
17243 		drq->queue_id = rc + (2 * idx) + 1;
17244 	}
17245 
17246 out:
17247 	lpfc_sli4_mbox_cmd_free(phba, mbox);
17248 	return status;
17249 }
17250 
17251 /**
17252  * lpfc_eq_destroy - Destroy an event Queue on the HBA
17253  * @phba: HBA structure that indicates port to destroy a queue on.
17254  * @eq: The queue structure associated with the queue to destroy.
17255  *
17256  * This function destroys a queue, as detailed in @eq by sending an mailbox
17257  * command, specific to the type of queue, to the HBA.
17258  *
17259  * The @eq struct is used to get the queue ID of the queue to destroy.
17260  *
17261  * On success this function will return a zero. If the queue destroy mailbox
17262  * command fails this function will return -ENXIO.
17263  **/
17264 int
17265 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
17266 {
17267 	LPFC_MBOXQ_t *mbox;
17268 	int rc, length, status = 0;
17269 	uint32_t shdr_status, shdr_add_status;
17270 	union lpfc_sli4_cfg_shdr *shdr;
17271 
17272 	/* sanity check on queue memory */
17273 	if (!eq)
17274 		return -ENODEV;
17275 
17276 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
17277 	if (!mbox)
17278 		return -ENOMEM;
17279 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
17280 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17281 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17282 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
17283 			 length, LPFC_SLI4_MBX_EMBED);
17284 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
17285 	       eq->queue_id);
17286 	mbox->vport = eq->phba->pport;
17287 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17288 
17289 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
17290 	/* The IOCTL status is embedded in the mailbox subheader. */
17291 	shdr = (union lpfc_sli4_cfg_shdr *)
17292 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
17293 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17294 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17295 	if (shdr_status || shdr_add_status || rc) {
17296 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17297 				"2505 EQ_DESTROY mailbox failed with "
17298 				"status x%x add_status x%x, mbx status x%x\n",
17299 				shdr_status, shdr_add_status, rc);
17300 		status = -ENXIO;
17301 	}
17302 
17303 	/* Remove eq from any list */
17304 	list_del_init(&eq->list);
17305 	mempool_free(mbox, eq->phba->mbox_mem_pool);
17306 	return status;
17307 }
17308 
17309 /**
17310  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
17311  * @phba: HBA structure that indicates port to destroy a queue on.
17312  * @cq: The queue structure associated with the queue to destroy.
17313  *
17314  * This function destroys a queue, as detailed in @cq by sending an mailbox
17315  * command, specific to the type of queue, to the HBA.
17316  *
17317  * The @cq struct is used to get the queue ID of the queue to destroy.
17318  *
17319  * On success this function will return a zero. If the queue destroy mailbox
17320  * command fails this function will return -ENXIO.
17321  **/
17322 int
17323 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
17324 {
17325 	LPFC_MBOXQ_t *mbox;
17326 	int rc, length, status = 0;
17327 	uint32_t shdr_status, shdr_add_status;
17328 	union lpfc_sli4_cfg_shdr *shdr;
17329 
17330 	/* sanity check on queue memory */
17331 	if (!cq)
17332 		return -ENODEV;
17333 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
17334 	if (!mbox)
17335 		return -ENOMEM;
17336 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
17337 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17338 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17339 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
17340 			 length, LPFC_SLI4_MBX_EMBED);
17341 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
17342 	       cq->queue_id);
17343 	mbox->vport = cq->phba->pport;
17344 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17345 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
17346 	/* The IOCTL status is embedded in the mailbox subheader. */
17347 	shdr = (union lpfc_sli4_cfg_shdr *)
17348 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
17349 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17350 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17351 	if (shdr_status || shdr_add_status || rc) {
17352 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17353 				"2506 CQ_DESTROY mailbox failed with "
17354 				"status x%x add_status x%x, mbx status x%x\n",
17355 				shdr_status, shdr_add_status, rc);
17356 		status = -ENXIO;
17357 	}
17358 	/* Remove cq from any list */
17359 	list_del_init(&cq->list);
17360 	mempool_free(mbox, cq->phba->mbox_mem_pool);
17361 	return status;
17362 }
17363 
17364 /**
17365  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
17366  * @phba: HBA structure that indicates port to destroy a queue on.
17367  * @mq: The queue structure associated with the queue to destroy.
17368  *
17369  * This function destroys a queue, as detailed in @mq by sending an mailbox
17370  * command, specific to the type of queue, to the HBA.
17371  *
17372  * The @mq struct is used to get the queue ID of the queue to destroy.
17373  *
17374  * On success this function will return a zero. If the queue destroy mailbox
17375  * command fails this function will return -ENXIO.
17376  **/
17377 int
17378 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
17379 {
17380 	LPFC_MBOXQ_t *mbox;
17381 	int rc, length, status = 0;
17382 	uint32_t shdr_status, shdr_add_status;
17383 	union lpfc_sli4_cfg_shdr *shdr;
17384 
17385 	/* sanity check on queue memory */
17386 	if (!mq)
17387 		return -ENODEV;
17388 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
17389 	if (!mbox)
17390 		return -ENOMEM;
17391 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
17392 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17393 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17394 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
17395 			 length, LPFC_SLI4_MBX_EMBED);
17396 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
17397 	       mq->queue_id);
17398 	mbox->vport = mq->phba->pport;
17399 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17400 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
17401 	/* The IOCTL status is embedded in the mailbox subheader. */
17402 	shdr = (union lpfc_sli4_cfg_shdr *)
17403 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
17404 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17405 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17406 	if (shdr_status || shdr_add_status || rc) {
17407 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17408 				"2507 MQ_DESTROY mailbox failed with "
17409 				"status x%x add_status x%x, mbx status x%x\n",
17410 				shdr_status, shdr_add_status, rc);
17411 		status = -ENXIO;
17412 	}
17413 	/* Remove mq from any list */
17414 	list_del_init(&mq->list);
17415 	mempool_free(mbox, mq->phba->mbox_mem_pool);
17416 	return status;
17417 }
17418 
17419 /**
17420  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
17421  * @phba: HBA structure that indicates port to destroy a queue on.
17422  * @wq: The queue structure associated with the queue to destroy.
17423  *
17424  * This function destroys a queue, as detailed in @wq by sending an mailbox
17425  * command, specific to the type of queue, to the HBA.
17426  *
17427  * The @wq struct is used to get the queue ID of the queue to destroy.
17428  *
17429  * On success this function will return a zero. If the queue destroy mailbox
17430  * command fails this function will return -ENXIO.
17431  **/
17432 int
17433 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
17434 {
17435 	LPFC_MBOXQ_t *mbox;
17436 	int rc, length, status = 0;
17437 	uint32_t shdr_status, shdr_add_status;
17438 	union lpfc_sli4_cfg_shdr *shdr;
17439 
17440 	/* sanity check on queue memory */
17441 	if (!wq)
17442 		return -ENODEV;
17443 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17444 	if (!mbox)
17445 		return -ENOMEM;
17446 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
17447 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17448 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17449 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17450 			 length, LPFC_SLI4_MBX_EMBED);
17451 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17452 	       wq->queue_id);
17453 	mbox->vport = wq->phba->pport;
17454 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17455 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17456 	shdr = (union lpfc_sli4_cfg_shdr *)
17457 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17458 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17459 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17460 	if (shdr_status || shdr_add_status || rc) {
17461 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17462 				"2508 WQ_DESTROY mailbox failed with "
17463 				"status x%x add_status x%x, mbx status x%x\n",
17464 				shdr_status, shdr_add_status, rc);
17465 		status = -ENXIO;
17466 	}
17467 	/* Remove wq from any list */
17468 	list_del_init(&wq->list);
17469 	kfree(wq->pring);
17470 	wq->pring = NULL;
17471 	mempool_free(mbox, wq->phba->mbox_mem_pool);
17472 	return status;
17473 }
17474 
17475 /**
17476  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17477  * @phba: HBA structure that indicates port to destroy a queue on.
17478  * @hrq: The queue structure associated with the queue to destroy.
17479  * @drq: The queue structure associated with the queue to destroy.
17480  *
17481  * This function destroys a queue, as detailed in @rq by sending an mailbox
17482  * command, specific to the type of queue, to the HBA.
17483  *
17484  * The @rq struct is used to get the queue ID of the queue to destroy.
17485  *
17486  * On success this function will return a zero. If the queue destroy mailbox
17487  * command fails this function will return -ENXIO.
17488  **/
17489 int
17490 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17491 		struct lpfc_queue *drq)
17492 {
17493 	LPFC_MBOXQ_t *mbox;
17494 	int rc, length, status = 0;
17495 	uint32_t shdr_status, shdr_add_status;
17496 	union lpfc_sli4_cfg_shdr *shdr;
17497 
17498 	/* sanity check on queue memory */
17499 	if (!hrq || !drq)
17500 		return -ENODEV;
17501 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17502 	if (!mbox)
17503 		return -ENOMEM;
17504 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
17505 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17506 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17507 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17508 			 length, LPFC_SLI4_MBX_EMBED);
17509 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17510 	       hrq->queue_id);
17511 	mbox->vport = hrq->phba->pport;
17512 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17513 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17514 	/* The IOCTL status is embedded in the mailbox subheader. */
17515 	shdr = (union lpfc_sli4_cfg_shdr *)
17516 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17517 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17518 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17519 	if (shdr_status || shdr_add_status || rc) {
17520 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17521 				"2509 RQ_DESTROY mailbox failed with "
17522 				"status x%x add_status x%x, mbx status x%x\n",
17523 				shdr_status, shdr_add_status, rc);
17524 		mempool_free(mbox, hrq->phba->mbox_mem_pool);
17525 		return -ENXIO;
17526 	}
17527 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17528 	       drq->queue_id);
17529 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17530 	shdr = (union lpfc_sli4_cfg_shdr *)
17531 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17532 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17533 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17534 	if (shdr_status || shdr_add_status || rc) {
17535 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17536 				"2510 RQ_DESTROY mailbox failed with "
17537 				"status x%x add_status x%x, mbx status x%x\n",
17538 				shdr_status, shdr_add_status, rc);
17539 		status = -ENXIO;
17540 	}
17541 	list_del_init(&hrq->list);
17542 	list_del_init(&drq->list);
17543 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
17544 	return status;
17545 }
17546 
17547 /**
17548  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17549  * @phba: The virtual port for which this call being executed.
17550  * @pdma_phys_addr0: Physical address of the 1st SGL page.
17551  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
17552  * @xritag: the xritag that ties this io to the SGL pages.
17553  *
17554  * This routine will post the sgl pages for the IO that has the xritag
17555  * that is in the iocbq structure. The xritag is assigned during iocbq
17556  * creation and persists for as long as the driver is loaded.
17557  * if the caller has fewer than 256 scatter gather segments to map then
17558  * pdma_phys_addr1 should be 0.
17559  * If the caller needs to map more than 256 scatter gather segment then
17560  * pdma_phys_addr1 should be a valid physical address.
17561  * physical address for SGLs must be 64 byte aligned.
17562  * If you are going to map 2 SGL's then the first one must have 256 entries
17563  * the second sgl can have between 1 and 256 entries.
17564  *
17565  * Return codes:
17566  * 	0 - Success
17567  * 	-ENXIO, -ENOMEM - Failure
17568  **/
17569 int
17570 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
17571 		dma_addr_t pdma_phys_addr0,
17572 		dma_addr_t pdma_phys_addr1,
17573 		uint16_t xritag)
17574 {
17575 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
17576 	LPFC_MBOXQ_t *mbox;
17577 	int rc;
17578 	uint32_t shdr_status, shdr_add_status;
17579 	uint32_t mbox_tmo;
17580 	union lpfc_sli4_cfg_shdr *shdr;
17581 
17582 	if (xritag == NO_XRI) {
17583 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17584 				"0364 Invalid param:\n");
17585 		return -EINVAL;
17586 	}
17587 
17588 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17589 	if (!mbox)
17590 		return -ENOMEM;
17591 
17592 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17593 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17594 			sizeof(struct lpfc_mbx_post_sgl_pages) -
17595 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17596 
17597 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
17598 				&mbox->u.mqe.un.post_sgl_pages;
17599 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
17600 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
17601 
17602 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
17603 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
17604 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
17605 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
17606 
17607 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
17608 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
17609 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
17610 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
17611 	if (!phba->sli4_hba.intr_enable)
17612 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17613 	else {
17614 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17615 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17616 	}
17617 	/* The IOCTL status is embedded in the mailbox subheader. */
17618 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
17619 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17620 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17621 	if (!phba->sli4_hba.intr_enable)
17622 		mempool_free(mbox, phba->mbox_mem_pool);
17623 	else if (rc != MBX_TIMEOUT)
17624 		mempool_free(mbox, phba->mbox_mem_pool);
17625 	if (shdr_status || shdr_add_status || rc) {
17626 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17627 				"2511 POST_SGL mailbox failed with "
17628 				"status x%x add_status x%x, mbx status x%x\n",
17629 				shdr_status, shdr_add_status, rc);
17630 	}
17631 	return 0;
17632 }
17633 
17634 /**
17635  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
17636  * @phba: pointer to lpfc hba data structure.
17637  *
17638  * This routine is invoked to post rpi header templates to the
17639  * HBA consistent with the SLI-4 interface spec.  This routine
17640  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
17641  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
17642  *
17643  * Returns
17644  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
17645  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
17646  **/
17647 static uint16_t
17648 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
17649 {
17650 	unsigned long xri;
17651 
17652 	/*
17653 	 * Fetch the next logical xri.  Because this index is logical,
17654 	 * the driver starts at 0 each time.
17655 	 */
17656 	spin_lock_irq(&phba->hbalock);
17657 	xri = find_first_zero_bit(phba->sli4_hba.xri_bmask,
17658 				 phba->sli4_hba.max_cfg_param.max_xri);
17659 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
17660 		spin_unlock_irq(&phba->hbalock);
17661 		return NO_XRI;
17662 	} else {
17663 		set_bit(xri, phba->sli4_hba.xri_bmask);
17664 		phba->sli4_hba.max_cfg_param.xri_used++;
17665 	}
17666 	spin_unlock_irq(&phba->hbalock);
17667 	return xri;
17668 }
17669 
17670 /**
17671  * __lpfc_sli4_free_xri - Release an xri for reuse.
17672  * @phba: pointer to lpfc hba data structure.
17673  * @xri: xri to release.
17674  *
17675  * This routine is invoked to release an xri to the pool of
17676  * available rpis maintained by the driver.
17677  **/
17678 static void
17679 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
17680 {
17681 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
17682 		phba->sli4_hba.max_cfg_param.xri_used--;
17683 	}
17684 }
17685 
17686 /**
17687  * lpfc_sli4_free_xri - Release an xri for reuse.
17688  * @phba: pointer to lpfc hba data structure.
17689  * @xri: xri to release.
17690  *
17691  * This routine is invoked to release an xri to the pool of
17692  * available rpis maintained by the driver.
17693  **/
17694 void
17695 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
17696 {
17697 	spin_lock_irq(&phba->hbalock);
17698 	__lpfc_sli4_free_xri(phba, xri);
17699 	spin_unlock_irq(&phba->hbalock);
17700 }
17701 
17702 /**
17703  * lpfc_sli4_next_xritag - Get an xritag for the io
17704  * @phba: Pointer to HBA context object.
17705  *
17706  * This function gets an xritag for the iocb. If there is no unused xritag
17707  * it will return 0xffff.
17708  * The function returns the allocated xritag if successful, else returns zero.
17709  * Zero is not a valid xritag.
17710  * The caller is not required to hold any lock.
17711  **/
17712 uint16_t
17713 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
17714 {
17715 	uint16_t xri_index;
17716 
17717 	xri_index = lpfc_sli4_alloc_xri(phba);
17718 	if (xri_index == NO_XRI)
17719 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
17720 				"2004 Failed to allocate XRI.last XRITAG is %d"
17721 				" Max XRI is %d, Used XRI is %d\n",
17722 				xri_index,
17723 				phba->sli4_hba.max_cfg_param.max_xri,
17724 				phba->sli4_hba.max_cfg_param.xri_used);
17725 	return xri_index;
17726 }
17727 
17728 /**
17729  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
17730  * @phba: pointer to lpfc hba data structure.
17731  * @post_sgl_list: pointer to els sgl entry list.
17732  * @post_cnt: number of els sgl entries on the list.
17733  *
17734  * This routine is invoked to post a block of driver's sgl pages to the
17735  * HBA using non-embedded mailbox command. No Lock is held. This routine
17736  * is only called when the driver is loading and after all IO has been
17737  * stopped.
17738  **/
17739 static int
17740 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
17741 			    struct list_head *post_sgl_list,
17742 			    int post_cnt)
17743 {
17744 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
17745 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
17746 	struct sgl_page_pairs *sgl_pg_pairs;
17747 	void *viraddr;
17748 	LPFC_MBOXQ_t *mbox;
17749 	uint32_t reqlen, alloclen, pg_pairs;
17750 	uint32_t mbox_tmo;
17751 	uint16_t xritag_start = 0;
17752 	int rc = 0;
17753 	uint32_t shdr_status, shdr_add_status;
17754 	union lpfc_sli4_cfg_shdr *shdr;
17755 
17756 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
17757 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
17758 	if (reqlen > SLI4_PAGE_SIZE) {
17759 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17760 				"2559 Block sgl registration required DMA "
17761 				"size (%d) great than a page\n", reqlen);
17762 		return -ENOMEM;
17763 	}
17764 
17765 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17766 	if (!mbox)
17767 		return -ENOMEM;
17768 
17769 	/* Allocate DMA memory and set up the non-embedded mailbox command */
17770 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17771 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
17772 			 LPFC_SLI4_MBX_NEMBED);
17773 
17774 	if (alloclen < reqlen) {
17775 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17776 				"0285 Allocated DMA memory size (%d) is "
17777 				"less than the requested DMA memory "
17778 				"size (%d)\n", alloclen, reqlen);
17779 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17780 		return -ENOMEM;
17781 	}
17782 	/* Set up the SGL pages in the non-embedded DMA pages */
17783 	viraddr = mbox->sge_array->addr[0];
17784 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
17785 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
17786 
17787 	pg_pairs = 0;
17788 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
17789 		/* Set up the sge entry */
17790 		sgl_pg_pairs->sgl_pg0_addr_lo =
17791 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
17792 		sgl_pg_pairs->sgl_pg0_addr_hi =
17793 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
17794 		sgl_pg_pairs->sgl_pg1_addr_lo =
17795 				cpu_to_le32(putPaddrLow(0));
17796 		sgl_pg_pairs->sgl_pg1_addr_hi =
17797 				cpu_to_le32(putPaddrHigh(0));
17798 
17799 		/* Keep the first xritag on the list */
17800 		if (pg_pairs == 0)
17801 			xritag_start = sglq_entry->sli4_xritag;
17802 		sgl_pg_pairs++;
17803 		pg_pairs++;
17804 	}
17805 
17806 	/* Complete initialization and perform endian conversion. */
17807 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
17808 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
17809 	sgl->word0 = cpu_to_le32(sgl->word0);
17810 
17811 	if (!phba->sli4_hba.intr_enable)
17812 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17813 	else {
17814 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17815 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17816 	}
17817 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
17818 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17819 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17820 	if (!phba->sli4_hba.intr_enable)
17821 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17822 	else if (rc != MBX_TIMEOUT)
17823 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17824 	if (shdr_status || shdr_add_status || rc) {
17825 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17826 				"2513 POST_SGL_BLOCK mailbox command failed "
17827 				"status x%x add_status x%x mbx status x%x\n",
17828 				shdr_status, shdr_add_status, rc);
17829 		rc = -ENXIO;
17830 	}
17831 	return rc;
17832 }
17833 
17834 /**
17835  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
17836  * @phba: pointer to lpfc hba data structure.
17837  * @nblist: pointer to nvme buffer list.
17838  * @count: number of scsi buffers on the list.
17839  *
17840  * This routine is invoked to post a block of @count scsi sgl pages from a
17841  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
17842  * No Lock is held.
17843  *
17844  **/
17845 static int
17846 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
17847 			    int count)
17848 {
17849 	struct lpfc_io_buf *lpfc_ncmd;
17850 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
17851 	struct sgl_page_pairs *sgl_pg_pairs;
17852 	void *viraddr;
17853 	LPFC_MBOXQ_t *mbox;
17854 	uint32_t reqlen, alloclen, pg_pairs;
17855 	uint32_t mbox_tmo;
17856 	uint16_t xritag_start = 0;
17857 	int rc = 0;
17858 	uint32_t shdr_status, shdr_add_status;
17859 	dma_addr_t pdma_phys_bpl1;
17860 	union lpfc_sli4_cfg_shdr *shdr;
17861 
17862 	/* Calculate the requested length of the dma memory */
17863 	reqlen = count * sizeof(struct sgl_page_pairs) +
17864 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
17865 	if (reqlen > SLI4_PAGE_SIZE) {
17866 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
17867 				"6118 Block sgl registration required DMA "
17868 				"size (%d) great than a page\n", reqlen);
17869 		return -ENOMEM;
17870 	}
17871 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17872 	if (!mbox) {
17873 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17874 				"6119 Failed to allocate mbox cmd memory\n");
17875 		return -ENOMEM;
17876 	}
17877 
17878 	/* Allocate DMA memory and set up the non-embedded mailbox command */
17879 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17880 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17881 				    reqlen, LPFC_SLI4_MBX_NEMBED);
17882 
17883 	if (alloclen < reqlen) {
17884 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17885 				"6120 Allocated DMA memory size (%d) is "
17886 				"less than the requested DMA memory "
17887 				"size (%d)\n", alloclen, reqlen);
17888 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17889 		return -ENOMEM;
17890 	}
17891 
17892 	/* Get the first SGE entry from the non-embedded DMA memory */
17893 	viraddr = mbox->sge_array->addr[0];
17894 
17895 	/* Set up the SGL pages in the non-embedded DMA pages */
17896 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
17897 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
17898 
17899 	pg_pairs = 0;
17900 	list_for_each_entry(lpfc_ncmd, nblist, list) {
17901 		/* Set up the sge entry */
17902 		sgl_pg_pairs->sgl_pg0_addr_lo =
17903 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
17904 		sgl_pg_pairs->sgl_pg0_addr_hi =
17905 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
17906 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
17907 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
17908 						SGL_PAGE_SIZE;
17909 		else
17910 			pdma_phys_bpl1 = 0;
17911 		sgl_pg_pairs->sgl_pg1_addr_lo =
17912 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
17913 		sgl_pg_pairs->sgl_pg1_addr_hi =
17914 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
17915 		/* Keep the first xritag on the list */
17916 		if (pg_pairs == 0)
17917 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
17918 		sgl_pg_pairs++;
17919 		pg_pairs++;
17920 	}
17921 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
17922 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
17923 	/* Perform endian conversion if necessary */
17924 	sgl->word0 = cpu_to_le32(sgl->word0);
17925 
17926 	if (!phba->sli4_hba.intr_enable) {
17927 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17928 	} else {
17929 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17930 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17931 	}
17932 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
17933 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17934 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17935 	if (!phba->sli4_hba.intr_enable)
17936 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17937 	else if (rc != MBX_TIMEOUT)
17938 		lpfc_sli4_mbox_cmd_free(phba, mbox);
17939 	if (shdr_status || shdr_add_status || rc) {
17940 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17941 				"6125 POST_SGL_BLOCK mailbox command failed "
17942 				"status x%x add_status x%x mbx status x%x\n",
17943 				shdr_status, shdr_add_status, rc);
17944 		rc = -ENXIO;
17945 	}
17946 	return rc;
17947 }
17948 
17949 /**
17950  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
17951  * @phba: pointer to lpfc hba data structure.
17952  * @post_nblist: pointer to the nvme buffer list.
17953  * @sb_count: number of nvme buffers.
17954  *
17955  * This routine walks a list of nvme buffers that was passed in. It attempts
17956  * to construct blocks of nvme buffer sgls which contains contiguous xris and
17957  * uses the non-embedded SGL block post mailbox commands to post to the port.
17958  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
17959  * embedded SGL post mailbox command for posting. The @post_nblist passed in
17960  * must be local list, thus no lock is needed when manipulate the list.
17961  *
17962  * Returns: 0 = failure, non-zero number of successfully posted buffers.
17963  **/
17964 int
17965 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
17966 			   struct list_head *post_nblist, int sb_count)
17967 {
17968 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
17969 	int status, sgl_size;
17970 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
17971 	dma_addr_t pdma_phys_sgl1;
17972 	int last_xritag = NO_XRI;
17973 	int cur_xritag;
17974 	LIST_HEAD(prep_nblist);
17975 	LIST_HEAD(blck_nblist);
17976 	LIST_HEAD(nvme_nblist);
17977 
17978 	/* sanity check */
17979 	if (sb_count <= 0)
17980 		return -EINVAL;
17981 
17982 	sgl_size = phba->cfg_sg_dma_buf_size;
17983 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
17984 		list_del_init(&lpfc_ncmd->list);
17985 		block_cnt++;
17986 		if ((last_xritag != NO_XRI) &&
17987 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
17988 			/* a hole in xri block, form a sgl posting block */
17989 			list_splice_init(&prep_nblist, &blck_nblist);
17990 			post_cnt = block_cnt - 1;
17991 			/* prepare list for next posting block */
17992 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17993 			block_cnt = 1;
17994 		} else {
17995 			/* prepare list for next posting block */
17996 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17997 			/* enough sgls for non-embed sgl mbox command */
17998 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
17999 				list_splice_init(&prep_nblist, &blck_nblist);
18000 				post_cnt = block_cnt;
18001 				block_cnt = 0;
18002 			}
18003 		}
18004 		num_posting++;
18005 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18006 
18007 		/* end of repost sgl list condition for NVME buffers */
18008 		if (num_posting == sb_count) {
18009 			if (post_cnt == 0) {
18010 				/* last sgl posting block */
18011 				list_splice_init(&prep_nblist, &blck_nblist);
18012 				post_cnt = block_cnt;
18013 			} else if (block_cnt == 1) {
18014 				/* last single sgl with non-contiguous xri */
18015 				if (sgl_size > SGL_PAGE_SIZE)
18016 					pdma_phys_sgl1 =
18017 						lpfc_ncmd->dma_phys_sgl +
18018 						SGL_PAGE_SIZE;
18019 				else
18020 					pdma_phys_sgl1 = 0;
18021 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18022 				status = lpfc_sli4_post_sgl(
18023 						phba, lpfc_ncmd->dma_phys_sgl,
18024 						pdma_phys_sgl1, cur_xritag);
18025 				if (status) {
18026 					/* Post error.  Buffer unavailable. */
18027 					lpfc_ncmd->flags |=
18028 						LPFC_SBUF_NOT_POSTED;
18029 				} else {
18030 					/* Post success. Bffer available. */
18031 					lpfc_ncmd->flags &=
18032 						~LPFC_SBUF_NOT_POSTED;
18033 					lpfc_ncmd->status = IOSTAT_SUCCESS;
18034 					num_posted++;
18035 				}
18036 				/* success, put on NVME buffer sgl list */
18037 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18038 			}
18039 		}
18040 
18041 		/* continue until a nembed page worth of sgls */
18042 		if (post_cnt == 0)
18043 			continue;
18044 
18045 		/* post block of NVME buffer list sgls */
18046 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
18047 						     post_cnt);
18048 
18049 		/* don't reset xirtag due to hole in xri block */
18050 		if (block_cnt == 0)
18051 			last_xritag = NO_XRI;
18052 
18053 		/* reset NVME buffer post count for next round of posting */
18054 		post_cnt = 0;
18055 
18056 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
18057 		while (!list_empty(&blck_nblist)) {
18058 			list_remove_head(&blck_nblist, lpfc_ncmd,
18059 					 struct lpfc_io_buf, list);
18060 			if (status) {
18061 				/* Post error.  Mark buffer unavailable. */
18062 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
18063 			} else {
18064 				/* Post success, Mark buffer available. */
18065 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
18066 				lpfc_ncmd->status = IOSTAT_SUCCESS;
18067 				num_posted++;
18068 			}
18069 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18070 		}
18071 	}
18072 	/* Push NVME buffers with sgl posted to the available list */
18073 	lpfc_io_buf_replenish(phba, &nvme_nblist);
18074 
18075 	return num_posted;
18076 }
18077 
18078 /**
18079  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
18080  * @phba: pointer to lpfc_hba struct that the frame was received on
18081  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18082  *
18083  * This function checks the fields in the @fc_hdr to see if the FC frame is a
18084  * valid type of frame that the LPFC driver will handle. This function will
18085  * return a zero if the frame is a valid frame or a non zero value when the
18086  * frame does not pass the check.
18087  **/
18088 static int
18089 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
18090 {
18091 	/*  make rctl_names static to save stack space */
18092 	struct fc_vft_header *fc_vft_hdr;
18093 	uint32_t *header = (uint32_t *) fc_hdr;
18094 
18095 #define FC_RCTL_MDS_DIAGS	0xF4
18096 
18097 	switch (fc_hdr->fh_r_ctl) {
18098 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
18099 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
18100 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
18101 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
18102 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
18103 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
18104 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
18105 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
18106 	case FC_RCTL_ELS_REQ:	/* extended link services request */
18107 	case FC_RCTL_ELS_REP:	/* extended link services reply */
18108 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
18109 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
18110 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
18111 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
18112 	case FC_RCTL_BA_RMC: 	/* remove connection */
18113 	case FC_RCTL_BA_ACC:	/* basic accept */
18114 	case FC_RCTL_BA_RJT:	/* basic reject */
18115 	case FC_RCTL_BA_PRMT:
18116 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
18117 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
18118 	case FC_RCTL_P_RJT:	/* port reject */
18119 	case FC_RCTL_F_RJT:	/* fabric reject */
18120 	case FC_RCTL_P_BSY:	/* port busy */
18121 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
18122 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
18123 	case FC_RCTL_LCR:	/* link credit reset */
18124 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
18125 	case FC_RCTL_END:	/* end */
18126 		break;
18127 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
18128 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18129 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
18130 		return lpfc_fc_frame_check(phba, fc_hdr);
18131 	default:
18132 		goto drop;
18133 	}
18134 
18135 	switch (fc_hdr->fh_type) {
18136 	case FC_TYPE_BLS:
18137 	case FC_TYPE_ELS:
18138 	case FC_TYPE_FCP:
18139 	case FC_TYPE_CT:
18140 	case FC_TYPE_NVME:
18141 		break;
18142 	case FC_TYPE_IP:
18143 	case FC_TYPE_ILS:
18144 	default:
18145 		goto drop;
18146 	}
18147 
18148 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
18149 			"2538 Received frame rctl:x%x, type:x%x, "
18150 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
18151 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
18152 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
18153 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
18154 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
18155 			be32_to_cpu(header[6]));
18156 	return 0;
18157 drop:
18158 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
18159 			"2539 Dropped frame rctl:x%x type:x%x\n",
18160 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18161 	return 1;
18162 }
18163 
18164 /**
18165  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
18166  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18167  *
18168  * This function processes the FC header to retrieve the VFI from the VF
18169  * header, if one exists. This function will return the VFI if one exists
18170  * or 0 if no VSAN Header exists.
18171  **/
18172 static uint32_t
18173 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
18174 {
18175 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18176 
18177 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
18178 		return 0;
18179 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
18180 }
18181 
18182 /**
18183  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
18184  * @phba: Pointer to the HBA structure to search for the vport on
18185  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18186  * @fcfi: The FC Fabric ID that the frame came from
18187  * @did: Destination ID to match against
18188  *
18189  * This function searches the @phba for a vport that matches the content of the
18190  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
18191  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
18192  * returns the matching vport pointer or NULL if unable to match frame to a
18193  * vport.
18194  **/
18195 static struct lpfc_vport *
18196 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
18197 		       uint16_t fcfi, uint32_t did)
18198 {
18199 	struct lpfc_vport **vports;
18200 	struct lpfc_vport *vport = NULL;
18201 	int i;
18202 
18203 	if (did == Fabric_DID)
18204 		return phba->pport;
18205 	if ((phba->pport->fc_flag & FC_PT2PT) &&
18206 		!(phba->link_state == LPFC_HBA_READY))
18207 		return phba->pport;
18208 
18209 	vports = lpfc_create_vport_work_array(phba);
18210 	if (vports != NULL) {
18211 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
18212 			if (phba->fcf.fcfi == fcfi &&
18213 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
18214 			    vports[i]->fc_myDID == did) {
18215 				vport = vports[i];
18216 				break;
18217 			}
18218 		}
18219 	}
18220 	lpfc_destroy_vport_work_array(phba, vports);
18221 	return vport;
18222 }
18223 
18224 /**
18225  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
18226  * @vport: The vport to work on.
18227  *
18228  * This function updates the receive sequence time stamp for this vport. The
18229  * receive sequence time stamp indicates the time that the last frame of the
18230  * the sequence that has been idle for the longest amount of time was received.
18231  * the driver uses this time stamp to indicate if any received sequences have
18232  * timed out.
18233  **/
18234 static void
18235 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
18236 {
18237 	struct lpfc_dmabuf *h_buf;
18238 	struct hbq_dmabuf *dmabuf = NULL;
18239 
18240 	/* get the oldest sequence on the rcv list */
18241 	h_buf = list_get_first(&vport->rcv_buffer_list,
18242 			       struct lpfc_dmabuf, list);
18243 	if (!h_buf)
18244 		return;
18245 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18246 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
18247 }
18248 
18249 /**
18250  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
18251  * @vport: The vport that the received sequences were sent to.
18252  *
18253  * This function cleans up all outstanding received sequences. This is called
18254  * by the driver when a link event or user action invalidates all the received
18255  * sequences.
18256  **/
18257 void
18258 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
18259 {
18260 	struct lpfc_dmabuf *h_buf, *hnext;
18261 	struct lpfc_dmabuf *d_buf, *dnext;
18262 	struct hbq_dmabuf *dmabuf = NULL;
18263 
18264 	/* start with the oldest sequence on the rcv list */
18265 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18266 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18267 		list_del_init(&dmabuf->hbuf.list);
18268 		list_for_each_entry_safe(d_buf, dnext,
18269 					 &dmabuf->dbuf.list, list) {
18270 			list_del_init(&d_buf->list);
18271 			lpfc_in_buf_free(vport->phba, d_buf);
18272 		}
18273 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18274 	}
18275 }
18276 
18277 /**
18278  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
18279  * @vport: The vport that the received sequences were sent to.
18280  *
18281  * This function determines whether any received sequences have timed out by
18282  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
18283  * indicates that there is at least one timed out sequence this routine will
18284  * go through the received sequences one at a time from most inactive to most
18285  * active to determine which ones need to be cleaned up. Once it has determined
18286  * that a sequence needs to be cleaned up it will simply free up the resources
18287  * without sending an abort.
18288  **/
18289 void
18290 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
18291 {
18292 	struct lpfc_dmabuf *h_buf, *hnext;
18293 	struct lpfc_dmabuf *d_buf, *dnext;
18294 	struct hbq_dmabuf *dmabuf = NULL;
18295 	unsigned long timeout;
18296 	int abort_count = 0;
18297 
18298 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18299 		   vport->rcv_buffer_time_stamp);
18300 	if (list_empty(&vport->rcv_buffer_list) ||
18301 	    time_before(jiffies, timeout))
18302 		return;
18303 	/* start with the oldest sequence on the rcv list */
18304 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18305 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18306 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18307 			   dmabuf->time_stamp);
18308 		if (time_before(jiffies, timeout))
18309 			break;
18310 		abort_count++;
18311 		list_del_init(&dmabuf->hbuf.list);
18312 		list_for_each_entry_safe(d_buf, dnext,
18313 					 &dmabuf->dbuf.list, list) {
18314 			list_del_init(&d_buf->list);
18315 			lpfc_in_buf_free(vport->phba, d_buf);
18316 		}
18317 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18318 	}
18319 	if (abort_count)
18320 		lpfc_update_rcv_time_stamp(vport);
18321 }
18322 
18323 /**
18324  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
18325  * @vport: pointer to a vitural port
18326  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
18327  *
18328  * This function searches through the existing incomplete sequences that have
18329  * been sent to this @vport. If the frame matches one of the incomplete
18330  * sequences then the dbuf in the @dmabuf is added to the list of frames that
18331  * make up that sequence. If no sequence is found that matches this frame then
18332  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
18333  * This function returns a pointer to the first dmabuf in the sequence list that
18334  * the frame was linked to.
18335  **/
18336 static struct hbq_dmabuf *
18337 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18338 {
18339 	struct fc_frame_header *new_hdr;
18340 	struct fc_frame_header *temp_hdr;
18341 	struct lpfc_dmabuf *d_buf;
18342 	struct lpfc_dmabuf *h_buf;
18343 	struct hbq_dmabuf *seq_dmabuf = NULL;
18344 	struct hbq_dmabuf *temp_dmabuf = NULL;
18345 	uint8_t	found = 0;
18346 
18347 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18348 	dmabuf->time_stamp = jiffies;
18349 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18350 
18351 	/* Use the hdr_buf to find the sequence that this frame belongs to */
18352 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18353 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18354 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18355 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18356 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18357 			continue;
18358 		/* found a pending sequence that matches this frame */
18359 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18360 		break;
18361 	}
18362 	if (!seq_dmabuf) {
18363 		/*
18364 		 * This indicates first frame received for this sequence.
18365 		 * Queue the buffer on the vport's rcv_buffer_list.
18366 		 */
18367 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18368 		lpfc_update_rcv_time_stamp(vport);
18369 		return dmabuf;
18370 	}
18371 	temp_hdr = seq_dmabuf->hbuf.virt;
18372 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
18373 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18374 		list_del_init(&seq_dmabuf->hbuf.list);
18375 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18376 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18377 		lpfc_update_rcv_time_stamp(vport);
18378 		return dmabuf;
18379 	}
18380 	/* move this sequence to the tail to indicate a young sequence */
18381 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
18382 	seq_dmabuf->time_stamp = jiffies;
18383 	lpfc_update_rcv_time_stamp(vport);
18384 	if (list_empty(&seq_dmabuf->dbuf.list)) {
18385 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18386 		return seq_dmabuf;
18387 	}
18388 	/* find the correct place in the sequence to insert this frame */
18389 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
18390 	while (!found) {
18391 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18392 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
18393 		/*
18394 		 * If the frame's sequence count is greater than the frame on
18395 		 * the list then insert the frame right after this frame
18396 		 */
18397 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
18398 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18399 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
18400 			found = 1;
18401 			break;
18402 		}
18403 
18404 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
18405 			break;
18406 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
18407 	}
18408 
18409 	if (found)
18410 		return seq_dmabuf;
18411 	return NULL;
18412 }
18413 
18414 /**
18415  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
18416  * @vport: pointer to a vitural port
18417  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18418  *
18419  * This function tries to abort from the partially assembed sequence, described
18420  * by the information from basic abbort @dmabuf. It checks to see whether such
18421  * partially assembled sequence held by the driver. If so, it shall free up all
18422  * the frames from the partially assembled sequence.
18423  *
18424  * Return
18425  * true  -- if there is matching partially assembled sequence present and all
18426  *          the frames freed with the sequence;
18427  * false -- if there is no matching partially assembled sequence present so
18428  *          nothing got aborted in the lower layer driver
18429  **/
18430 static bool
18431 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
18432 			    struct hbq_dmabuf *dmabuf)
18433 {
18434 	struct fc_frame_header *new_hdr;
18435 	struct fc_frame_header *temp_hdr;
18436 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
18437 	struct hbq_dmabuf *seq_dmabuf = NULL;
18438 
18439 	/* Use the hdr_buf to find the sequence that matches this frame */
18440 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18441 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
18442 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18443 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18444 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18445 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18446 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18447 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18448 			continue;
18449 		/* found a pending sequence that matches this frame */
18450 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18451 		break;
18452 	}
18453 
18454 	/* Free up all the frames from the partially assembled sequence */
18455 	if (seq_dmabuf) {
18456 		list_for_each_entry_safe(d_buf, n_buf,
18457 					 &seq_dmabuf->dbuf.list, list) {
18458 			list_del_init(&d_buf->list);
18459 			lpfc_in_buf_free(vport->phba, d_buf);
18460 		}
18461 		return true;
18462 	}
18463 	return false;
18464 }
18465 
18466 /**
18467  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18468  * @vport: pointer to a vitural port
18469  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18470  *
18471  * This function tries to abort from the assembed sequence from upper level
18472  * protocol, described by the information from basic abbort @dmabuf. It
18473  * checks to see whether such pending context exists at upper level protocol.
18474  * If so, it shall clean up the pending context.
18475  *
18476  * Return
18477  * true  -- if there is matching pending context of the sequence cleaned
18478  *          at ulp;
18479  * false -- if there is no matching pending context of the sequence present
18480  *          at ulp.
18481  **/
18482 static bool
18483 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18484 {
18485 	struct lpfc_hba *phba = vport->phba;
18486 	int handled;
18487 
18488 	/* Accepting abort at ulp with SLI4 only */
18489 	if (phba->sli_rev < LPFC_SLI_REV4)
18490 		return false;
18491 
18492 	/* Register all caring upper level protocols to attend abort */
18493 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18494 	if (handled)
18495 		return true;
18496 
18497 	return false;
18498 }
18499 
18500 /**
18501  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18502  * @phba: Pointer to HBA context object.
18503  * @cmd_iocbq: pointer to the command iocbq structure.
18504  * @rsp_iocbq: pointer to the response iocbq structure.
18505  *
18506  * This function handles the sequence abort response iocb command complete
18507  * event. It properly releases the memory allocated to the sequence abort
18508  * accept iocb.
18509  **/
18510 static void
18511 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18512 			     struct lpfc_iocbq *cmd_iocbq,
18513 			     struct lpfc_iocbq *rsp_iocbq)
18514 {
18515 	struct lpfc_nodelist *ndlp;
18516 
18517 	if (cmd_iocbq) {
18518 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
18519 		lpfc_nlp_put(ndlp);
18520 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
18521 	}
18522 
18523 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
18524 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18525 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18526 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
18527 			get_job_ulpstatus(phba, rsp_iocbq),
18528 			get_job_word4(phba, rsp_iocbq));
18529 }
18530 
18531 /**
18532  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
18533  * @phba: Pointer to HBA context object.
18534  * @xri: xri id in transaction.
18535  *
18536  * This function validates the xri maps to the known range of XRIs allocated an
18537  * used by the driver.
18538  **/
18539 uint16_t
18540 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
18541 		      uint16_t xri)
18542 {
18543 	uint16_t i;
18544 
18545 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
18546 		if (xri == phba->sli4_hba.xri_ids[i])
18547 			return i;
18548 	}
18549 	return NO_XRI;
18550 }
18551 
18552 /**
18553  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
18554  * @vport: pointer to a virtual port.
18555  * @fc_hdr: pointer to a FC frame header.
18556  * @aborted: was the partially assembled receive sequence successfully aborted
18557  *
18558  * This function sends a basic response to a previous unsol sequence abort
18559  * event after aborting the sequence handling.
18560  **/
18561 void
18562 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
18563 			struct fc_frame_header *fc_hdr, bool aborted)
18564 {
18565 	struct lpfc_hba *phba = vport->phba;
18566 	struct lpfc_iocbq *ctiocb = NULL;
18567 	struct lpfc_nodelist *ndlp;
18568 	uint16_t oxid, rxid, xri, lxri;
18569 	uint32_t sid, fctl;
18570 	union lpfc_wqe128 *icmd;
18571 	int rc;
18572 
18573 	if (!lpfc_is_link_up(phba))
18574 		return;
18575 
18576 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18577 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
18578 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
18579 
18580 	ndlp = lpfc_findnode_did(vport, sid);
18581 	if (!ndlp) {
18582 		ndlp = lpfc_nlp_init(vport, sid);
18583 		if (!ndlp) {
18584 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
18585 					 "1268 Failed to allocate ndlp for "
18586 					 "oxid:x%x SID:x%x\n", oxid, sid);
18587 			return;
18588 		}
18589 		/* Put ndlp onto pport node list */
18590 		lpfc_enqueue_node(vport, ndlp);
18591 	}
18592 
18593 	/* Allocate buffer for rsp iocb */
18594 	ctiocb = lpfc_sli_get_iocbq(phba);
18595 	if (!ctiocb)
18596 		return;
18597 
18598 	icmd = &ctiocb->wqe;
18599 
18600 	/* Extract the F_CTL field from FC_HDR */
18601 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
18602 
18603 	ctiocb->context1 = lpfc_nlp_get(ndlp);
18604 	if (!ctiocb->context1) {
18605 		lpfc_sli_release_iocbq(phba, ctiocb);
18606 		return;
18607 	}
18608 
18609 	ctiocb->vport = phba->pport;
18610 	ctiocb->cmd_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
18611 	ctiocb->sli4_lxritag = NO_XRI;
18612 	ctiocb->sli4_xritag = NO_XRI;
18613 	ctiocb->abort_rctl = FC_RCTL_BA_ACC;
18614 
18615 	if (fctl & FC_FC_EX_CTX)
18616 		/* Exchange responder sent the abort so we
18617 		 * own the oxid.
18618 		 */
18619 		xri = oxid;
18620 	else
18621 		xri = rxid;
18622 	lxri = lpfc_sli4_xri_inrange(phba, xri);
18623 	if (lxri != NO_XRI)
18624 		lpfc_set_rrq_active(phba, ndlp, lxri,
18625 			(xri == oxid) ? rxid : oxid, 0);
18626 	/* For BA_ABTS from exchange responder, if the logical xri with
18627 	 * the oxid maps to the FCP XRI range, the port no longer has
18628 	 * that exchange context, send a BLS_RJT. Override the IOCB for
18629 	 * a BA_RJT.
18630 	 */
18631 	if ((fctl & FC_FC_EX_CTX) &&
18632 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
18633 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
18634 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
18635 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
18636 		       FC_BA_RJT_INV_XID);
18637 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
18638 		       FC_BA_RJT_UNABLE);
18639 	}
18640 
18641 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
18642 	 * the driver no longer has that exchange, send a BLS_RJT. Override
18643 	 * the IOCB for a BA_RJT.
18644 	 */
18645 	if (aborted == false) {
18646 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
18647 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
18648 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
18649 		       FC_BA_RJT_INV_XID);
18650 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
18651 		       FC_BA_RJT_UNABLE);
18652 	}
18653 
18654 	if (fctl & FC_FC_EX_CTX) {
18655 		/* ABTS sent by responder to CT exchange, construction
18656 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
18657 		 * field and RX_ID from ABTS for RX_ID field.
18658 		 */
18659 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_RSP;
18660 		bf_set(xmit_bls_rsp64_rxid, &icmd->xmit_bls_rsp, rxid);
18661 	} else {
18662 		/* ABTS sent by initiator to CT exchange, construction
18663 		 * of BA_ACC will need to allocate a new XRI as for the
18664 		 * XRI_TAG field.
18665 		 */
18666 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_INT;
18667 	}
18668 
18669 	/* OX_ID is invariable to who sent ABTS to CT exchange */
18670 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, oxid);
18671 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, rxid);
18672 
18673 	/* Use CT=VPI */
18674 	bf_set(wqe_els_did, &icmd->xmit_bls_rsp.wqe_dest,
18675 	       ndlp->nlp_DID);
18676 	bf_set(xmit_bls_rsp64_temprpi, &icmd->xmit_bls_rsp,
18677 	       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
18678 	bf_set(wqe_cmnd, &icmd->generic.wqe_com, CMD_XMIT_BLS_RSP64_CX);
18679 
18680 
18681 	/* Xmit CT abts response on exchange <xid> */
18682 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
18683 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
18684 			 ctiocb->abort_rctl, oxid, phba->link_state);
18685 
18686 	lpfc_sli_prep_wqe(phba, ctiocb);
18687 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
18688 	if (rc == IOCB_ERROR) {
18689 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
18690 				 "2925 Failed to issue CT ABTS RSP x%x on "
18691 				 "xri x%x, Data x%x\n",
18692 				 ctiocb->abort_rctl, oxid,
18693 				 phba->link_state);
18694 		lpfc_nlp_put(ndlp);
18695 		ctiocb->context1 = NULL;
18696 		lpfc_sli_release_iocbq(phba, ctiocb);
18697 	}
18698 }
18699 
18700 /**
18701  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
18702  * @vport: Pointer to the vport on which this sequence was received
18703  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18704  *
18705  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
18706  * receive sequence is only partially assembed by the driver, it shall abort
18707  * the partially assembled frames for the sequence. Otherwise, if the
18708  * unsolicited receive sequence has been completely assembled and passed to
18709  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
18710  * unsolicited sequence has been aborted. After that, it will issue a basic
18711  * accept to accept the abort.
18712  **/
18713 static void
18714 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
18715 			     struct hbq_dmabuf *dmabuf)
18716 {
18717 	struct lpfc_hba *phba = vport->phba;
18718 	struct fc_frame_header fc_hdr;
18719 	uint32_t fctl;
18720 	bool aborted;
18721 
18722 	/* Make a copy of fc_hdr before the dmabuf being released */
18723 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
18724 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
18725 
18726 	if (fctl & FC_FC_EX_CTX) {
18727 		/* ABTS by responder to exchange, no cleanup needed */
18728 		aborted = true;
18729 	} else {
18730 		/* ABTS by initiator to exchange, need to do cleanup */
18731 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
18732 		if (aborted == false)
18733 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
18734 	}
18735 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
18736 
18737 	if (phba->nvmet_support) {
18738 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
18739 		return;
18740 	}
18741 
18742 	/* Respond with BA_ACC or BA_RJT accordingly */
18743 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
18744 }
18745 
18746 /**
18747  * lpfc_seq_complete - Indicates if a sequence is complete
18748  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18749  *
18750  * This function checks the sequence, starting with the frame described by
18751  * @dmabuf, to see if all the frames associated with this sequence are present.
18752  * the frames associated with this sequence are linked to the @dmabuf using the
18753  * dbuf list. This function looks for two major things. 1) That the first frame
18754  * has a sequence count of zero. 2) There is a frame with last frame of sequence
18755  * set. 3) That there are no holes in the sequence count. The function will
18756  * return 1 when the sequence is complete, otherwise it will return 0.
18757  **/
18758 static int
18759 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
18760 {
18761 	struct fc_frame_header *hdr;
18762 	struct lpfc_dmabuf *d_buf;
18763 	struct hbq_dmabuf *seq_dmabuf;
18764 	uint32_t fctl;
18765 	int seq_count = 0;
18766 
18767 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18768 	/* make sure first fame of sequence has a sequence count of zero */
18769 	if (hdr->fh_seq_cnt != seq_count)
18770 		return 0;
18771 	fctl = (hdr->fh_f_ctl[0] << 16 |
18772 		hdr->fh_f_ctl[1] << 8 |
18773 		hdr->fh_f_ctl[2]);
18774 	/* If last frame of sequence we can return success. */
18775 	if (fctl & FC_FC_END_SEQ)
18776 		return 1;
18777 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
18778 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18779 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18780 		/* If there is a hole in the sequence count then fail. */
18781 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
18782 			return 0;
18783 		fctl = (hdr->fh_f_ctl[0] << 16 |
18784 			hdr->fh_f_ctl[1] << 8 |
18785 			hdr->fh_f_ctl[2]);
18786 		/* If last frame of sequence we can return success. */
18787 		if (fctl & FC_FC_END_SEQ)
18788 			return 1;
18789 	}
18790 	return 0;
18791 }
18792 
18793 /**
18794  * lpfc_prep_seq - Prep sequence for ULP processing
18795  * @vport: Pointer to the vport on which this sequence was received
18796  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
18797  *
18798  * This function takes a sequence, described by a list of frames, and creates
18799  * a list of iocbq structures to describe the sequence. This iocbq list will be
18800  * used to issue to the generic unsolicited sequence handler. This routine
18801  * returns a pointer to the first iocbq in the list. If the function is unable
18802  * to allocate an iocbq then it throw out the received frames that were not
18803  * able to be described and return a pointer to the first iocbq. If unable to
18804  * allocate any iocbqs (including the first) this function will return NULL.
18805  **/
18806 static struct lpfc_iocbq *
18807 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
18808 {
18809 	struct hbq_dmabuf *hbq_buf;
18810 	struct lpfc_dmabuf *d_buf, *n_buf;
18811 	struct lpfc_iocbq *first_iocbq, *iocbq;
18812 	struct fc_frame_header *fc_hdr;
18813 	uint32_t sid;
18814 	uint32_t len, tot_len;
18815 
18816 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18817 	/* remove from receive buffer list */
18818 	list_del_init(&seq_dmabuf->hbuf.list);
18819 	lpfc_update_rcv_time_stamp(vport);
18820 	/* get the Remote Port's SID */
18821 	sid = sli4_sid_from_fc_hdr(fc_hdr);
18822 	tot_len = 0;
18823 	/* Get an iocbq struct to fill in. */
18824 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
18825 	if (first_iocbq) {
18826 		/* Initialize the first IOCB. */
18827 		first_iocbq->wcqe_cmpl.total_data_placed = 0;
18828 		bf_set(lpfc_wcqe_c_status, &first_iocbq->wcqe_cmpl,
18829 		       IOSTAT_SUCCESS);
18830 		first_iocbq->vport = vport;
18831 
18832 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
18833 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
18834 			bf_set(els_rsp64_sid, &first_iocbq->wqe.xmit_els_rsp,
18835 			       sli4_did_from_fc_hdr(fc_hdr));
18836 		}
18837 
18838 		bf_set(wqe_ctxt_tag, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
18839 		       NO_XRI);
18840 		bf_set(wqe_rcvoxid, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
18841 		       be16_to_cpu(fc_hdr->fh_ox_id));
18842 
18843 		/* put the first buffer into the first iocb */
18844 		tot_len = bf_get(lpfc_rcqe_length,
18845 				 &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
18846 
18847 		first_iocbq->context2 = &seq_dmabuf->dbuf;
18848 		first_iocbq->context3 = NULL;
18849 		/* Keep track of the BDE count */
18850 		first_iocbq->wcqe_cmpl.word3 = 1;
18851 
18852 		if (tot_len > LPFC_DATA_BUF_SIZE)
18853 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize =
18854 				LPFC_DATA_BUF_SIZE;
18855 		else
18856 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize = tot_len;
18857 
18858 		first_iocbq->wcqe_cmpl.total_data_placed = tot_len;
18859 		bf_set(wqe_els_did, &first_iocbq->wqe.xmit_els_rsp.wqe_dest,
18860 		       sid);
18861 	}
18862 	iocbq = first_iocbq;
18863 	/*
18864 	 * Each IOCBq can have two Buffers assigned, so go through the list
18865 	 * of buffers for this sequence and save two buffers in each IOCBq
18866 	 */
18867 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
18868 		if (!iocbq) {
18869 			lpfc_in_buf_free(vport->phba, d_buf);
18870 			continue;
18871 		}
18872 		if (!iocbq->context3) {
18873 			iocbq->context3 = d_buf;
18874 			iocbq->wcqe_cmpl.word3++;
18875 			/* We need to get the size out of the right CQE */
18876 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18877 			len = bf_get(lpfc_rcqe_length,
18878 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
18879 			iocbq->unsol_rcv_len = len;
18880 			iocbq->wcqe_cmpl.total_data_placed += len;
18881 			tot_len += len;
18882 		} else {
18883 			iocbq = lpfc_sli_get_iocbq(vport->phba);
18884 			if (!iocbq) {
18885 				if (first_iocbq) {
18886 					bf_set(lpfc_wcqe_c_status,
18887 					       &first_iocbq->wcqe_cmpl,
18888 					       IOSTAT_SUCCESS);
18889 					first_iocbq->wcqe_cmpl.parameter =
18890 						IOERR_NO_RESOURCES;
18891 				}
18892 				lpfc_in_buf_free(vport->phba, d_buf);
18893 				continue;
18894 			}
18895 			/* We need to get the size out of the right CQE */
18896 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18897 			len = bf_get(lpfc_rcqe_length,
18898 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
18899 			iocbq->context2 = d_buf;
18900 			iocbq->context3 = NULL;
18901 			iocbq->wcqe_cmpl.word3 = 1;
18902 
18903 			if (len > LPFC_DATA_BUF_SIZE)
18904 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
18905 					LPFC_DATA_BUF_SIZE;
18906 			else
18907 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
18908 					len;
18909 
18910 			tot_len += len;
18911 			iocbq->wcqe_cmpl.total_data_placed = tot_len;
18912 			bf_set(wqe_els_did, &iocbq->wqe.xmit_els_rsp.wqe_dest,
18913 			       sid);
18914 			list_add_tail(&iocbq->list, &first_iocbq->list);
18915 		}
18916 	}
18917 	/* Free the sequence's header buffer */
18918 	if (!first_iocbq)
18919 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
18920 
18921 	return first_iocbq;
18922 }
18923 
18924 static void
18925 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
18926 			  struct hbq_dmabuf *seq_dmabuf)
18927 {
18928 	struct fc_frame_header *fc_hdr;
18929 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
18930 	struct lpfc_hba *phba = vport->phba;
18931 
18932 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
18933 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
18934 	if (!iocbq) {
18935 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18936 				"2707 Ring %d handler: Failed to allocate "
18937 				"iocb Rctl x%x Type x%x received\n",
18938 				LPFC_ELS_RING,
18939 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18940 		return;
18941 	}
18942 	if (!lpfc_complete_unsol_iocb(phba,
18943 				      phba->sli4_hba.els_wq->pring,
18944 				      iocbq, fc_hdr->fh_r_ctl,
18945 				      fc_hdr->fh_type))
18946 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18947 				"2540 Ring %d handler: unexpected Rctl "
18948 				"x%x Type x%x received\n",
18949 				LPFC_ELS_RING,
18950 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18951 
18952 	/* Free iocb created in lpfc_prep_seq */
18953 	list_for_each_entry_safe(curr_iocb, next_iocb,
18954 		&iocbq->list, list) {
18955 		list_del_init(&curr_iocb->list);
18956 		lpfc_sli_release_iocbq(phba, curr_iocb);
18957 	}
18958 	lpfc_sli_release_iocbq(phba, iocbq);
18959 }
18960 
18961 static void
18962 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
18963 			    struct lpfc_iocbq *rspiocb)
18964 {
18965 	struct lpfc_dmabuf *pcmd = cmdiocb->context2;
18966 
18967 	if (pcmd && pcmd->virt)
18968 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18969 	kfree(pcmd);
18970 	lpfc_sli_release_iocbq(phba, cmdiocb);
18971 	lpfc_drain_txq(phba);
18972 }
18973 
18974 static void
18975 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
18976 			      struct hbq_dmabuf *dmabuf)
18977 {
18978 	struct fc_frame_header *fc_hdr;
18979 	struct lpfc_hba *phba = vport->phba;
18980 	struct lpfc_iocbq *iocbq = NULL;
18981 	union  lpfc_wqe128 *pwqe;
18982 	struct lpfc_dmabuf *pcmd = NULL;
18983 	uint32_t frame_len;
18984 	int rc;
18985 	unsigned long iflags;
18986 
18987 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18988 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
18989 
18990 	/* Send the received frame back */
18991 	iocbq = lpfc_sli_get_iocbq(phba);
18992 	if (!iocbq) {
18993 		/* Queue cq event and wakeup worker thread to process it */
18994 		spin_lock_irqsave(&phba->hbalock, iflags);
18995 		list_add_tail(&dmabuf->cq_event.list,
18996 			      &phba->sli4_hba.sp_queue_event);
18997 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
18998 		spin_unlock_irqrestore(&phba->hbalock, iflags);
18999 		lpfc_worker_wake_up(phba);
19000 		return;
19001 	}
19002 
19003 	/* Allocate buffer for command payload */
19004 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
19005 	if (pcmd)
19006 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
19007 					    &pcmd->phys);
19008 	if (!pcmd || !pcmd->virt)
19009 		goto exit;
19010 
19011 	INIT_LIST_HEAD(&pcmd->list);
19012 
19013 	/* copyin the payload */
19014 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
19015 
19016 	iocbq->context2 = pcmd;
19017 	iocbq->vport = vport;
19018 	iocbq->cmd_flag &= ~LPFC_FIP_ELS_ID_MASK;
19019 	iocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
19020 	iocbq->num_bdes = 0;
19021 
19022 	pwqe = &iocbq->wqe;
19023 	/* fill in BDE's for command */
19024 	pwqe->gen_req.bde.addrHigh = putPaddrHigh(pcmd->phys);
19025 	pwqe->gen_req.bde.addrLow = putPaddrLow(pcmd->phys);
19026 	pwqe->gen_req.bde.tus.f.bdeSize = frame_len;
19027 	pwqe->gen_req.bde.tus.f.bdeFlags = BUFF_TYPE_BDE_64;
19028 
19029 	pwqe->send_frame.frame_len = frame_len;
19030 	pwqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((__be32 *)fc_hdr));
19031 	pwqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((__be32 *)fc_hdr + 1));
19032 	pwqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((__be32 *)fc_hdr + 2));
19033 	pwqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((__be32 *)fc_hdr + 3));
19034 	pwqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((__be32 *)fc_hdr + 4));
19035 	pwqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((__be32 *)fc_hdr + 5));
19036 
19037 	pwqe->generic.wqe_com.word7 = 0;
19038 	pwqe->generic.wqe_com.word10 = 0;
19039 
19040 	bf_set(wqe_cmnd, &pwqe->generic.wqe_com, CMD_SEND_FRAME);
19041 	bf_set(wqe_sof, &pwqe->generic.wqe_com, 0x2E); /* SOF byte */
19042 	bf_set(wqe_eof, &pwqe->generic.wqe_com, 0x41); /* EOF byte */
19043 	bf_set(wqe_lenloc, &pwqe->generic.wqe_com, 1);
19044 	bf_set(wqe_xbl, &pwqe->generic.wqe_com, 1);
19045 	bf_set(wqe_dbde, &pwqe->generic.wqe_com, 1);
19046 	bf_set(wqe_xc, &pwqe->generic.wqe_com, 1);
19047 	bf_set(wqe_cmd_type, &pwqe->generic.wqe_com, 0xA);
19048 	bf_set(wqe_cqid, &pwqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
19049 	bf_set(wqe_xri_tag, &pwqe->generic.wqe_com, iocbq->sli4_xritag);
19050 	bf_set(wqe_reqtag, &pwqe->generic.wqe_com, iocbq->iotag);
19051 	bf_set(wqe_class, &pwqe->generic.wqe_com, CLASS3);
19052 	pwqe->generic.wqe_com.abort_tag = iocbq->iotag;
19053 
19054 	iocbq->cmd_cmpl = lpfc_sli4_mds_loopback_cmpl;
19055 
19056 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
19057 	if (rc == IOCB_ERROR)
19058 		goto exit;
19059 
19060 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19061 	return;
19062 
19063 exit:
19064 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
19065 			"2023 Unable to process MDS loopback frame\n");
19066 	if (pcmd && pcmd->virt)
19067 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19068 	kfree(pcmd);
19069 	if (iocbq)
19070 		lpfc_sli_release_iocbq(phba, iocbq);
19071 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19072 }
19073 
19074 /**
19075  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
19076  * @phba: Pointer to HBA context object.
19077  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
19078  *
19079  * This function is called with no lock held. This function processes all
19080  * the received buffers and gives it to upper layers when a received buffer
19081  * indicates that it is the final frame in the sequence. The interrupt
19082  * service routine processes received buffers at interrupt contexts.
19083  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
19084  * appropriate receive function when the final frame in a sequence is received.
19085  **/
19086 void
19087 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
19088 				 struct hbq_dmabuf *dmabuf)
19089 {
19090 	struct hbq_dmabuf *seq_dmabuf;
19091 	struct fc_frame_header *fc_hdr;
19092 	struct lpfc_vport *vport;
19093 	uint32_t fcfi;
19094 	uint32_t did;
19095 
19096 	/* Process each received buffer */
19097 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19098 
19099 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
19100 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
19101 		vport = phba->pport;
19102 		/* Handle MDS Loopback frames */
19103 		if  (!(phba->pport->load_flag & FC_UNLOADING))
19104 			lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19105 		else
19106 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19107 		return;
19108 	}
19109 
19110 	/* check to see if this a valid type of frame */
19111 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
19112 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19113 		return;
19114 	}
19115 
19116 	if ((bf_get(lpfc_cqe_code,
19117 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
19118 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
19119 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19120 	else
19121 		fcfi = bf_get(lpfc_rcqe_fcf_id,
19122 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19123 
19124 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
19125 		vport = phba->pport;
19126 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
19127 				"2023 MDS Loopback %d bytes\n",
19128 				bf_get(lpfc_rcqe_length,
19129 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
19130 		/* Handle MDS Loopback frames */
19131 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19132 		return;
19133 	}
19134 
19135 	/* d_id this frame is directed to */
19136 	did = sli4_did_from_fc_hdr(fc_hdr);
19137 
19138 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
19139 	if (!vport) {
19140 		/* throw out the frame */
19141 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19142 		return;
19143 	}
19144 
19145 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
19146 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
19147 		(did != Fabric_DID)) {
19148 		/*
19149 		 * Throw out the frame if we are not pt2pt.
19150 		 * The pt2pt protocol allows for discovery frames
19151 		 * to be received without a registered VPI.
19152 		 */
19153 		if (!(vport->fc_flag & FC_PT2PT) ||
19154 			(phba->link_state == LPFC_HBA_READY)) {
19155 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19156 			return;
19157 		}
19158 	}
19159 
19160 	/* Handle the basic abort sequence (BA_ABTS) event */
19161 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
19162 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
19163 		return;
19164 	}
19165 
19166 	/* Link this frame */
19167 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
19168 	if (!seq_dmabuf) {
19169 		/* unable to add frame to vport - throw it out */
19170 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19171 		return;
19172 	}
19173 	/* If not last frame in sequence continue processing frames. */
19174 	if (!lpfc_seq_complete(seq_dmabuf))
19175 		return;
19176 
19177 	/* Send the complete sequence to the upper layer protocol */
19178 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
19179 }
19180 
19181 /**
19182  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
19183  * @phba: pointer to lpfc hba data structure.
19184  *
19185  * This routine is invoked to post rpi header templates to the
19186  * HBA consistent with the SLI-4 interface spec.  This routine
19187  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19188  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19189  *
19190  * This routine does not require any locks.  It's usage is expected
19191  * to be driver load or reset recovery when the driver is
19192  * sequential.
19193  *
19194  * Return codes
19195  * 	0 - successful
19196  *      -EIO - The mailbox failed to complete successfully.
19197  * 	When this error occurs, the driver is not guaranteed
19198  *	to have any rpi regions posted to the device and
19199  *	must either attempt to repost the regions or take a
19200  *	fatal error.
19201  **/
19202 int
19203 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
19204 {
19205 	struct lpfc_rpi_hdr *rpi_page;
19206 	uint32_t rc = 0;
19207 	uint16_t lrpi = 0;
19208 
19209 	/* SLI4 ports that support extents do not require RPI headers. */
19210 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19211 		goto exit;
19212 	if (phba->sli4_hba.extents_in_use)
19213 		return -EIO;
19214 
19215 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
19216 		/*
19217 		 * Assign the rpi headers a physical rpi only if the driver
19218 		 * has not initialized those resources.  A port reset only
19219 		 * needs the headers posted.
19220 		 */
19221 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
19222 		    LPFC_RPI_RSRC_RDY)
19223 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19224 
19225 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
19226 		if (rc != MBX_SUCCESS) {
19227 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19228 					"2008 Error %d posting all rpi "
19229 					"headers\n", rc);
19230 			rc = -EIO;
19231 			break;
19232 		}
19233 	}
19234 
19235  exit:
19236 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
19237 	       LPFC_RPI_RSRC_RDY);
19238 	return rc;
19239 }
19240 
19241 /**
19242  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
19243  * @phba: pointer to lpfc hba data structure.
19244  * @rpi_page:  pointer to the rpi memory region.
19245  *
19246  * This routine is invoked to post a single rpi header to the
19247  * HBA consistent with the SLI-4 interface spec.  This memory region
19248  * maps up to 64 rpi context regions.
19249  *
19250  * Return codes
19251  * 	0 - successful
19252  * 	-ENOMEM - No available memory
19253  *      -EIO - The mailbox failed to complete successfully.
19254  **/
19255 int
19256 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
19257 {
19258 	LPFC_MBOXQ_t *mboxq;
19259 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
19260 	uint32_t rc = 0;
19261 	uint32_t shdr_status, shdr_add_status;
19262 	union lpfc_sli4_cfg_shdr *shdr;
19263 
19264 	/* SLI4 ports that support extents do not require RPI headers. */
19265 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19266 		return rc;
19267 	if (phba->sli4_hba.extents_in_use)
19268 		return -EIO;
19269 
19270 	/* The port is notified of the header region via a mailbox command. */
19271 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19272 	if (!mboxq) {
19273 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19274 				"2001 Unable to allocate memory for issuing "
19275 				"SLI_CONFIG_SPECIAL mailbox command\n");
19276 		return -ENOMEM;
19277 	}
19278 
19279 	/* Post all rpi memory regions to the port. */
19280 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
19281 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19282 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
19283 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
19284 			 sizeof(struct lpfc_sli4_cfg_mhdr),
19285 			 LPFC_SLI4_MBX_EMBED);
19286 
19287 
19288 	/* Post the physical rpi to the port for this rpi header. */
19289 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
19290 	       rpi_page->start_rpi);
19291 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
19292 	       hdr_tmpl, rpi_page->page_count);
19293 
19294 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
19295 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
19296 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19297 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
19298 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19299 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19300 	mempool_free(mboxq, phba->mbox_mem_pool);
19301 	if (shdr_status || shdr_add_status || rc) {
19302 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19303 				"2514 POST_RPI_HDR mailbox failed with "
19304 				"status x%x add_status x%x, mbx status x%x\n",
19305 				shdr_status, shdr_add_status, rc);
19306 		rc = -ENXIO;
19307 	} else {
19308 		/*
19309 		 * The next_rpi stores the next logical module-64 rpi value used
19310 		 * to post physical rpis in subsequent rpi postings.
19311 		 */
19312 		spin_lock_irq(&phba->hbalock);
19313 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
19314 		spin_unlock_irq(&phba->hbalock);
19315 	}
19316 	return rc;
19317 }
19318 
19319 /**
19320  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
19321  * @phba: pointer to lpfc hba data structure.
19322  *
19323  * This routine is invoked to post rpi header templates to the
19324  * HBA consistent with the SLI-4 interface spec.  This routine
19325  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19326  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19327  *
19328  * Returns
19329  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
19330  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
19331  **/
19332 int
19333 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
19334 {
19335 	unsigned long rpi;
19336 	uint16_t max_rpi, rpi_limit;
19337 	uint16_t rpi_remaining, lrpi = 0;
19338 	struct lpfc_rpi_hdr *rpi_hdr;
19339 	unsigned long iflag;
19340 
19341 	/*
19342 	 * Fetch the next logical rpi.  Because this index is logical,
19343 	 * the  driver starts at 0 each time.
19344 	 */
19345 	spin_lock_irqsave(&phba->hbalock, iflag);
19346 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
19347 	rpi_limit = phba->sli4_hba.next_rpi;
19348 
19349 	rpi = find_first_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit);
19350 	if (rpi >= rpi_limit)
19351 		rpi = LPFC_RPI_ALLOC_ERROR;
19352 	else {
19353 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
19354 		phba->sli4_hba.max_cfg_param.rpi_used++;
19355 		phba->sli4_hba.rpi_count++;
19356 	}
19357 	lpfc_printf_log(phba, KERN_INFO,
19358 			LOG_NODE | LOG_DISCOVERY,
19359 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
19360 			(int) rpi, max_rpi, rpi_limit);
19361 
19362 	/*
19363 	 * Don't try to allocate more rpi header regions if the device limit
19364 	 * has been exhausted.
19365 	 */
19366 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
19367 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
19368 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19369 		return rpi;
19370 	}
19371 
19372 	/*
19373 	 * RPI header postings are not required for SLI4 ports capable of
19374 	 * extents.
19375 	 */
19376 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
19377 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19378 		return rpi;
19379 	}
19380 
19381 	/*
19382 	 * If the driver is running low on rpi resources, allocate another
19383 	 * page now.  Note that the next_rpi value is used because
19384 	 * it represents how many are actually in use whereas max_rpi notes
19385 	 * how many are supported max by the device.
19386 	 */
19387 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
19388 	spin_unlock_irqrestore(&phba->hbalock, iflag);
19389 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
19390 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
19391 		if (!rpi_hdr) {
19392 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19393 					"2002 Error Could not grow rpi "
19394 					"count\n");
19395 		} else {
19396 			lrpi = rpi_hdr->start_rpi;
19397 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19398 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
19399 		}
19400 	}
19401 
19402 	return rpi;
19403 }
19404 
19405 /**
19406  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
19407  * @phba: pointer to lpfc hba data structure.
19408  * @rpi: rpi to free
19409  *
19410  * This routine is invoked to release an rpi to the pool of
19411  * available rpis maintained by the driver.
19412  **/
19413 static void
19414 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19415 {
19416 	/*
19417 	 * if the rpi value indicates a prior unreg has already
19418 	 * been done, skip the unreg.
19419 	 */
19420 	if (rpi == LPFC_RPI_ALLOC_ERROR)
19421 		return;
19422 
19423 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
19424 		phba->sli4_hba.rpi_count--;
19425 		phba->sli4_hba.max_cfg_param.rpi_used--;
19426 	} else {
19427 		lpfc_printf_log(phba, KERN_INFO,
19428 				LOG_NODE | LOG_DISCOVERY,
19429 				"2016 rpi %x not inuse\n",
19430 				rpi);
19431 	}
19432 }
19433 
19434 /**
19435  * lpfc_sli4_free_rpi - Release an rpi for reuse.
19436  * @phba: pointer to lpfc hba data structure.
19437  * @rpi: rpi to free
19438  *
19439  * This routine is invoked to release an rpi to the pool of
19440  * available rpis maintained by the driver.
19441  **/
19442 void
19443 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19444 {
19445 	spin_lock_irq(&phba->hbalock);
19446 	__lpfc_sli4_free_rpi(phba, rpi);
19447 	spin_unlock_irq(&phba->hbalock);
19448 }
19449 
19450 /**
19451  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19452  * @phba: pointer to lpfc hba data structure.
19453  *
19454  * This routine is invoked to remove the memory region that
19455  * provided rpi via a bitmask.
19456  **/
19457 void
19458 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19459 {
19460 	kfree(phba->sli4_hba.rpi_bmask);
19461 	kfree(phba->sli4_hba.rpi_ids);
19462 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19463 }
19464 
19465 /**
19466  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
19467  * @ndlp: pointer to lpfc nodelist data structure.
19468  * @cmpl: completion call-back.
19469  * @arg: data to load as MBox 'caller buffer information'
19470  *
19471  * This routine is invoked to remove the memory region that
19472  * provided rpi via a bitmask.
19473  **/
19474 int
19475 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19476 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
19477 {
19478 	LPFC_MBOXQ_t *mboxq;
19479 	struct lpfc_hba *phba = ndlp->phba;
19480 	int rc;
19481 
19482 	/* The port is notified of the header region via a mailbox command. */
19483 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19484 	if (!mboxq)
19485 		return -ENOMEM;
19486 
19487 	/* If cmpl assigned, then this nlp_get pairs with
19488 	 * lpfc_mbx_cmpl_resume_rpi.
19489 	 *
19490 	 * Else cmpl is NULL, then this nlp_get pairs with
19491 	 * lpfc_sli_def_mbox_cmpl.
19492 	 */
19493 	if (!lpfc_nlp_get(ndlp)) {
19494 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19495 				"2122 %s: Failed to get nlp ref\n",
19496 				__func__);
19497 		mempool_free(mboxq, phba->mbox_mem_pool);
19498 		return -EIO;
19499 	}
19500 
19501 	/* Post all rpi memory regions to the port. */
19502 	lpfc_resume_rpi(mboxq, ndlp);
19503 	if (cmpl) {
19504 		mboxq->mbox_cmpl = cmpl;
19505 		mboxq->ctx_buf = arg;
19506 	} else
19507 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19508 	mboxq->ctx_ndlp = ndlp;
19509 	mboxq->vport = ndlp->vport;
19510 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19511 	if (rc == MBX_NOT_FINISHED) {
19512 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19513 				"2010 Resume RPI Mailbox failed "
19514 				"status %d, mbxStatus x%x\n", rc,
19515 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19516 		lpfc_nlp_put(ndlp);
19517 		mempool_free(mboxq, phba->mbox_mem_pool);
19518 		return -EIO;
19519 	}
19520 	return 0;
19521 }
19522 
19523 /**
19524  * lpfc_sli4_init_vpi - Initialize a vpi with the port
19525  * @vport: Pointer to the vport for which the vpi is being initialized
19526  *
19527  * This routine is invoked to activate a vpi with the port.
19528  *
19529  * Returns:
19530  *    0 success
19531  *    -Evalue otherwise
19532  **/
19533 int
19534 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
19535 {
19536 	LPFC_MBOXQ_t *mboxq;
19537 	int rc = 0;
19538 	int retval = MBX_SUCCESS;
19539 	uint32_t mbox_tmo;
19540 	struct lpfc_hba *phba = vport->phba;
19541 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19542 	if (!mboxq)
19543 		return -ENOMEM;
19544 	lpfc_init_vpi(phba, mboxq, vport->vpi);
19545 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
19546 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
19547 	if (rc != MBX_SUCCESS) {
19548 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19549 				"2022 INIT VPI Mailbox failed "
19550 				"status %d, mbxStatus x%x\n", rc,
19551 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19552 		retval = -EIO;
19553 	}
19554 	if (rc != MBX_TIMEOUT)
19555 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
19556 
19557 	return retval;
19558 }
19559 
19560 /**
19561  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
19562  * @phba: pointer to lpfc hba data structure.
19563  * @mboxq: Pointer to mailbox object.
19564  *
19565  * This routine is invoked to manually add a single FCF record. The caller
19566  * must pass a completely initialized FCF_Record.  This routine takes
19567  * care of the nonembedded mailbox operations.
19568  **/
19569 static void
19570 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
19571 {
19572 	void *virt_addr;
19573 	union lpfc_sli4_cfg_shdr *shdr;
19574 	uint32_t shdr_status, shdr_add_status;
19575 
19576 	virt_addr = mboxq->sge_array->addr[0];
19577 	/* The IOCTL status is embedded in the mailbox subheader. */
19578 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
19579 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19580 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19581 
19582 	if ((shdr_status || shdr_add_status) &&
19583 		(shdr_status != STATUS_FCF_IN_USE))
19584 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19585 			"2558 ADD_FCF_RECORD mailbox failed with "
19586 			"status x%x add_status x%x\n",
19587 			shdr_status, shdr_add_status);
19588 
19589 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
19590 }
19591 
19592 /**
19593  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
19594  * @phba: pointer to lpfc hba data structure.
19595  * @fcf_record:  pointer to the initialized fcf record to add.
19596  *
19597  * This routine is invoked to manually add a single FCF record. The caller
19598  * must pass a completely initialized FCF_Record.  This routine takes
19599  * care of the nonembedded mailbox operations.
19600  **/
19601 int
19602 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
19603 {
19604 	int rc = 0;
19605 	LPFC_MBOXQ_t *mboxq;
19606 	uint8_t *bytep;
19607 	void *virt_addr;
19608 	struct lpfc_mbx_sge sge;
19609 	uint32_t alloc_len, req_len;
19610 	uint32_t fcfindex;
19611 
19612 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19613 	if (!mboxq) {
19614 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19615 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
19616 		return -ENOMEM;
19617 	}
19618 
19619 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
19620 		  sizeof(uint32_t);
19621 
19622 	/* Allocate DMA memory and set up the non-embedded mailbox command */
19623 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19624 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
19625 				     req_len, LPFC_SLI4_MBX_NEMBED);
19626 	if (alloc_len < req_len) {
19627 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19628 			"2523 Allocated DMA memory size (x%x) is "
19629 			"less than the requested DMA memory "
19630 			"size (x%x)\n", alloc_len, req_len);
19631 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19632 		return -ENOMEM;
19633 	}
19634 
19635 	/*
19636 	 * Get the first SGE entry from the non-embedded DMA memory.  This
19637 	 * routine only uses a single SGE.
19638 	 */
19639 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
19640 	virt_addr = mboxq->sge_array->addr[0];
19641 	/*
19642 	 * Configure the FCF record for FCFI 0.  This is the driver's
19643 	 * hardcoded default and gets used in nonFIP mode.
19644 	 */
19645 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
19646 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
19647 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
19648 
19649 	/*
19650 	 * Copy the fcf_index and the FCF Record Data. The data starts after
19651 	 * the FCoE header plus word10. The data copy needs to be endian
19652 	 * correct.
19653 	 */
19654 	bytep += sizeof(uint32_t);
19655 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
19656 	mboxq->vport = phba->pport;
19657 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
19658 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19659 	if (rc == MBX_NOT_FINISHED) {
19660 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19661 			"2515 ADD_FCF_RECORD mailbox failed with "
19662 			"status 0x%x\n", rc);
19663 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19664 		rc = -EIO;
19665 	} else
19666 		rc = 0;
19667 
19668 	return rc;
19669 }
19670 
19671 /**
19672  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
19673  * @phba: pointer to lpfc hba data structure.
19674  * @fcf_record:  pointer to the fcf record to write the default data.
19675  * @fcf_index: FCF table entry index.
19676  *
19677  * This routine is invoked to build the driver's default FCF record.  The
19678  * values used are hardcoded.  This routine handles memory initialization.
19679  *
19680  **/
19681 void
19682 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
19683 				struct fcf_record *fcf_record,
19684 				uint16_t fcf_index)
19685 {
19686 	memset(fcf_record, 0, sizeof(struct fcf_record));
19687 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
19688 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
19689 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
19690 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
19691 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
19692 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
19693 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
19694 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
19695 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
19696 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
19697 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
19698 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
19699 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
19700 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
19701 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
19702 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
19703 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
19704 	/* Set the VLAN bit map */
19705 	if (phba->valid_vlan) {
19706 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
19707 			= 1 << (phba->vlan_id % 8);
19708 	}
19709 }
19710 
19711 /**
19712  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
19713  * @phba: pointer to lpfc hba data structure.
19714  * @fcf_index: FCF table entry offset.
19715  *
19716  * This routine is invoked to scan the entire FCF table by reading FCF
19717  * record and processing it one at a time starting from the @fcf_index
19718  * for initial FCF discovery or fast FCF failover rediscovery.
19719  *
19720  * Return 0 if the mailbox command is submitted successfully, none 0
19721  * otherwise.
19722  **/
19723 int
19724 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19725 {
19726 	int rc = 0, error;
19727 	LPFC_MBOXQ_t *mboxq;
19728 
19729 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
19730 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
19731 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19732 	if (!mboxq) {
19733 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19734 				"2000 Failed to allocate mbox for "
19735 				"READ_FCF cmd\n");
19736 		error = -ENOMEM;
19737 		goto fail_fcf_scan;
19738 	}
19739 	/* Construct the read FCF record mailbox command */
19740 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19741 	if (rc) {
19742 		error = -EINVAL;
19743 		goto fail_fcf_scan;
19744 	}
19745 	/* Issue the mailbox command asynchronously */
19746 	mboxq->vport = phba->pport;
19747 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
19748 
19749 	spin_lock_irq(&phba->hbalock);
19750 	phba->hba_flag |= FCF_TS_INPROG;
19751 	spin_unlock_irq(&phba->hbalock);
19752 
19753 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19754 	if (rc == MBX_NOT_FINISHED)
19755 		error = -EIO;
19756 	else {
19757 		/* Reset eligible FCF count for new scan */
19758 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
19759 			phba->fcf.eligible_fcf_cnt = 0;
19760 		error = 0;
19761 	}
19762 fail_fcf_scan:
19763 	if (error) {
19764 		if (mboxq)
19765 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
19766 		/* FCF scan failed, clear FCF_TS_INPROG flag */
19767 		spin_lock_irq(&phba->hbalock);
19768 		phba->hba_flag &= ~FCF_TS_INPROG;
19769 		spin_unlock_irq(&phba->hbalock);
19770 	}
19771 	return error;
19772 }
19773 
19774 /**
19775  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
19776  * @phba: pointer to lpfc hba data structure.
19777  * @fcf_index: FCF table entry offset.
19778  *
19779  * This routine is invoked to read an FCF record indicated by @fcf_index
19780  * and to use it for FLOGI roundrobin FCF failover.
19781  *
19782  * Return 0 if the mailbox command is submitted successfully, none 0
19783  * otherwise.
19784  **/
19785 int
19786 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19787 {
19788 	int rc = 0, error;
19789 	LPFC_MBOXQ_t *mboxq;
19790 
19791 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19792 	if (!mboxq) {
19793 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
19794 				"2763 Failed to allocate mbox for "
19795 				"READ_FCF cmd\n");
19796 		error = -ENOMEM;
19797 		goto fail_fcf_read;
19798 	}
19799 	/* Construct the read FCF record mailbox command */
19800 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19801 	if (rc) {
19802 		error = -EINVAL;
19803 		goto fail_fcf_read;
19804 	}
19805 	/* Issue the mailbox command asynchronously */
19806 	mboxq->vport = phba->pport;
19807 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
19808 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19809 	if (rc == MBX_NOT_FINISHED)
19810 		error = -EIO;
19811 	else
19812 		error = 0;
19813 
19814 fail_fcf_read:
19815 	if (error && mboxq)
19816 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19817 	return error;
19818 }
19819 
19820 /**
19821  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
19822  * @phba: pointer to lpfc hba data structure.
19823  * @fcf_index: FCF table entry offset.
19824  *
19825  * This routine is invoked to read an FCF record indicated by @fcf_index to
19826  * determine whether it's eligible for FLOGI roundrobin failover list.
19827  *
19828  * Return 0 if the mailbox command is submitted successfully, none 0
19829  * otherwise.
19830  **/
19831 int
19832 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
19833 {
19834 	int rc = 0, error;
19835 	LPFC_MBOXQ_t *mboxq;
19836 
19837 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19838 	if (!mboxq) {
19839 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
19840 				"2758 Failed to allocate mbox for "
19841 				"READ_FCF cmd\n");
19842 				error = -ENOMEM;
19843 				goto fail_fcf_read;
19844 	}
19845 	/* Construct the read FCF record mailbox command */
19846 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
19847 	if (rc) {
19848 		error = -EINVAL;
19849 		goto fail_fcf_read;
19850 	}
19851 	/* Issue the mailbox command asynchronously */
19852 	mboxq->vport = phba->pport;
19853 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
19854 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19855 	if (rc == MBX_NOT_FINISHED)
19856 		error = -EIO;
19857 	else
19858 		error = 0;
19859 
19860 fail_fcf_read:
19861 	if (error && mboxq)
19862 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
19863 	return error;
19864 }
19865 
19866 /**
19867  * lpfc_check_next_fcf_pri_level
19868  * @phba: pointer to the lpfc_hba struct for this port.
19869  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
19870  * routine when the rr_bmask is empty. The FCF indecies are put into the
19871  * rr_bmask based on their priority level. Starting from the highest priority
19872  * to the lowest. The most likely FCF candidate will be in the highest
19873  * priority group. When this routine is called it searches the fcf_pri list for
19874  * next lowest priority group and repopulates the rr_bmask with only those
19875  * fcf_indexes.
19876  * returns:
19877  * 1=success 0=failure
19878  **/
19879 static int
19880 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
19881 {
19882 	uint16_t next_fcf_pri;
19883 	uint16_t last_index;
19884 	struct lpfc_fcf_pri *fcf_pri;
19885 	int rc;
19886 	int ret = 0;
19887 
19888 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
19889 			LPFC_SLI4_FCF_TBL_INDX_MAX);
19890 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19891 			"3060 Last IDX %d\n", last_index);
19892 
19893 	/* Verify the priority list has 2 or more entries */
19894 	spin_lock_irq(&phba->hbalock);
19895 	if (list_empty(&phba->fcf.fcf_pri_list) ||
19896 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
19897 		spin_unlock_irq(&phba->hbalock);
19898 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19899 			"3061 Last IDX %d\n", last_index);
19900 		return 0; /* Empty rr list */
19901 	}
19902 	spin_unlock_irq(&phba->hbalock);
19903 
19904 	next_fcf_pri = 0;
19905 	/*
19906 	 * Clear the rr_bmask and set all of the bits that are at this
19907 	 * priority.
19908 	 */
19909 	memset(phba->fcf.fcf_rr_bmask, 0,
19910 			sizeof(*phba->fcf.fcf_rr_bmask));
19911 	spin_lock_irq(&phba->hbalock);
19912 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
19913 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
19914 			continue;
19915 		/*
19916 		 * the 1st priority that has not FLOGI failed
19917 		 * will be the highest.
19918 		 */
19919 		if (!next_fcf_pri)
19920 			next_fcf_pri = fcf_pri->fcf_rec.priority;
19921 		spin_unlock_irq(&phba->hbalock);
19922 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
19923 			rc = lpfc_sli4_fcf_rr_index_set(phba,
19924 						fcf_pri->fcf_rec.fcf_index);
19925 			if (rc)
19926 				return 0;
19927 		}
19928 		spin_lock_irq(&phba->hbalock);
19929 	}
19930 	/*
19931 	 * if next_fcf_pri was not set above and the list is not empty then
19932 	 * we have failed flogis on all of them. So reset flogi failed
19933 	 * and start at the beginning.
19934 	 */
19935 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
19936 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
19937 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
19938 			/*
19939 			 * the 1st priority that has not FLOGI failed
19940 			 * will be the highest.
19941 			 */
19942 			if (!next_fcf_pri)
19943 				next_fcf_pri = fcf_pri->fcf_rec.priority;
19944 			spin_unlock_irq(&phba->hbalock);
19945 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
19946 				rc = lpfc_sli4_fcf_rr_index_set(phba,
19947 						fcf_pri->fcf_rec.fcf_index);
19948 				if (rc)
19949 					return 0;
19950 			}
19951 			spin_lock_irq(&phba->hbalock);
19952 		}
19953 	} else
19954 		ret = 1;
19955 	spin_unlock_irq(&phba->hbalock);
19956 
19957 	return ret;
19958 }
19959 /**
19960  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
19961  * @phba: pointer to lpfc hba data structure.
19962  *
19963  * This routine is to get the next eligible FCF record index in a round
19964  * robin fashion. If the next eligible FCF record index equals to the
19965  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
19966  * shall be returned, otherwise, the next eligible FCF record's index
19967  * shall be returned.
19968  **/
19969 uint16_t
19970 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
19971 {
19972 	uint16_t next_fcf_index;
19973 
19974 initial_priority:
19975 	/* Search start from next bit of currently registered FCF index */
19976 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
19977 
19978 next_priority:
19979 	/* Determine the next fcf index to check */
19980 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
19981 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
19982 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
19983 				       next_fcf_index);
19984 
19985 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
19986 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19987 		/*
19988 		 * If we have wrapped then we need to clear the bits that
19989 		 * have been tested so that we can detect when we should
19990 		 * change the priority level.
19991 		 */
19992 		next_fcf_index = find_first_bit(phba->fcf.fcf_rr_bmask,
19993 					       LPFC_SLI4_FCF_TBL_INDX_MAX);
19994 	}
19995 
19996 
19997 	/* Check roundrobin failover list empty condition */
19998 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
19999 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
20000 		/*
20001 		 * If next fcf index is not found check if there are lower
20002 		 * Priority level fcf's in the fcf_priority list.
20003 		 * Set up the rr_bmask with all of the avaiable fcf bits
20004 		 * at that level and continue the selection process.
20005 		 */
20006 		if (lpfc_check_next_fcf_pri_level(phba))
20007 			goto initial_priority;
20008 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
20009 				"2844 No roundrobin failover FCF available\n");
20010 
20011 		return LPFC_FCOE_FCF_NEXT_NONE;
20012 	}
20013 
20014 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
20015 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
20016 		LPFC_FCF_FLOGI_FAILED) {
20017 		if (list_is_singular(&phba->fcf.fcf_pri_list))
20018 			return LPFC_FCOE_FCF_NEXT_NONE;
20019 
20020 		goto next_priority;
20021 	}
20022 
20023 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20024 			"2845 Get next roundrobin failover FCF (x%x)\n",
20025 			next_fcf_index);
20026 
20027 	return next_fcf_index;
20028 }
20029 
20030 /**
20031  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
20032  * @phba: pointer to lpfc hba data structure.
20033  * @fcf_index: index into the FCF table to 'set'
20034  *
20035  * This routine sets the FCF record index in to the eligible bmask for
20036  * roundrobin failover search. It checks to make sure that the index
20037  * does not go beyond the range of the driver allocated bmask dimension
20038  * before setting the bit.
20039  *
20040  * Returns 0 if the index bit successfully set, otherwise, it returns
20041  * -EINVAL.
20042  **/
20043 int
20044 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
20045 {
20046 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20047 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20048 				"2610 FCF (x%x) reached driver's book "
20049 				"keeping dimension:x%x\n",
20050 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20051 		return -EINVAL;
20052 	}
20053 	/* Set the eligible FCF record index bmask */
20054 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20055 
20056 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20057 			"2790 Set FCF (x%x) to roundrobin FCF failover "
20058 			"bmask\n", fcf_index);
20059 
20060 	return 0;
20061 }
20062 
20063 /**
20064  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
20065  * @phba: pointer to lpfc hba data structure.
20066  * @fcf_index: index into the FCF table to 'clear'
20067  *
20068  * This routine clears the FCF record index from the eligible bmask for
20069  * roundrobin failover search. It checks to make sure that the index
20070  * does not go beyond the range of the driver allocated bmask dimension
20071  * before clearing the bit.
20072  **/
20073 void
20074 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
20075 {
20076 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
20077 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20078 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20079 				"2762 FCF (x%x) reached driver's book "
20080 				"keeping dimension:x%x\n",
20081 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20082 		return;
20083 	}
20084 	/* Clear the eligible FCF record index bmask */
20085 	spin_lock_irq(&phba->hbalock);
20086 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
20087 				 list) {
20088 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
20089 			list_del_init(&fcf_pri->list);
20090 			break;
20091 		}
20092 	}
20093 	spin_unlock_irq(&phba->hbalock);
20094 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20095 
20096 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20097 			"2791 Clear FCF (x%x) from roundrobin failover "
20098 			"bmask\n", fcf_index);
20099 }
20100 
20101 /**
20102  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
20103  * @phba: pointer to lpfc hba data structure.
20104  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
20105  *
20106  * This routine is the completion routine for the rediscover FCF table mailbox
20107  * command. If the mailbox command returned failure, it will try to stop the
20108  * FCF rediscover wait timer.
20109  **/
20110 static void
20111 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
20112 {
20113 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20114 	uint32_t shdr_status, shdr_add_status;
20115 
20116 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20117 
20118 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20119 			     &redisc_fcf->header.cfg_shdr.response);
20120 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20121 			     &redisc_fcf->header.cfg_shdr.response);
20122 	if (shdr_status || shdr_add_status) {
20123 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20124 				"2746 Requesting for FCF rediscovery failed "
20125 				"status x%x add_status x%x\n",
20126 				shdr_status, shdr_add_status);
20127 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
20128 			spin_lock_irq(&phba->hbalock);
20129 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
20130 			spin_unlock_irq(&phba->hbalock);
20131 			/*
20132 			 * CVL event triggered FCF rediscover request failed,
20133 			 * last resort to re-try current registered FCF entry.
20134 			 */
20135 			lpfc_retry_pport_discovery(phba);
20136 		} else {
20137 			spin_lock_irq(&phba->hbalock);
20138 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
20139 			spin_unlock_irq(&phba->hbalock);
20140 			/*
20141 			 * DEAD FCF event triggered FCF rediscover request
20142 			 * failed, last resort to fail over as a link down
20143 			 * to FCF registration.
20144 			 */
20145 			lpfc_sli4_fcf_dead_failthrough(phba);
20146 		}
20147 	} else {
20148 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20149 				"2775 Start FCF rediscover quiescent timer\n");
20150 		/*
20151 		 * Start FCF rediscovery wait timer for pending FCF
20152 		 * before rescan FCF record table.
20153 		 */
20154 		lpfc_fcf_redisc_wait_start_timer(phba);
20155 	}
20156 
20157 	mempool_free(mbox, phba->mbox_mem_pool);
20158 }
20159 
20160 /**
20161  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
20162  * @phba: pointer to lpfc hba data structure.
20163  *
20164  * This routine is invoked to request for rediscovery of the entire FCF table
20165  * by the port.
20166  **/
20167 int
20168 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
20169 {
20170 	LPFC_MBOXQ_t *mbox;
20171 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20172 	int rc, length;
20173 
20174 	/* Cancel retry delay timers to all vports before FCF rediscover */
20175 	lpfc_cancel_all_vport_retry_delay_timer(phba);
20176 
20177 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20178 	if (!mbox) {
20179 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20180 				"2745 Failed to allocate mbox for "
20181 				"requesting FCF rediscover.\n");
20182 		return -ENOMEM;
20183 	}
20184 
20185 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
20186 		  sizeof(struct lpfc_sli4_cfg_mhdr));
20187 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
20188 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
20189 			 length, LPFC_SLI4_MBX_EMBED);
20190 
20191 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20192 	/* Set count to 0 for invalidating the entire FCF database */
20193 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
20194 
20195 	/* Issue the mailbox command asynchronously */
20196 	mbox->vport = phba->pport;
20197 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
20198 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
20199 
20200 	if (rc == MBX_NOT_FINISHED) {
20201 		mempool_free(mbox, phba->mbox_mem_pool);
20202 		return -EIO;
20203 	}
20204 	return 0;
20205 }
20206 
20207 /**
20208  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
20209  * @phba: pointer to lpfc hba data structure.
20210  *
20211  * This function is the failover routine as a last resort to the FCF DEAD
20212  * event when driver failed to perform fast FCF failover.
20213  **/
20214 void
20215 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
20216 {
20217 	uint32_t link_state;
20218 
20219 	/*
20220 	 * Last resort as FCF DEAD event failover will treat this as
20221 	 * a link down, but save the link state because we don't want
20222 	 * it to be changed to Link Down unless it is already down.
20223 	 */
20224 	link_state = phba->link_state;
20225 	lpfc_linkdown(phba);
20226 	phba->link_state = link_state;
20227 
20228 	/* Unregister FCF if no devices connected to it */
20229 	lpfc_unregister_unused_fcf(phba);
20230 }
20231 
20232 /**
20233  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
20234  * @phba: pointer to lpfc hba data structure.
20235  * @rgn23_data: pointer to configure region 23 data.
20236  *
20237  * This function gets SLI3 port configure region 23 data through memory dump
20238  * mailbox command. When it successfully retrieves data, the size of the data
20239  * will be returned, otherwise, 0 will be returned.
20240  **/
20241 static uint32_t
20242 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20243 {
20244 	LPFC_MBOXQ_t *pmb = NULL;
20245 	MAILBOX_t *mb;
20246 	uint32_t offset = 0;
20247 	int rc;
20248 
20249 	if (!rgn23_data)
20250 		return 0;
20251 
20252 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20253 	if (!pmb) {
20254 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20255 				"2600 failed to allocate mailbox memory\n");
20256 		return 0;
20257 	}
20258 	mb = &pmb->u.mb;
20259 
20260 	do {
20261 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
20262 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
20263 
20264 		if (rc != MBX_SUCCESS) {
20265 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20266 					"2601 failed to read config "
20267 					"region 23, rc 0x%x Status 0x%x\n",
20268 					rc, mb->mbxStatus);
20269 			mb->un.varDmp.word_cnt = 0;
20270 		}
20271 		/*
20272 		 * dump mem may return a zero when finished or we got a
20273 		 * mailbox error, either way we are done.
20274 		 */
20275 		if (mb->un.varDmp.word_cnt == 0)
20276 			break;
20277 
20278 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
20279 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
20280 
20281 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
20282 				       rgn23_data + offset,
20283 				       mb->un.varDmp.word_cnt);
20284 		offset += mb->un.varDmp.word_cnt;
20285 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
20286 
20287 	mempool_free(pmb, phba->mbox_mem_pool);
20288 	return offset;
20289 }
20290 
20291 /**
20292  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
20293  * @phba: pointer to lpfc hba data structure.
20294  * @rgn23_data: pointer to configure region 23 data.
20295  *
20296  * This function gets SLI4 port configure region 23 data through memory dump
20297  * mailbox command. When it successfully retrieves data, the size of the data
20298  * will be returned, otherwise, 0 will be returned.
20299  **/
20300 static uint32_t
20301 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20302 {
20303 	LPFC_MBOXQ_t *mboxq = NULL;
20304 	struct lpfc_dmabuf *mp = NULL;
20305 	struct lpfc_mqe *mqe;
20306 	uint32_t data_length = 0;
20307 	int rc;
20308 
20309 	if (!rgn23_data)
20310 		return 0;
20311 
20312 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20313 	if (!mboxq) {
20314 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20315 				"3105 failed to allocate mailbox memory\n");
20316 		return 0;
20317 	}
20318 
20319 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
20320 		goto out;
20321 	mqe = &mboxq->u.mqe;
20322 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
20323 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
20324 	if (rc)
20325 		goto out;
20326 	data_length = mqe->un.mb_words[5];
20327 	if (data_length == 0)
20328 		goto out;
20329 	if (data_length > DMP_RGN23_SIZE) {
20330 		data_length = 0;
20331 		goto out;
20332 	}
20333 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
20334 out:
20335 	mempool_free(mboxq, phba->mbox_mem_pool);
20336 	if (mp) {
20337 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
20338 		kfree(mp);
20339 	}
20340 	return data_length;
20341 }
20342 
20343 /**
20344  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
20345  * @phba: pointer to lpfc hba data structure.
20346  *
20347  * This function read region 23 and parse TLV for port status to
20348  * decide if the user disaled the port. If the TLV indicates the
20349  * port is disabled, the hba_flag is set accordingly.
20350  **/
20351 void
20352 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
20353 {
20354 	uint8_t *rgn23_data = NULL;
20355 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
20356 	uint32_t offset = 0;
20357 
20358 	/* Get adapter Region 23 data */
20359 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
20360 	if (!rgn23_data)
20361 		goto out;
20362 
20363 	if (phba->sli_rev < LPFC_SLI_REV4)
20364 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
20365 	else {
20366 		if_type = bf_get(lpfc_sli_intf_if_type,
20367 				 &phba->sli4_hba.sli_intf);
20368 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
20369 			goto out;
20370 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
20371 	}
20372 
20373 	if (!data_size)
20374 		goto out;
20375 
20376 	/* Check the region signature first */
20377 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
20378 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20379 			"2619 Config region 23 has bad signature\n");
20380 			goto out;
20381 	}
20382 	offset += 4;
20383 
20384 	/* Check the data structure version */
20385 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
20386 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20387 			"2620 Config region 23 has bad version\n");
20388 		goto out;
20389 	}
20390 	offset += 4;
20391 
20392 	/* Parse TLV entries in the region */
20393 	while (offset < data_size) {
20394 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
20395 			break;
20396 		/*
20397 		 * If the TLV is not driver specific TLV or driver id is
20398 		 * not linux driver id, skip the record.
20399 		 */
20400 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
20401 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
20402 		    (rgn23_data[offset + 3] != 0)) {
20403 			offset += rgn23_data[offset + 1] * 4 + 4;
20404 			continue;
20405 		}
20406 
20407 		/* Driver found a driver specific TLV in the config region */
20408 		sub_tlv_len = rgn23_data[offset + 1] * 4;
20409 		offset += 4;
20410 		tlv_offset = 0;
20411 
20412 		/*
20413 		 * Search for configured port state sub-TLV.
20414 		 */
20415 		while ((offset < data_size) &&
20416 			(tlv_offset < sub_tlv_len)) {
20417 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
20418 				offset += 4;
20419 				tlv_offset += 4;
20420 				break;
20421 			}
20422 			if (rgn23_data[offset] != PORT_STE_TYPE) {
20423 				offset += rgn23_data[offset + 1] * 4 + 4;
20424 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
20425 				continue;
20426 			}
20427 
20428 			/* This HBA contains PORT_STE configured */
20429 			if (!rgn23_data[offset + 2])
20430 				phba->hba_flag |= LINK_DISABLED;
20431 
20432 			goto out;
20433 		}
20434 	}
20435 
20436 out:
20437 	kfree(rgn23_data);
20438 	return;
20439 }
20440 
20441 /**
20442  * lpfc_log_fw_write_cmpl - logs firmware write completion status
20443  * @phba: pointer to lpfc hba data structure
20444  * @shdr_status: wr_object rsp's status field
20445  * @shdr_add_status: wr_object rsp's add_status field
20446  * @shdr_add_status_2: wr_object rsp's add_status_2 field
20447  * @shdr_change_status: wr_object rsp's change_status field
20448  * @shdr_csf: wr_object rsp's csf bit
20449  *
20450  * This routine is intended to be called after a firmware write completes.
20451  * It will log next action items to be performed by the user to instantiate
20452  * the newly downloaded firmware or reason for incompatibility.
20453  **/
20454 static void
20455 lpfc_log_fw_write_cmpl(struct lpfc_hba *phba, u32 shdr_status,
20456 		       u32 shdr_add_status, u32 shdr_add_status_2,
20457 		       u32 shdr_change_status, u32 shdr_csf)
20458 {
20459 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20460 			"4198 %s: flash_id x%02x, asic_rev x%02x, "
20461 			"status x%02x, add_status x%02x, add_status_2 x%02x, "
20462 			"change_status x%02x, csf %01x\n", __func__,
20463 			phba->sli4_hba.flash_id, phba->sli4_hba.asic_rev,
20464 			shdr_status, shdr_add_status, shdr_add_status_2,
20465 			shdr_change_status, shdr_csf);
20466 
20467 	if (shdr_add_status == LPFC_ADD_STATUS_INCOMPAT_OBJ) {
20468 		switch (shdr_add_status_2) {
20469 		case LPFC_ADD_STATUS_2_INCOMPAT_FLASH:
20470 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20471 					"4199 Firmware write failed: "
20472 					"image incompatible with flash x%02x\n",
20473 					phba->sli4_hba.flash_id);
20474 			break;
20475 		case LPFC_ADD_STATUS_2_INCORRECT_ASIC:
20476 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20477 					"4200 Firmware write failed: "
20478 					"image incompatible with ASIC "
20479 					"architecture x%02x\n",
20480 					phba->sli4_hba.asic_rev);
20481 			break;
20482 		default:
20483 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20484 					"4210 Firmware write failed: "
20485 					"add_status_2 x%02x\n",
20486 					shdr_add_status_2);
20487 			break;
20488 		}
20489 	} else if (!shdr_status && !shdr_add_status) {
20490 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20491 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20492 			if (shdr_csf)
20493 				shdr_change_status =
20494 						   LPFC_CHANGE_STATUS_PCI_RESET;
20495 		}
20496 
20497 		switch (shdr_change_status) {
20498 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20499 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20500 					"3198 Firmware write complete: System "
20501 					"reboot required to instantiate\n");
20502 			break;
20503 		case (LPFC_CHANGE_STATUS_FW_RESET):
20504 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20505 					"3199 Firmware write complete: "
20506 					"Firmware reset required to "
20507 					"instantiate\n");
20508 			break;
20509 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20510 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20511 					"3200 Firmware write complete: Port "
20512 					"Migration or PCI Reset required to "
20513 					"instantiate\n");
20514 			break;
20515 		case (LPFC_CHANGE_STATUS_PCI_RESET):
20516 			lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20517 					"3201 Firmware write complete: PCI "
20518 					"Reset required to instantiate\n");
20519 			break;
20520 		default:
20521 			break;
20522 		}
20523 	}
20524 }
20525 
20526 /**
20527  * lpfc_wr_object - write an object to the firmware
20528  * @phba: HBA structure that indicates port to create a queue on.
20529  * @dmabuf_list: list of dmabufs to write to the port.
20530  * @size: the total byte value of the objects to write to the port.
20531  * @offset: the current offset to be used to start the transfer.
20532  *
20533  * This routine will create a wr_object mailbox command to send to the port.
20534  * the mailbox command will be constructed using the dma buffers described in
20535  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
20536  * BDEs that the imbedded mailbox can support. The @offset variable will be
20537  * used to indicate the starting offset of the transfer and will also return
20538  * the offset after the write object mailbox has completed. @size is used to
20539  * determine the end of the object and whether the eof bit should be set.
20540  *
20541  * Return 0 is successful and offset will contain the the new offset to use
20542  * for the next write.
20543  * Return negative value for error cases.
20544  **/
20545 int
20546 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
20547 	       uint32_t size, uint32_t *offset)
20548 {
20549 	struct lpfc_mbx_wr_object *wr_object;
20550 	LPFC_MBOXQ_t *mbox;
20551 	int rc = 0, i = 0;
20552 	uint32_t shdr_status, shdr_add_status, shdr_add_status_2;
20553 	uint32_t shdr_change_status = 0, shdr_csf = 0;
20554 	uint32_t mbox_tmo;
20555 	struct lpfc_dmabuf *dmabuf;
20556 	uint32_t written = 0;
20557 	bool check_change_status = false;
20558 
20559 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20560 	if (!mbox)
20561 		return -ENOMEM;
20562 
20563 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
20564 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
20565 			sizeof(struct lpfc_mbx_wr_object) -
20566 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
20567 
20568 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
20569 	wr_object->u.request.write_offset = *offset;
20570 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
20571 	wr_object->u.request.object_name[0] =
20572 		cpu_to_le32(wr_object->u.request.object_name[0]);
20573 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
20574 	list_for_each_entry(dmabuf, dmabuf_list, list) {
20575 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
20576 			break;
20577 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
20578 		wr_object->u.request.bde[i].addrHigh =
20579 			putPaddrHigh(dmabuf->phys);
20580 		if (written + SLI4_PAGE_SIZE >= size) {
20581 			wr_object->u.request.bde[i].tus.f.bdeSize =
20582 				(size - written);
20583 			written += (size - written);
20584 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
20585 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
20586 			check_change_status = true;
20587 		} else {
20588 			wr_object->u.request.bde[i].tus.f.bdeSize =
20589 				SLI4_PAGE_SIZE;
20590 			written += SLI4_PAGE_SIZE;
20591 		}
20592 		i++;
20593 	}
20594 	wr_object->u.request.bde_count = i;
20595 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
20596 	if (!phba->sli4_hba.intr_enable)
20597 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
20598 	else {
20599 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
20600 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
20601 	}
20602 	/* The IOCTL status is embedded in the mailbox subheader. */
20603 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20604 			     &wr_object->header.cfg_shdr.response);
20605 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20606 				 &wr_object->header.cfg_shdr.response);
20607 	shdr_add_status_2 = bf_get(lpfc_mbox_hdr_add_status_2,
20608 				   &wr_object->header.cfg_shdr.response);
20609 	if (check_change_status) {
20610 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
20611 					    &wr_object->u.response);
20612 		shdr_csf = bf_get(lpfc_wr_object_csf,
20613 				  &wr_object->u.response);
20614 	}
20615 
20616 	if (!phba->sli4_hba.intr_enable)
20617 		mempool_free(mbox, phba->mbox_mem_pool);
20618 	else if (rc != MBX_TIMEOUT)
20619 		mempool_free(mbox, phba->mbox_mem_pool);
20620 	if (shdr_status || shdr_add_status || shdr_add_status_2 || rc) {
20621 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20622 				"3025 Write Object mailbox failed with "
20623 				"status x%x add_status x%x, add_status_2 x%x, "
20624 				"mbx status x%x\n",
20625 				shdr_status, shdr_add_status, shdr_add_status_2,
20626 				rc);
20627 		rc = -ENXIO;
20628 		*offset = shdr_add_status;
20629 	} else {
20630 		*offset += wr_object->u.response.actual_write_length;
20631 	}
20632 
20633 	if (rc || check_change_status)
20634 		lpfc_log_fw_write_cmpl(phba, shdr_status, shdr_add_status,
20635 				       shdr_add_status_2, shdr_change_status,
20636 				       shdr_csf);
20637 	return rc;
20638 }
20639 
20640 /**
20641  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
20642  * @vport: pointer to vport data structure.
20643  *
20644  * This function iterate through the mailboxq and clean up all REG_LOGIN
20645  * and REG_VPI mailbox commands associated with the vport. This function
20646  * is called when driver want to restart discovery of the vport due to
20647  * a Clear Virtual Link event.
20648  **/
20649 void
20650 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
20651 {
20652 	struct lpfc_hba *phba = vport->phba;
20653 	LPFC_MBOXQ_t *mb, *nextmb;
20654 	struct lpfc_dmabuf *mp;
20655 	struct lpfc_nodelist *ndlp;
20656 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
20657 	LIST_HEAD(mbox_cmd_list);
20658 	uint8_t restart_loop;
20659 
20660 	/* Clean up internally queued mailbox commands with the vport */
20661 	spin_lock_irq(&phba->hbalock);
20662 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
20663 		if (mb->vport != vport)
20664 			continue;
20665 
20666 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
20667 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
20668 			continue;
20669 
20670 		list_move_tail(&mb->list, &mbox_cmd_list);
20671 	}
20672 	/* Clean up active mailbox command with the vport */
20673 	mb = phba->sli.mbox_active;
20674 	if (mb && (mb->vport == vport)) {
20675 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
20676 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
20677 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
20678 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20679 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20680 			/* Put reference count for delayed processing */
20681 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
20682 			/* Unregister the RPI when mailbox complete */
20683 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
20684 		}
20685 	}
20686 	/* Cleanup any mailbox completions which are not yet processed */
20687 	do {
20688 		restart_loop = 0;
20689 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
20690 			/*
20691 			 * If this mailox is already processed or it is
20692 			 * for another vport ignore it.
20693 			 */
20694 			if ((mb->vport != vport) ||
20695 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
20696 				continue;
20697 
20698 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
20699 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
20700 				continue;
20701 
20702 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
20703 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20704 				ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20705 				/* Unregister the RPI when mailbox complete */
20706 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
20707 				restart_loop = 1;
20708 				spin_unlock_irq(&phba->hbalock);
20709 				spin_lock(&ndlp->lock);
20710 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20711 				spin_unlock(&ndlp->lock);
20712 				spin_lock_irq(&phba->hbalock);
20713 				break;
20714 			}
20715 		}
20716 	} while (restart_loop);
20717 
20718 	spin_unlock_irq(&phba->hbalock);
20719 
20720 	/* Release the cleaned-up mailbox commands */
20721 	while (!list_empty(&mbox_cmd_list)) {
20722 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
20723 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
20724 			mp = (struct lpfc_dmabuf *)(mb->ctx_buf);
20725 			if (mp) {
20726 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
20727 				kfree(mp);
20728 			}
20729 			mb->ctx_buf = NULL;
20730 			ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
20731 			mb->ctx_ndlp = NULL;
20732 			if (ndlp) {
20733 				spin_lock(&ndlp->lock);
20734 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20735 				spin_unlock(&ndlp->lock);
20736 				lpfc_nlp_put(ndlp);
20737 			}
20738 		}
20739 		mempool_free(mb, phba->mbox_mem_pool);
20740 	}
20741 
20742 	/* Release the ndlp with the cleaned-up active mailbox command */
20743 	if (act_mbx_ndlp) {
20744 		spin_lock(&act_mbx_ndlp->lock);
20745 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
20746 		spin_unlock(&act_mbx_ndlp->lock);
20747 		lpfc_nlp_put(act_mbx_ndlp);
20748 	}
20749 }
20750 
20751 /**
20752  * lpfc_drain_txq - Drain the txq
20753  * @phba: Pointer to HBA context object.
20754  *
20755  * This function attempt to submit IOCBs on the txq
20756  * to the adapter.  For SLI4 adapters, the txq contains
20757  * ELS IOCBs that have been deferred because the there
20758  * are no SGLs.  This congestion can occur with large
20759  * vport counts during node discovery.
20760  **/
20761 
20762 uint32_t
20763 lpfc_drain_txq(struct lpfc_hba *phba)
20764 {
20765 	LIST_HEAD(completions);
20766 	struct lpfc_sli_ring *pring;
20767 	struct lpfc_iocbq *piocbq = NULL;
20768 	unsigned long iflags = 0;
20769 	char *fail_msg = NULL;
20770 	uint32_t txq_cnt = 0;
20771 	struct lpfc_queue *wq;
20772 	int ret = 0;
20773 
20774 	if (phba->link_flag & LS_MDS_LOOPBACK) {
20775 		/* MDS WQE are posted only to first WQ*/
20776 		wq = phba->sli4_hba.hdwq[0].io_wq;
20777 		if (unlikely(!wq))
20778 			return 0;
20779 		pring = wq->pring;
20780 	} else {
20781 		wq = phba->sli4_hba.els_wq;
20782 		if (unlikely(!wq))
20783 			return 0;
20784 		pring = lpfc_phba_elsring(phba);
20785 	}
20786 
20787 	if (unlikely(!pring) || list_empty(&pring->txq))
20788 		return 0;
20789 
20790 	spin_lock_irqsave(&pring->ring_lock, iflags);
20791 	list_for_each_entry(piocbq, &pring->txq, list) {
20792 		txq_cnt++;
20793 	}
20794 
20795 	if (txq_cnt > pring->txq_max)
20796 		pring->txq_max = txq_cnt;
20797 
20798 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
20799 
20800 	while (!list_empty(&pring->txq)) {
20801 		spin_lock_irqsave(&pring->ring_lock, iflags);
20802 
20803 		piocbq = lpfc_sli_ringtx_get(phba, pring);
20804 		if (!piocbq) {
20805 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20806 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20807 				"2823 txq empty and txq_cnt is %d\n ",
20808 				txq_cnt);
20809 			break;
20810 		}
20811 		txq_cnt--;
20812 
20813 		ret = __lpfc_sli_issue_iocb(phba, pring->ringno, piocbq, 0);
20814 
20815 		if (ret && ret != IOCB_BUSY) {
20816 			fail_msg = " - Cannot send IO ";
20817 			piocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
20818 		}
20819 		if (fail_msg) {
20820 			piocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
20821 			/* Failed means we can't issue and need to cancel */
20822 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20823 					"2822 IOCB failed %s iotag 0x%x "
20824 					"xri 0x%x %d flg x%x\n",
20825 					fail_msg, piocbq->iotag,
20826 					piocbq->sli4_xritag, ret,
20827 					piocbq->cmd_flag);
20828 			list_add_tail(&piocbq->list, &completions);
20829 			fail_msg = NULL;
20830 		}
20831 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
20832 		if (txq_cnt == 0 || ret == IOCB_BUSY)
20833 			break;
20834 	}
20835 	/* Cancel all the IOCBs that cannot be issued */
20836 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
20837 			      IOERR_SLI_ABORTED);
20838 
20839 	return txq_cnt;
20840 }
20841 
20842 /**
20843  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
20844  * @phba: Pointer to HBA context object.
20845  * @pwqeq: Pointer to command WQE.
20846  * @sglq: Pointer to the scatter gather queue object.
20847  *
20848  * This routine converts the bpl or bde that is in the WQE
20849  * to a sgl list for the sli4 hardware. The physical address
20850  * of the bpl/bde is converted back to a virtual address.
20851  * If the WQE contains a BPL then the list of BDE's is
20852  * converted to sli4_sge's. If the WQE contains a single
20853  * BDE then it is converted to a single sli_sge.
20854  * The WQE is still in cpu endianness so the contents of
20855  * the bpl can be used without byte swapping.
20856  *
20857  * Returns valid XRI = Success, NO_XRI = Failure.
20858  */
20859 static uint16_t
20860 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
20861 		 struct lpfc_sglq *sglq)
20862 {
20863 	uint16_t xritag = NO_XRI;
20864 	struct ulp_bde64 *bpl = NULL;
20865 	struct ulp_bde64 bde;
20866 	struct sli4_sge *sgl  = NULL;
20867 	struct lpfc_dmabuf *dmabuf;
20868 	union lpfc_wqe128 *wqe;
20869 	int numBdes = 0;
20870 	int i = 0;
20871 	uint32_t offset = 0; /* accumulated offset in the sg request list */
20872 	int inbound = 0; /* number of sg reply entries inbound from firmware */
20873 	uint32_t cmd;
20874 
20875 	if (!pwqeq || !sglq)
20876 		return xritag;
20877 
20878 	sgl  = (struct sli4_sge *)sglq->sgl;
20879 	wqe = &pwqeq->wqe;
20880 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
20881 
20882 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
20883 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
20884 		return sglq->sli4_xritag;
20885 	numBdes = pwqeq->num_bdes;
20886 	if (numBdes) {
20887 		/* The addrHigh and addrLow fields within the WQE
20888 		 * have not been byteswapped yet so there is no
20889 		 * need to swap them back.
20890 		 */
20891 		if (pwqeq->context3)
20892 			dmabuf = (struct lpfc_dmabuf *)pwqeq->context3;
20893 		else
20894 			return xritag;
20895 
20896 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
20897 		if (!bpl)
20898 			return xritag;
20899 
20900 		for (i = 0; i < numBdes; i++) {
20901 			/* Should already be byte swapped. */
20902 			sgl->addr_hi = bpl->addrHigh;
20903 			sgl->addr_lo = bpl->addrLow;
20904 
20905 			sgl->word2 = le32_to_cpu(sgl->word2);
20906 			if ((i+1) == numBdes)
20907 				bf_set(lpfc_sli4_sge_last, sgl, 1);
20908 			else
20909 				bf_set(lpfc_sli4_sge_last, sgl, 0);
20910 			/* swap the size field back to the cpu so we
20911 			 * can assign it to the sgl.
20912 			 */
20913 			bde.tus.w = le32_to_cpu(bpl->tus.w);
20914 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
20915 			/* The offsets in the sgl need to be accumulated
20916 			 * separately for the request and reply lists.
20917 			 * The request is always first, the reply follows.
20918 			 */
20919 			switch (cmd) {
20920 			case CMD_GEN_REQUEST64_WQE:
20921 				/* add up the reply sg entries */
20922 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
20923 					inbound++;
20924 				/* first inbound? reset the offset */
20925 				if (inbound == 1)
20926 					offset = 0;
20927 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
20928 				bf_set(lpfc_sli4_sge_type, sgl,
20929 					LPFC_SGE_TYPE_DATA);
20930 				offset += bde.tus.f.bdeSize;
20931 				break;
20932 			case CMD_FCP_TRSP64_WQE:
20933 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
20934 				bf_set(lpfc_sli4_sge_type, sgl,
20935 					LPFC_SGE_TYPE_DATA);
20936 				break;
20937 			case CMD_FCP_TSEND64_WQE:
20938 			case CMD_FCP_TRECEIVE64_WQE:
20939 				bf_set(lpfc_sli4_sge_type, sgl,
20940 					bpl->tus.f.bdeFlags);
20941 				if (i < 3)
20942 					offset = 0;
20943 				else
20944 					offset += bde.tus.f.bdeSize;
20945 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
20946 				break;
20947 			}
20948 			sgl->word2 = cpu_to_le32(sgl->word2);
20949 			bpl++;
20950 			sgl++;
20951 		}
20952 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
20953 		/* The addrHigh and addrLow fields of the BDE have not
20954 		 * been byteswapped yet so they need to be swapped
20955 		 * before putting them in the sgl.
20956 		 */
20957 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
20958 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
20959 		sgl->word2 = le32_to_cpu(sgl->word2);
20960 		bf_set(lpfc_sli4_sge_last, sgl, 1);
20961 		sgl->word2 = cpu_to_le32(sgl->word2);
20962 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
20963 	}
20964 	return sglq->sli4_xritag;
20965 }
20966 
20967 /**
20968  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
20969  * @phba: Pointer to HBA context object.
20970  * @qp: Pointer to HDW queue.
20971  * @pwqe: Pointer to command WQE.
20972  **/
20973 int
20974 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
20975 		    struct lpfc_iocbq *pwqe)
20976 {
20977 	union lpfc_wqe128 *wqe = &pwqe->wqe;
20978 	struct lpfc_async_xchg_ctx *ctxp;
20979 	struct lpfc_queue *wq;
20980 	struct lpfc_sglq *sglq;
20981 	struct lpfc_sli_ring *pring;
20982 	unsigned long iflags;
20983 	uint32_t ret = 0;
20984 
20985 	/* NVME_LS and NVME_LS ABTS requests. */
20986 	if (pwqe->cmd_flag & LPFC_IO_NVME_LS) {
20987 		pring =  phba->sli4_hba.nvmels_wq->pring;
20988 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
20989 					  qp, wq_access);
20990 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
20991 		if (!sglq) {
20992 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20993 			return WQE_BUSY;
20994 		}
20995 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
20996 		pwqe->sli4_xritag = sglq->sli4_xritag;
20997 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
20998 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
20999 			return WQE_ERROR;
21000 		}
21001 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21002 		       pwqe->sli4_xritag);
21003 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
21004 		if (ret) {
21005 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21006 			return ret;
21007 		}
21008 
21009 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21010 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21011 
21012 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
21013 		return 0;
21014 	}
21015 
21016 	/* NVME_FCREQ and NVME_ABTS requests */
21017 	if (pwqe->cmd_flag & (LPFC_IO_NVME | LPFC_IO_FCP | LPFC_IO_CMF)) {
21018 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21019 		wq = qp->io_wq;
21020 		pring = wq->pring;
21021 
21022 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21023 
21024 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21025 					  qp, wq_access);
21026 		ret = lpfc_sli4_wq_put(wq, wqe);
21027 		if (ret) {
21028 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21029 			return ret;
21030 		}
21031 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21032 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21033 
21034 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
21035 		return 0;
21036 	}
21037 
21038 	/* NVMET requests */
21039 	if (pwqe->cmd_flag & LPFC_IO_NVMET) {
21040 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21041 		wq = qp->io_wq;
21042 		pring = wq->pring;
21043 
21044 		ctxp = pwqe->context2;
21045 		sglq = ctxp->ctxbuf->sglq;
21046 		if (pwqe->sli4_xritag ==  NO_XRI) {
21047 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
21048 			pwqe->sli4_xritag = sglq->sli4_xritag;
21049 		}
21050 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21051 		       pwqe->sli4_xritag);
21052 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21053 
21054 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21055 					  qp, wq_access);
21056 		ret = lpfc_sli4_wq_put(wq, wqe);
21057 		if (ret) {
21058 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21059 			return ret;
21060 		}
21061 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21062 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21063 
21064 		lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
21065 		return 0;
21066 	}
21067 	return WQE_ERROR;
21068 }
21069 
21070 /**
21071  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
21072  * @phba: Pointer to HBA context object.
21073  * @cmdiocb: Pointer to driver command iocb object.
21074  * @cmpl: completion function.
21075  *
21076  * Fill the appropriate fields for the abort WQE and call
21077  * internal routine lpfc_sli4_issue_wqe to send the WQE
21078  * This function is called with hbalock held and no ring_lock held.
21079  *
21080  * RETURNS 0 - SUCCESS
21081  **/
21082 
21083 int
21084 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
21085 			    void *cmpl)
21086 {
21087 	struct lpfc_vport *vport = cmdiocb->vport;
21088 	struct lpfc_iocbq *abtsiocb = NULL;
21089 	union lpfc_wqe128 *abtswqe;
21090 	struct lpfc_io_buf *lpfc_cmd;
21091 	int retval = IOCB_ERROR;
21092 	u16 xritag = cmdiocb->sli4_xritag;
21093 
21094 	/*
21095 	 * The scsi command can not be in txq and it is in flight because the
21096 	 * pCmd is still pointing at the SCSI command we have to abort. There
21097 	 * is no need to search the txcmplq. Just send an abort to the FW.
21098 	 */
21099 
21100 	abtsiocb = __lpfc_sli_get_iocbq(phba);
21101 	if (!abtsiocb)
21102 		return WQE_NORESOURCE;
21103 
21104 	/* Indicate the IO is being aborted by the driver. */
21105 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
21106 
21107 	abtswqe = &abtsiocb->wqe;
21108 	memset(abtswqe, 0, sizeof(*abtswqe));
21109 
21110 	if (!lpfc_is_link_up(phba))
21111 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
21112 	bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
21113 	abtswqe->abort_cmd.rsrvd5 = 0;
21114 	abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
21115 	bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
21116 	bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
21117 	bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
21118 	bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
21119 	bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
21120 	bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
21121 
21122 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
21123 	abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
21124 	abtsiocb->cmd_flag |= LPFC_USE_FCPWQIDX;
21125 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
21126 		abtsiocb->cmd_flag |= LPFC_IO_FCP;
21127 	if (cmdiocb->cmd_flag & LPFC_IO_NVME)
21128 		abtsiocb->cmd_flag |= LPFC_IO_NVME;
21129 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
21130 		abtsiocb->cmd_flag |= LPFC_IO_FOF;
21131 	abtsiocb->vport = vport;
21132 	abtsiocb->cmd_cmpl = cmpl;
21133 
21134 	lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
21135 	retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
21136 
21137 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21138 			 "0359 Abort xri x%x, original iotag x%x, "
21139 			 "abort cmd iotag x%x retval x%x\n",
21140 			 xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
21141 
21142 	if (retval) {
21143 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21144 		__lpfc_sli_release_iocbq(phba, abtsiocb);
21145 	}
21146 
21147 	return retval;
21148 }
21149 
21150 #ifdef LPFC_MXP_STAT
21151 /**
21152  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
21153  * @phba: pointer to lpfc hba data structure.
21154  * @hwqid: belong to which HWQ.
21155  *
21156  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
21157  * 15 seconds after a test case is running.
21158  *
21159  * The user should call lpfc_debugfs_multixripools_write before running a test
21160  * case to clear stat_snapshot_taken. Then the user starts a test case. During
21161  * test case is running, stat_snapshot_taken is incremented by 1 every time when
21162  * this routine is called from heartbeat timer. When stat_snapshot_taken is
21163  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
21164  **/
21165 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
21166 {
21167 	struct lpfc_sli4_hdw_queue *qp;
21168 	struct lpfc_multixri_pool *multixri_pool;
21169 	struct lpfc_pvt_pool *pvt_pool;
21170 	struct lpfc_pbl_pool *pbl_pool;
21171 	u32 txcmplq_cnt;
21172 
21173 	qp = &phba->sli4_hba.hdwq[hwqid];
21174 	multixri_pool = qp->p_multixri_pool;
21175 	if (!multixri_pool)
21176 		return;
21177 
21178 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
21179 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21180 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21181 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21182 
21183 		multixri_pool->stat_pbl_count = pbl_pool->count;
21184 		multixri_pool->stat_pvt_count = pvt_pool->count;
21185 		multixri_pool->stat_busy_count = txcmplq_cnt;
21186 	}
21187 
21188 	multixri_pool->stat_snapshot_taken++;
21189 }
21190 #endif
21191 
21192 /**
21193  * lpfc_adjust_pvt_pool_count - Adjust private pool count
21194  * @phba: pointer to lpfc hba data structure.
21195  * @hwqid: belong to which HWQ.
21196  *
21197  * This routine moves some XRIs from private to public pool when private pool
21198  * is not busy.
21199  **/
21200 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
21201 {
21202 	struct lpfc_multixri_pool *multixri_pool;
21203 	u32 io_req_count;
21204 	u32 prev_io_req_count;
21205 
21206 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21207 	if (!multixri_pool)
21208 		return;
21209 	io_req_count = multixri_pool->io_req_count;
21210 	prev_io_req_count = multixri_pool->prev_io_req_count;
21211 
21212 	if (prev_io_req_count != io_req_count) {
21213 		/* Private pool is busy */
21214 		multixri_pool->prev_io_req_count = io_req_count;
21215 	} else {
21216 		/* Private pool is not busy.
21217 		 * Move XRIs from private to public pool.
21218 		 */
21219 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
21220 	}
21221 }
21222 
21223 /**
21224  * lpfc_adjust_high_watermark - Adjust high watermark
21225  * @phba: pointer to lpfc hba data structure.
21226  * @hwqid: belong to which HWQ.
21227  *
21228  * This routine sets high watermark as number of outstanding XRIs,
21229  * but make sure the new value is between xri_limit/2 and xri_limit.
21230  **/
21231 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
21232 {
21233 	u32 new_watermark;
21234 	u32 watermark_max;
21235 	u32 watermark_min;
21236 	u32 xri_limit;
21237 	u32 txcmplq_cnt;
21238 	u32 abts_io_bufs;
21239 	struct lpfc_multixri_pool *multixri_pool;
21240 	struct lpfc_sli4_hdw_queue *qp;
21241 
21242 	qp = &phba->sli4_hba.hdwq[hwqid];
21243 	multixri_pool = qp->p_multixri_pool;
21244 	if (!multixri_pool)
21245 		return;
21246 	xri_limit = multixri_pool->xri_limit;
21247 
21248 	watermark_max = xri_limit;
21249 	watermark_min = xri_limit / 2;
21250 
21251 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21252 	abts_io_bufs = qp->abts_scsi_io_bufs;
21253 	abts_io_bufs += qp->abts_nvme_io_bufs;
21254 
21255 	new_watermark = txcmplq_cnt + abts_io_bufs;
21256 	new_watermark = min(watermark_max, new_watermark);
21257 	new_watermark = max(watermark_min, new_watermark);
21258 	multixri_pool->pvt_pool.high_watermark = new_watermark;
21259 
21260 #ifdef LPFC_MXP_STAT
21261 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
21262 					  new_watermark);
21263 #endif
21264 }
21265 
21266 /**
21267  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
21268  * @phba: pointer to lpfc hba data structure.
21269  * @hwqid: belong to which HWQ.
21270  *
21271  * This routine is called from hearbeat timer when pvt_pool is idle.
21272  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
21273  * The first step moves (all - low_watermark) amount of XRIs.
21274  * The second step moves the rest of XRIs.
21275  **/
21276 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
21277 {
21278 	struct lpfc_pbl_pool *pbl_pool;
21279 	struct lpfc_pvt_pool *pvt_pool;
21280 	struct lpfc_sli4_hdw_queue *qp;
21281 	struct lpfc_io_buf *lpfc_ncmd;
21282 	struct lpfc_io_buf *lpfc_ncmd_next;
21283 	unsigned long iflag;
21284 	struct list_head tmp_list;
21285 	u32 tmp_count;
21286 
21287 	qp = &phba->sli4_hba.hdwq[hwqid];
21288 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
21289 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
21290 	tmp_count = 0;
21291 
21292 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
21293 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
21294 
21295 	if (pvt_pool->count > pvt_pool->low_watermark) {
21296 		/* Step 1: move (all - low_watermark) from pvt_pool
21297 		 * to pbl_pool
21298 		 */
21299 
21300 		/* Move low watermark of bufs from pvt_pool to tmp_list */
21301 		INIT_LIST_HEAD(&tmp_list);
21302 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21303 					 &pvt_pool->list, list) {
21304 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
21305 			tmp_count++;
21306 			if (tmp_count >= pvt_pool->low_watermark)
21307 				break;
21308 		}
21309 
21310 		/* Move all bufs from pvt_pool to pbl_pool */
21311 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21312 
21313 		/* Move all bufs from tmp_list to pvt_pool */
21314 		list_splice(&tmp_list, &pvt_pool->list);
21315 
21316 		pbl_pool->count += (pvt_pool->count - tmp_count);
21317 		pvt_pool->count = tmp_count;
21318 	} else {
21319 		/* Step 2: move the rest from pvt_pool to pbl_pool */
21320 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21321 		pbl_pool->count += pvt_pool->count;
21322 		pvt_pool->count = 0;
21323 	}
21324 
21325 	spin_unlock(&pvt_pool->lock);
21326 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21327 }
21328 
21329 /**
21330  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21331  * @phba: pointer to lpfc hba data structure
21332  * @qp: pointer to HDW queue
21333  * @pbl_pool: specified public free XRI pool
21334  * @pvt_pool: specified private free XRI pool
21335  * @count: number of XRIs to move
21336  *
21337  * This routine tries to move some free common bufs from the specified pbl_pool
21338  * to the specified pvt_pool. It might move less than count XRIs if there's not
21339  * enough in public pool.
21340  *
21341  * Return:
21342  *   true - if XRIs are successfully moved from the specified pbl_pool to the
21343  *          specified pvt_pool
21344  *   false - if the specified pbl_pool is empty or locked by someone else
21345  **/
21346 static bool
21347 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21348 			  struct lpfc_pbl_pool *pbl_pool,
21349 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
21350 {
21351 	struct lpfc_io_buf *lpfc_ncmd;
21352 	struct lpfc_io_buf *lpfc_ncmd_next;
21353 	unsigned long iflag;
21354 	int ret;
21355 
21356 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
21357 	if (ret) {
21358 		if (pbl_pool->count) {
21359 			/* Move a batch of XRIs from public to private pool */
21360 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
21361 			list_for_each_entry_safe(lpfc_ncmd,
21362 						 lpfc_ncmd_next,
21363 						 &pbl_pool->list,
21364 						 list) {
21365 				list_move_tail(&lpfc_ncmd->list,
21366 					       &pvt_pool->list);
21367 				pvt_pool->count++;
21368 				pbl_pool->count--;
21369 				count--;
21370 				if (count == 0)
21371 					break;
21372 			}
21373 
21374 			spin_unlock(&pvt_pool->lock);
21375 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21376 			return true;
21377 		}
21378 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21379 	}
21380 
21381 	return false;
21382 }
21383 
21384 /**
21385  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21386  * @phba: pointer to lpfc hba data structure.
21387  * @hwqid: belong to which HWQ.
21388  * @count: number of XRIs to move
21389  *
21390  * This routine tries to find some free common bufs in one of public pools with
21391  * Round Robin method. The search always starts from local hwqid, then the next
21392  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
21393  * a batch of free common bufs are moved to private pool on hwqid.
21394  * It might move less than count XRIs if there's not enough in public pool.
21395  **/
21396 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
21397 {
21398 	struct lpfc_multixri_pool *multixri_pool;
21399 	struct lpfc_multixri_pool *next_multixri_pool;
21400 	struct lpfc_pvt_pool *pvt_pool;
21401 	struct lpfc_pbl_pool *pbl_pool;
21402 	struct lpfc_sli4_hdw_queue *qp;
21403 	u32 next_hwqid;
21404 	u32 hwq_count;
21405 	int ret;
21406 
21407 	qp = &phba->sli4_hba.hdwq[hwqid];
21408 	multixri_pool = qp->p_multixri_pool;
21409 	pvt_pool = &multixri_pool->pvt_pool;
21410 	pbl_pool = &multixri_pool->pbl_pool;
21411 
21412 	/* Check if local pbl_pool is available */
21413 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
21414 	if (ret) {
21415 #ifdef LPFC_MXP_STAT
21416 		multixri_pool->local_pbl_hit_count++;
21417 #endif
21418 		return;
21419 	}
21420 
21421 	hwq_count = phba->cfg_hdw_queue;
21422 
21423 	/* Get the next hwqid which was found last time */
21424 	next_hwqid = multixri_pool->rrb_next_hwqid;
21425 
21426 	do {
21427 		/* Go to next hwq */
21428 		next_hwqid = (next_hwqid + 1) % hwq_count;
21429 
21430 		next_multixri_pool =
21431 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
21432 		pbl_pool = &next_multixri_pool->pbl_pool;
21433 
21434 		/* Check if the public free xri pool is available */
21435 		ret = _lpfc_move_xri_pbl_to_pvt(
21436 			phba, qp, pbl_pool, pvt_pool, count);
21437 
21438 		/* Exit while-loop if success or all hwqid are checked */
21439 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
21440 
21441 	/* Starting point for the next time */
21442 	multixri_pool->rrb_next_hwqid = next_hwqid;
21443 
21444 	if (!ret) {
21445 		/* stats: all public pools are empty*/
21446 		multixri_pool->pbl_empty_count++;
21447 	}
21448 
21449 #ifdef LPFC_MXP_STAT
21450 	if (ret) {
21451 		if (next_hwqid == hwqid)
21452 			multixri_pool->local_pbl_hit_count++;
21453 		else
21454 			multixri_pool->other_pbl_hit_count++;
21455 	}
21456 #endif
21457 }
21458 
21459 /**
21460  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
21461  * @phba: pointer to lpfc hba data structure.
21462  * @hwqid: belong to which HWQ.
21463  *
21464  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
21465  * low watermark.
21466  **/
21467 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
21468 {
21469 	struct lpfc_multixri_pool *multixri_pool;
21470 	struct lpfc_pvt_pool *pvt_pool;
21471 
21472 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21473 	pvt_pool = &multixri_pool->pvt_pool;
21474 
21475 	if (pvt_pool->count < pvt_pool->low_watermark)
21476 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21477 }
21478 
21479 /**
21480  * lpfc_release_io_buf - Return one IO buf back to free pool
21481  * @phba: pointer to lpfc hba data structure.
21482  * @lpfc_ncmd: IO buf to be returned.
21483  * @qp: belong to which HWQ.
21484  *
21485  * This routine returns one IO buf back to free pool. If this is an urgent IO,
21486  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
21487  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
21488  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
21489  * lpfc_io_buf_list_put.
21490  **/
21491 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
21492 			 struct lpfc_sli4_hdw_queue *qp)
21493 {
21494 	unsigned long iflag;
21495 	struct lpfc_pbl_pool *pbl_pool;
21496 	struct lpfc_pvt_pool *pvt_pool;
21497 	struct lpfc_epd_pool *epd_pool;
21498 	u32 txcmplq_cnt;
21499 	u32 xri_owned;
21500 	u32 xri_limit;
21501 	u32 abts_io_bufs;
21502 
21503 	/* MUST zero fields if buffer is reused by another protocol */
21504 	lpfc_ncmd->nvmeCmd = NULL;
21505 	lpfc_ncmd->cur_iocbq.cmd_cmpl = NULL;
21506 
21507 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
21508 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
21509 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
21510 
21511 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
21512 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
21513 
21514 	if (phba->cfg_xri_rebalancing) {
21515 		if (lpfc_ncmd->expedite) {
21516 			/* Return to expedite pool */
21517 			epd_pool = &phba->epd_pool;
21518 			spin_lock_irqsave(&epd_pool->lock, iflag);
21519 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21520 			epd_pool->count++;
21521 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
21522 			return;
21523 		}
21524 
21525 		/* Avoid invalid access if an IO sneaks in and is being rejected
21526 		 * just _after_ xri pools are destroyed in lpfc_offline.
21527 		 * Nothing much can be done at this point.
21528 		 */
21529 		if (!qp->p_multixri_pool)
21530 			return;
21531 
21532 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21533 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21534 
21535 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21536 		abts_io_bufs = qp->abts_scsi_io_bufs;
21537 		abts_io_bufs += qp->abts_nvme_io_bufs;
21538 
21539 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21540 		xri_limit = qp->p_multixri_pool->xri_limit;
21541 
21542 #ifdef LPFC_MXP_STAT
21543 		if (xri_owned <= xri_limit)
21544 			qp->p_multixri_pool->below_limit_count++;
21545 		else
21546 			qp->p_multixri_pool->above_limit_count++;
21547 #endif
21548 
21549 		/* XRI goes to either public or private free xri pool
21550 		 *     based on watermark and xri_limit
21551 		 */
21552 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
21553 		    (xri_owned < xri_limit &&
21554 		     pvt_pool->count < pvt_pool->high_watermark)) {
21555 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
21556 						  qp, free_pvt_pool);
21557 			list_add_tail(&lpfc_ncmd->list,
21558 				      &pvt_pool->list);
21559 			pvt_pool->count++;
21560 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21561 		} else {
21562 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
21563 						  qp, free_pub_pool);
21564 			list_add_tail(&lpfc_ncmd->list,
21565 				      &pbl_pool->list);
21566 			pbl_pool->count++;
21567 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21568 		}
21569 	} else {
21570 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
21571 					  qp, free_xri);
21572 		list_add_tail(&lpfc_ncmd->list,
21573 			      &qp->lpfc_io_buf_list_put);
21574 		qp->put_io_bufs++;
21575 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
21576 				       iflag);
21577 	}
21578 }
21579 
21580 /**
21581  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
21582  * @phba: pointer to lpfc hba data structure.
21583  * @qp: pointer to HDW queue
21584  * @pvt_pool: pointer to private pool data structure.
21585  * @ndlp: pointer to lpfc nodelist data structure.
21586  *
21587  * This routine tries to get one free IO buf from private pool.
21588  *
21589  * Return:
21590  *   pointer to one free IO buf - if private pool is not empty
21591  *   NULL - if private pool is empty
21592  **/
21593 static struct lpfc_io_buf *
21594 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
21595 				  struct lpfc_sli4_hdw_queue *qp,
21596 				  struct lpfc_pvt_pool *pvt_pool,
21597 				  struct lpfc_nodelist *ndlp)
21598 {
21599 	struct lpfc_io_buf *lpfc_ncmd;
21600 	struct lpfc_io_buf *lpfc_ncmd_next;
21601 	unsigned long iflag;
21602 
21603 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
21604 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21605 				 &pvt_pool->list, list) {
21606 		if (lpfc_test_rrq_active(
21607 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
21608 			continue;
21609 		list_del(&lpfc_ncmd->list);
21610 		pvt_pool->count--;
21611 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21612 		return lpfc_ncmd;
21613 	}
21614 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21615 
21616 	return NULL;
21617 }
21618 
21619 /**
21620  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
21621  * @phba: pointer to lpfc hba data structure.
21622  *
21623  * This routine tries to get one free IO buf from expedite pool.
21624  *
21625  * Return:
21626  *   pointer to one free IO buf - if expedite pool is not empty
21627  *   NULL - if expedite pool is empty
21628  **/
21629 static struct lpfc_io_buf *
21630 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
21631 {
21632 	struct lpfc_io_buf *lpfc_ncmd;
21633 	struct lpfc_io_buf *lpfc_ncmd_next;
21634 	unsigned long iflag;
21635 	struct lpfc_epd_pool *epd_pool;
21636 
21637 	epd_pool = &phba->epd_pool;
21638 	lpfc_ncmd = NULL;
21639 
21640 	spin_lock_irqsave(&epd_pool->lock, iflag);
21641 	if (epd_pool->count > 0) {
21642 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21643 					 &epd_pool->list, list) {
21644 			list_del(&lpfc_ncmd->list);
21645 			epd_pool->count--;
21646 			break;
21647 		}
21648 	}
21649 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
21650 
21651 	return lpfc_ncmd;
21652 }
21653 
21654 /**
21655  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
21656  * @phba: pointer to lpfc hba data structure.
21657  * @ndlp: pointer to lpfc nodelist data structure.
21658  * @hwqid: belong to which HWQ
21659  * @expedite: 1 means this request is urgent.
21660  *
21661  * This routine will do the following actions and then return a pointer to
21662  * one free IO buf.
21663  *
21664  * 1. If private free xri count is empty, move some XRIs from public to
21665  *    private pool.
21666  * 2. Get one XRI from private free xri pool.
21667  * 3. If we fail to get one from pvt_pool and this is an expedite request,
21668  *    get one free xri from expedite pool.
21669  *
21670  * Note: ndlp is only used on SCSI side for RRQ testing.
21671  *       The caller should pass NULL for ndlp on NVME side.
21672  *
21673  * Return:
21674  *   pointer to one free IO buf - if private pool is not empty
21675  *   NULL - if private pool is empty
21676  **/
21677 static struct lpfc_io_buf *
21678 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
21679 				    struct lpfc_nodelist *ndlp,
21680 				    int hwqid, int expedite)
21681 {
21682 	struct lpfc_sli4_hdw_queue *qp;
21683 	struct lpfc_multixri_pool *multixri_pool;
21684 	struct lpfc_pvt_pool *pvt_pool;
21685 	struct lpfc_io_buf *lpfc_ncmd;
21686 
21687 	qp = &phba->sli4_hba.hdwq[hwqid];
21688 	lpfc_ncmd = NULL;
21689 	if (!qp) {
21690 		lpfc_printf_log(phba, KERN_INFO,
21691 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21692 				"5556 NULL qp for hwqid  x%x\n", hwqid);
21693 		return lpfc_ncmd;
21694 	}
21695 	multixri_pool = qp->p_multixri_pool;
21696 	if (!multixri_pool) {
21697 		lpfc_printf_log(phba, KERN_INFO,
21698 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21699 				"5557 NULL multixri for hwqid  x%x\n", hwqid);
21700 		return lpfc_ncmd;
21701 	}
21702 	pvt_pool = &multixri_pool->pvt_pool;
21703 	if (!pvt_pool) {
21704 		lpfc_printf_log(phba, KERN_INFO,
21705 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21706 				"5558 NULL pvt_pool for hwqid  x%x\n", hwqid);
21707 		return lpfc_ncmd;
21708 	}
21709 	multixri_pool->io_req_count++;
21710 
21711 	/* If pvt_pool is empty, move some XRIs from public to private pool */
21712 	if (pvt_pool->count == 0)
21713 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21714 
21715 	/* Get one XRI from private free xri pool */
21716 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
21717 
21718 	if (lpfc_ncmd) {
21719 		lpfc_ncmd->hdwq = qp;
21720 		lpfc_ncmd->hdwq_no = hwqid;
21721 	} else if (expedite) {
21722 		/* If we fail to get one from pvt_pool and this is an expedite
21723 		 * request, get one free xri from expedite pool.
21724 		 */
21725 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
21726 	}
21727 
21728 	return lpfc_ncmd;
21729 }
21730 
21731 static inline struct lpfc_io_buf *
21732 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
21733 {
21734 	struct lpfc_sli4_hdw_queue *qp;
21735 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
21736 
21737 	qp = &phba->sli4_hba.hdwq[idx];
21738 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
21739 				 &qp->lpfc_io_buf_list_get, list) {
21740 		if (lpfc_test_rrq_active(phba, ndlp,
21741 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
21742 			continue;
21743 
21744 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
21745 			continue;
21746 
21747 		list_del_init(&lpfc_cmd->list);
21748 		qp->get_io_bufs--;
21749 		lpfc_cmd->hdwq = qp;
21750 		lpfc_cmd->hdwq_no = idx;
21751 		return lpfc_cmd;
21752 	}
21753 	return NULL;
21754 }
21755 
21756 /**
21757  * lpfc_get_io_buf - Get one IO buffer from free pool
21758  * @phba: The HBA for which this call is being executed.
21759  * @ndlp: pointer to lpfc nodelist data structure.
21760  * @hwqid: belong to which HWQ
21761  * @expedite: 1 means this request is urgent.
21762  *
21763  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
21764  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
21765  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
21766  *
21767  * Note: ndlp is only used on SCSI side for RRQ testing.
21768  *       The caller should pass NULL for ndlp on NVME side.
21769  *
21770  * Return codes:
21771  *   NULL - Error
21772  *   Pointer to lpfc_io_buf - Success
21773  **/
21774 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
21775 				    struct lpfc_nodelist *ndlp,
21776 				    u32 hwqid, int expedite)
21777 {
21778 	struct lpfc_sli4_hdw_queue *qp;
21779 	unsigned long iflag;
21780 	struct lpfc_io_buf *lpfc_cmd;
21781 
21782 	qp = &phba->sli4_hba.hdwq[hwqid];
21783 	lpfc_cmd = NULL;
21784 	if (!qp) {
21785 		lpfc_printf_log(phba, KERN_WARNING,
21786 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21787 				"5555 NULL qp for hwqid  x%x\n", hwqid);
21788 		return lpfc_cmd;
21789 	}
21790 
21791 	if (phba->cfg_xri_rebalancing)
21792 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
21793 			phba, ndlp, hwqid, expedite);
21794 	else {
21795 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
21796 					  qp, alloc_xri_get);
21797 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
21798 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
21799 		if (!lpfc_cmd) {
21800 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
21801 					  qp, alloc_xri_put);
21802 			list_splice(&qp->lpfc_io_buf_list_put,
21803 				    &qp->lpfc_io_buf_list_get);
21804 			qp->get_io_bufs += qp->put_io_bufs;
21805 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
21806 			qp->put_io_bufs = 0;
21807 			spin_unlock(&qp->io_buf_list_put_lock);
21808 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
21809 			    expedite)
21810 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
21811 		}
21812 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
21813 	}
21814 
21815 	return lpfc_cmd;
21816 }
21817 
21818 /**
21819  * lpfc_read_object - Retrieve object data from HBA
21820  * @phba: The HBA for which this call is being executed.
21821  * @rdobject: Pathname of object data we want to read.
21822  * @datap: Pointer to where data will be copied to.
21823  * @datasz: size of data area
21824  *
21825  * This routine is limited to object sizes of LPFC_BPL_SIZE (1024) or less.
21826  * The data will be truncated if datasz is not large enough.
21827  * Version 1 is not supported with Embedded mbox cmd, so we must use version 0.
21828  * Returns the actual bytes read from the object.
21829  */
21830 int
21831 lpfc_read_object(struct lpfc_hba *phba, char *rdobject, uint32_t *datap,
21832 		 uint32_t datasz)
21833 {
21834 	struct lpfc_mbx_read_object *read_object;
21835 	LPFC_MBOXQ_t *mbox;
21836 	int rc, length, eof, j, byte_cnt = 0;
21837 	uint32_t shdr_status, shdr_add_status;
21838 	union lpfc_sli4_cfg_shdr *shdr;
21839 	struct lpfc_dmabuf *pcmd;
21840 	u32 rd_object_name[LPFC_MBX_OBJECT_NAME_LEN_DW] = {0};
21841 
21842 	/* sanity check on queue memory */
21843 	if (!datap)
21844 		return -ENODEV;
21845 
21846 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
21847 	if (!mbox)
21848 		return -ENOMEM;
21849 	length = (sizeof(struct lpfc_mbx_read_object) -
21850 		  sizeof(struct lpfc_sli4_cfg_mhdr));
21851 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
21852 			 LPFC_MBOX_OPCODE_READ_OBJECT,
21853 			 length, LPFC_SLI4_MBX_EMBED);
21854 	read_object = &mbox->u.mqe.un.read_object;
21855 	shdr = (union lpfc_sli4_cfg_shdr *)&read_object->header.cfg_shdr;
21856 
21857 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_0);
21858 	bf_set(lpfc_mbx_rd_object_rlen, &read_object->u.request, datasz);
21859 	read_object->u.request.rd_object_offset = 0;
21860 	read_object->u.request.rd_object_cnt = 1;
21861 
21862 	memset((void *)read_object->u.request.rd_object_name, 0,
21863 	       LPFC_OBJ_NAME_SZ);
21864 	scnprintf((char *)rd_object_name, sizeof(rd_object_name), rdobject);
21865 	for (j = 0; j < strlen(rdobject); j++)
21866 		read_object->u.request.rd_object_name[j] =
21867 			cpu_to_le32(rd_object_name[j]);
21868 
21869 	pcmd = kmalloc(sizeof(*pcmd), GFP_KERNEL);
21870 	if (pcmd)
21871 		pcmd->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &pcmd->phys);
21872 	if (!pcmd || !pcmd->virt) {
21873 		kfree(pcmd);
21874 		mempool_free(mbox, phba->mbox_mem_pool);
21875 		return -ENOMEM;
21876 	}
21877 	memset((void *)pcmd->virt, 0, LPFC_BPL_SIZE);
21878 	read_object->u.request.rd_object_hbuf[0].pa_lo =
21879 		putPaddrLow(pcmd->phys);
21880 	read_object->u.request.rd_object_hbuf[0].pa_hi =
21881 		putPaddrHigh(pcmd->phys);
21882 	read_object->u.request.rd_object_hbuf[0].length = LPFC_BPL_SIZE;
21883 
21884 	mbox->vport = phba->pport;
21885 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21886 	mbox->ctx_buf = NULL;
21887 	mbox->ctx_ndlp = NULL;
21888 
21889 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
21890 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
21891 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
21892 
21893 	if (shdr_status == STATUS_FAILED &&
21894 	    shdr_add_status == ADD_STATUS_INVALID_OBJECT_NAME) {
21895 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
21896 				"4674 No port cfg file in FW.\n");
21897 		byte_cnt = -ENOENT;
21898 	} else if (shdr_status || shdr_add_status || rc) {
21899 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
21900 				"2625 READ_OBJECT mailbox failed with "
21901 				"status x%x add_status x%x, mbx status x%x\n",
21902 				shdr_status, shdr_add_status, rc);
21903 		byte_cnt = -ENXIO;
21904 	} else {
21905 		/* Success */
21906 		length = read_object->u.response.rd_object_actual_rlen;
21907 		eof = bf_get(lpfc_mbx_rd_object_eof, &read_object->u.response);
21908 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_CGN_MGMT,
21909 				"2626 READ_OBJECT Success len %d:%d, EOF %d\n",
21910 				length, datasz, eof);
21911 
21912 		/* Detect the port config file exists but is empty */
21913 		if (!length && eof) {
21914 			byte_cnt = 0;
21915 			goto exit;
21916 		}
21917 
21918 		byte_cnt = length;
21919 		lpfc_sli_pcimem_bcopy(pcmd->virt, datap, byte_cnt);
21920 	}
21921 
21922  exit:
21923 	lpfc_mbuf_free(phba, pcmd->virt, pcmd->phys);
21924 	kfree(pcmd);
21925 	mempool_free(mbox, phba->mbox_mem_pool);
21926 	return byte_cnt;
21927 }
21928 
21929 /**
21930  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
21931  * @phba: The HBA for which this call is being executed.
21932  * @lpfc_buf: IO buf structure to append the SGL chunk
21933  *
21934  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
21935  * and will allocate an SGL chunk if the pool is empty.
21936  *
21937  * Return codes:
21938  *   NULL - Error
21939  *   Pointer to sli4_hybrid_sgl - Success
21940  **/
21941 struct sli4_hybrid_sgl *
21942 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
21943 {
21944 	struct sli4_hybrid_sgl *list_entry = NULL;
21945 	struct sli4_hybrid_sgl *tmp = NULL;
21946 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
21947 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
21948 	struct list_head *buf_list = &hdwq->sgl_list;
21949 	unsigned long iflags;
21950 
21951 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21952 
21953 	if (likely(!list_empty(buf_list))) {
21954 		/* break off 1 chunk from the sgl_list */
21955 		list_for_each_entry_safe(list_entry, tmp,
21956 					 buf_list, list_node) {
21957 			list_move_tail(&list_entry->list_node,
21958 				       &lpfc_buf->dma_sgl_xtra_list);
21959 			break;
21960 		}
21961 	} else {
21962 		/* allocate more */
21963 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21964 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
21965 				   cpu_to_node(hdwq->io_wq->chann));
21966 		if (!tmp) {
21967 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21968 					"8353 error kmalloc memory for HDWQ "
21969 					"%d %s\n",
21970 					lpfc_buf->hdwq_no, __func__);
21971 			return NULL;
21972 		}
21973 
21974 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
21975 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
21976 		if (!tmp->dma_sgl) {
21977 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
21978 					"8354 error pool_alloc memory for HDWQ "
21979 					"%d %s\n",
21980 					lpfc_buf->hdwq_no, __func__);
21981 			kfree(tmp);
21982 			return NULL;
21983 		}
21984 
21985 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
21986 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
21987 	}
21988 
21989 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
21990 					struct sli4_hybrid_sgl,
21991 					list_node);
21992 
21993 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
21994 
21995 	return allocated_sgl;
21996 }
21997 
21998 /**
21999  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
22000  * @phba: The HBA for which this call is being executed.
22001  * @lpfc_buf: IO buf structure with the SGL chunk
22002  *
22003  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
22004  *
22005  * Return codes:
22006  *   0 - Success
22007  *   -EINVAL - Error
22008  **/
22009 int
22010 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22011 {
22012 	int rc = 0;
22013 	struct sli4_hybrid_sgl *list_entry = NULL;
22014 	struct sli4_hybrid_sgl *tmp = NULL;
22015 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22016 	struct list_head *buf_list = &hdwq->sgl_list;
22017 	unsigned long iflags;
22018 
22019 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22020 
22021 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
22022 		list_for_each_entry_safe(list_entry, tmp,
22023 					 &lpfc_buf->dma_sgl_xtra_list,
22024 					 list_node) {
22025 			list_move_tail(&list_entry->list_node,
22026 				       buf_list);
22027 		}
22028 	} else {
22029 		rc = -EINVAL;
22030 	}
22031 
22032 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22033 	return rc;
22034 }
22035 
22036 /**
22037  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
22038  * @phba: phba object
22039  * @hdwq: hdwq to cleanup sgl buff resources on
22040  *
22041  * This routine frees all SGL chunks of hdwq SGL chunk pool.
22042  *
22043  * Return codes:
22044  *   None
22045  **/
22046 void
22047 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
22048 		       struct lpfc_sli4_hdw_queue *hdwq)
22049 {
22050 	struct list_head *buf_list = &hdwq->sgl_list;
22051 	struct sli4_hybrid_sgl *list_entry = NULL;
22052 	struct sli4_hybrid_sgl *tmp = NULL;
22053 	unsigned long iflags;
22054 
22055 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22056 
22057 	/* Free sgl pool */
22058 	list_for_each_entry_safe(list_entry, tmp,
22059 				 buf_list, list_node) {
22060 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
22061 			      list_entry->dma_sgl,
22062 			      list_entry->dma_phys_sgl);
22063 		list_del(&list_entry->list_node);
22064 		kfree(list_entry);
22065 	}
22066 
22067 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22068 }
22069 
22070 /**
22071  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
22072  * @phba: The HBA for which this call is being executed.
22073  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
22074  *
22075  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
22076  * and will allocate an CMD/RSP buffer if the pool is empty.
22077  *
22078  * Return codes:
22079  *   NULL - Error
22080  *   Pointer to fcp_cmd_rsp_buf - Success
22081  **/
22082 struct fcp_cmd_rsp_buf *
22083 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22084 			      struct lpfc_io_buf *lpfc_buf)
22085 {
22086 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22087 	struct fcp_cmd_rsp_buf *tmp = NULL;
22088 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
22089 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22090 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22091 	unsigned long iflags;
22092 
22093 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22094 
22095 	if (likely(!list_empty(buf_list))) {
22096 		/* break off 1 chunk from the list */
22097 		list_for_each_entry_safe(list_entry, tmp,
22098 					 buf_list,
22099 					 list_node) {
22100 			list_move_tail(&list_entry->list_node,
22101 				       &lpfc_buf->dma_cmd_rsp_list);
22102 			break;
22103 		}
22104 	} else {
22105 		/* allocate more */
22106 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22107 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22108 				   cpu_to_node(hdwq->io_wq->chann));
22109 		if (!tmp) {
22110 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22111 					"8355 error kmalloc memory for HDWQ "
22112 					"%d %s\n",
22113 					lpfc_buf->hdwq_no, __func__);
22114 			return NULL;
22115 		}
22116 
22117 		tmp->fcp_cmnd = dma_pool_alloc(phba->lpfc_cmd_rsp_buf_pool,
22118 						GFP_ATOMIC,
22119 						&tmp->fcp_cmd_rsp_dma_handle);
22120 
22121 		if (!tmp->fcp_cmnd) {
22122 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22123 					"8356 error pool_alloc memory for HDWQ "
22124 					"%d %s\n",
22125 					lpfc_buf->hdwq_no, __func__);
22126 			kfree(tmp);
22127 			return NULL;
22128 		}
22129 
22130 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
22131 				sizeof(struct fcp_cmnd));
22132 
22133 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22134 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
22135 	}
22136 
22137 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
22138 					struct fcp_cmd_rsp_buf,
22139 					list_node);
22140 
22141 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22142 
22143 	return allocated_buf;
22144 }
22145 
22146 /**
22147  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
22148  * @phba: The HBA for which this call is being executed.
22149  * @lpfc_buf: IO buf structure with the CMD/RSP buf
22150  *
22151  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
22152  *
22153  * Return codes:
22154  *   0 - Success
22155  *   -EINVAL - Error
22156  **/
22157 int
22158 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22159 			      struct lpfc_io_buf *lpfc_buf)
22160 {
22161 	int rc = 0;
22162 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22163 	struct fcp_cmd_rsp_buf *tmp = NULL;
22164 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22165 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22166 	unsigned long iflags;
22167 
22168 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22169 
22170 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
22171 		list_for_each_entry_safe(list_entry, tmp,
22172 					 &lpfc_buf->dma_cmd_rsp_list,
22173 					 list_node) {
22174 			list_move_tail(&list_entry->list_node,
22175 				       buf_list);
22176 		}
22177 	} else {
22178 		rc = -EINVAL;
22179 	}
22180 
22181 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22182 	return rc;
22183 }
22184 
22185 /**
22186  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
22187  * @phba: phba object
22188  * @hdwq: hdwq to cleanup cmd rsp buff resources on
22189  *
22190  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
22191  *
22192  * Return codes:
22193  *   None
22194  **/
22195 void
22196 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22197 			       struct lpfc_sli4_hdw_queue *hdwq)
22198 {
22199 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22200 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22201 	struct fcp_cmd_rsp_buf *tmp = NULL;
22202 	unsigned long iflags;
22203 
22204 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22205 
22206 	/* Free cmd_rsp buf pool */
22207 	list_for_each_entry_safe(list_entry, tmp,
22208 				 buf_list,
22209 				 list_node) {
22210 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
22211 			      list_entry->fcp_cmnd,
22212 			      list_entry->fcp_cmd_rsp_dma_handle);
22213 		list_del(&list_entry->list_node);
22214 		kfree(list_entry);
22215 	}
22216 
22217 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22218 }
22219 
22220 /**
22221  * lpfc_sli_prep_wqe - Prepare WQE for the command to be posted
22222  * @phba: phba object
22223  * @job: job entry of the command to be posted.
22224  *
22225  * Fill the common fields of the wqe for each of the command.
22226  *
22227  * Return codes:
22228  *	None
22229  **/
22230 void
22231 lpfc_sli_prep_wqe(struct lpfc_hba *phba, struct lpfc_iocbq *job)
22232 {
22233 	u8 cmnd;
22234 	u32 *pcmd;
22235 	u32 if_type = 0;
22236 	u32 fip, abort_tag;
22237 	struct lpfc_nodelist *ndlp = NULL;
22238 	union lpfc_wqe128 *wqe = &job->wqe;
22239 	struct lpfc_dmabuf *context2;
22240 	u32 els_id = LPFC_ELS_ID_DEFAULT;
22241 	u8 command_type = ELS_COMMAND_NON_FIP;
22242 
22243 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
22244 	/* The fcp commands will set command type */
22245 	if (job->cmd_flag &  LPFC_IO_FCP)
22246 		command_type = FCP_COMMAND;
22247 	else if (fip && (job->cmd_flag & LPFC_FIP_ELS_ID_MASK))
22248 		command_type = ELS_COMMAND_FIP;
22249 	else
22250 		command_type = ELS_COMMAND_NON_FIP;
22251 
22252 	abort_tag = job->iotag;
22253 	cmnd = bf_get(wqe_cmnd, &wqe->els_req.wqe_com);
22254 
22255 	switch (cmnd) {
22256 	case CMD_ELS_REQUEST64_WQE:
22257 		if (job->cmd_flag & LPFC_IO_LIBDFC)
22258 			ndlp = job->context_un.ndlp;
22259 		else
22260 			ndlp = (struct lpfc_nodelist *)job->context1;
22261 
22262 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
22263 		if (command_type == ELS_COMMAND_FIP)
22264 			els_id = ((job->cmd_flag & LPFC_FIP_ELS_ID_MASK)
22265 				  >> LPFC_FIP_ELS_ID_SHIFT);
22266 
22267 		if_type = bf_get(lpfc_sli_intf_if_type,
22268 				 &phba->sli4_hba.sli_intf);
22269 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22270 			context2 = (struct lpfc_dmabuf *)job->context2;
22271 			pcmd = (u32 *)context2->virt;
22272 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
22273 				     *pcmd == ELS_CMD_SCR ||
22274 				     *pcmd == ELS_CMD_RDF ||
22275 				     *pcmd == ELS_CMD_EDC ||
22276 				     *pcmd == ELS_CMD_RSCN_XMT ||
22277 				     *pcmd == ELS_CMD_FDISC ||
22278 				     *pcmd == ELS_CMD_LOGO ||
22279 				     *pcmd == ELS_CMD_QFPA ||
22280 				     *pcmd == ELS_CMD_UVEM ||
22281 				     *pcmd == ELS_CMD_PLOGI)) {
22282 				bf_set(els_req64_sp, &wqe->els_req, 1);
22283 				bf_set(els_req64_sid, &wqe->els_req,
22284 				       job->vport->fc_myDID);
22285 
22286 				if ((*pcmd == ELS_CMD_FLOGI) &&
22287 				    !(phba->fc_topology ==
22288 				      LPFC_TOPOLOGY_LOOP))
22289 					bf_set(els_req64_sid, &wqe->els_req, 0);
22290 
22291 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
22292 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22293 				       phba->vpi_ids[job->vport->vpi]);
22294 			} else if (pcmd) {
22295 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
22296 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22297 				       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22298 			}
22299 		}
22300 
22301 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
22302 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22303 
22304 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
22305 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
22306 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
22307 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
22308 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22309 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
22310 		break;
22311 	case CMD_XMIT_ELS_RSP64_WQE:
22312 		ndlp = (struct lpfc_nodelist *)job->context1;
22313 
22314 		/* word4 */
22315 		wqe->xmit_els_rsp.word4 = 0;
22316 
22317 		if_type = bf_get(lpfc_sli_intf_if_type,
22318 				 &phba->sli4_hba.sli_intf);
22319 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22320 			if (job->vport->fc_flag & FC_PT2PT) {
22321 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22322 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22323 				       job->vport->fc_myDID);
22324 				if (job->vport->fc_myDID == Fabric_DID) {
22325 					bf_set(wqe_els_did,
22326 					       &wqe->xmit_els_rsp.wqe_dest, 0);
22327 				}
22328 			}
22329 		}
22330 
22331 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
22332 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
22333 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
22334 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
22335 		       LPFC_WQE_LENLOC_WORD3);
22336 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
22337 
22338 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
22339 			bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22340 			bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22341 			       job->vport->fc_myDID);
22342 			bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
22343 		}
22344 
22345 		if (phba->sli_rev == LPFC_SLI_REV4) {
22346 			bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
22347 			       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22348 
22349 			if (bf_get(wqe_ct, &wqe->xmit_els_rsp.wqe_com))
22350 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
22351 				       phba->vpi_ids[job->vport->vpi]);
22352 		}
22353 		command_type = OTHER_COMMAND;
22354 		break;
22355 	case CMD_GEN_REQUEST64_WQE:
22356 		/* Word 10 */
22357 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
22358 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
22359 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
22360 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22361 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
22362 		command_type = OTHER_COMMAND;
22363 		break;
22364 	case CMD_XMIT_SEQUENCE64_WQE:
22365 		if (phba->link_flag & LS_LOOPBACK_MODE)
22366 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
22367 
22368 		wqe->xmit_sequence.rsvd3 = 0;
22369 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
22370 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
22371 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
22372 		       LPFC_WQE_IOD_WRITE);
22373 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
22374 		       LPFC_WQE_LENLOC_WORD12);
22375 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
22376 		command_type = OTHER_COMMAND;
22377 		break;
22378 	case CMD_XMIT_BLS_RSP64_WQE:
22379 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
22380 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
22381 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
22382 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
22383 		       phba->vpi_ids[phba->pport->vpi]);
22384 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
22385 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
22386 		       LPFC_WQE_LENLOC_NONE);
22387 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
22388 		command_type = OTHER_COMMAND;
22389 		break;
22390 	case CMD_FCP_ICMND64_WQE:	/* task mgmt commands */
22391 	case CMD_ABORT_XRI_WQE:		/* abort iotag */
22392 	case CMD_SEND_FRAME:		/* mds loopback */
22393 		/* cases already formatted for sli4 wqe - no chgs necessary */
22394 		return;
22395 	default:
22396 		dump_stack();
22397 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
22398 				"6207 Invalid command 0x%x\n",
22399 				cmnd);
22400 		break;
22401 	}
22402 
22403 	wqe->generic.wqe_com.abort_tag = abort_tag;
22404 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, job->iotag);
22405 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
22406 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
22407 }
22408